diff --git a/generators/python/core_utilities/fastapi/pydantic_utilities.py b/generators/python/core_utilities/fastapi/pydantic_utilities.py index 118e5af43bc..fa828e2baf6 100644 --- a/generators/python/core_utilities/fastapi/pydantic_utilities.py +++ b/generators/python/core_utilities/fastapi/pydantic_utilities.py @@ -92,15 +92,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -109,7 +121,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -149,12 +162,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -170,7 +187,9 @@ def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/generators/python/core_utilities/fastapi/route_args.py b/generators/python/core_utilities/fastapi/route_args.py index f4d11cee58e..180ba9e7034 100644 --- a/generators/python/core_utilities/fastapi/route_args.py +++ b/generators/python/core_utilities/fastapi/route_args.py @@ -54,7 +54,11 @@ def decorator(endpoint_function: T) -> T: setattr( endpoint_function, FERN_CONFIG_KEY, - RouteArgs(openapi_extra=openapi_extra, tags=tags, include_in_schema=include_in_schema), + RouteArgs( + openapi_extra=openapi_extra, + tags=tags, + include_in_schema=include_in_schema, + ), ) return endpoint_function diff --git a/generators/python/core_utilities/pydantic/pydantic_utilities.py b/generators/python/core_utilities/pydantic/pydantic_utilities.py index 118e5af43bc..fa828e2baf6 100644 --- a/generators/python/core_utilities/pydantic/pydantic_utilities.py +++ b/generators/python/core_utilities/pydantic/pydantic_utilities.py @@ -92,15 +92,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -109,7 +121,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -149,12 +162,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -170,7 +187,9 @@ def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/generators/python/core_utilities/pydantic/serialization.py b/generators/python/core_utilities/pydantic/serialization.py index dd782612b2d..0a85fb2c2f6 100644 --- a/generators/python/core_utilities/pydantic/serialization.py +++ b/generators/python/core_utilities/pydantic/serialization.py @@ -23,7 +23,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively diff --git a/generators/python/core_utilities/pydantic/unchecked_base_model.py b/generators/python/core_utilities/pydantic/unchecked_base_model.py index 9a003d8e37e..a4d2fcf6cc0 100644 --- a/generators/python/core_utilities/pydantic/unchecked_base_model.py +++ b/generators/python/core_utilities/pydantic/unchecked_base_model.py @@ -34,7 +34,9 @@ def __init__(self, *, discriminant: str) -> None: class UncheckedBaseModel(UniversalBaseModel): if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -42,7 +44,9 @@ class Config: @classmethod def model_construct( - cls: typing.Type["Model"], _fields_set: typing.Optional[typing.Set[str]] = None, **values: typing.Any + cls: typing.Type["Model"], + _fields_set: typing.Optional[typing.Set[str]] = None, + **values: typing.Any, ) -> "Model": # Fallback construct function to the specified override below. return cls.construct(_fields_set=_fields_set, **values) @@ -51,7 +55,9 @@ def model_construct( # Implementation taken from: https://github.com/pydantic/pydantic/issues/1168#issuecomment-817742836 @classmethod def construct( - cls: typing.Type["Model"], _fields_set: typing.Optional[typing.Set[str]] = None, **values: typing.Any + cls: typing.Type["Model"], + _fields_set: typing.Optional[typing.Set[str]] = None, + **values: typing.Any, ) -> "Model": m = cls.__new__(cls) fields_values = {} @@ -259,9 +265,12 @@ def _get_is_populate_by_name(model: typing.Type["Model"]) -> bool: PydanticField = typing.Union[ModelField, pydantic.fields.FieldInfo] + # Pydantic V1 swapped the typing of __fields__'s values from ModelField to FieldInfo # And so we try to handle both V1 cases, as well as V2 (FieldInfo from model.model_fields) -def _get_model_fields(model: typing.Type["Model"]) -> typing.Mapping[str, PydanticField]: +def _get_model_fields( + model: typing.Type["Model"], +) -> typing.Mapping[str, PydanticField]: if IS_PYDANTIC_V2: return model.model_fields # type: ignore # Pydantic v2 else: diff --git a/generators/python/core_utilities/sdk/base_test_utilities.py b/generators/python/core_utilities/sdk/base_test_utilities.py index d3676bdb487..40c7db56fcf 100644 --- a/generators/python/core_utilities/sdk/base_test_utilities.py +++ b/generators/python/core_utilities/sdk/base_test_utilities.py @@ -43,7 +43,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(entry_expectation, dict): is_container_of_complex_type = True validate_response( - response=response[idx], json_expectation=ex, type_expectations=entry_expectation + response=response[idx], + json_expectation=ex, + type_expectations=entry_expectation, ) else: cast_json_expectation.append(cast_field(ex, entry_expectation)) @@ -55,7 +57,10 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # if any of the values of the set have a type_expectation of a dict, we're assuming it's a pydantic # model and keeping it a list. if container_expectation != "set" or not any( - map(lambda value: isinstance(value, dict), list(contents_expectation.values())) + map( + lambda value: isinstance(value, dict), + list(contents_expectation.values()), + ) ): json_expectation = cast_field(json_expectation, container_expectation) elif isinstance(type_expectation, tuple): @@ -64,9 +69,15 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(contents_expectation, dict): json_expectation = { cast_field( - key, contents_expectation.get(idx)[0] if contents_expectation.get(idx) is not None else None # type: ignore + key, + contents_expectation.get(idx)[0] + if contents_expectation.get(idx) is not None + else None, # type: ignore ): cast_field( - value, contents_expectation.get(idx)[1] if contents_expectation.get(idx) is not None else None # type: ignore + value, + contents_expectation.get(idx)[1] + if contents_expectation.get(idx) is not None + else None, # type: ignore ) for idx, (key, value) in enumerate(json_expectation.items()) } @@ -95,7 +106,11 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e and not isinstance(response, dict) and not issubclass(type(response), pydantic.BaseModel) ): - validate_field(response=response, json_expectation=json_expectation, type_expectation=type_expectations) + validate_field( + response=response, + json_expectation=json_expectation, + type_expectation=type_expectations, + ) return if isinstance(response, list): @@ -107,7 +122,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e content_expectation = type_expectations[1] for idx, item in enumerate(response): validate_response( - response=item, json_expectation=json_expectation[idx], type_expectations=content_expectation[idx] + response=item, + json_expectation=json_expectation[idx], + type_expectations=content_expectation[idx], ) else: response_json = response @@ -127,10 +144,16 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e # Otherwise, we're just validating a single field that's a pydantic model. if isinstance(value, dict) and not isinstance(type_expectation, tuple): validate_response( - response=response_json[key], json_expectation=value, type_expectations=type_expectation + response=response_json[key], + json_expectation=value, + type_expectations=type_expectation, ) else: - validate_field(response=response_json[key], json_expectation=value, type_expectation=type_expectation) + validate_field( + response=response_json[key], + json_expectation=value, + type_expectation=type_expectation, + ) # Ensure there are no additional fields here either del response_json[key] diff --git a/generators/python/core_utilities/sdk/file.py b/generators/python/core_utilities/sdk/file.py index 4fc0b33faaa..e4de09f9b59 100644 --- a/generators/python/core_utilities/sdk/file.py +++ b/generators/python/core_utilities/sdk/file.py @@ -11,12 +11,17 @@ # (filename, file (or bytes), content_type) typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str]], # (filename, file (or bytes), content_type, headers) - typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str], typing.Mapping[str, str]], + typing.Tuple[ + typing.Optional[str], + FileContent, + typing.Optional[str], + typing.Mapping[str, str], + ], ] def convert_file_dict_to_httpx_tuples( - d: typing.Dict[str, typing.Union[File, typing.List[File]]] + d: typing.Dict[str, typing.Union[File, typing.List[File]]], ) -> typing.List[typing.Tuple[str, File]]: """ The format we use is a list of tuples, where the first element is the diff --git a/generators/python/core_utilities/sdk/http_client.py b/generators/python/core_utilities/sdk/http_client.py index 0d4f2d5566a..9a1f67d0564 100644 --- a/generators/python/core_utilities/sdk/http_client.py +++ b/generators/python/core_utilities/sdk/http_client.py @@ -88,7 +88,8 @@ def _should_retry(response: httpx.Response) -> bool: def remove_omit_from_dict( - original: typing.Dict[str, typing.Optional[typing.Any]], omit: typing.Optional[typing.Any] + original: typing.Dict[str, typing.Optional[typing.Any]], + omit: typing.Optional[typing.Any], ) -> typing.Dict[str, typing.Any]: if omit is None: return original diff --git a/generators/python/core_utilities/sdk/pydantic_utilities.py b/generators/python/core_utilities/sdk/pydantic_utilities.py index a9b77c2a679..89443988593 100644 --- a/generators/python/core_utilities/sdk/pydantic_utilities.py +++ b/generators/python/core_utilities/sdk/pydantic_utilities.py @@ -92,15 +92,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -109,7 +121,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -149,12 +162,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -170,7 +187,9 @@ def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) # type: ignore # Pydantic v1 diff --git a/generators/python/core_utilities/sdk/serialization.py b/generators/python/core_utilities/sdk/serialization.py index dd782612b2d..0a85fb2c2f6 100644 --- a/generators/python/core_utilities/sdk/serialization.py +++ b/generators/python/core_utilities/sdk/serialization.py @@ -23,7 +23,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively diff --git a/generators/python/core_utilities/sdk/unchecked_base_model.py b/generators/python/core_utilities/sdk/unchecked_base_model.py index 25fa70a3543..4cf9e531aab 100644 --- a/generators/python/core_utilities/sdk/unchecked_base_model.py +++ b/generators/python/core_utilities/sdk/unchecked_base_model.py @@ -34,7 +34,9 @@ def __init__(self, *, discriminant: str) -> None: class UncheckedBaseModel(UniversalBaseModel): if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -42,7 +44,9 @@ class Config: @classmethod def model_construct( - cls: typing.Type["Model"], _fields_set: typing.Optional[typing.Set[str]] = None, **values: typing.Any + cls: typing.Type["Model"], + _fields_set: typing.Optional[typing.Set[str]] = None, + **values: typing.Any, ) -> "Model": # Fallback construct function to the specified override below. return cls.construct(_fields_set=_fields_set, **values) @@ -51,7 +55,9 @@ def model_construct( # Implementation taken from: https://github.com/pydantic/pydantic/issues/1168#issuecomment-817742836 @classmethod def construct( - cls: typing.Type["Model"], _fields_set: typing.Optional[typing.Set[str]] = None, **values: typing.Any + cls: typing.Type["Model"], + _fields_set: typing.Optional[typing.Set[str]] = None, + **values: typing.Any, ) -> "Model": m = cls.__new__(cls) fields_values = {} @@ -259,9 +265,12 @@ def _get_is_populate_by_name(model: typing.Type["Model"]) -> bool: PydanticField = typing.Union[ModelField, pydantic.fields.FieldInfo] + # Pydantic V1 swapped the typing of __fields__'s values from ModelField to FieldInfo # And so we try to handle both V1 cases, as well as V2 (FieldInfo from model.model_fields) -def _get_model_fields(model: typing.Type["Model"]) -> typing.Mapping[str, PydanticField]: +def _get_model_fields( + model: typing.Type["Model"], +) -> typing.Mapping[str, PydanticField]: if IS_PYDANTIC_V2: return model.model_fields # type: ignore # Pydantic v2 else: diff --git a/generators/python/fastapi/CHANGELOG.md b/generators/python/fastapi/CHANGELOG.md index 58e41d39781..0e8f6762164 100644 --- a/generators/python/fastapi/CHANGELOG.md +++ b/generators/python/fastapi/CHANGELOG.md @@ -5,6 +5,11 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [1.4.0-rc0] = 2024-08-05 + +- Feature: The generator now uses ruff to format the generated code. Additionally, + if `skip_formatting` is turned on then none of the code snippets will be formatted. + ## [1.3.0] - 2024-08-04 - Internal: The generator has now been upgraded to use Pydantic V2 internally. Note that diff --git a/generators/python/fastapi/VERSION b/generators/python/fastapi/VERSION index 589268e6fed..cc85fc6c372 100644 --- a/generators/python/fastapi/VERSION +++ b/generators/python/fastapi/VERSION @@ -1 +1 @@ -1.3.0 \ No newline at end of file +1.4.0-rc0 \ No newline at end of file diff --git a/generators/python/poetry.lock b/generators/python/poetry.lock index a5048f1d553..56d614fb872 100644 --- a/generators/python/poetry.lock +++ b/generators/python/poetry.lock @@ -858,6 +858,33 @@ pygments = ">=2.6.0,<3.0.0" [package.extras] jupyter = ["ipywidgets (>=7.5.1,<8.0.0)"] +[[package]] +name = "ruff" +version = "0.5.6" +description = "An extremely fast Python linter and code formatter, written in Rust." +optional = false +python-versions = ">=3.7" +files = [ + {file = "ruff-0.5.6-py3-none-linux_armv6l.whl", hash = "sha256:a0ef5930799a05522985b9cec8290b185952f3fcd86c1772c3bdbd732667fdcd"}, + {file = "ruff-0.5.6-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:b652dc14f6ef5d1552821e006f747802cc32d98d5509349e168f6bf0ee9f8f42"}, + {file = "ruff-0.5.6-py3-none-macosx_11_0_arm64.whl", hash = "sha256:80521b88d26a45e871f31e4b88938fd87db7011bb961d8afd2664982dfc3641a"}, + {file = "ruff-0.5.6-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:d9bc8f328a9f1309ae80e4d392836e7dbc77303b38ed4a7112699e63d3b066ab"}, + {file = "ruff-0.5.6-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:4d394940f61f7720ad371ddedf14722ee1d6250fd8d020f5ea5a86e7be217daf"}, + {file = "ruff-0.5.6-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:111a99cdb02f69ddb2571e2756e017a1496c2c3a2aeefe7b988ddab38b416d36"}, + {file = "ruff-0.5.6-py3-none-manylinux_2_17_ppc64.manylinux2014_ppc64.whl", hash = "sha256:e395daba77a79f6dc0d07311f94cc0560375ca20c06f354c7c99af3bf4560c5d"}, + {file = "ruff-0.5.6-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:c476acb43c3c51e3c614a2e878ee1589655fa02dab19fe2db0423a06d6a5b1b6"}, + {file = "ruff-0.5.6-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:e2ff8003f5252fd68425fd53d27c1f08b201d7ed714bb31a55c9ac1d4c13e2eb"}, + {file = "ruff-0.5.6-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:c94e084ba3eaa80c2172918c2ca2eb2230c3f15925f4ed8b6297260c6ef179ad"}, + {file = "ruff-0.5.6-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:1f77c1c3aa0669fb230b06fb24ffa3e879391a3ba3f15e3d633a752da5a3e670"}, + {file = "ruff-0.5.6-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:f908148c93c02873210a52cad75a6eda856b2cbb72250370ce3afef6fb99b1ed"}, + {file = "ruff-0.5.6-py3-none-musllinux_1_2_i686.whl", hash = "sha256:563a7ae61ad284187d3071d9041c08019975693ff655438d8d4be26e492760bd"}, + {file = "ruff-0.5.6-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:94fe60869bfbf0521e04fd62b74cbca21cbc5beb67cbb75ab33fe8c174f54414"}, + {file = "ruff-0.5.6-py3-none-win32.whl", hash = "sha256:e6a584c1de6f8591c2570e171cc7ce482bb983d49c70ddf014393cd39e9dfaed"}, + {file = "ruff-0.5.6-py3-none-win_amd64.whl", hash = "sha256:d7fe7dccb1a89dc66785d7aa0ac283b2269712d8ed19c63af908fdccca5ccc1a"}, + {file = "ruff-0.5.6-py3-none-win_arm64.whl", hash = "sha256:57c6c0dd997b31b536bff49b9eee5ed3194d60605a4427f735eeb1f9c1b8d264"}, + {file = "ruff-0.5.6.tar.gz", hash = "sha256:07c9e3c2a8e1fe377dd460371c3462671a728c981c3205a5217291422209f642"}, +] + [[package]] name = "shellingham" version = "1.5.4" @@ -1040,4 +1067,4 @@ files = [ [metadata] lock-version = "2.0" python-versions = "^3.9" -content-hash = "3c0a55f7e324bf8bc878b1af9eb6ba7e2d54fb5675edf8a88534dab62c809027" +content-hash = "6fdf449f90f2a8a044109cadaf07b436438807ab17e7a23784d9a84e257ddb16" diff --git a/generators/python/pydantic/CHANGELOG.md b/generators/python/pydantic/CHANGELOG.md index e184a3d3f12..94aaac3ecff 100644 --- a/generators/python/pydantic/CHANGELOG.md +++ b/generators/python/pydantic/CHANGELOG.md @@ -5,6 +5,11 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [1.3.0-rc0] = 2024-08-05 + +- Feature: The generator now uses ruff to format the generated code. Additionally, + if `skip_formatting` is turned on then none of the code snippets will be formatted. + ## [1.2.0] - 2024-08-04 - Internal: The generator has now been upgraded to use Pydantic V2 internally. Note that diff --git a/generators/python/pydantic/VERSION b/generators/python/pydantic/VERSION index 867e52437ab..14f7c717a7a 100644 --- a/generators/python/pydantic/VERSION +++ b/generators/python/pydantic/VERSION @@ -1 +1 @@ -1.2.0 \ No newline at end of file +1.3.0-rc0 \ No newline at end of file diff --git a/generators/python/pyproject.toml b/generators/python/pyproject.toml index 9a89d9a8fce..2ef0c757cf4 100644 --- a/generators/python/pyproject.toml +++ b/generators/python/pyproject.toml @@ -24,6 +24,7 @@ flake8 = "^5.0.4" isort = "^5.10.1" pre-commit = "^2.20.0" snapshottest = "^0.6.0" +ruff = "^0.5.6" [[tool.poetry.source]] name = "fern-prod" diff --git a/generators/python/sdk/CHANGELOG.md b/generators/python/sdk/CHANGELOG.md index b32e0237dc7..ca5b1f0e5bb 100644 --- a/generators/python/sdk/CHANGELOG.md +++ b/generators/python/sdk/CHANGELOG.md @@ -5,6 +5,11 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [3.5.0-rc0] = 2024-08-05 + +- Feature: The generator now uses ruff to format all of the generated code. Additionally, + if `skip_formatting` is turned on then none of the code snippets will be formatted. + ## [3.4.0] - 2024-08-02 - Internal: The SDK generator has now been upgraded to use Pydantic V2 internally. Note that diff --git a/generators/python/sdk/VERSION b/generators/python/sdk/VERSION index 18091983f59..15ef755a7d0 100644 --- a/generators/python/sdk/VERSION +++ b/generators/python/sdk/VERSION @@ -1 +1 @@ -3.4.0 +3.5.0-rc0 diff --git a/generators/python/src/fern_python/cli/abstract_generator.py b/generators/python/src/fern_python/cli/abstract_generator.py index d36943c547f..e219377f0c6 100644 --- a/generators/python/src/fern_python/cli/abstract_generator.py +++ b/generators/python/src/fern_python/cli/abstract_generator.py @@ -9,10 +9,12 @@ from fern.generator_exec.config import ( GeneratorPublishConfig, GithubOutputMode, + OutputMode, PypiGithubPublishInfo, ) from fern_python.codegen.project import Project, ProjectConfig +from fern_python.external_dependencies.ruff import RUFF_DEPENDENCY from fern_python.generator_exec_wrapper import GeneratorExecWrapper from .publisher import Publisher @@ -55,7 +57,6 @@ def generate_project( if project_config is not None else generator_config.organization, project_config=project_config, - should_format_files=self.should_format_files(generator_config=generator_config), sorted_modules=self.get_sorted_modules(), flat_layout=self.is_flat_layout(generator_config=generator_config), whitelabel=generator_config.whitelabel, @@ -65,9 +66,14 @@ def generate_project( license_=generator_config.license, ) as project: self.run( - generator_exec_wrapper=generator_exec_wrapper, ir=ir, generator_config=generator_config, project=project + generator_exec_wrapper=generator_exec_wrapper, + ir=ir, + generator_config=generator_config, + project=project, ) + project.add_dev_dependency(dependency=RUFF_DEPENDENCY) + generator_config.output.mode.visit( download_files=lambda: None, github=lambda github_output_mode: self._write_files_for_github_repo( @@ -78,19 +84,27 @@ def generate_project( publish=lambda x: None, ) - generator_config.output.mode.visit( - download_files=lambda: None, - github=lambda _: self._poetry_install( - generator_exec_wrapper=generator_exec_wrapper, - generator_config=generator_config, - ), - publish=lambda publish_config: self._publish( - generator_exec_wrapper=generator_exec_wrapper, - publish_config=publish_config, - generator_config=generator_config, - ), + publisher = Publisher( + should_format=self.should_format_files(generator_config=generator_config), + generator_exec_wrapper=generator_exec_wrapper, + generator_config=generator_config, ) + output_mode: OutputMode = generator_config.output.mode + output_mode_union = output_mode.get_as_union() + + if output_mode_union.type == "downloadFiles": + publisher._run_command( + command=["poetry", "run", "ruff", "format", "/fern/output"], + safe_command="poetry run ruff format /fern/output", + cwd="/", + ) + elif output_mode_union.type == "github": + publisher.run_poetry_install() + publisher.run_ruff_format() + elif output_mode_union.type == "publish": + publisher.publish_package(publish_config=output_mode_union) + def _get_github_publish_config( self, generator_config: GeneratorConfig, output_mode: GithubOutputMode ) -> ProjectConfig: @@ -118,14 +132,19 @@ def _get_pypi_metadata(self, generator_config: GeneratorConfig) -> Optional[Pypi else None, ) - def _poetry_install( - self, *, generator_exec_wrapper: GeneratorExecWrapper, generator_config: GeneratorConfig + def _poetry_install_and_format( + self, + *, + generator_exec_wrapper: GeneratorExecWrapper, + generator_config: GeneratorConfig, ) -> None: publisher = Publisher( + should_format=self.should_format_files(generator_config=generator_config), generator_exec_wrapper=generator_exec_wrapper, generator_config=generator_config, ) publisher.run_poetry_install() + publisher.run_ruff_format() def _publish( self, @@ -134,6 +153,7 @@ def _publish( generator_config: GeneratorConfig, ) -> None: publisher = Publisher( + should_format=self.should_format_files(generator_config=generator_config), generator_exec_wrapper=generator_exec_wrapper, generator_config=generator_config, ) @@ -150,7 +170,10 @@ def _write_files_for_github_repo( poetry.toml """, ) - project.add_file(".github/workflows/ci.yml", self._get_github_workflow(output_mode, write_unit_tests)) + project.add_file( + ".github/workflows/ci.yml", + self._get_github_workflow(output_mode, write_unit_tests), + ) project.add_file("tests/custom/test_client.py", self._get_client_test()) def _get_github_workflow(self, output_mode: GithubOutputMode, write_unit_tests: bool) -> str: diff --git a/generators/python/src/fern_python/cli/generator_cli.py b/generators/python/src/fern_python/cli/generator_cli.py index 18959b2f42d..442585816ab 100644 --- a/generators/python/src/fern_python/cli/generator_cli.py +++ b/generators/python/src/fern_python/cli/generator_cli.py @@ -43,7 +43,9 @@ def run(self) -> None: ) self.abstract_generator.generate_project( - generator_exec_wrapper=generator_exec_wrapper, ir=ir, generator_config=config + generator_exec_wrapper=generator_exec_wrapper, + ir=ir, + generator_config=config, ) generator_exec_wrapper.send_update( GeneratorUpdate.factory.exit_status_update( diff --git a/generators/python/src/fern_python/cli/publisher.py b/generators/python/src/fern_python/cli/publisher.py index 4aea1a3186f..759a4d3d403 100644 --- a/generators/python/src/fern_python/cli/publisher.py +++ b/generators/python/src/fern_python/cli/publisher.py @@ -13,12 +13,20 @@ class Publisher: def __init__( self, *, + should_format: bool, generator_exec_wrapper: GeneratorExecWrapper, generator_config: GeneratorConfig, ): + self._should_format = should_format self._generator_exec_wrapper = generator_exec_wrapper self._generator_config = generator_config + def run_ruff_format(self) -> None: + self._run_command( + command=["poetry", "run", "ruff", "format"], + safe_command="poetry run ruff format", + ) + def run_poetry_install(self) -> None: self._run_command( command=["poetry", "install"], @@ -31,6 +39,8 @@ def publish_package( publish_config: GeneratorPublishConfig, ) -> None: self.run_poetry_install() + if self._should_format: + self.run_ruff_format() pypi_registry_config = publish_config.registries_v_2.pypi self._run_command( command=[ @@ -71,6 +81,7 @@ def _run_command( *, command: List[str], safe_command: str, + cwd=None, ) -> None: try: self._generator_exec_wrapper.send_update( @@ -82,7 +93,7 @@ def _run_command( command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, - cwd=self._generator_config.output.path, + cwd=self._generator_config.output.path if cwd is None else cwd, check=True, ) print(f"Ran command: {' '.join(command)}") diff --git a/generators/python/src/fern_python/codegen/ast/ast_node/__init__.py b/generators/python/src/fern_python/codegen/ast/ast_node/__init__.py index b6910e34f39..8ea7c3c6098 100644 --- a/generators/python/src/fern_python/codegen/ast/ast_node/__init__.py +++ b/generators/python/src/fern_python/codegen/ast/ast_node/__init__.py @@ -4,4 +4,11 @@ from .node_writer import NodeWriter from .writer import IndentableWriter, Writer -__all__ = ["AstNode", "Writer", "NodeWriter", "IndentableWriter", "GenericTypeVar", "AstNodeMetadata"] +__all__ = [ + "AstNode", + "Writer", + "NodeWriter", + "IndentableWriter", + "GenericTypeVar", + "AstNodeMetadata", +] diff --git a/generators/python/src/fern_python/codegen/ast/dependency/__init__.py b/generators/python/src/fern_python/codegen/ast/dependency/__init__.py index 13773b26805..1a602b218de 100644 --- a/generators/python/src/fern_python/codegen/ast/dependency/__init__.py +++ b/generators/python/src/fern_python/codegen/ast/dependency/__init__.py @@ -5,4 +5,9 @@ DependencyVersion, ) -__all__ = ["Dependency", "DependencyName", "DependencyVersion", "DependencyCompatibility"] +__all__ = [ + "Dependency", + "DependencyName", + "DependencyVersion", + "DependencyCompatibility", +] diff --git a/generators/python/src/fern_python/codegen/ast/nodes/declarations/function/__init__.py b/generators/python/src/fern_python/codegen/ast/nodes/declarations/function/__init__.py index 2233d1c69d7..f2518782f05 100644 --- a/generators/python/src/fern_python/codegen/ast/nodes/declarations/function/__init__.py +++ b/generators/python/src/fern_python/codegen/ast/nodes/declarations/function/__init__.py @@ -3,4 +3,9 @@ from .function_signature import FunctionSignature from .named_function_parameter import NamedFunctionParameter -__all__ = ["FunctionDeclaration", "FunctionParameter", "FunctionSignature", "NamedFunctionParameter"] +__all__ = [ + "FunctionDeclaration", + "FunctionParameter", + "FunctionSignature", + "NamedFunctionParameter", +] diff --git a/generators/python/src/fern_python/codegen/ast/nodes/declarations/function/function_declaration.py b/generators/python/src/fern_python/codegen/ast/nodes/declarations/function/function_declaration.py index d2d64704562..fab177e1d69 100644 --- a/generators/python/src/fern_python/codegen/ast/nodes/declarations/function/function_declaration.py +++ b/generators/python/src/fern_python/codegen/ast/nodes/declarations/function/function_declaration.py @@ -53,7 +53,12 @@ def write(self, writer: NodeWriter, should_write_as_snippet: Optional[bool] = No self._write(writer, signature=overload, body=None) self._write(writer, signature=self.signature, body=self.body) - def _write(self, writer: NodeWriter, signature: FunctionSignature, body: Optional[CodeWriter]) -> None: + def _write( + self, + writer: NodeWriter, + signature: FunctionSignature, + body: Optional[CodeWriter], + ) -> None: if body is None: writer.write("@") writer.write_reference(OVERLOAD_DECORATOR) diff --git a/generators/python/src/fern_python/codegen/ast/references/module.py b/generators/python/src/fern_python/codegen/ast/references/module.py index d2418840bff..2023889cd28 100644 --- a/generators/python/src/fern_python/codegen/ast/references/module.py +++ b/generators/python/src/fern_python/codegen/ast/references/module.py @@ -36,7 +36,10 @@ def is_local(self) -> bool: @staticmethod def external( - module_path: ModulePath, *, dependency: Dependency, types_package: Optional[Dependency] = None + module_path: ModulePath, + *, + dependency: Dependency, + types_package: Optional[Dependency] = None, ) -> Module: return Module(path=module_path, source=dependency, types_package=types_package) diff --git a/generators/python/src/fern_python/codegen/imports_manager.py b/generators/python/src/fern_python/codegen/imports_manager.py index 79756c50704..01a14142b0d 100644 --- a/generators/python/src/fern_python/codegen/imports_manager.py +++ b/generators/python/src/fern_python/codegen/imports_manager.py @@ -52,16 +52,27 @@ def write_top_imports_for_file(self, writer: AST.Writer, reference_resolver: Ref self._has_written_top_imports = True def write_top_imports_for_statement( - self, *, statement_id: StatementId, writer: AST.NodeWriter, reference_resolver: ReferenceResolverImpl + self, + *, + statement_id: StatementId, + writer: AST.NodeWriter, + reference_resolver: ReferenceResolverImpl, ) -> None: if not self._has_written_top_imports: raise RuntimeError("Top imports haven't been written yet") # write (and forget) all imports that have no constraints written_imports: Set[AST.ReferenceImport] = set() - for import_, statements_that_must_precede_it in self._import_to_statements_that_must_precede_it.items(): + for ( + import_, + statements_that_must_precede_it, + ) in self._import_to_statements_that_must_precede_it.items(): if len(statements_that_must_precede_it) == 0: - self._write_import(import_=import_, writer=writer, reference_resolver=reference_resolver) + self._write_import( + import_=import_, + writer=writer, + reference_resolver=reference_resolver, + ) written_imports.add(import_) elif statement_id in statements_that_must_precede_it: statements_that_must_precede_it.remove(statement_id) @@ -70,14 +81,22 @@ def write_top_imports_for_statement( # write all the imports that must be un-type checked (e.g. for circular references) if len(self._if_type_checking_imports.items()) > 0: - self._write_import(import_=TYPING_REFERENCE_IMPORT, writer=writer, reference_resolver=reference_resolver) + self._write_import( + import_=TYPING_REFERENCE_IMPORT, + writer=writer, + reference_resolver=reference_resolver, + ) writer.write("if ") writer.write_node(AST.TypeHint.type_checking()) writer.write_line(":") with writer.indent(): un_type_checked_written_imports: Set[AST.ReferenceImport] = set() for import_, _ in self._if_type_checking_imports.items(): - self._write_import(import_=import_, writer=writer, reference_resolver=reference_resolver) + self._write_import( + import_=import_, + writer=writer, + reference_resolver=reference_resolver, + ) un_type_checked_written_imports.add(import_) for import_ in un_type_checked_written_imports: del self._if_type_checking_imports[import_] @@ -96,7 +115,10 @@ def write_remaining_imports(self, writer: AST.NodeWriter, reference_resolver: Re self._write_import(import_=import_, writer=writer, reference_resolver=reference_resolver) def _write_import( - self, import_: AST.ReferenceImport, writer: AST.NodeWriter, reference_resolver: ReferenceResolverImpl + self, + import_: AST.ReferenceImport, + writer: AST.NodeWriter, + reference_resolver: ReferenceResolverImpl, ) -> None: resolved_import = reference_resolver.resolve_import(import_) if resolved_import.import_ is not None: diff --git a/generators/python/src/fern_python/codegen/module_manager.py b/generators/python/src/fern_python/codegen/module_manager.py index bef7602db53..fbdaa617b5c 100644 --- a/generators/python/src/fern_python/codegen/module_manager.py +++ b/generators/python/src/fern_python/codegen/module_manager.py @@ -45,9 +45,8 @@ class ModuleManager: _module_infos: DefaultDict[AST.ModulePath, ModuleInfo] - def __init__(self, *, should_format: bool, sorted_modules: Optional[Sequence[str]] = None) -> None: + def __init__(self, *, sorted_modules: Optional[Sequence[str]] = None) -> None: self._module_infos = defaultdict(create_empty_module_info) - self._should_format = should_format self._sorted_modules = sorted_modules or [] def register_additional_exports(self, path: AST.ModulePath, exports: List[ModuleExport]) -> None: @@ -95,7 +94,7 @@ def register_exports(self, filepath: Filepath, exports: Set[str], from_src: Opti def write_modules(self, base_filepath: str, filepath: str) -> None: for module, module_info in self._module_infos.items(): writer = WriterImpl( - should_format=self._should_format, + should_format=False, # don't sort imports in __init__.py because the import order is # controlled to avoid issues with circular imports should_sort_imports=False, @@ -110,7 +109,11 @@ def write_modules(self, base_filepath: str, filepath: str) -> None: if len(all_exports) > 0: writer.write_line("__all__ = [" + ", ".join(f'"{export}"' for export in sorted(all_exports)) + "]") writer.write_to_file( - os.path.join(filepath if module_info.from_src else base_filepath, *module, "__init__.py") + os.path.join( + filepath if module_info.from_src else base_filepath, + *module, + "__init__.py", + ) ) def _build_sorted_exports(self, module_info: ModuleInfo) -> List[ModuleExportsLine]: diff --git a/generators/python/src/fern_python/codegen/project.py b/generators/python/src/fern_python/codegen/project.py index a25ff9041be..29fa43be01e 100644 --- a/generators/python/src/fern_python/codegen/project.py +++ b/generators/python/src/fern_python/codegen/project.py @@ -40,7 +40,6 @@ def __init__( relative_path_to_project: str, python_version: str = "^3.8", project_config: Optional[ProjectConfig] = None, - should_format_files: bool, sorted_modules: Optional[Sequence[str]] = None, flat_layout: bool = False, whitelabel: bool = False, @@ -60,10 +59,9 @@ def __init__( self._root_filepath = filepath self._relative_path_to_project = relative_path_to_project self._project_config = project_config - self._module_manager = ModuleManager(should_format=should_format_files, sorted_modules=sorted_modules) + self._module_manager = ModuleManager(sorted_modules=sorted_modules) self._python_version = python_version self._dependency_manager = DependencyManager() - self._should_format_files = should_format_files self._whitelabel = whitelabel self._github_output_mode = github_output_mode self._pypi_metadata = pypi_metadata @@ -93,7 +91,9 @@ def source_file(self, filepath: Filepath, from_src: Optional[bool] = True) -> So def on_finish(source_file: SourceFileImpl) -> None: self._module_manager.register_exports( - filepath=filepath, exports=source_file.get_exports() if from_src else set(), from_src=from_src + filepath=filepath, + exports=source_file.get_exports() if from_src else set(), + from_src=from_src, ) module = filepath.to_module() @@ -103,18 +103,23 @@ def on_finish(source_file: SourceFileImpl) -> None: reference_resolver=ReferenceResolverImpl( module_path_of_source_file=module.path, ), + should_format=False, dependency_manager=self._dependency_manager, - should_format=self._should_format_files, whitelabel=self._whitelabel, ) return source_file def write_source_file( - self, *, source_file: SourceFile, filepath: Filepath, include_src_root: Optional[bool] = True + self, + *, + source_file: SourceFile, + filepath: Filepath, + include_src_root: Optional[bool] = True, ) -> None: source_file.write_to_file( filepath=self.get_source_file_filepath( - filepath, include_src_root=(include_src_root if include_src_root is not None else True) + filepath, + include_src_root=(include_src_root if include_src_root is not None else True), ) ) @@ -144,7 +149,7 @@ def add_source_file_from_disk( string_replacements: Optional[dict[str, str]] = None, ) -> None: with open(path_on_disk, "r") as existing_file: - writer = WriterImpl(should_format=self._should_format_files) + writer = WriterImpl(should_format=False) read_file = existing_file.read() if string_replacements is not None: for k, v in string_replacements.items(): @@ -153,7 +158,8 @@ def add_source_file_from_disk( writer.write(read_file) writer.write_to_file( filepath=self.get_source_file_filepath( - filepath_in_project, include_src_root=(include_src_root if include_src_root is not None else True) + filepath_in_project, + include_src_root=(include_src_root if include_src_root is not None else True), ) ) if include_src_root: diff --git a/generators/python/src/fern_python/codegen/reference_resolver_impl.py b/generators/python/src/fern_python/codegen/reference_resolver_impl.py index 4c62a31ba56..37e398a1ec6 100644 --- a/generators/python/src/fern_python/codegen/reference_resolver_impl.py +++ b/generators/python/src/fern_python/codegen/reference_resolver_impl.py @@ -34,7 +34,10 @@ def register_declaration(self, declaration: str) -> None: def resolve_references(self) -> None: self._original_import_to_resolved_import = {} - for default_name, original_references in self._default_name_to_original_references.items(): + for ( + default_name, + original_references, + ) in self._default_name_to_original_references.items(): # get the set of all imports that result in this default name. # if len(set) > 1, or this default name is the same as a declaration, # then there's a collision, so we need to alias the imports. diff --git a/generators/python/src/fern_python/external_dependencies/fastapi.py b/generators/python/src/fern_python/external_dependencies/fastapi.py index 03a0e626254..d691a674fde 100644 --- a/generators/python/src/fern_python/external_dependencies/fastapi.py +++ b/generators/python/src/fern_python/external_dependencies/fastapi.py @@ -12,7 +12,10 @@ def _export(*name: str) -> AST.ClassReference: - return AST.ClassReference(qualified_name_excluding_import=name, import_=AST.ReferenceImport(module=FAST_API_MODULE)) + return AST.ClassReference( + qualified_name_excluding_import=name, + import_=AST.ReferenceImport(module=FAST_API_MODULE), + ) class JSONResponse: @@ -140,7 +143,10 @@ def Query( @staticmethod def include_router( - *, app_variable: str, router: AST.Expression, kwargs: List[Tuple[str, AST.Expression]] + *, + app_variable: str, + router: AST.Expression, + kwargs: List[Tuple[str, AST.Expression]], ) -> AST.Expression: return AST.Expression( AST.FunctionInvocation( @@ -181,9 +187,13 @@ def exception_handler( name=exception_handler_name, signature=AST.FunctionSignature( parameters=[ - AST.FunctionParameter(name=FastAPI.EXCEPTION_HANDLER_REQUEST_ARGUMENT, type_hint=FastAPI.Request), AST.FunctionParameter( - name=FastAPI.EXCEPTION_HANDLER_EXCEPTION_ARGUMENT, type_hint=AST.TypeHint(type=exception_type) + name=FastAPI.EXCEPTION_HANDLER_REQUEST_ARGUMENT, + type_hint=FastAPI.Request, + ), + AST.FunctionParameter( + name=FastAPI.EXCEPTION_HANDLER_EXCEPTION_ARGUMENT, + type_hint=AST.TypeHint(type=exception_type), ), ], return_type=AST.TypeHint(FastAPI.JSONResponse.REFERENCE), diff --git a/generators/python/src/fern_python/external_dependencies/functools.py b/generators/python/src/fern_python/external_dependencies/functools.py index 52adfef3bc5..eaabeff83bc 100644 --- a/generators/python/src/fern_python/external_dependencies/functools.py +++ b/generators/python/src/fern_python/external_dependencies/functools.py @@ -5,7 +5,8 @@ def _export(*name: str) -> AST.ClassReference: return AST.ClassReference( - qualified_name_excluding_import=name, import_=AST.ReferenceImport(module=FUNCTOOLS_MODULE) + qualified_name_excluding_import=name, + import_=AST.ReferenceImport(module=FUNCTOOLS_MODULE), ) diff --git a/generators/python/src/fern_python/external_dependencies/json.py b/generators/python/src/fern_python/external_dependencies/json.py index fb6ddd63b76..86821930b7d 100644 --- a/generators/python/src/fern_python/external_dependencies/json.py +++ b/generators/python/src/fern_python/external_dependencies/json.py @@ -4,7 +4,10 @@ def _export(*name: str) -> AST.ClassReference: - return AST.ClassReference(qualified_name_excluding_import=name, import_=AST.ReferenceImport(module=JSON_MODULE)) + return AST.ClassReference( + qualified_name_excluding_import=name, + import_=AST.ReferenceImport(module=JSON_MODULE), + ) class Json: @@ -12,7 +15,8 @@ class Json: def JSONDecodeError() -> AST.ClassReference: return AST.ClassReference( import_=AST.ReferenceImport( - module=AST.Module.built_in(("json", "decoder")), named_import="JSONDecodeError" + module=AST.Module.built_in(("json", "decoder")), + named_import="JSONDecodeError", ), qualified_name_excluding_import=(), ) diff --git a/generators/python/src/fern_python/external_dependencies/ruff.py b/generators/python/src/fern_python/external_dependencies/ruff.py new file mode 100644 index 00000000000..48db5a70b54 --- /dev/null +++ b/generators/python/src/fern_python/external_dependencies/ruff.py @@ -0,0 +1,6 @@ +from fern_python.codegen import AST + +RUFF_DEPENDENCY = AST.Dependency( + name="ruff", + version="^0.5.6", +) diff --git a/generators/python/src/fern_python/external_dependencies/starlette.py b/generators/python/src/fern_python/external_dependencies/starlette.py index 1e40d5642f5..f0ab8b85148 100644 --- a/generators/python/src/fern_python/external_dependencies/starlette.py +++ b/generators/python/src/fern_python/external_dependencies/starlette.py @@ -19,13 +19,15 @@ def _export(*name: str) -> AST.ClassReference: return AST.ClassReference( - qualified_name_excluding_import=name, import_=AST.ReferenceImport(module=STARLETTE_MODULE) + qualified_name_excluding_import=name, + import_=AST.ReferenceImport(module=STARLETTE_MODULE), ) def _export_exception(*name: str) -> AST.ClassReference: return AST.ClassReference( - qualified_name_excluding_import=name, import_=AST.ReferenceImport(module=STARLETTE_EXCEPTIONS_MODULE) + qualified_name_excluding_import=name, + import_=AST.ReferenceImport(module=STARLETTE_EXCEPTIONS_MODULE), ) diff --git a/generators/python/src/fern_python/external_dependencies/urllib_parse.py b/generators/python/src/fern_python/external_dependencies/urllib_parse.py index bbc92235ef6..56f5f1590a0 100644 --- a/generators/python/src/fern_python/external_dependencies/urllib_parse.py +++ b/generators/python/src/fern_python/external_dependencies/urllib_parse.py @@ -5,7 +5,8 @@ def _export(*name: str) -> AST.ClassReference: return AST.ClassReference( - qualified_name_excluding_import=name, import_=AST.ReferenceImport(module=URL_LIB_PARSE_MODULE) + qualified_name_excluding_import=name, + import_=AST.ReferenceImport(module=URL_LIB_PARSE_MODULE), ) diff --git a/generators/python/src/fern_python/generator_cli/generator_cli.py b/generators/python/src/fern_python/generator_cli/generator_cli.py index c672ac0c95b..7ac0e13c80f 100644 --- a/generators/python/src/fern_python/generator_cli/generator_cli.py +++ b/generators/python/src/fern_python/generator_cli/generator_cli.py @@ -79,7 +79,12 @@ def generate_reference(self, snippets: generator_exec.Snippets, project: Project if self._should_write_reference(reference_config): reference_config_filepath = self._write_reference_config(reference_config=reference_config) return self._run_command( - command=[GENERATOR_CLI, "generate-reference", "--config", reference_config_filepath] + command=[ + GENERATOR_CLI, + "generate-reference", + "--config", + reference_config_filepath, + ] ) return None diff --git a/generators/python/src/fern_python/generator_cli/readme_snippet_builder.py b/generators/python/src/fern_python/generator_cli/readme_snippet_builder.py index 138dc663246..b6c19589e52 100644 --- a/generators/python/src/fern_python/generator_cli/readme_snippet_builder.py +++ b/generators/python/src/fern_python/generator_cli/readme_snippet_builder.py @@ -152,7 +152,9 @@ def _build_exception_handling_snippets(self) -> List[str]: if endpoint is not None: has_parameters = self._endpoint_metadata.has_parameters(endpoint_id) - def _get_error_writer(current_endpoint: EndpointMetadata) -> AST.CodeWriterFunction: + def _get_error_writer( + current_endpoint: EndpointMetadata, + ) -> AST.CodeWriterFunction: def _error_writer(writer: AST.NodeWriter) -> None: writer.write_line("try:") with writer.indent(): @@ -206,8 +208,14 @@ def _build_custom_client_snippets(self) -> str: AST.ClassInstantiation( class_=HttpX.CLIENT, kwargs=[ - ("proxies", AST.Expression('"http://my.test.proxy.example.com"')), - ("transport", AST.Expression('httpx.HTTPTransport(local_address="0.0.0.0")')), + ( + "proxies", + AST.Expression('"http://my.test.proxy.example.com"'), + ), + ( + "transport", + AST.Expression('httpx.HTTPTransport(local_address="0.0.0.0")'), + ), ], ) ), @@ -311,7 +319,8 @@ def _get_default_endpoint_id( # Prefer POST endpoints because they include better request structures in snippets. default_endpoint = next( - (endpoint for endpoint in filtered_snippet_endpoints if endpoint.id.method == "POST"), None + (endpoint for endpoint in filtered_snippet_endpoints if endpoint.id.method == "POST"), + None, ) if default_endpoint is None: if len(snippets.endpoints) == 0: diff --git a/generators/python/src/fern_python/generator_cli/reference_config_builder.py b/generators/python/src/fern_python/generator_cli/reference_config_builder.py index 68e3474b0a9..5e1033264a2 100644 --- a/generators/python/src/fern_python/generator_cli/reference_config_builder.py +++ b/generators/python/src/fern_python/generator_cli/reference_config_builder.py @@ -107,16 +107,22 @@ def add_endpoint( converted_parameters = [self._convert_parameter(parameter) for parameter in parameters] # has_parameters is > 1 since we always stuff in a request_options parameter converted_title = self._convert_endpoint_metadata_to_title( - endpoint_metadata=endpoint_metadata, has_parameters=len(converted_parameters) > 1 + endpoint_metadata=endpoint_metadata, + has_parameters=len(converted_parameters) > 1, ) self.endpoints.append( generatorcli.reference.EndpointReference( - title=converted_title, description=description, snippet=snippet, parameters=converted_parameters + title=converted_title, + description=description, + snippet=snippet, + parameters=converted_parameters, ) ) - def build_root_reference(self) -> generatorcli.reference.RootPackageReferenceSection: + def build_root_reference( + self, + ) -> generatorcli.reference.RootPackageReferenceSection: return generatorcli.reference.RootPackageReferenceSection( description=self.description, endpoints=self.endpoints, @@ -163,7 +169,9 @@ def get_package_location(self, package_id: ir_types.SubpackageId) -> str: def build_reference_section(self, service: ir_types.HttpService, package_location: str) -> ReferenceSectionBuilder: reference_section = ReferenceSectionBuilder( - package_location=package_location, context=self._context, project=self._project + package_location=package_location, + context=self._context, + project=self._project, ) for endpoint in service.endpoints: @@ -195,11 +203,17 @@ def generate_reference_config(self) -> generatorcli.reference.ReferenceConfig: package_service = self._ir.services[subpackage.service] reference_section = self.build_reference_section( - service=package_service, package_location=self.get_package_location(subpackage_id) + service=package_service, + package_location=self.get_package_location(subpackage_id), ) fallback_name = " ".join( - list(map(lambda part: part.pascal_case.unsafe_name, package_service.name.fern_filepath.all_parts)) + list( + map( + lambda part: part.pascal_case.unsafe_name, + package_service.name.fern_filepath.all_parts, + ) + ) ) self.reference_config_sections.append( reference_section.build(title=package_service.display_name or fallback_name) diff --git a/generators/python/src/fern_python/generators/context/type_reference_to_type_hint_converter.py b/generators/python/src/fern_python/generators/context/type_reference_to_type_hint_converter.py index f3757896cd3..3a367fd1d69 100644 --- a/generators/python/src/fern_python/generators/context/type_reference_to_type_hint_converter.py +++ b/generators/python/src/fern_python/generators/context/type_reference_to_type_hint_converter.py @@ -52,7 +52,10 @@ def _get_set_type_hint_for_named( ) -> AST.TypeHint: is_primative = self._context.get_declaration_for_type_id(name.type_id).shape.visit( alias=lambda alias_td: alias_td.resolved_type.visit( - container=lambda c: False, named=lambda n: False, primitive=lambda p: True, unknown=lambda: False + container=lambda c: False, + named=lambda n: False, + primitive=lambda p: True, + unknown=lambda: False, ), enum=lambda enum_td: True, object=lambda object_td: False, diff --git a/generators/python/src/fern_python/generators/core_utilities/core_utilities.py b/generators/python/src/fern_python/generators/core_utilities/core_utilities.py index 18008c5c7fe..93f57986f8e 100644 --- a/generators/python/src/fern_python/generators/core_utilities/core_utilities.py +++ b/generators/python/src/fern_python/generators/core_utilities/core_utilities.py @@ -67,7 +67,12 @@ def copy_to_project(self, *, project: Project) -> None: ) def _copy_file_to_project( - self, *, project: Project, relative_filepath_on_disk: str, filepath_in_project: Filepath, exports: Set[str] + self, + *, + project: Project, + relative_filepath_on_disk: str, + filepath_in_project: Filepath, + exports: Set[str], ) -> None: source = ( os.path.join(os.path.dirname(__file__), "../../../../../core_utilities/pydantic") @@ -85,7 +90,8 @@ def get_serialize_datetime(self) -> AST.Reference: return AST.Reference( qualified_name_excluding_import=(), import_=AST.ReferenceImport( - module=AST.Module.local(*self._module_path, "datetime_utils"), named_import="serialize_datetime" + module=AST.Module.local(*self._module_path, "datetime_utils"), + named_import="serialize_datetime", ), ) @@ -93,7 +99,8 @@ def get_field_metadata(self) -> FieldMetadata: field_metadata_reference = AST.ClassReference( qualified_name_excluding_import=(), import_=AST.ReferenceImport( - module=AST.Module.local(*self._module_path, "serialization"), named_import="FieldMetadata" + module=AST.Module.local(*self._module_path, "serialization"), + named_import="FieldMetadata", ), ) @@ -103,7 +110,8 @@ def get_union_metadata(self) -> AST.ClassReference: return AST.ClassReference( qualified_name_excluding_import=(), import_=AST.ReferenceImport( - module=AST.Module.local(*self._module_path, "unchecked_base_model"), named_import="UnionMetadata" + module=AST.Module.local(*self._module_path, "unchecked_base_model"), + named_import="UnionMetadata", ), ) @@ -124,7 +132,8 @@ def get_construct_type(self) -> AST.Reference: return AST.Reference( qualified_name_excluding_import=(), import_=AST.ReferenceImport( - module=AST.Module.local(*self._module_path, "unchecked_base_model"), named_import="construct_type" + module=AST.Module.local(*self._module_path, "unchecked_base_model"), + named_import="construct_type", ), ) @@ -136,7 +145,10 @@ def write(writer: AST.NodeWriter) -> None: value_being_casted=AST.Expression( AST.FunctionInvocation( function_definition=self.get_construct_type(), - kwargs=[("type_", AST.Expression(type_of_obj)), ("object_", obj)], + kwargs=[ + ("type_", AST.Expression(type_of_obj)), + ("object_", obj), + ], ) ), ) @@ -188,7 +200,8 @@ def get_parse_obj_as(self, type_of_obj: AST.TypeHint, obj: AST.Expression) -> AS function_definition=AST.Reference( qualified_name_excluding_import=(), import_=AST.ReferenceImport( - module=AST.Module.local(*self._module_path, "pydantic_utilities"), named_import="parse_obj_as" + module=AST.Module.local(*self._module_path, "pydantic_utilities"), + named_import="parse_obj_as", ), ), args=[AST.Expression(type_of_obj), obj], @@ -200,7 +213,8 @@ def get_is_pydantic_v2(self) -> AST.Expression: AST.Reference( qualified_name_excluding_import=(), import_=AST.ReferenceImport( - module=AST.Module.local(*self._module_path, "pydantic_utilities"), named_import="IS_PYDANTIC_V2" + module=AST.Module.local(*self._module_path, "pydantic_utilities"), + named_import="IS_PYDANTIC_V2", ), ) ) @@ -234,6 +248,7 @@ def get_universal_root_model(self) -> AST.ClassReference: return AST.ClassReference( qualified_name_excluding_import=(), import_=AST.ReferenceImport( - module=AST.Module.local(*self._module_path, "pydantic_utilities"), named_import="UniversalRootModel" + module=AST.Module.local(*self._module_path, "pydantic_utilities"), + named_import="UniversalRootModel", ), ) diff --git a/generators/python/src/fern_python/generators/fastapi/auth/security_file_generator.py b/generators/python/src/fern_python/generators/fastapi/auth/security_file_generator.py index d96abb0643a..e959deaf87b 100644 --- a/generators/python/src/fern_python/generators/fastapi/auth/security_file_generator.py +++ b/generators/python/src/fern_python/generators/fastapi/auth/security_file_generator.py @@ -19,7 +19,9 @@ def __init__(self, context: FastApiGeneratorContext): self._context = context @staticmethod - def get_reference_to_fern_auth_dependency(context: FastApiGeneratorContext) -> AST.Expression: + def get_reference_to_fern_auth_dependency( + context: FastApiGeneratorContext, + ) -> AST.Expression: return FastAPI.Depends( AST.Expression( AST.Reference( diff --git a/generators/python/src/fern_python/generators/fastapi/context/fastapi_generator_context.py b/generators/python/src/fern_python/generators/fastapi/context/fastapi_generator_context.py index 677fd290f93..1d2d85be5b6 100644 --- a/generators/python/src/fern_python/generators/fastapi/context/fastapi_generator_context.py +++ b/generators/python/src/fern_python/generators/fastapi/context/fastapi_generator_context.py @@ -46,19 +46,25 @@ def get_reference_to_service(self, service_name: ir_types.DeclaredServiceName) - @abstractmethod def get_filepath_for_inlined_request( - self, service_name: ir_types.DeclaredServiceName, request: ir_types.InlinedRequestBody + self, + service_name: ir_types.DeclaredServiceName, + request: ir_types.InlinedRequestBody, ) -> Filepath: ... @abstractmethod def get_class_name_for_inlined_request( - self, service_name: ir_types.DeclaredServiceName, request: ir_types.InlinedRequestBody + self, + service_name: ir_types.DeclaredServiceName, + request: ir_types.InlinedRequestBody, ) -> str: ... @abstractmethod def get_reference_to_inlined_request( - self, service_name: ir_types.DeclaredServiceName, request: ir_types.InlinedRequestBody + self, + service_name: ir_types.DeclaredServiceName, + request: ir_types.InlinedRequestBody, ) -> AST.ClassReference: ... diff --git a/generators/python/src/fern_python/generators/fastapi/context/fastapi_generator_context_impl.py b/generators/python/src/fern_python/generators/fastapi/context/fastapi_generator_context_impl.py index 8c0f03f6ab1..881c315800c 100644 --- a/generators/python/src/fern_python/generators/fastapi/context/fastapi_generator_context_impl.py +++ b/generators/python/src/fern_python/generators/fastapi/context/fastapi_generator_context_impl.py @@ -42,24 +42,31 @@ def get_reference_to_service(self, service_name: ir_types.DeclaredServiceName) - return self._service_declaration_referencer.get_class_reference(name=service_name, as_request=False) def get_filepath_for_inlined_request( - self, service_name: ir_types.DeclaredServiceName, request: ir_types.InlinedRequestBody + self, + service_name: ir_types.DeclaredServiceName, + request: ir_types.InlinedRequestBody, ) -> Filepath: return self._inlined_request_declaration_referencer.get_filepath( name=ServiceNameAndInlinedRequestBody(service_name=service_name, request=request) ) def get_class_name_for_inlined_request( - self, service_name: ir_types.DeclaredServiceName, request: ir_types.InlinedRequestBody + self, + service_name: ir_types.DeclaredServiceName, + request: ir_types.InlinedRequestBody, ) -> str: return self._inlined_request_declaration_referencer.get_class_name( name=ServiceNameAndInlinedRequestBody(service_name=service_name, request=request) ) def get_reference_to_inlined_request( - self, service_name: ir_types.DeclaredServiceName, request: ir_types.InlinedRequestBody + self, + service_name: ir_types.DeclaredServiceName, + request: ir_types.InlinedRequestBody, ) -> AST.ClassReference: return self._inlined_request_declaration_referencer.get_class_reference( - name=ServiceNameAndInlinedRequestBody(service_name=service_name, request=request), as_request=False + name=ServiceNameAndInlinedRequestBody(service_name=service_name, request=request), + as_request=False, ) def get_filepath_for_error(self, error_name: ir_types.DeclaredErrorName) -> Filepath: diff --git a/generators/python/src/fern_python/generators/fastapi/core_utilities/core_utilities.py b/generators/python/src/fern_python/generators/fastapi/core_utilities/core_utilities.py index 6eeabad5881..f802f9997f7 100644 --- a/generators/python/src/fern_python/generators/fastapi/core_utilities/core_utilities.py +++ b/generators/python/src/fern_python/generators/fastapi/core_utilities/core_utilities.py @@ -13,7 +13,10 @@ class FernHTTPException: CONTENT_MEMBER = "content" def __init__(self, filepath: Tuple[Filepath.DirectoryFilepathPart, ...]): - self.filepath = Filepath(directories=filepath, file=Filepath.FilepathPart(module_name="fern_http_exception")) + self.filepath = Filepath( + directories=filepath, + file=Filepath.FilepathPart(module_name="fern_http_exception"), + ) def get_reference_to(self) -> AST.ClassReference: return AST.ClassReference( @@ -49,7 +52,10 @@ def create( class Exceptions: def __init__(self, filepath: Tuple[Filepath.DirectoryFilepathPart, ...]): self.filepath = filepath + ( - Filepath.DirectoryFilepathPart(module_name="exceptions", export_strategy=ExportStrategy(export_all=True)), + Filepath.DirectoryFilepathPart( + module_name="exceptions", + export_strategy=ExportStrategy(export_all=True), + ), ) self._module_path = tuple(part.module_name for part in self.filepath) self.FernHTTPException = FernHTTPException(filepath=self.filepath) @@ -167,7 +173,11 @@ def _copy_exceptions_to_project(self, *, project: Project) -> None: directories=self.exceptions.filepath, file=Filepath.FilepathPart(module_name="handlers"), ), - exports={"default_exception_handler", "fern_http_exception_handler", "http_exception_handler"}, + exports={ + "default_exception_handler", + "fern_http_exception_handler", + "http_exception_handler", + }, ) self._copy_file_to_project( project=project, @@ -180,7 +190,12 @@ def _copy_exceptions_to_project(self, *, project: Project) -> None: ) def _copy_file_to_project( - self, *, project: Project, relative_filepath_on_disk: str, filepath_in_project: Filepath, exports: Set[str] + self, + *, + project: Project, + relative_filepath_on_disk: str, + filepath_in_project: Filepath, + exports: Set[str], ) -> None: source = ( os.path.join(os.path.dirname(__file__), "../../../../../core_utilities/fastapi") @@ -211,7 +226,8 @@ def get_route_args(self, *, endpoint_method: AST.Expression, default_tag: str) - function_definition=AST.Reference( qualified_name_excluding_import=(), import_=AST.ReferenceImport( - module=AST.Module.local(*self._module_path, "route_args"), named_import="get_route_args" + module=AST.Module.local(*self._module_path, "route_args"), + named_import="get_route_args", ), ), args=[endpoint_method], @@ -223,7 +239,8 @@ def get_serialize_datetime(self) -> AST.Reference: return AST.Reference( qualified_name_excluding_import=(), import_=AST.ReferenceImport( - module=AST.Module.local(*self._module_path, "datetime_utils"), named_import="serialize_datetime" + module=AST.Module.local(*self._module_path, "datetime_utils"), + named_import="serialize_datetime", ), ) @@ -231,7 +248,8 @@ def BearerToken(self) -> AST.ClassReference: return AST.ClassReference( qualified_name_excluding_import=(), import_=AST.ReferenceImport( - module=AST.Module.local(*self._get_bearer_module_path()), named_import="BearerToken" + module=AST.Module.local(*self._get_bearer_module_path()), + named_import="BearerToken", ), ) @@ -239,7 +257,8 @@ def HTTPBearer(self) -> AST.ClassReference: return AST.ClassReference( qualified_name_excluding_import=(), import_=AST.ReferenceImport( - module=AST.Module.local(*self._get_bearer_module_path()), named_import="HTTPBearer" + module=AST.Module.local(*self._get_bearer_module_path()), + named_import="HTTPBearer", ), ) @@ -271,7 +290,8 @@ def get_is_pydantic_v2(self) -> AST.Expression: AST.Reference( qualified_name_excluding_import=(), import_=AST.ReferenceImport( - module=AST.Module.local(*self._module_path, "pydantic_utilities"), named_import="IS_PYDANTIC_V2" + module=AST.Module.local(*self._module_path, "pydantic_utilities"), + named_import="IS_PYDANTIC_V2", ), ) ) diff --git a/generators/python/src/fern_python/generators/fastapi/fastapi_generator.py b/generators/python/src/fern_python/generators/fastapi/fastapi_generator.py index b0fe2cfdd43..20ae808ccd7 100644 --- a/generators/python/src/fern_python/generators/fastapi/fastapi_generator.py +++ b/generators/python/src/fern_python/generators/fastapi/fastapi_generator.py @@ -138,7 +138,9 @@ def _generate_service( ) -> None: filepath = context.get_filepath_for_service(service.name) service_file = SourceFileFactory.create( - project=project, filepath=filepath, generator_exec_wrapper=generator_exec_wrapper + project=project, + filepath=filepath, + generator_exec_wrapper=generator_exec_wrapper, ) ServiceGenerator(context=context, service=service).generate(source_file=service_file) project.write_source_file(source_file=service_file, filepath=filepath) @@ -164,7 +166,8 @@ def _generate_service( source_file=inlined_request_source_file, ) project.write_source_file( - source_file=inlined_request_source_file, filepath=inlined_request_filepath + source_file=inlined_request_source_file, + filepath=inlined_request_filepath, ) def _generate_error( @@ -177,7 +180,9 @@ def _generate_error( ) -> None: filepath = context.get_filepath_for_error(error.name) source_file = SourceFileFactory.create( - project=project, filepath=filepath, generator_exec_wrapper=generator_exec_wrapper + project=project, + filepath=filepath, + generator_exec_wrapper=generator_exec_wrapper, ) ErrorGenerator(context=context, error=error).generate(source_file=source_file) project.write_source_file(source_file=source_file, filepath=filepath) diff --git a/generators/python/src/fern_python/generators/fastapi/fern_http_exception/fern_http_exception_generator.py b/generators/python/src/fern_python/generators/fastapi/fern_http_exception/fern_http_exception_generator.py index e20f871a5b7..078b4930d5b 100644 --- a/generators/python/src/fern_python/generators/fastapi/fern_http_exception/fern_http_exception_generator.py +++ b/generators/python/src/fern_python/generators/fastapi/fern_http_exception/fern_http_exception_generator.py @@ -43,7 +43,8 @@ def generate(self, project: Project, generator_exec_wrapper: GeneratorExecWrappe name="to_json_response", signature=AST.FunctionSignature(return_type=AST.TypeHint(FastAPI.JSONResponse.REFERENCE)), body=self._create_json_response_body_writer( - error_discrimination_strategy.discriminant, reference_to_body=reference_to_body + error_discrimination_strategy.discriminant, + reference_to_body=reference_to_body, ), ) ) @@ -63,7 +64,8 @@ def _get_constructor(self) -> AST.ClassConstructor: signature=AST.FunctionSignature( parameters=[ AST.FunctionParameter( - name=self.FernHTTPException.STATUS_CODE_MEMBER, type_hint=AST.TypeHint.int_() + name=self.FernHTTPException.STATUS_CODE_MEMBER, + type_hint=AST.TypeHint.int_(), ), AST.FunctionParameter( name=self.FernHTTPException.NAME_MEMBER, @@ -88,7 +90,10 @@ def _write_constructor_body(self, writer: AST.NodeWriter) -> None: writer.write_line(f"self.{self.FernHTTPException.CONTENT_MEMBER} = {self.FernHTTPException.CONTENT_MEMBER}") def _construct_pydantic_model( - self, source_file: SourceFile, error_discriminant: NameAndWireValue, exception_class: LocalClassReference + self, + source_file: SourceFile, + error_discriminant: NameAndWireValue, + exception_class: LocalClassReference, ) -> AST.ClassReference: with PydanticModel( source_file=source_file, @@ -159,7 +164,9 @@ def _get_content_property(self) -> NameAndWireValue: return error_discrimination_strategy.content_property def _create_json_response_body_writer( - self, error_discriminant: NameAndWireValue, reference_to_body: AST.ClassReference + self, + error_discriminant: NameAndWireValue, + reference_to_body: AST.ClassReference, ) -> AST.CodeWriter: def write_body(writer: AST.NodeWriter) -> None: BODY_VARIABLE_NAME = "body" @@ -181,7 +188,7 @@ def write_body(writer: AST.NodeWriter) -> None: ], ) ) - writer.write_line(), + (writer.write_line(),) writer.write(f"{CONTENT_VARIABLE_NAME} = ") writer.write_node(FastAPI.jsonable_encoder(AST.Expression(BODY_VARIABLE_NAME), exclude_none=True)) @@ -203,7 +210,8 @@ def write_body(writer: AST.NodeWriter) -> None: writer.write(f"{CONTENT_VARIABLE_NAME} = ") writer.write_node( FastAPI.jsonable_encoder( - AST.Expression(f"self.{self.FernHTTPException.CONTENT_MEMBER}"), exclude_none=True + AST.Expression(f"self.{self.FernHTTPException.CONTENT_MEMBER}"), + exclude_none=True, ) ) writer.write_line() diff --git a/generators/python/src/fern_python/generators/fastapi/register/register_file_generator.py b/generators/python/src/fern_python/generators/fastapi/register/register_file_generator.py index 81f3b5dfbff..95c1f97a029 100644 --- a/generators/python/src/fern_python/generators/fastapi/register/register_file_generator.py +++ b/generators/python/src/fern_python/generators/fastapi/register/register_file_generator.py @@ -37,7 +37,9 @@ def generate_registry_file(self, project: Project, generator_exec_wrapper: Gener file=Filepath.FilepathPart(module_name=RegisterFileGenerator._MODULE_NAME), ) source_file = SourceFileFactory.create( - project=project, generator_exec_wrapper=generator_exec_wrapper, filepath=filepath + project=project, + generator_exec_wrapper=generator_exec_wrapper, + filepath=filepath, ) source_file.add_declaration(declaration=self._get_register_method(), should_export=False) source_file.add_declaration(declaration=self._get_register_service_method(), should_export=False) @@ -49,7 +51,10 @@ def _get_register_method(self) -> AST.FunctionDeclaration: name=RegisterFileGenerator._REGISTER_FUNCTION_NAME, signature=AST.FunctionSignature( parameters=[ - AST.FunctionParameter(name=RegisterFileGenerator._APP_PARAMETER_NAME, type_hint=FastAPI.FastAPI), + AST.FunctionParameter( + name=RegisterFileGenerator._APP_PARAMETER_NAME, + type_hint=FastAPI.FastAPI, + ), ], named_parameters=[ service_initializer.get_register_parameter() for service_initializer in self._service_initializers @@ -103,7 +108,11 @@ def _write_register_method_body(self, writer: AST.NodeWriter) -> None: ) def _write_exception_handler( - self, *, writer: AST.NodeWriter, exception_type: AST.ClassReference, handler: AST.Reference + self, + *, + writer: AST.NodeWriter, + exception_type: AST.ClassReference, + handler: AST.Reference, ) -> None: writer.write_node( FastAPI.add_exception_handler( @@ -177,7 +186,10 @@ def write_register_validators_method_body(writer: AST.NodeWriter) -> None: import_=AST.ReferenceImport(module=AST.Module.built_in(("os",))), qualified_name_excluding_import=("path", "join"), ), - args=[AST.Expression(VALIDATORS_DIRECTORY_VARIABLE), AST.Expression('"**/*.py"')], + args=[ + AST.Expression(VALIDATORS_DIRECTORY_VARIABLE), + AST.Expression('"**/*.py"'), + ], ) ) ], diff --git a/generators/python/src/fern_python/generators/fastapi/register/service_initializer.py b/generators/python/src/fern_python/generators/fastapi/register/service_initializer.py index 5263c7db4bd..a43db79de58 100644 --- a/generators/python/src/fern_python/generators/fastapi/register/service_initializer.py +++ b/generators/python/src/fern_python/generators/fastapi/register/service_initializer.py @@ -6,7 +6,12 @@ class ServiceInitializer: - def __init__(self, service: ir_types.HttpService, context: FastApiGeneratorContext, is_in_development: bool): + def __init__( + self, + service: ir_types.HttpService, + context: FastApiGeneratorContext, + is_in_development: bool, + ): self._service = service self._context = context self.is_in_development = is_in_development diff --git a/generators/python/src/fern_python/generators/fastapi/service_generator/endpoint_generator.py b/generators/python/src/fern_python/generators/fastapi/service_generator/endpoint_generator.py index 5c5749e04f9..a29648a8634 100644 --- a/generators/python/src/fern_python/generators/fastapi/service_generator/endpoint_generator.py +++ b/generators/python/src/fern_python/generators/fastapi/service_generator/endpoint_generator.py @@ -149,7 +149,9 @@ def _write_init_body(writer: AST.NodeWriter) -> None: name=_TRY_EXCEPT_WRAPPER_NAME, body=AST.CodeWriter(self._write_try_except_wrapper_body), signature=AST.FunctionSignature( - include_args=True, include_kwargs=True, return_type=self._get_return_type() + include_args=True, + include_kwargs=True, + return_type=self._get_return_type(), ), decorators=[ AST.FunctionInvocation( @@ -276,7 +278,12 @@ def invoke_init_method(self, *, reference_to_fastapi_router: AST.Expression) -> function_definition=AST.Reference( qualified_name_excluding_import=(self._get_reference_to_init_method_on_cls(),), ), - kwargs=[(EndpointGenerator._INIT_ENDPOINT_ROUTER_ARG, reference_to_fastapi_router)], + kwargs=[ + ( + EndpointGenerator._INIT_ENDPOINT_ROUTER_ARG, + reference_to_fastapi_router, + ) + ], ) def _get_method_name(self) -> str: @@ -386,7 +393,9 @@ def raise_file_upload_unsupported() -> Never: raise RuntimeError("File upload is not supported") -def raise_file_download_unsupported(file_download_response: ir_types.FileDownloadResponse) -> Never: +def raise_file_download_unsupported( + file_download_response: ir_types.FileDownloadResponse, +) -> Never: raise RuntimeError("File download is not supported") diff --git a/generators/python/src/fern_python/generators/fastapi/service_generator/endpoint_parameters/auth_endpoint_parameter.py b/generators/python/src/fern_python/generators/fastapi/service_generator/endpoint_parameters/auth_endpoint_parameter.py index b2b79a49b7c..1ebc80a2c15 100644 --- a/generators/python/src/fern_python/generators/fastapi/service_generator/endpoint_parameters/auth_endpoint_parameter.py +++ b/generators/python/src/fern_python/generators/fastapi/service_generator/endpoint_parameters/auth_endpoint_parameter.py @@ -17,5 +17,7 @@ def get_default(self) -> AST.Expression: return SecurityFileGenerator.get_reference_to_fern_auth_dependency(context=self._context) @staticmethod - def get_variable_name_of_path_parameter(path_parameter: ir_types.PathParameter) -> str: + def get_variable_name_of_path_parameter( + path_parameter: ir_types.PathParameter, + ) -> str: return path_parameter.name.snake_case.safe_name diff --git a/generators/python/src/fern_python/generators/fastapi/service_generator/endpoint_parameters/convert_to_singular_type.py b/generators/python/src/fern_python/generators/fastapi/service_generator/endpoint_parameters/convert_to_singular_type.py index 73bdb14d61f..68c35e7bb75 100644 --- a/generators/python/src/fern_python/generators/fastapi/service_generator/endpoint_parameters/convert_to_singular_type.py +++ b/generators/python/src/fern_python/generators/fastapi/service_generator/endpoint_parameters/convert_to_singular_type.py @@ -25,15 +25,18 @@ def convert_to_singular_type(context: FastApiGeneratorContext, type: ir_types.Ty resolved_type_union = shape_union.resolved_type.get_as_union() if resolved_type_union.type == "primitive": return convert_to_singular_type( - context, ir_types.TypeReference.factory.primitive(resolved_type_union.primitive) + context, + ir_types.TypeReference.factory.primitive(resolved_type_union.primitive), ) elif resolved_type_union.type == "container": return convert_to_singular_type( - context, ir_types.TypeReference.factory.container(resolved_type_union.container) + context, + ir_types.TypeReference.factory.container(resolved_type_union.container), ) elif resolved_type_union.type == "named": return convert_to_singular_type( - context, ir_types.TypeReference.factory.named(cast(ir_types.NamedType, resolved_type_union.name)) + context, + ir_types.TypeReference.factory.named(cast(ir_types.NamedType, resolved_type_union.name)), ) elif resolved_type_union.type == "unknown": return convert_to_singular_type(context, ir_types.TypeReference.factory.unknown()) diff --git a/generators/python/src/fern_python/generators/fastapi/service_generator/endpoint_parameters/path_endpoint_parameter.py b/generators/python/src/fern_python/generators/fastapi/service_generator/endpoint_parameters/path_endpoint_parameter.py index 9a204e637c6..c86ce524bd4 100644 --- a/generators/python/src/fern_python/generators/fastapi/service_generator/endpoint_parameters/path_endpoint_parameter.py +++ b/generators/python/src/fern_python/generators/fastapi/service_generator/endpoint_parameters/path_endpoint_parameter.py @@ -23,5 +23,7 @@ def get_default(self) -> AST.Expression: return FastAPI.Path @staticmethod - def get_variable_name_of_path_parameter(path_parameter: ir_types.PathParameter) -> str: + def get_variable_name_of_path_parameter( + path_parameter: ir_types.PathParameter, + ) -> str: return path_parameter.name.snake_case.safe_name diff --git a/generators/python/src/fern_python/generators/fastapi/service_generator/endpoint_parameters/query_endpoint_parameter.py b/generators/python/src/fern_python/generators/fastapi/service_generator/endpoint_parameters/query_endpoint_parameter.py index 4233141be1a..083cd90be79 100644 --- a/generators/python/src/fern_python/generators/fastapi/service_generator/endpoint_parameters/query_endpoint_parameter.py +++ b/generators/python/src/fern_python/generators/fastapi/service_generator/endpoint_parameters/query_endpoint_parameter.py @@ -47,5 +47,7 @@ def get_list_wrapped_type_hint(self) -> AST.TypeHint: return AST.TypeHint.list(convert_to_singular_type(self._context, self._query_parameter.value_type)) @staticmethod - def get_variable_name_of_query_parameter(query_parameter: ir_types.QueryParameter) -> str: + def get_variable_name_of_query_parameter( + query_parameter: ir_types.QueryParameter, + ) -> str: return query_parameter.name.name.snake_case.safe_name diff --git a/generators/python/src/fern_python/generators/pydantic_model/fern_aware_pydantic_model.py b/generators/python/src/fern_python/generators/pydantic_model/fern_aware_pydantic_model.py index 708716d3303..49400a18240 100644 --- a/generators/python/src/fern_python/generators/pydantic_model/fern_aware_pydantic_model.py +++ b/generators/python/src/fern_python/generators/pydantic_model/fern_aware_pydantic_model.py @@ -165,7 +165,8 @@ def add_method( signature=AST.FunctionSignature( parameters=[ AST.FunctionParameter( - name=parameter_name, type_hint=self.get_type_hint_for_type_reference(parameter_type) + name=parameter_name, + type_hint=self.get_type_hint_for_type_reference(parameter_type), ) for parameter_name, parameter_type in parameters ], diff --git a/generators/python/src/fern_python/generators/pydantic_model/pydantic_model_generator.py b/generators/python/src/fern_python/generators/pydantic_model/pydantic_model_generator.py index e283235fe01..71e9f9988ec 100644 --- a/generators/python/src/fern_python/generators/pydantic_model/pydantic_model_generator.py +++ b/generators/python/src/fern_python/generators/pydantic_model/pydantic_model_generator.py @@ -54,7 +54,8 @@ def run( context = PydanticGeneratorContextImpl( ir=ir, type_declaration_referencer=TypeDeclarationReferencer( - use_typeddict_requests=custom_config.use_typeddict_requests, types=ir.types + use_typeddict_requests=custom_config.use_typeddict_requests, + types=ir.types, ), generator_config=generator_config, project_module_path=self.get_relative_path_to_project_for_publish( @@ -68,7 +69,9 @@ def run( ) snippet_registry = SnippetRegistry() snippet_writer = self._build_snippet_writer( - context=context, improved_imports=False, use_str_enums=custom_config.use_str_enums + context=context, + improved_imports=False, + use_str_enums=custom_config.use_str_enums, ) self.generate_types( generator_exec_wrapper=generator_exec_wrapper, @@ -123,7 +126,9 @@ def _generate_type( if self._should_generate_typedict(context=context, type_=type.shape): typeddict_filepath = context.get_filepath_for_type_id(type_id=type.name.type_id, as_request=True) typeddict_source_file = SourceFileFactory.create( - project=project, filepath=typeddict_filepath, generator_exec_wrapper=generator_exec_wrapper + project=project, + filepath=typeddict_filepath, + generator_exec_wrapper=generator_exec_wrapper, ) typeddict_handler = TypeDeclarationHandler( @@ -141,7 +146,9 @@ def _generate_type( # Write the pydantic model filepath = context.get_filepath_for_type_id(type_id=type.name.type_id, as_request=False) source_file = SourceFileFactory.create( - project=project, filepath=filepath, generator_exec_wrapper=generator_exec_wrapper + project=project, + filepath=filepath, + generator_exec_wrapper=generator_exec_wrapper, ) type_declaration_handler = TypeDeclarationHandler( @@ -171,7 +178,10 @@ def is_flat_layout( return False def _build_snippet_writer( - self, context: PydanticGeneratorContext, improved_imports: bool = False, use_str_enums: bool = False + self, + context: PydanticGeneratorContext, + improved_imports: bool = False, + use_str_enums: bool = False, ) -> SnippetWriter: """ Note that this function is a copy of the function with the same name in diff --git a/generators/python/src/fern_python/generators/pydantic_model/type_declaration_handler/__init__.py b/generators/python/src/fern_python/generators/pydantic_model/type_declaration_handler/__init__.py index 4f495c09440..2e4d95e6837 100644 --- a/generators/python/src/fern_python/generators/pydantic_model/type_declaration_handler/__init__.py +++ b/generators/python/src/fern_python/generators/pydantic_model/type_declaration_handler/__init__.py @@ -5,4 +5,9 @@ TypeDeclarationSnippetGeneratorBuilder, ) -__all__ = ["EnumSnippetGenerator", "ObjectProperty", "TypeDeclarationHandler", "TypeDeclarationSnippetGeneratorBuilder"] +__all__ = [ + "EnumSnippetGenerator", + "ObjectProperty", + "TypeDeclarationHandler", + "TypeDeclarationSnippetGeneratorBuilder", +] diff --git a/generators/python/src/fern_python/generators/pydantic_model/type_declaration_handler/discriminated_union/discriminated_union_with_utils_generator.py b/generators/python/src/fern_python/generators/pydantic_model/type_declaration_handler/discriminated_union/discriminated_union_with_utils_generator.py index 5fb5814ac1b..58f9f968a0e 100644 --- a/generators/python/src/fern_python/generators/pydantic_model/type_declaration_handler/discriminated_union/discriminated_union_with_utils_generator.py +++ b/generators/python/src/fern_python/generators/pydantic_model/type_declaration_handler/discriminated_union/discriminated_union_with_utils_generator.py @@ -42,7 +42,9 @@ def __init__( self._union = union def _add_conditional_base_methods( - self, base_class: FernAwarePydanticModel, internal_single_union_types: List[LocalClassReference] + self, + base_class: FernAwarePydanticModel, + internal_single_union_types: List[LocalClassReference], ) -> None: if self._custom_config.skip_validation: root_type = AST.TypeHint.annotated( @@ -308,7 +310,8 @@ def generate(self) -> None: expression=AST.Expression( AST.FunctionInvocation( function_definition=self._context.get_class_reference_for_type_id( - declared_type_name.type_id, as_request=False + declared_type_name.type_id, + as_request=False, ), args=[ AST.Expression( @@ -381,7 +384,10 @@ def write(writer: AST.NodeWriter) -> None: single_union_type.shape.visit( same_properties_as_object=lambda type_name: [], single_property=lambda property: [ - (get_field_name_for_single_property(property), AST.Expression(BUILDER_ARGUMENT_NAME)) + ( + get_field_name_for_single_property(property), + AST.Expression(BUILDER_ARGUMENT_NAME), + ) ], no_properties=lambda: [], ) @@ -392,7 +398,12 @@ def write_condition(root_str: str) -> AST.CodeWriter: def write_condition_for_root(writer: AST.NodeWriter) -> None: sub_union_instantiation = AST.ClassInstantiation( class_=external_union, - kwargs=[(root_str, AST.Expression(internal_single_union_type_instantiation))], + kwargs=[ + ( + root_str, + AST.Expression(internal_single_union_type_instantiation), + ) + ], ) writer.write("return ") @@ -440,5 +451,7 @@ def assert_never(arg: Never) -> Never: raise AssertionError("Expected code to be unreachable") -def get_field_name_for_single_property(property: ir_types.SingleUnionTypeProperty) -> str: +def get_field_name_for_single_property( + property: ir_types.SingleUnionTypeProperty, +) -> str: return property.name.name.snake_case.safe_name diff --git a/generators/python/src/fern_python/generators/pydantic_model/type_declaration_handler/discriminated_union/simple_discriminated_union_generator.py b/generators/python/src/fern_python/generators/pydantic_model/type_declaration_handler/discriminated_union/simple_discriminated_union_generator.py index f488cbdccb3..d615ee6ebda 100644 --- a/generators/python/src/fern_python/generators/pydantic_model/type_declaration_handler/discriminated_union/simple_discriminated_union_generator.py +++ b/generators/python/src/fern_python/generators/pydantic_model/type_declaration_handler/discriminated_union/simple_discriminated_union_generator.py @@ -145,7 +145,8 @@ def generate(self) -> None: single_union_type_references.append( self._generate_same_properties_as_object_member( - class_name=member_class_name, properties=same_properties_as_object_property_fields + class_name=member_class_name, + properties=same_properties_as_object_property_fields, ) ) @@ -164,7 +165,8 @@ def generate(self) -> None: single_union_type_references.append( self._generate_no_property_member( - class_name=member_class_name, discriminant_field=no_properties_property_field + class_name=member_class_name, + discriminant_field=no_properties_property_field, ) ) @@ -260,7 +262,10 @@ def _get_direct_references_for_union(self) -> Set[ir_types.TypeId]: shape = single_union_type.shape.get_as_union() if shape.properties_type == "samePropertiesAsObject": type_ids = list( - map(lambda p: p.value_type, self._context.get_all_properties_including_extensions(shape.type_id)) + map( + lambda p: p.value_type, + self._context.get_all_properties_including_extensions(shape.type_id), + ) ) property_references += type_ids @@ -450,5 +455,7 @@ def get_discriminant_parameter_name(discriminant: ir_types.NameAndWireValue) -> return discriminant.name.snake_case.safe_name -def get_field_name_for_single_property(property: ir_types.SingleUnionTypeProperty) -> str: +def get_field_name_for_single_property( + property: ir_types.SingleUnionTypeProperty, +) -> str: return property.name.name.snake_case.safe_name diff --git a/generators/python/src/fern_python/generators/pydantic_model/type_declaration_handler/enum_generator.py b/generators/python/src/fern_python/generators/pydantic_model/type_declaration_handler/enum_generator.py index 6adb4d5605e..d9204dd0209 100644 --- a/generators/python/src/fern_python/generators/pydantic_model/type_declaration_handler/enum_generator.py +++ b/generators/python/src/fern_python/generators/pydantic_model/type_declaration_handler/enum_generator.py @@ -27,7 +27,11 @@ def __init__( snippet: Optional[str] = None, ): super().__init__( - context=context, custom_config=custom_config, source_file=source_file, docs=docs, snippet=snippet + context=context, + custom_config=custom_config, + source_file=source_file, + docs=docs, + snippet=snippet, ) self._use_str_enums = custom_config.use_str_enums self._class_name = context.get_class_name_for_type_id(name.type_id, as_request=False) @@ -40,7 +44,14 @@ def generate(self) -> None: AST.TypeAliasDeclaration( type_hint=AST.TypeHint.union( AST.TypeHint.literal( - AST.Expression(", ".join(map(lambda v: f'"{v.name.wire_value}"', self._enum.values))) + AST.Expression( + ", ".join( + map( + lambda v: f'"{v.name.wire_value}"', + self._enum.values, + ) + ) + ) ), AST.TypeHint.any(), ), diff --git a/generators/python/src/fern_python/generators/pydantic_model/type_declaration_handler/type_declaration_handler.py b/generators/python/src/fern_python/generators/pydantic_model/type_declaration_handler/type_declaration_handler.py index 8c3d7e416e0..3fee1a16781 100644 --- a/generators/python/src/fern_python/generators/pydantic_model/type_declaration_handler/type_declaration_handler.py +++ b/generators/python/src/fern_python/generators/pydantic_model/type_declaration_handler/type_declaration_handler.py @@ -67,7 +67,9 @@ def run(self) -> GeneratedType: snippet=snippet, ) - def _get_typeddict_generator(self) -> Tuple[Optional[AST.Expression], AbstractTypeGenerator]: + def _get_typeddict_generator( + self, + ) -> Tuple[Optional[AST.Expression], AbstractTypeGenerator]: docstring = None return None, self._declaration.shape.visit( alias=lambda alias: TypedDictAliasGenerator( @@ -126,7 +128,9 @@ def _get_typeddict_generator(self) -> Tuple[Optional[AST.Expression], AbstractTy ), ) - def _get_pydantic_model_generator(self) -> Tuple[Optional[AST.Expression], AbstractTypeGenerator]: + def _get_pydantic_model_generator( + self, + ) -> Tuple[Optional[AST.Expression], AbstractTypeGenerator]: snippet, docstring = self._get_snippet_for_type_declaration(self._declaration) type_generator = self._declaration.shape.visit( alias=lambda alias: PydanticModelAliasGenerator( @@ -182,7 +186,9 @@ def _get_pydantic_union_generator( self, snippet: Optional[str] = None, ) -> Callable[[ir_types.UnionTypeDeclaration], AbstractTypeGenerator]: - def get_union_generator(union: ir_types.UnionTypeDeclaration) -> AbstractTypeGenerator: + def get_union_generator( + union: ir_types.UnionTypeDeclaration, + ) -> AbstractTypeGenerator: if self._custom_config.include_union_utils: return DiscriminatedUnionWithUtilsGenerator( name=self._declaration.name, diff --git a/generators/python/src/fern_python/generators/pydantic_model/type_declaration_handler/type_declaration_snippet_generator_builder.py b/generators/python/src/fern_python/generators/pydantic_model/type_declaration_handler/type_declaration_snippet_generator_builder.py index fda176fd054..6387adcb269 100644 --- a/generators/python/src/fern_python/generators/pydantic_model/type_declaration_handler/type_declaration_snippet_generator_builder.py +++ b/generators/python/src/fern_python/generators/pydantic_model/type_declaration_handler/type_declaration_snippet_generator_builder.py @@ -101,7 +101,9 @@ def _get_discriminated_union_snippet_generator( ).generate_snippet() def _get_undiscriminated_union_snippet_generator( - self, name: ir_types.DeclaredTypeName, example: ir_types.ExampleUndiscriminatedUnionType + self, + name: ir_types.DeclaredTypeName, + example: ir_types.ExampleUndiscriminatedUnionType, ) -> Optional[AST.Expression]: if self._context.use_typeddict_requests: return TypeddictUndiscriminatedUnionSnippetGenerator( diff --git a/generators/python/src/fern_python/generators/pydantic_model/typeddict.py b/generators/python/src/fern_python/generators/pydantic_model/typeddict.py index 50e97f2a18a..5b63d1cea8c 100644 --- a/generators/python/src/fern_python/generators/pydantic_model/typeddict.py +++ b/generators/python/src/fern_python/generators/pydantic_model/typeddict.py @@ -174,7 +174,9 @@ def wrap_string_as_example(cls, string: str) -> ir_types.ExampleTypeReference: @classmethod def snippet_from_properties( - cls, example_properties: List[SimpleObjectProperty], snippet_writer: SnippetWriter + cls, + example_properties: List[SimpleObjectProperty], + snippet_writer: SnippetWriter, ) -> AST.Expression: example_dict_pairs: List[ir_types.ExampleKeyValuePair] = [] for property in example_properties: @@ -190,7 +192,10 @@ def snippet_from_properties( ) ) return snippet_writer._get_snippet_for_map( - example_dict_pairs, use_typeddict_request=True, as_request=True, in_typeddict=True + example_dict_pairs, + use_typeddict_request=True, + as_request=True, + in_typeddict=True, ) @classmethod @@ -215,7 +220,9 @@ def type_to_snippet( @classmethod def can_tr_be_typeddict( - cls, tr: ir_types.TypeReference, types: Dict[ir_types.TypeId, ir_types.TypeDeclaration] + cls, + tr: ir_types.TypeReference, + types: Dict[ir_types.TypeId, ir_types.TypeDeclaration], ) -> bool: return tr.visit( named=lambda nt: FernTypedDict.can_be_typeddict(types[nt.type_id].shape, types), @@ -232,7 +239,11 @@ def can_tr_be_typeddict( ) @classmethod - def can_be_typeddict(cls, type_: ir_types.Type, types: Dict[ir_types.TypeId, ir_types.TypeDeclaration]) -> bool: + def can_be_typeddict( + cls, + type_: ir_types.Type, + types: Dict[ir_types.TypeId, ir_types.TypeDeclaration], + ) -> bool: return type_.visit( alias=lambda atd: atd.resolved_type.visit( named=lambda nt: nt.shape.visit( @@ -260,6 +271,8 @@ def can_be_typeddict(cls, type_: ir_types.Type, types: Dict[ir_types.TypeId, ir_ @classmethod def can_type_id_be_typeddict( - cls, type_id: ir_types.TypeId, types: Dict[ir_types.TypeId, ir_types.TypeDeclaration] + cls, + type_id: ir_types.TypeId, + types: Dict[ir_types.TypeId, ir_types.TypeDeclaration], ) -> bool: return cls.can_be_typeddict(types[type_id].shape, types) diff --git a/generators/python/src/fern_python/generators/pydantic_model/validators/pydantic_validators_generator.py b/generators/python/src/fern_python/generators/pydantic_model/validators/pydantic_validators_generator.py index 987c743dac0..0c2a85f0b22 100644 --- a/generators/python/src/fern_python/generators/pydantic_model/validators/pydantic_validators_generator.py +++ b/generators/python/src/fern_python/generators/pydantic_model/validators/pydantic_validators_generator.py @@ -15,7 +15,12 @@ class PydanticValidatorsGenerator(ValidatorsGenerator): _DECORATOR_FUNCTION_NAME = "field" - def __init__(self, model: PydanticModel, extended_pydantic_fields: List[PydanticField], unique_name: List[str]): + def __init__( + self, + model: PydanticModel, + extended_pydantic_fields: List[PydanticField], + unique_name: List[str], + ): super().__init__(model=model) reference_to_validators_class = self._get_reference_to_validators_class() diff --git a/generators/python/src/fern_python/generators/pydantic_model/validators/validator_generators/field_validator_generator.py b/generators/python/src/fern_python/generators/pydantic_model/validators/validator_generators/field_validator_generator.py index 49a1043c45b..873bd94c481 100644 --- a/generators/python/src/fern_python/generators/pydantic_model/validators/validator_generators/field_validator_generator.py +++ b/generators/python/src/fern_python/generators/pydantic_model/validators/validator_generators/field_validator_generator.py @@ -55,7 +55,15 @@ def _write_validator_body(writer: AST.NodeWriter) -> None: INDIVIDUAL_VALIDATOR_NAME = "validator" writer.write(f"for {INDIVIDUAL_VALIDATOR_NAME} in ") - writer.write_line(".".join((*self._reference_to_validators_class, self.get_validator_class_var(pre))) + ":") + writer.write_line( + ".".join( + ( + *self._reference_to_validators_class, + self.get_validator_class_var(pre), + ) + ) + + ":" + ) with writer.indent(): writer.write(f"{field_value_parameter_name} = ") diff --git a/generators/python/src/fern_python/generators/pydantic_model/validators/validator_generators/root_validator_generator.py b/generators/python/src/fern_python/generators/pydantic_model/validators/validator_generators/root_validator_generator.py index ab3bb230f8a..831c39b2413 100644 --- a/generators/python/src/fern_python/generators/pydantic_model/validators/validator_generators/root_validator_generator.py +++ b/generators/python/src/fern_python/generators/pydantic_model/validators/validator_generators/root_validator_generator.py @@ -15,7 +15,10 @@ class RootValidatorGenerator(ValidatorGenerator): _VALIDATOR_PARAMETER_NAME = "validator" def __init__( - self, model: PydanticModel, reference_to_validators_class: Tuple[str, ...], unique_model_name: List[str] + self, + model: PydanticModel, + reference_to_validators_class: Tuple[str, ...], + unique_model_name: List[str], ): super().__init__(model, reference_to_validators_class) self._unique_model_name = unique_model_name @@ -167,7 +170,10 @@ def _get_root_validator_protocol_name(self, pre: bool) -> str: def write_example_for_docstring(self, writer: AST.NodeWriter) -> None: reference_to_decorator = ".".join( - (*self._reference_to_validators_class, RootValidatorGenerator._DECORATOR_FUNCTION_NAME) + ( + *self._reference_to_validators_class, + RootValidatorGenerator._DECORATOR_FUNCTION_NAME, + ) ) reference_to_partial = self._model.get_reference_to_partial_class() diff --git a/generators/python/src/fern_python/generators/sdk/client_generator/client_generator.py b/generators/python/src/fern_python/generators/sdk/client_generator/client_generator.py index 1e723339148..df5f97df997 100644 --- a/generators/python/src/fern_python/generators/sdk/client_generator/client_generator.py +++ b/generators/python/src/fern_python/generators/sdk/client_generator/client_generator.py @@ -129,11 +129,15 @@ def _create_class_declaration(self, *, is_async: bool) -> AST.ClassDeclaration: for snippet in generated_endpoint_function.snippets or []: if is_async: self._snippet_registry.register_async_client_endpoint_snippet( - endpoint=endpoint, expr=snippet.snippet, example_id=snippet.example_id + endpoint=endpoint, + expr=snippet.snippet, + example_id=snippet.example_id, ) else: self._snippet_registry.register_sync_client_endpoint_snippet( - endpoint=endpoint, expr=snippet.snippet, example_id=snippet.example_id + endpoint=endpoint, + expr=snippet.snippet, + example_id=snippet.example_id, ) return class_declaration @@ -165,7 +169,10 @@ def _write_constructor_body(writer: AST.NodeWriter) -> None: if subpackage.has_endpoints_in_tree: writer.write_node(AST.Expression(f"self.{subpackage.name.snake_case.safe_name} = ")) kwargs = [ - (param.constructor_parameter_name, AST.Expression(f"self.{param.private_member_name}")) + ( + param.constructor_parameter_name, + AST.Expression(f"self.{param.private_member_name}"), + ) for param in self._get_constructor_parameters(is_async=is_async) ] writer.write_node( diff --git a/generators/python/src/fern_python/generators/sdk/client_generator/endpoint_function_generator.py b/generators/python/src/fern_python/generators/sdk/client_generator/endpoint_function_generator.py index 4571c83b352..e45bfb554cd 100644 --- a/generators/python/src/fern_python/generators/sdk/client_generator/endpoint_function_generator.py +++ b/generators/python/src/fern_python/generators/sdk/client_generator/endpoint_function_generator.py @@ -121,10 +121,14 @@ def __init__( context=self._context, ), file_upload=lambda file_upload_request: FileUploadRequestBodyParameters( - endpoint=self._endpoint, request=file_upload_request, context=self._context + endpoint=self._endpoint, + request=file_upload_request, + context=self._context, ), bytes=lambda bytes_request: BytesRequestBodyParameters( - endpoint=self._endpoint, request=bytes_request, context=self._context + endpoint=self._endpoint, + request=bytes_request, + context=self._context, ), ) if self._endpoint.request_body is not None @@ -429,7 +433,11 @@ def write(writer: AST.NodeWriter) -> None: return AST.CodeWriter(write) def _get_request_body( - self, *, method: str, request_body_parameters: Optional[AbstractRequestBodyParameters], writer: AST.NodeWriter + self, + *, + method: str, + request_body_parameters: Optional[AbstractRequestBodyParameters], + writer: AST.NodeWriter, ) -> Optional[AST.Expression]: json_request_body = request_body_parameters.get_json_body() if request_body_parameters is not None else None @@ -449,7 +457,10 @@ def write_request_body(writer: AST.NodeWriter) -> None: return json_request_body_var def _get_files( - self, *, request_body_parameters: Optional[AbstractRequestBodyParameters], writer: AST.NodeWriter + self, + *, + request_body_parameters: Optional[AbstractRequestBodyParameters], + writer: AST.NodeWriter, ) -> Optional[AST.Expression]: files = ( request_body_parameters.get_files() @@ -486,7 +497,9 @@ def write(writer: AST.NodeWriter) -> None: ) json_request_body_var = self._get_request_body( - method=method, request_body_parameters=request_body_parameters, writer=writer + method=method, + request_body_parameters=request_body_parameters, + writer=writer, ) files = self._get_files(request_body_parameters=request_body_parameters, writer=writer) @@ -546,7 +559,8 @@ def write_stream_generator(writer: AST.NodeWriter) -> None: ), ) streaming_request = get_httpx_request( - is_streaming=True, response_code_writer=streaming_response_code_writer + is_streaming=True, + response_code_writer=streaming_response_code_writer, ) writer.write_node(streaming_request) @@ -581,7 +595,8 @@ def write_stream_generator(writer: AST.NodeWriter) -> None: ), ) non_streaming_request = get_httpx_request( - is_streaming=False, response_code_writer=non_streaming_response_code_writer + is_streaming=False, + response_code_writer=non_streaming_response_code_writer, ) writer.write_newline_if_last_line_not() writer.write_line("else:") @@ -663,7 +678,7 @@ def write(writer: AST.NodeWriter) -> None: # Include a dashed line between the endpoint snippet and the rest of the docs, if any. writer.write_line("Examples") writer.write_line("--------") - source_file = SourceFileFactory.create_snippet() + source_file = SourceFileFactory.create_snippet(not self._context.custom_config.skip_formatting) source_file.add_expression(snippet) snippet_docstring = source_file.to_str() writer.write(snippet_docstring) @@ -962,7 +977,9 @@ def _get_response_body_type( ), text=lambda _: AST.TypeHint.str_(), stream_parameter=lambda stream_param_response: self._get_streaming_parameter_response_body_type( - stream_param_response=stream_param_response, is_async=is_async, streaming_parameter=streaming_parameter + stream_param_response=stream_param_response, + is_async=is_async, + streaming_parameter=streaming_parameter, ), ) @@ -985,7 +1002,10 @@ def _write_standard_return(self, writer: NodeWriter, response_hint: AST.TypeHint writer.write_line() def _write_response_body_type( - self, writer: NodeWriter, response: Optional[ir_types.HttpResponse], response_hint: AST.TypeHint + self, + writer: NodeWriter, + response: Optional[ir_types.HttpResponse], + response_hint: AST.TypeHint, ) -> None: if response is not None and response.body: response.body.visit( @@ -1133,9 +1153,19 @@ def _get_headers_for_endpoint( for header in ir_headers: literal_header_value = self._context.get_literal_header_value(header) if literal_header_value is not None and type(literal_header_value) is str: - headers.append((header.name.wire_value, AST.Expression(f'"{literal_header_value}"'))) + headers.append( + ( + header.name.wire_value, + AST.Expression(f'"{literal_header_value}"'), + ) + ) elif literal_header_value is not None and type(literal_header_value) is bool: - headers.append((header.name.wire_value, AST.Expression(f'"{str(literal_header_value).lower()}"'))) + headers.append( + ( + header.name.wire_value, + AST.Expression(f'"{str(literal_header_value).lower()}"'), + ) + ) else: headers.append( ( @@ -1178,7 +1208,10 @@ def _get_query_parameters_for_endpoint( self, *, endpoint: ir_types.HttpEndpoint, parent_writer: AST.NodeWriter ) -> Optional[AST.Expression]: query_parameters = [ - (query_parameter.name.wire_value, self._get_query_parameter_reference(query_parameter)) + ( + query_parameter.name.wire_value, + self._get_query_parameter_reference(query_parameter), + ) for query_parameter in endpoint.query_parameters ] @@ -1230,7 +1263,10 @@ def _is_date( def _is_httpx_primitive_data(self, type_reference: ir_types.TypeReference, *, allow_optional: bool) -> bool: return self._does_type_reference_match_primitives( - type_reference, expected=HTTPX_PRIMITIVE_DATA_TYPES, allow_optional=allow_optional, allow_enum=True + type_reference, + expected=HTTPX_PRIMITIVE_DATA_TYPES, + allow_optional=allow_optional, + allow_enum=True, ) def _does_type_reference_match_primitives( @@ -1296,7 +1332,9 @@ def _environment_is_enum(self) -> bool: return self._context.ir.environments is not None def _get_typehint_for_query_param( - self, query_parameter: ir_types.QueryParameter, query_parameter_type_hint: AST.TypeHint + self, + query_parameter: ir_types.QueryParameter, + query_parameter_type_hint: AST.TypeHint, ) -> AST.TypeHint: value_type = query_parameter.value_type.get_as_union() is_optional = value_type.type == "container" and value_type.container.get_as_union().type == "optional" @@ -1578,7 +1616,11 @@ def _get_request_parameter_name(self) -> str: # but if they're optional we don't and so if an example is provided for that we must respect it. def _is_query_literal(self, query_parameter_wire_value: str, disqualify_optionals: bool) -> bool: param = next( - filter(lambda q: q.name.wire_value == query_parameter_wire_value, self.endpoint.query_parameters), None + filter( + lambda q: q.name.wire_value == query_parameter_wire_value, + self.endpoint.query_parameters, + ), + None, ) if param is not None: if disqualify_optionals: @@ -1590,7 +1632,10 @@ def _is_query_literal(self, query_parameter_wire_value: str, disqualify_optional def _is_path_literal(self, path_parameter_original_name: str, disqualify_optionals: bool) -> bool: param = next( - filter(lambda p: p.name.original_name == path_parameter_original_name, self.endpoint.all_path_parameters), + filter( + lambda p: p.name.original_name == path_parameter_original_name, + self.endpoint.all_path_parameters, + ), None, ) if param is not None: @@ -1602,7 +1647,10 @@ def _is_path_literal(self, path_parameter_original_name: str, disqualify_optiona return False def _is_header_literal(self, header_wire_value: str, disqualify_optionals: bool) -> bool: - param = next(filter(lambda h: h.name.wire_value == header_wire_value, self.endpoint.headers), None) + param = next( + filter(lambda h: h.name.wire_value == header_wire_value, self.endpoint.headers), + None, + ) if param is not None: if disqualify_optionals: # Not a direct literal, return False @@ -1617,7 +1665,11 @@ def _is_inlined_request_literal(self, property_wire_value: str, disqualify_optio request_body_union = self.endpoint.request_body.get_as_union() if request_body_union.type == "inlinedRequestBody": param = next( - filter(lambda p: p.name.wire_value == property_wire_value, request_body_union.properties), None + filter( + lambda p: p.name.wire_value == property_wire_value, + request_body_union.properties, + ), + None, ) if param is not None: if disqualify_optionals: @@ -1654,7 +1706,9 @@ def is_endpoint_path_empty(endpoint: ir_types.HttpEndpoint) -> bool: return len(endpoint.full_path.head) == 0 and len(endpoint.full_path.parts) == 0 -def unwrap_optional_type(type_reference: ir_types.TypeReference) -> ir_types.TypeReference: +def unwrap_optional_type( + type_reference: ir_types.TypeReference, +) -> ir_types.TypeReference: type_as_union = type_reference.get_as_union() if type_as_union.type == "container": container_as_union = type_as_union.container.get_as_union() diff --git a/generators/python/src/fern_python/generators/sdk/client_generator/endpoint_response_code_writer.py b/generators/python/src/fern_python/generators/sdk/client_generator/endpoint_response_code_writer.py index 9bf3750465c..904188e1a46 100644 --- a/generators/python/src/fern_python/generators/sdk/client_generator/endpoint_response_code_writer.py +++ b/generators/python/src/fern_python/generators/sdk/client_generator/endpoint_response_code_writer.py @@ -69,7 +69,8 @@ def _handle_success_stream(self, *, writer: AST.NodeWriter, stream_response: ir_ writer.write(f"{EndpointResponseCodeWriter.EVENT_SOURCE_VARIABLE} = ") writer.write_node( AST.ClassInstantiation( - HttpxSSE.EVENT_SOURCE, [AST.Expression(EndpointResponseCodeWriter.RESPONSE_VARIABLE)] + HttpxSSE.EVENT_SOURCE, + [AST.Expression(EndpointResponseCodeWriter.RESPONSE_VARIABLE)], ) ) writer.write_newline_if_last_line_not() @@ -148,7 +149,11 @@ def _get_iter_sse_method(self, *, is_async: bool) -> str: return "iter_sse" def _handle_success_json( - self, *, writer: AST.NodeWriter, json_response: ir_types.JsonResponse, use_response_json: bool + self, + *, + writer: AST.NodeWriter, + json_response: ir_types.JsonResponse, + use_response_json: bool, ) -> None: pydantic_parse_expression = self._context.core_utilities.get_construct( self._get_json_response_body_type(json_response), @@ -217,7 +222,9 @@ def handle_endpoint_response(writer: AST.NodeWriter) -> None: else: self._response.body.visit( json=lambda json_response: self._handle_success_json( - writer=writer, json_response=json_response, use_response_json=False + writer=writer, + json_response=json_response, + use_response_json=False, ), streaming=lambda stream_response: self._handle_success_stream( writer=writer, stream_response=stream_response @@ -225,12 +232,15 @@ def handle_endpoint_response(writer: AST.NodeWriter) -> None: file_download=lambda _: self._handle_success_file_download(writer=writer), text=lambda _: self._handle_success_text(writer=writer), stream_parameter=lambda stream_param_response: self._handle_success_stream( - writer=writer, stream_response=stream_param_response.stream_response + writer=writer, + stream_response=stream_param_response.stream_response, ) if self._streaming_parameter == "streaming" else stream_param_response.non_stream_response.visit( json=lambda json_response: self._handle_success_json( - writer=writer, json_response=json_response, use_response_json=False + writer=writer, + json_response=json_response, + use_response_json=False, ), file_download=lambda _: self._handle_success_file_download(writer=writer), text=lambda _: self._handle_success_text(writer=writer), @@ -306,7 +316,9 @@ def _write_property_discriminated_response_handler( else: self._response.body.visit( json=lambda json_response: self._handle_success_json( - writer=writer, json_response=json_response, use_response_json=True + writer=writer, + json_response=json_response, + use_response_json=True, ), streaming=lambda stream_response: self._handle_success_stream( writer=writer, stream_response=stream_response @@ -314,12 +326,15 @@ def _write_property_discriminated_response_handler( file_download=lambda _: self._handle_success_file_download(writer=writer), text=lambda _: self._handle_success_text(writer=writer), stream_parameter=lambda stream_param_response: self._handle_success_stream( - writer=writer, stream_response=stream_param_response.stream_response + writer=writer, + stream_response=stream_param_response.stream_response, ) if self._streaming_parameter == "streaming" else stream_param_response.non_stream_response.visit( json=lambda json_response: self._handle_success_json( - writer=writer, json_response=json_response, use_response_json=False + writer=writer, + json_response=json_response, + use_response_json=False, ), file_download=lambda _: self._handle_success_file_download(writer=writer), text=lambda _: self._handle_success_text(writer=writer), @@ -376,7 +391,10 @@ def _deserialize_json_response(self, *, writer: AST.NodeWriter) -> None: ) def _try_deserialize_json_response( - self, *, writer: AST.NodeWriter, response_handler: Optional[Callable[[AST.NodeWriter], None]] = None + self, + *, + writer: AST.NodeWriter, + response_handler: Optional[Callable[[AST.NodeWriter], None]] = None, ) -> None: writer.write_line("try:") with writer.indent(): diff --git a/generators/python/src/fern_python/generators/sdk/client_generator/oauth_token_provider_generator.py b/generators/python/src/fern_python/generators/sdk/client_generator/oauth_token_provider_generator.py index 0c294e1b678..6154fd98b5f 100644 --- a/generators/python/src/fern_python/generators/sdk/client_generator/oauth_token_provider_generator.py +++ b/generators/python/src/fern_python/generators/sdk/client_generator/oauth_token_provider_generator.py @@ -382,7 +382,10 @@ def _write_expires_at_setter(writer: AST.NodeWriter) -> None: f"token_response.{self._get_response_property_path(property_path)}{property_name}" ), ), - ("buffer_in_minutes", AST.Expression(f"self.{self._get_buffer_in_minutes_member_name()}")), + ( + "buffer_in_minutes", + AST.Expression(f"self.{self._get_buffer_in_minutes_member_name()}"), + ), ], ), ) diff --git a/generators/python/src/fern_python/generators/sdk/client_generator/pagination/cursor.py b/generators/python/src/fern_python/generators/sdk/client_generator/pagination/cursor.py index 4e68c9da525..840800a4b10 100644 --- a/generators/python/src/fern_python/generators/sdk/client_generator/pagination/cursor.py +++ b/generators/python/src/fern_python/generators/sdk/client_generator/pagination/cursor.py @@ -43,7 +43,8 @@ def init_has_next(self) -> str: def init_get_next(self, *, writer: AST.NodeWriter) -> None: writer.write("lambda: ") page_parameter_name = self.cursor.page.property.visit( - body=lambda b: b.name.name.snake_case.safe_name, query=lambda q: q.name.name.snake_case.safe_name + body=lambda b: b.name.name.snake_case.safe_name, + query=lambda q: q.name.name.snake_case.safe_name, ) writer.write(f"self.{self._config.endpoint_name}(") for parameter in self._config.parameters: diff --git a/generators/python/src/fern_python/generators/sdk/client_generator/request_body_parameters/inlined_request_body_parameters.py b/generators/python/src/fern_python/generators/sdk/client_generator/request_body_parameters/inlined_request_body_parameters.py index 712241622ec..9b2d90f5fdd 100644 --- a/generators/python/src/fern_python/generators/sdk/client_generator/request_body_parameters/inlined_request_body_parameters.py +++ b/generators/python/src/fern_python/generators/sdk/client_generator/request_body_parameters/inlined_request_body_parameters.py @@ -91,7 +91,9 @@ def _get_non_parameter_properties(self) -> List[AST.NamedFunctionParameter]: def _is_type_literal(self, type_reference: ir_types.TypeReference) -> bool: return self._context.get_literal_value(reference=type_reference) is not None - def _get_all_properties_for_inlined_request_body(self) -> List[ir_types.InlinedRequestBodyProperty]: + def _get_all_properties_for_inlined_request_body( + self, + ) -> List[ir_types.InlinedRequestBodyProperty]: properties = self._request_body.properties.copy() for extension in self._request_body.extends: properties.extend( diff --git a/generators/python/src/fern_python/generators/sdk/client_generator/request_body_parameters/referenced_request_body_parameters.py b/generators/python/src/fern_python/generators/sdk/client_generator/request_body_parameters/referenced_request_body_parameters.py index ab80321a3a4..a5e34362e8e 100644 --- a/generators/python/src/fern_python/generators/sdk/client_generator/request_body_parameters/referenced_request_body_parameters.py +++ b/generators/python/src/fern_python/generators/sdk/client_generator/request_body_parameters/referenced_request_body_parameters.py @@ -129,7 +129,9 @@ def _get_non_parameter_properties(self) -> List[AST.NamedFunctionParameter]: def _get_property_name(self, property: ir_types.InlinedRequestBodyProperty) -> str: return property.name.name.snake_case.safe_name - def _get_all_properties_for_inlined_request_body(self) -> List[ir_types.InlinedRequestBodyProperty]: + def _get_all_properties_for_inlined_request_body( + self, + ) -> List[ir_types.InlinedRequestBodyProperty]: if self._type_id is None: raise RuntimeError("Request body type is not defined, this should never happen.") object_properties = self._context.pydantic_generator_context.get_all_properties_including_extensions( diff --git a/generators/python/src/fern_python/generators/sdk/client_generator/root_client_generator.py b/generators/python/src/fern_python/generators/sdk/client_generator/root_client_generator.py index 3efb8964c28..ff1c790760a 100644 --- a/generators/python/src/fern_python/generators/sdk/client_generator/root_client_generator.py +++ b/generators/python/src/fern_python/generators/sdk/client_generator/root_client_generator.py @@ -241,7 +241,7 @@ def _create_class_declaration( for param in constructor_parameters ] - snippet = SourceFileFactory.create_snippet() + snippet = SourceFileFactory.create_snippet(should_format=not self._context.custom_config.skip_formatting) snippet.add_expression( generated_root_client.async_instantiation if is_async else generated_root_client.sync_instantiation ) @@ -290,11 +290,15 @@ def _create_class_declaration( for val in generated_endpoint_function.snippets or []: if is_async: self._snippet_registry.register_async_client_endpoint_snippet( - endpoint=endpoint, expr=val.snippet, example_id=val.example_id + endpoint=endpoint, + expr=val.snippet, + example_id=val.example_id, ) else: self._snippet_registry.register_sync_client_endpoint_snippet( - endpoint=endpoint, expr=val.snippet, example_id=val.example_id + endpoint=endpoint, + expr=val.snippet, + example_id=val.example_id, ) return class_declaration @@ -330,10 +334,12 @@ def _get_constructor_parameters(self, *, is_async: bool) -> List[RootClientConst AST.Expression( environments_config.environments.visit( single_base_url=lambda single_base_url_environments: SingleBaseUrlEnvironmentGenerator( - context=self._context, environments=single_base_url_environments + context=self._context, + environments=single_base_url_environments, ).get_reference_to_default_environment(), multiple_base_urls=lambda multiple_base_urls_environments: MultipleBaseUrlsEnvironmentGenerator( - context=self._context, environments=multiple_base_urls_environments + context=self._context, + environments=multiple_base_urls_environments, ).get_reference_to_default_environment(), ) ) @@ -342,7 +348,7 @@ def _get_constructor_parameters(self, *, is_async: bool) -> List[RootClientConst ) environment_docs = f"{RootClientGenerator.ENVIRONMENT_CONSTRUCTOR_PARAMETER_DOCS}" if default_environment is not None: - snippet = SourceFileFactory.create_snippet() + snippet = SourceFileFactory.create_snippet(should_format=False) def write_default_environment(writer: AST.NodeWriter) -> None: writer.write("Defaults to ") @@ -368,10 +374,12 @@ def write_default_environment(writer: AST.NodeWriter) -> None: AST.Expression( environments_config.environments.visit( single_base_url=lambda single_base_url_environments: SingleBaseUrlEnvironmentGenerator( - context=self._context, environments=single_base_url_environments + context=self._context, + environments=single_base_url_environments, ).get_reference_to_default_environment(), multiple_base_urls=lambda multiple_base_urls_environments: MultipleBaseUrlsEnvironmentGenerator( - context=self._context, environments=multiple_base_urls_environments + context=self._context, + environments=multiple_base_urls_environments, ).get_reference_to_default_environment(), ) ) @@ -380,7 +388,7 @@ def write_default_environment(writer: AST.NodeWriter) -> None: ) environment_docs = f"{RootClientGenerator.ENVIRONMENT_CONSTRUCTOR_PARAMETER_DOCS}" if default_environment is not None: - snippet = SourceFileFactory.create_snippet() + snippet = SourceFileFactory.create_snippet(should_format=False) def write_default_environment(writer: AST.NodeWriter) -> None: writer.write("Defaults to ") @@ -580,7 +588,10 @@ def _write_parameter_validation(writer: AST.NodeWriter) -> None: return _write_parameter_validation def _get_write_constructor_body( - self, *, is_async: bool, constructor_parameters: List[RootClientConstructorParameter] + self, + *, + is_async: bool, + constructor_parameters: List[RootClientConstructorParameter], ) -> CodeWriterFunction: def _write_constructor_body(writer: AST.NodeWriter) -> None: timeout_local_variable = "_defaulted_timeout" @@ -672,7 +683,10 @@ def _write_constructor_body(writer: AST.NodeWriter) -> None: if subpackage.has_endpoints_in_tree: writer.write_node(AST.Expression(f"self.{subpackage.name.snake_case.safe_name} = ")) client_wrapper_constructor_kwargs = [ - (param.constructor_parameter_name, AST.Expression(f"self.{param.constructor_parameter_name}")) + ( + param.constructor_parameter_name, + AST.Expression(f"self.{param.constructor_parameter_name}"), + ) for param in self._get_constructor_parameters(is_async=is_async) ] client_wrapper_constructor_kwargs.append( @@ -888,7 +902,9 @@ def __init__( self._constructor_parameters = constructor_parameters def build(self) -> GeneratedRootClient: - def client_snippet_writer(class_name: str) -> typing.Tuple[AST.ClassReference, CodeWriterFunction]: + def client_snippet_writer( + class_name: str, + ) -> typing.Tuple[AST.ClassReference, CodeWriterFunction]: client_class_reference = AST.ClassReference( qualified_name_excluding_import=(), import_=AST.ReferenceImport( @@ -919,7 +935,13 @@ def write_client_snippet(writer: AST.NodeWriter) -> None: sync_class_reference, sync_class_snippet_writer = client_snippet_writer(self._class_name) return GeneratedRootClient( async_instantiation=AST.Expression(AST.CodeWriter(async_class_snippet_writer)), - async_client=RootClient(class_reference=async_class_reference, parameters=self._constructor_parameters), + async_client=RootClient( + class_reference=async_class_reference, + parameters=self._constructor_parameters, + ), sync_instantiation=AST.Expression(AST.CodeWriter(sync_class_snippet_writer)), - sync_client=RootClient(class_reference=sync_class_reference, parameters=self._constructor_parameters), + sync_client=RootClient( + class_reference=sync_class_reference, + parameters=self._constructor_parameters, + ), ) diff --git a/generators/python/src/fern_python/generators/sdk/context/sdk_generator_context.py b/generators/python/src/fern_python/generators/sdk/context/sdk_generator_context.py index dcb4e96bc43..189aaa1a261 100644 --- a/generators/python/src/fern_python/generators/sdk/context/sdk_generator_context.py +++ b/generators/python/src/fern_python/generators/sdk/context/sdk_generator_context.py @@ -49,7 +49,10 @@ def __init__( # This should be replaced with `hasPaginatedEndpoints` in the IR, but that's on IR44, not 39, which is what Python's on _has_paginated_endpoints = any( - map(lambda service: any(map(lambda ep: ep.pagination is not None, service.endpoints)), ir.services.values()) + map( + lambda service: any(map(lambda ep: ep.pagination is not None, service.endpoints)), + ir.services.values(), + ) ) self.core_utilities = CoreUtilities( allow_skipping_validation=custom_config.pydantic_config.skip_validation, diff --git a/generators/python/src/fern_python/generators/sdk/context/sdk_generator_context_impl.py b/generators/python/src/fern_python/generators/sdk/context/sdk_generator_context_impl.py index 85bbfcefb91..c3e36b1a228 100644 --- a/generators/python/src/fern_python/generators/sdk/context/sdk_generator_context_impl.py +++ b/generators/python/src/fern_python/generators/sdk/context/sdk_generator_context_impl.py @@ -60,7 +60,8 @@ def __init__( skip_resources_module=custom_config.improved_imports ) self._environments_enum_declaration_referencer = EnvironmentsEnumDeclarationReferencer( - client_class_name=exported_client_class_name, skip_resources_module=custom_config.improved_imports + client_class_name=exported_client_class_name, + skip_resources_module=custom_config.improved_imports, ) self._subpackage_client_declaration_referencer = SubpackageClientDeclarationReferencer( skip_resources_module=custom_config.improved_imports diff --git a/generators/python/src/fern_python/generators/sdk/core_utilities/client_wrapper_generator.py b/generators/python/src/fern_python/generators/sdk/core_utilities/client_wrapper_generator.py index b216b3dc730..265f35b4279 100644 --- a/generators/python/src/fern_python/generators/sdk/core_utilities/client_wrapper_generator.py +++ b/generators/python/src/fern_python/generators/sdk/core_utilities/client_wrapper_generator.py @@ -68,7 +68,8 @@ class ClientWrapperGenerator: HTTPX_CLIENT_MEMBER_NAME = "httpx_client" STRING_OR_SUPPLIER_TYPE_HINT = AST.TypeHint.union( - AST.TypeHint.str_(), AST.TypeHint.callable(parameters=[], return_type=AST.TypeHint.str_()) + AST.TypeHint.str_(), + AST.TypeHint.callable(parameters=[], return_type=AST.TypeHint.str_()), ) def __init__( @@ -266,7 +267,9 @@ def _get_write_derived_client_wrapper_constructor_body( ) -> CodeWriterFunction: has_base_url = get_client_wrapper_url_type(ir=self._context.ir) == ClientWrapperUrlStorage.URL - def _write_derived_client_wrapper_constructor_body(writer: AST.NodeWriter) -> None: + def _write_derived_client_wrapper_constructor_body( + writer: AST.NodeWriter, + ) -> None: writer.write_line( "super().__init__(" + ", ".join( diff --git a/generators/python/src/fern_python/generators/sdk/core_utilities/core_utilities.py b/generators/python/src/fern_python/generators/sdk/core_utilities/core_utilities.py index 915cdbd8bda..58b8ffa87ba 100644 --- a/generators/python/src/fern_python/generators/sdk/core_utilities/core_utilities.py +++ b/generators/python/src/fern_python/generators/sdk/core_utilities/core_utilities.py @@ -174,7 +174,12 @@ def copy_to_project(self, *, project: Project) -> None: project.add_dependency(PYDANTIC_DEPENDENCY) def _copy_file_to_project( - self, *, project: Project, relative_filepath_on_disk: str, filepath_in_project: Filepath, exports: Set[str] + self, + *, + project: Project, + relative_filepath_on_disk: str, + filepath_in_project: Filepath, + exports: Set[str], ) -> None: source = ( os.path.join(os.path.dirname(__file__), "../../../../../core_utilities/sdk") @@ -204,7 +209,8 @@ def get_oauth_token_provider(self) -> AST.ClassReference: return AST.ClassReference( qualified_name_excluding_import=(), import_=AST.ReferenceImport( - module=AST.Module.local(*self._module_path, "oauth_token_provider"), named_import="OAuthTokenProvider" + module=AST.Module.local(*self._module_path, "oauth_token_provider"), + named_import="OAuthTokenProvider", ), ) @@ -212,14 +218,18 @@ def instantiate_api_error( self, *, status_code: Optional[AST.Expression], body: Optional[AST.Expression] ) -> AST.AstNode: return self._instantiate_api_error( - constructor=AST.Expression(self.get_reference_to_api_error()), status_code=status_code, body=body + constructor=AST.Expression(self.get_reference_to_api_error()), + status_code=status_code, + body=body, ) def instantiate_api_error_from_subclass( self, *, status_code: Optional[AST.Expression], body: Optional[AST.Expression] ) -> AST.AstNode: return self._instantiate_api_error( - constructor=AST.Expression("super().__init__"), status_code=status_code, body=body + constructor=AST.Expression("super().__init__"), + status_code=status_code, + body=body, ) def _instantiate_api_error( @@ -315,7 +325,8 @@ def serialize_datetime(self, datetime: AST.Expression) -> AST.Expression: function_definition=AST.Reference( qualified_name_excluding_import=(), import_=AST.ReferenceImport( - module=AST.Module.local(*self._module_path, "datetime_utils"), named_import="serialize_datetime" + module=AST.Module.local(*self._module_path, "datetime_utils"), + named_import="serialize_datetime", ), ), args=[datetime], @@ -326,7 +337,8 @@ def get_reference_to_request_options(self) -> AST.ClassReference: return AST.ClassReference( qualified_name_excluding_import=(), import_=AST.ReferenceImport( - module=AST.Module.local(*self._module_path, "request_options"), named_import="RequestOptions" + module=AST.Module.local(*self._module_path, "request_options"), + named_import="RequestOptions", ), ) @@ -345,7 +357,8 @@ def httpx_tuple_converter(self, obj: AST.Expression) -> AST.Expression: function_definition=AST.Reference( qualified_name_excluding_import=("convert_file_dict_to_httpx_tuples",), import_=AST.ReferenceImport( - module=AST.Module.local(*self._module_path_unnamed), named_import="core" + module=AST.Module.local(*self._module_path_unnamed), + named_import="core", ), ), args=[obj], @@ -384,7 +397,8 @@ def get_field_metadata(self) -> FieldMetadata: field_metadata_reference = AST.ClassReference( qualified_name_excluding_import=(), import_=AST.ReferenceImport( - module=AST.Module.local(*self._module_path, "serialization"), named_import="FieldMetadata" + module=AST.Module.local(*self._module_path, "serialization"), + named_import="FieldMetadata", ), ) @@ -394,7 +408,8 @@ def get_union_metadata(self) -> AST.Reference: return AST.Reference( qualified_name_excluding_import=(), import_=AST.ReferenceImport( - module=AST.Module.local(*self._module_path, "unchecked_base_model"), named_import="UnionMetadata" + module=AST.Module.local(*self._module_path, "unchecked_base_model"), + named_import="UnionMetadata", ), ) @@ -415,7 +430,8 @@ def get_construct_type(self) -> AST.Reference: return AST.Reference( qualified_name_excluding_import=(), import_=AST.ReferenceImport( - module=AST.Module.local(*self._module_path, "unchecked_base_model"), named_import="construct_type" + module=AST.Module.local(*self._module_path, "unchecked_base_model"), + named_import="construct_type", ), ) @@ -427,7 +443,10 @@ def write(writer: AST.NodeWriter) -> None: value_being_casted=AST.Expression( AST.FunctionInvocation( function_definition=self.get_construct_type(), - kwargs=[("type_", AST.Expression(type_of_obj)), ("object_", obj)], + kwargs=[ + ("type_", AST.Expression(type_of_obj)), + ("object_", obj), + ], ) ), ) @@ -471,7 +490,11 @@ def get_paginator_type(self, inner_type: AST.TypeHint, is_async: bool) -> AST.Ty ) def instantiate_paginator( - self, is_async: bool, has_next: AST.Expression, items: AST.Expression, get_next: AST.Expression + self, + is_async: bool, + has_next: AST.Expression, + items: AST.Expression, + get_next: AST.Expression, ) -> AST.Expression: return AST.Expression( AST.ClassInstantiation( @@ -525,7 +548,10 @@ def write(writer: AST.NodeWriter) -> None: value_being_casted=AST.Expression( AST.FunctionInvocation( function_definition=self.get_parse_obj_as(), - kwargs=[("type_", AST.Expression(type_of_obj)), ("object_", obj)], + kwargs=[ + ("type_", AST.Expression(type_of_obj)), + ("object_", obj), + ], ) ), ) @@ -541,7 +567,8 @@ def get_parse_obj_as(self) -> AST.Reference: return AST.Reference( qualified_name_excluding_import=(), import_=AST.ReferenceImport( - module=AST.Module.local(*self._module_path, "pydantic_utilities"), named_import="parse_obj_as" + module=AST.Module.local(*self._module_path, "pydantic_utilities"), + named_import="parse_obj_as", ), ) @@ -550,7 +577,8 @@ def get_is_pydantic_v2(self) -> AST.Expression: AST.Reference( qualified_name_excluding_import=(), import_=AST.ReferenceImport( - module=AST.Module.local(*self._module_path, "pydantic_utilities"), named_import="IS_PYDANTIC_V2" + module=AST.Module.local(*self._module_path, "pydantic_utilities"), + named_import="IS_PYDANTIC_V2", ), ) ) diff --git a/generators/python/src/fern_python/generators/sdk/environment_generators/multiple_base_urls_environment_generator.py b/generators/python/src/fern_python/generators/sdk/environment_generators/multiple_base_urls_environment_generator.py index 50efa28482d..d6ddd264e89 100644 --- a/generators/python/src/fern_python/generators/sdk/environment_generators/multiple_base_urls_environment_generator.py +++ b/generators/python/src/fern_python/generators/sdk/environment_generators/multiple_base_urls_environment_generator.py @@ -7,7 +7,11 @@ class MultipleBaseUrlsEnvironmentGenerator: - def __init__(self, context: SdkGeneratorContext, environments: ir_types.MultipleBaseUrlsEnvironments): + def __init__( + self, + context: SdkGeneratorContext, + environments: ir_types.MultipleBaseUrlsEnvironments, + ): self._context = context self._environments = environments self.class_name = self._context.get_class_name_of_environments() @@ -30,7 +34,8 @@ def generate( name=class_var_name, type_hint=AST.TypeHint( AST.ClassReference( - qualified_name_excluding_import=(self.class_name,), is_forward_reference=True + qualified_name_excluding_import=(self.class_name,), + is_forward_reference=True, ) ), docstring=AST.Docstring(environment.docs) if environment.docs is not None else None, @@ -88,7 +93,10 @@ def write(writer: AST.NodeWriter) -> None: return AST.Expression(AST.CodeWriter(write)) def get_reference_to_base_url( - self, *, reference_to_environments: AST.Expression, base_url_id: ir_types.EnvironmentBaseUrlId + self, + *, + reference_to_environments: AST.Expression, + base_url_id: ir_types.EnvironmentBaseUrlId, ) -> AST.Expression: def write(writer: AST.NodeWriter) -> None: writer.write_node(reference_to_environments) @@ -140,7 +148,8 @@ def get_base_url_property_name(base_url: ir_types.EnvironmentBaseUrlWithId) -> s def get_base_url( - environments: ir_types.MultipleBaseUrlsEnvironments, base_url_id: ir_types.EnvironmentBaseUrlId + environments: ir_types.MultipleBaseUrlsEnvironments, + base_url_id: ir_types.EnvironmentBaseUrlId, ) -> ir_types.EnvironmentBaseUrlWithId: for base_url in environments.base_urls: if base_url.id == base_url_id: diff --git a/generators/python/src/fern_python/generators/sdk/environment_generators/single_base_url_environment_generator.py b/generators/python/src/fern_python/generators/sdk/environment_generators/single_base_url_environment_generator.py index e4093618731..d03c1362825 100644 --- a/generators/python/src/fern_python/generators/sdk/environment_generators/single_base_url_environment_generator.py +++ b/generators/python/src/fern_python/generators/sdk/environment_generators/single_base_url_environment_generator.py @@ -7,7 +7,11 @@ class SingleBaseUrlEnvironmentGenerator: - def __init__(self, context: SdkGeneratorContext, environments: ir_types.SingleBaseUrlEnvironments): + def __init__( + self, + context: SdkGeneratorContext, + environments: ir_types.SingleBaseUrlEnvironments, + ): self._context = context self._environments = environments diff --git a/generators/python/src/fern_python/generators/sdk/sdk_generator.py b/generators/python/src/fern_python/generators/sdk/sdk_generator.py index b31eadad5a7..010f6de8a57 100644 --- a/generators/python/src/fern_python/generators/sdk/sdk_generator.py +++ b/generators/python/src/fern_python/generators/sdk/sdk_generator.py @@ -155,7 +155,8 @@ def run( ) maybe_oauth_scheme = next( - (scheme for scheme in context.ir.auth.schemes if scheme.get_as_union().type == "oauth"), None + (scheme for scheme in context.ir.auth.schemes if scheme.get_as_union().type == "oauth"), + None, ) oauth_scheme = ( maybe_oauth_scheme.visit( @@ -252,49 +253,57 @@ def run( context=context, endpoint_metadata=endpoint_metadata_collector, ) - snippets = snippet_registry.snippets() - if snippets is not None: - self._maybe_write_snippets( - context=context, - snippets=snippets, - project=project, - ) + if generator_config.output.mode.get_as_union().type != "downloadFiles": + snippets = snippet_registry.snippets() - try: - self._write_readme( + if snippets is not None: + self._maybe_write_snippets( context=context, - generator_cli=generator_cli, snippets=snippets, project=project, - generated_root_client=generated_root_client, ) - except Exception: - generator_exec_wrapper.send_update( - GeneratorUpdate.factory.log( - LogUpdate(level=LogLevel.DEBUG, message=f"Failed to generate README.md; this is OK") + + try: + self._write_readme( + context=context, + generator_cli=generator_cli, + snippets=snippets, + project=project, + generated_root_client=generated_root_client, + ) + except Exception: + generator_exec_wrapper.send_update( + GeneratorUpdate.factory.log( + LogUpdate( + level=LogLevel.DEBUG, + message=f"Failed to generate README.md; this is OK", + ) + ) ) - ) - try: - self._write_reference( - context=context, - generator_cli=generator_cli, - snippets=snippets, - project=project, - ) - except Exception: - generator_exec_wrapper.send_update( - GeneratorUpdate.factory.log( - LogUpdate(level=LogLevel.DEBUG, message=f"Failed to generate reference.md; this is OK") + try: + self._write_reference( + context=context, + generator_cli=generator_cli, + snippets=snippets, + project=project, + ) + except Exception: + generator_exec_wrapper.send_update( + GeneratorUpdate.factory.log( + LogUpdate( + level=LogLevel.DEBUG, + message=f"Failed to generate reference.md; this is OK", + ) + ) ) - ) context.core_utilities.copy_to_project(project=project) if not (generator_config.output.mode.get_as_union().type == "downloadFiles"): as_is_copier.copy_to_project(project=project) - snippet_template_source_file = SourceFileFactory.create_snippet() + snippet_template_source_file = SourceFileFactory.create_snippet(not context.custom_config.skip_formatting) self._maybe_write_snippet_templates( context=context, snippet_template_factory=SnippetTemplateFactory( @@ -354,7 +363,9 @@ def _generate_environments( ) -> GeneratedEnvironment: filepath = context.get_filepath_for_environments_enum() source_file = SourceFileFactory.create( - project=project, filepath=filepath, generator_exec_wrapper=generator_exec_wrapper + project=project, + filepath=filepath, + generator_exec_wrapper=generator_exec_wrapper, ) generated_environment = environments.generate(source_file=source_file) project.write_source_file(source_file=source_file, filepath=filepath) @@ -372,7 +383,9 @@ def _generate_client_wrapper( file=Filepath.FilepathPart(module_name="client_wrapper"), ) source_file = SourceFileFactory.create( - project=project, filepath=filepath, generator_exec_wrapper=generator_exec_wrapper + project=project, + filepath=filepath, + generator_exec_wrapper=generator_exec_wrapper, ) ClientWrapperGenerator( context=context, @@ -390,7 +403,9 @@ def _generate_oauth_token_provider( ) -> None: filepath = context.get_filepath_for_generated_oauth_token_provider() source_file = SourceFileFactory.create( - project=project, filepath=filepath, generator_exec_wrapper=generator_exec_wrapper + project=project, + filepath=filepath, + generator_exec_wrapper=generator_exec_wrapper, ) OAuthTokenProviderGenerator( context=context, @@ -412,7 +427,9 @@ def _generate_root_client( ) -> GeneratedRootClient: filepath = context.get_filepath_for_generated_root_client() source_file = SourceFileFactory.create( - project=project, filepath=filepath, generator_exec_wrapper=generator_exec_wrapper + project=project, + filepath=filepath, + generator_exec_wrapper=generator_exec_wrapper, ) generated_root_client = RootClientGenerator( context=context, @@ -442,7 +459,9 @@ def _generate_subpackage_client( ) -> None: filepath = context.get_filepath_for_subpackage_service(subpackage_id) source_file = SourceFileFactory.create( - project=project, filepath=filepath, generator_exec_wrapper=generator_exec_wrapper + project=project, + filepath=filepath, + generator_exec_wrapper=generator_exec_wrapper, ) ClientGenerator( context=context, @@ -465,7 +484,9 @@ def _generate_error( ) -> None: filepath = context.get_filepath_for_error(error.name) source_file = SourceFileFactory.create( - project=project, filepath=filepath, generator_exec_wrapper=generator_exec_wrapper + project=project, + filepath=filepath, + generator_exec_wrapper=generator_exec_wrapper, ) ErrorGenerator(context=context, error=error).generate(source_file=source_file) project.write_source_file(source_file=source_file, filepath=filepath) @@ -529,7 +550,10 @@ def _maybe_write_snippet_templates( ) generator_exec_wrapper.send_update( GeneratorUpdate.factory.log( - LogUpdate(level=LogLevel.DEBUG, message=f"Uploaded snippet templates to FDR.") + LogUpdate( + level=LogLevel.DEBUG, + message=f"Uploaded snippet templates to FDR.", + ) ) ) except Exception as e: @@ -546,11 +570,17 @@ def _maybe_write_snippet_templates( # Otherwise write them for local project.add_file( context.generator_config.output.snippet_template_filepath, - json.dumps(list(map(lambda template: template.dict(by_alias=True), snippets)), indent=4), + json.dumps( + list(map(lambda template: template.dict(by_alias=True), snippets)), + indent=4, + ), ) generator_exec_wrapper.send_update( GeneratorUpdate.factory.log( - LogUpdate(level=LogLevel.DEBUG, message=f"Wrote snippet templates to disk.") + LogUpdate( + level=LogLevel.DEBUG, + message=f"Wrote snippet templates to disk.", + ) ) ) @@ -561,7 +591,10 @@ def _maybe_write_snippets( project: Project, ) -> None: if context.generator_config.output.snippet_filepath is not None: - project.add_file(context.generator_config.output.snippet_filepath, snippets.json(indent=4)) + project.add_file( + context.generator_config.output.snippet_filepath, + snippets.json(indent=4), + ) def _write_readme( self, diff --git a/generators/python/src/fern_python/pydantic_codegen/pydantic_model.py b/generators/python/src/fern_python/pydantic_codegen/pydantic_model.py index b5f3fb93d77..1f761364a16 100644 --- a/generators/python/src/fern_python/pydantic_codegen/pydantic_model.py +++ b/generators/python/src/fern_python/pydantic_codegen/pydantic_model.py @@ -140,7 +140,10 @@ def get_public_fields(self) -> List[PydanticField]: return self._fields def add_private_instance_field( - self, name: str, type_hint: AST.TypeHint, default_factory: Optional[AST.Expression] = None + self, + name: str, + type_hint: AST.TypeHint, + default_factory: Optional[AST.Expression] = None, ) -> None: if not name.startswith("_"): raise RuntimeError( @@ -162,7 +165,12 @@ def add_private_instance_field( def add_statement(self, statement: AST.AstNode) -> None: self._class_declaration.add_statement(statement) - def add_class_var(self, name: str, type_hint: AST.TypeHint, initializer: Optional[AST.Expression] = None) -> None: + def add_class_var( + self, + name: str, + type_hint: AST.TypeHint, + initializer: Optional[AST.Expression] = None, + ) -> None: self._class_declaration.add_class_var( AST.VariableDeclaration( name=name, @@ -216,7 +224,12 @@ def add_field_validator( ) def add_root_validator( - self, *, validator_name: str, body: AST.CodeWriter, should_use_partial_type: bool = False, pre: bool = False + self, + *, + validator_name: str, + body: AST.CodeWriter, + should_use_partial_type: bool = False, + pre: bool = False, ) -> None: value_type = ( AST.TypeHint(type=self.get_reference_to_partial_class()) @@ -230,7 +243,10 @@ def add_root_validator( name=validator_name, signature=AST.FunctionSignature( parameters=[ - AST.FunctionParameter(name=PydanticModel.VALIDATOR_VALUES_PARAMETER_NAME, type_hint=value_type) + AST.FunctionParameter( + name=PydanticModel.VALIDATOR_VALUES_PARAMETER_NAME, + type_hint=value_type, + ) ], return_type=value_type, ), @@ -277,7 +293,10 @@ def add_partial_class(self) -> None: def get_reference_to_partial_class(self) -> AST.ClassReference: return AST.ClassReference( - qualified_name_excluding_import=(self.name, PydanticModel._PARTIAL_CLASS_NAME), + qualified_name_excluding_import=( + self.name, + PydanticModel._PARTIAL_CLASS_NAME, + ), is_forward_reference=True, ) @@ -324,7 +343,13 @@ def update_forward_refs(self, localns: Iterable[AST.ClassReference] = []) -> Non function_definition=self._update_forward_ref_function_reference, args=[AST.Expression(self._local_class_reference)], kwargs=sorted( - [(get_named_import_or_throw(reference), AST.Expression(reference)) for reference in localns], + [ + ( + get_named_import_or_throw(reference), + AST.Expression(reference), + ) + for reference in localns + ], # sort by name for consistency key=lambda kwarg: kwarg[0], ), diff --git a/generators/python/src/fern_python/snippet/snippet_registry.py b/generators/python/src/fern_python/snippet/snippet_registry.py index 8d6d215308c..02882fa4e86 100644 --- a/generators/python/src/fern_python/snippet/snippet_registry.py +++ b/generators/python/src/fern_python/snippet/snippet_registry.py @@ -30,7 +30,10 @@ def snippets(self) -> Optional[generator_exec.Snippets]: types[generator_exec.TypeId(typeId)] = self._expression_to_snippet_str(expr) endpoints: List[generator_exec.Endpoint] = [] - for endpointId, sync_endpoint_expressions in self._sync_client_endpoint_snippets.items(): + for ( + endpointId, + sync_endpoint_expressions, + ) in self._sync_client_endpoint_snippets.items(): for idx, expression in enumerate(sync_endpoint_expressions): endpoints.append( generator_exec.Endpoint( diff --git a/generators/python/src/fern_python/snippet/snippet_template_factory.py b/generators/python/src/fern_python/snippet/snippet_template_factory.py index 4f83329e4f7..bb60f9aad30 100644 --- a/generators/python/src/fern_python/snippet/snippet_template_factory.py +++ b/generators/python/src/fern_python/snippet/snippet_template_factory.py @@ -100,7 +100,7 @@ def _expression_to_snippet_str( self, expr: AST.Expression, ) -> str: - snippet = SourceFileFactory.create_snippet() + snippet = SourceFileFactory.create_snippet(should_format=(not self._context.custom_config.skip_formatting)) snippet.add_expression(expr) # For some reason we're appending newlines to snippets, so we need to strip them for tempaltes return snippet.to_str().strip() @@ -109,7 +109,7 @@ def _expression_to_snippet_str_and_imports( self, expr: AST.Expression, ) -> Tuple[str, str]: - snippet = SourceFileFactory.create_snippet() + snippet = SourceFileFactory.create_snippet(should_format=(not self._context.custom_config.skip_formatting)) snippet.add_expression(expr) snippet_full = snippet.to_str() snippet_without_imports = snippet.to_str(include_imports=False) @@ -177,7 +177,9 @@ def _is_type_literal(self, type_reference: ir_types.TypeReference) -> bool: return self._context.get_literal_value(reference=type_reference) is not None def _get_breadcrumb_path( - self, wire_or_original_name: Optional[str], name_breadcrumbs: Optional[List[str]] + self, + wire_or_original_name: Optional[str], + name_breadcrumbs: Optional[List[str]], ) -> Union[str, None]: if wire_or_original_name is None and name_breadcrumbs is None: return None @@ -246,7 +248,8 @@ def _get_container_template( delimiter=f",\n{self.TAB_CHAR * child_indentation_level}", inner_template=inner_template, template_input=PayloadInput( - location=location, path=self._get_breadcrumb_path(wire_or_original_name, name_breadcrumbs) + location=location, + path=self._get_breadcrumb_path(wire_or_original_name, name_breadcrumbs), ), ) ) @@ -273,7 +276,8 @@ def _get_container_template( delimiter=f",\n{self.TAB_CHAR * child_indentation_level}", inner_template=inner_template, template_input=PayloadInput( - location=location, path=self._get_breadcrumb_path(wire_or_original_name, name_breadcrumbs) + location=location, + path=self._get_breadcrumb_path(wire_or_original_name, name_breadcrumbs), ), ) ) if inner_template is not None else None @@ -308,7 +312,8 @@ def _get_container_template( key_template=key_template, value_template=value_template, template_input=PayloadInput( - location=location, path=self._get_breadcrumb_path(wire_or_original_name, name_breadcrumbs) + location=location, + path=self._get_breadcrumb_path(wire_or_original_name, name_breadcrumbs), ), ) ) @@ -331,7 +336,9 @@ def _get_container_template( return None def _convert_enum_value_to_str( - self, type_name: ir_types.DeclaredTypeName, enum_value: ir_types.NameAndWireValue + self, + type_name: ir_types.DeclaredTypeName, + enum_value: ir_types.NameAndWireValue, ) -> Tuple[str, str]: enum_snippet = EnumSnippetGenerator( snippet_writer=self._snippet_writer, @@ -998,7 +1005,8 @@ def generate_templates(self) -> List[SnippetRegistryEntry]: endpoint_id=self._endpoint_to_identifier(endpoint), snippet_template=VersionedSnippetTemplate.factory.v_1( SnippetTemplate( - client_instantiation=client_instantiation, function_invocation=function_template + client_instantiation=client_instantiation, + function_invocation=function_template, ) ), additional_templates={ diff --git a/generators/python/src/fern_python/snippet/snippet_test_factory.py b/generators/python/src/fern_python/snippet/snippet_test_factory.py index 23f0554cf22..202de2b6ea3 100644 --- a/generators/python/src/fern_python/snippet/snippet_test_factory.py +++ b/generators/python/src/fern_python/snippet/snippet_test_factory.py @@ -93,7 +93,10 @@ def envvar_writer(writer: AST.NodeWriter) -> None: return AST.Expression(AST.CodeWriter(envvar_writer)) def _enviroment(self, generated_environment: MultipleBaseUrlsEnvironmentGenerator) -> AST.ClassInstantiation: - args = [AST.Expression(f'"{self.TEST_URL_ENVVAR}"'), AST.Expression('"base_url"')] + args = [ + AST.Expression(f'"{self.TEST_URL_ENVVAR}"'), + AST.Expression('"base_url"'), + ] os_get = AST.Expression( AST.FunctionInvocation( function_definition=AST.Reference( @@ -261,7 +264,10 @@ def _generate_type_expectations_for_type_reference(self, reference: ir_types.Exa "list", dict( [ - (idx, self._generate_type_expectations_for_type_reference(ex)) + ( + idx, + self._generate_type_expectations_for_type_reference(ex), + ) for idx, ex in enumerate(item_type.list_) ] ), @@ -270,7 +276,10 @@ def _generate_type_expectations_for_type_reference(self, reference: ir_types.Exa "set", dict( [ - (idx, self._generate_type_expectations_for_type_reference(ex)) + ( + idx, + self._generate_type_expectations_for_type_reference(ex), + ) for idx, ex in enumerate(item_type.set_) ] ), @@ -300,7 +309,10 @@ def _generate_type_expectations_for_type_reference(self, reference: ir_types.Exa enum=lambda _: None, object=lambda obj: dict( [ - (prop.name.wire_value, self._generate_type_expectations_for_type_reference(prop.value)) + ( + prop.name.wire_value, + self._generate_type_expectations_for_type_reference(prop.value), + ) for prop in obj.properties ] ), @@ -345,7 +357,11 @@ def writer(writer: AST.NodeWriter) -> None: maybe_stringify_expectations = f"'{expectations}'" if type(expectations) is str else expectations writer.write(f"{type_expectation_name}: ") - writer.write_node(AST.Expression(AST.TypeHint.tuple_(AST.TypeHint.any(), AST.TypeHint.any())) if isinstance(expectations, Tuple) else AST.Expression(AST.TypeHint.any())) # type: ignore + writer.write_node( + AST.Expression(AST.TypeHint.tuple_(AST.TypeHint.any(), AST.TypeHint.any())) + if isinstance(expectations, Tuple) + else AST.Expression(AST.TypeHint.any()) + ) # type: ignore writer.write_line(f" = {maybe_stringify_expectations}") if sync_expression: if response_json is not None: @@ -406,7 +422,9 @@ def maybe_get_response_body( return ( example_response.visit( ok=lambda res: res.visit( - body=lambda body: body if body else None, stream=lambda _: None, sse=lambda _: None + body=lambda body: body if body else None, + stream=lambda _: None, + sse=lambda _: None, ), error=lambda _: None, ) @@ -541,7 +559,10 @@ def _generate_service_test(self, service: ir_types.HttpService, snippet_writer: self._service_test_files[filepath] = source_file def _function_generator( - self, service: ir_types.HttpService, endpoint: ir_types.HttpEndpoint, snippet_writer: SnippetWriter + self, + service: ir_types.HttpService, + endpoint: ir_types.HttpEndpoint, + snippet_writer: SnippetWriter, ) -> EndpointFunctionGenerator: return EndpointFunctionGenerator( context=self._context, @@ -602,7 +623,11 @@ def _validate_response( named_import="validate_response", ), ), - args=[response_expression, expected_expression, expected_types_expression], + args=[ + response_expression, + expected_expression, + expected_types_expression, + ], ) ) diff --git a/generators/python/src/fern_python/snippet/type_declaration_snippet_generator.py b/generators/python/src/fern_python/snippet/type_declaration_snippet_generator.py index ce10b09436f..7dd403e8256 100644 --- a/generators/python/src/fern_python/snippet/type_declaration_snippet_generator.py +++ b/generators/python/src/fern_python/snippet/type_declaration_snippet_generator.py @@ -9,7 +9,8 @@ ObjectSnippetGenerator = Callable[[ir_types.DeclaredTypeName, ir_types.ExampleObjectType], AST.Expression] DiscriminatedUnionGenerator = Callable[[ir_types.DeclaredTypeName, ir_types.ExampleUnionType], AST.Expression] UndiscriminatedUnionGenerator = Callable[ - [ir_types.DeclaredTypeName, ir_types.ExampleUndiscriminatedUnionType], Optional[AST.Expression] + [ir_types.DeclaredTypeName, ir_types.ExampleUndiscriminatedUnionType], + Optional[AST.Expression], ] diff --git a/generators/python/src/fern_python/source_file_factory/source_file_factory.py b/generators/python/src/fern_python/source_file_factory/source_file_factory.py index c4c09ff65b2..45762697dfe 100644 --- a/generators/python/src/fern_python/source_file_factory/source_file_factory.py +++ b/generators/python/src/fern_python/source_file_factory/source_file_factory.py @@ -25,14 +25,14 @@ def create( return project.source_file(filepath=filepath, from_src=from_src) @staticmethod - def create_snippet() -> SourceFile: + def create_snippet(should_format: bool = True) -> SourceFile: return SourceFileImpl( module_path=(), reference_resolver=ReferenceResolverImpl( module_path_of_source_file=(), ), dependency_manager=DependencyManager(), - should_format=True, + should_format=should_format, should_format_as_snippet=True, should_include_header=False, ) diff --git a/generators/python/src/fern_python/utils/build_snippet_writer.py b/generators/python/src/fern_python/utils/build_snippet_writer.py index b278cae0c7e..f3a52bddceb 100644 --- a/generators/python/src/fern_python/utils/build_snippet_writer.py +++ b/generators/python/src/fern_python/utils/build_snippet_writer.py @@ -6,7 +6,10 @@ def build_snippet_writer( - *, context: PydanticGeneratorContext, improved_imports: bool = False, use_str_enums: bool = False + *, + context: PydanticGeneratorContext, + improved_imports: bool = False, + use_str_enums: bool = False, ) -> SnippetWriter: """ Builds a new SnippetWriter. Using this function is preferred over diff --git a/generators/python/tests/codegen/test_pyproject_toml.py b/generators/python/tests/codegen/test_pyproject_toml.py index 9ecd1260f7a..9c884b83de2 100644 --- a/generators/python/tests/codegen/test_pyproject_toml.py +++ b/generators/python/tests/codegen/test_pyproject_toml.py @@ -7,7 +7,9 @@ def test_pyproject_toml_gen(tmpdir: Path) -> None: dependency_manager = DependencyManager() - dependency_manager.add_dependency(ast.Dependency(name="pydantic", version="^1.10.2")) + dependency_manager.add_dependency( + ast.Dependency(name="pydantic", version="^1.10.2") + ) pyproject_toml = PyProjectToml( name="fern-fern-ir-model", version="0.0.0", diff --git a/generators/python/tests/sdk/test_custom_config.py b/generators/python/tests/sdk/test_custom_config.py index cf876a3e546..3a89629aea6 100644 --- a/generators/python/tests/sdk/test_custom_config.py +++ b/generators/python/tests/sdk/test_custom_config.py @@ -11,17 +11,31 @@ }, } + def test_parse_obj_override() -> None: top_level_custom_config = SDKCustomConfig.parse_obj(top_level_payload) - pydantic_config_custom_config = SDKCustomConfig.parse_obj(pydantic_config_level_payload) - + pydantic_config_custom_config = SDKCustomConfig.parse_obj( + pydantic_config_level_payload + ) + assert top_level_custom_config.use_typeddict_requests is True assert pydantic_config_custom_config.pydantic_config.use_typeddict_requests is True - assert top_level_custom_config.use_typeddict_requests == top_level_custom_config.pydantic_config.use_typeddict_requests - - assert pydantic_config_custom_config.use_typeddict_requests == pydantic_config_custom_config.pydantic_config.use_typeddict_requests + assert ( + top_level_custom_config.use_typeddict_requests + == top_level_custom_config.pydantic_config.use_typeddict_requests + ) - assert top_level_custom_config.use_typeddict_requests == pydantic_config_custom_config.use_typeddict_requests - assert top_level_custom_config.pydantic_config.use_typeddict_requests == pydantic_config_custom_config.pydantic_config.use_typeddict_requests + assert ( + pydantic_config_custom_config.use_typeddict_requests + == pydantic_config_custom_config.pydantic_config.use_typeddict_requests + ) + assert ( + top_level_custom_config.use_typeddict_requests + == pydantic_config_custom_config.use_typeddict_requests + ) + assert ( + top_level_custom_config.pydantic_config.use_typeddict_requests + == pydantic_config_custom_config.pydantic_config.use_typeddict_requests + ) diff --git a/generators/python/tests/sdk/test_jsonable_encoder.py b/generators/python/tests/sdk/test_jsonable_encoder.py index 6d0d4f59a75..09f2a0df37d 100644 --- a/generators/python/tests/sdk/test_jsonable_encoder.py +++ b/generators/python/tests/sdk/test_jsonable_encoder.py @@ -6,6 +6,8 @@ def test_jsonable_encoder() -> None: - updates: List[GeneratorUpdate] = [GeneratorUpdate.factory.init_v_2(InitUpdateV2(publishing_to_registry=None))] + updates: List[GeneratorUpdate] = [ + GeneratorUpdate.factory.init_v_2(InitUpdateV2(publishing_to_registry=None)) + ] serialized = jsonable_encoder(updates) assert serialized == [{"_type": "initV2", "publishingToRegistry": None}] diff --git a/generators/python/tests/utils/example_models/manual_types/defaulted_object.py b/generators/python/tests/utils/example_models/manual_types/defaulted_object.py index 0548b8af053..e9eec771bb3 100644 --- a/generators/python/tests/utils/example_models/manual_types/defaulted_object.py +++ b/generators/python/tests/utils/example_models/manual_types/defaulted_object.py @@ -5,7 +5,9 @@ class ObjectWithDefaultedOptionalFields(UncheckedBaseModel): - literal_: typing.Optional[typing.Literal["lit_one", "lit_two"]] = pydantic.Field(alias="literal", default="lit_one") + literal_: typing.Optional[typing.Literal["lit_one", "lit_two"]] = pydantic.Field( + alias="literal", default="lit_one" + ) string: typing.Optional[str] = None integer: typing.Optional[int] = None long_: typing.Optional[int] = pydantic.Field(alias="long", default=200000) @@ -15,9 +17,17 @@ class ObjectWithDefaultedOptionalFields(UncheckedBaseModel): date: typing.Optional[dt.date] = None def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) diff --git a/generators/python/tests/utils/example_models/types/core/datetime_utils.py b/generators/python/tests/utils/example_models/types/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/generators/python/tests/utils/example_models/types/core/datetime_utils.py +++ b/generators/python/tests/utils/example_models/types/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/generators/python/tests/utils/example_models/types/core/pydantic_utilities.py b/generators/python/tests/utils/example_models/types/core/pydantic_utilities.py index 0b53853c101..68c1681d981 100644 --- a/generators/python/tests/utils/example_models/types/core/pydantic_utilities.py +++ b/generators/python/tests/utils/example_models/types/core/pydantic_utilities.py @@ -90,15 +90,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +119,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +160,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +180,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) # type: ignore # Pydantic v1 diff --git a/generators/python/tests/utils/example_models/types/core/serialization.py b/generators/python/tests/utils/example_models/types/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/generators/python/tests/utils/example_models/types/core/serialization.py +++ b/generators/python/tests/utils/example_models/types/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/generators/python/tests/utils/example_models/types/core/unchecked_base_model.py b/generators/python/tests/utils/example_models/types/core/unchecked_base_model.py index 401cc513bd1..5a639666364 100644 --- a/generators/python/tests/utils/example_models/types/core/unchecked_base_model.py +++ b/generators/python/tests/utils/example_models/types/core/unchecked_base_model.py @@ -35,7 +35,9 @@ def __init__(self, *, discriminant: str) -> None: class UncheckedBaseModel(UniversalBaseModel): if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -43,7 +45,9 @@ class Config: @classmethod def model_construct( - cls: typing.Type["Model"], _fields_set: typing.Optional[typing.Set[str]] = None, **values: typing.Any + cls: typing.Type["Model"], + _fields_set: typing.Optional[typing.Set[str]] = None, + **values: typing.Any, ) -> "Model": # Fallback construct function to the specified override below. return cls.construct(_fields_set=_fields_set, **values) @@ -52,7 +56,9 @@ def model_construct( # Implementation taken from: https://github.com/pydantic/pydantic/issues/1168#issuecomment-817742836 @classmethod def construct( - cls: typing.Type["Model"], _fields_set: typing.Optional[typing.Set[str]] = None, **values: typing.Any + cls: typing.Type["Model"], + _fields_set: typing.Optional[typing.Set[str]] = None, + **values: typing.Any, ) -> "Model": m = cls.__new__(cls) fields_values = {} @@ -68,7 +74,9 @@ def construct( # you should always use the NAME of the field to for field_values, etc. # because that's how the object is constructed from a pydantic perspective key = field.alias - if key is None or (key not in values and populate_by_name): # Added this to allow population by field name + if key is None or ( + key not in values and populate_by_name + ): # Added this to allow population by field name key = name if key in values: @@ -78,7 +86,9 @@ def construct( type_ = typing.cast(typing.Type, field.outer_type_) # type: ignore # Pydantic < v1.10.15 fields_values[name] = ( - construct_type(object_=values[key], type_=type_) if type_ is not None else values[key] + construct_type(object_=values[key], type_=type_) + if type_ is not None + else values[key] ) _fields_set.add(name) else: @@ -114,14 +124,18 @@ def construct( return m -def _convert_undiscriminated_union_type(union_type: typing.Type[typing.Any], object_: typing.Any) -> typing.Any: +def _convert_undiscriminated_union_type( + union_type: typing.Type[typing.Any], object_: typing.Any +) -> typing.Any: inner_types = get_args(union_type) if typing.Any in inner_types: return object_ for inner_type in inner_types: try: - if inspect.isclass(inner_type) and issubclass(inner_type, pydantic.BaseModel): + if inspect.isclass(inner_type) and issubclass( + inner_type, pydantic.BaseModel + ): # Attempt a validated parse until one works return parse_obj_as(inner_type, object_) except Exception: @@ -135,7 +149,9 @@ def _convert_undiscriminated_union_type(union_type: typing.Type[typing.Any], obj continue -def _convert_union_type(type_: typing.Type[typing.Any], object_: typing.Any) -> typing.Any: +def _convert_union_type( + type_: typing.Type[typing.Any], object_: typing.Any +) -> typing.Any: base_type = get_origin(type_) or type_ union_type = type_ if base_type == typing_extensions.Annotated: @@ -147,10 +163,15 @@ def _convert_union_type(type_: typing.Type[typing.Any], object_: typing.Any) -> # Cast to the correct type, based on the discriminant for inner_type in get_args(union_type): try: - objects_discriminant = getattr(object_, metadata.discriminant) + objects_discriminant = getattr( + object_, metadata.discriminant + ) except: objects_discriminant = object_[metadata.discriminant] - if inner_type.__fields__[metadata.discriminant].default == objects_discriminant: + if ( + inner_type.__fields__[metadata.discriminant].default + == objects_discriminant + ): return construct_type(object_=object_, type_=inner_type) except Exception: # Allow to fall through to our regular union handling @@ -158,7 +179,9 @@ def _convert_union_type(type_: typing.Type[typing.Any], object_: typing.Any) -> return _convert_undiscriminated_union_type(union_type, object_) -def construct_type(*, type_: typing.Type[typing.Any], object_: typing.Any) -> typing.Any: +def construct_type( + *, type_: typing.Type[typing.Any], object_: typing.Any +) -> typing.Any: """ Here we are essentially creating the same `construct` method in spirit as the above, but for all types, not just Pydantic models. @@ -171,7 +194,9 @@ def construct_type(*, type_: typing.Type[typing.Any], object_: typing.Any) -> ty base_type = get_origin(type_) or type_ is_annotated = base_type == typing_extensions.Annotated maybe_annotation_members = get_args(type_) - is_annotated_union = is_annotated and is_union(get_origin(maybe_annotation_members[0])) + is_annotated_union = is_annotated and is_union( + get_origin(maybe_annotation_members[0]) + ) if base_type == typing.Any: return object_ @@ -182,7 +207,9 @@ def construct_type(*, type_: typing.Type[typing.Any], object_: typing.Any) -> ty key_type, items_type = get_args(type_) d = { - construct_type(object_=key, type_=key_type): construct_type(object_=item, type_=items_type) + construct_type(object_=key, type_=key_type): construct_type( + object_=item, type_=items_type + ) for key, item in object_.items() } return d @@ -263,7 +290,9 @@ def _get_is_populate_by_name(model: typing.Type["Model"]) -> bool: # Pydantic V1 swapped the typing of __fields__'s values from ModelField to FieldInfo # And so we try to handle both V1 cases, as well as V2 (FieldInfo from model.model_fields) -def _get_model_fields(model: typing.Type["Model"]) -> typing.Mapping[str, PydanticField]: +def _get_model_fields( + model: typing.Type["Model"], +) -> typing.Mapping[str, PydanticField]: if IS_PYDANTIC_V2: return model.model_fields # type: ignore # Pydantic v2 else: diff --git a/generators/python/tests/utils/example_models/types/resources/types/circle.py b/generators/python/tests/utils/example_models/types/resources/types/circle.py index 28095b84b0e..02ed8b0be1b 100644 --- a/generators/python/tests/utils/example_models/types/resources/types/circle.py +++ b/generators/python/tests/utils/example_models/types/resources/types/circle.py @@ -12,7 +12,9 @@ class Circle(UncheckedBaseModel): radius: float if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/generators/python/tests/utils/example_models/types/resources/types/object_with_defaults.py b/generators/python/tests/utils/example_models/types/resources/types/object_with_defaults.py index 0a59546a07c..790fe57a01d 100644 --- a/generators/python/tests/utils/example_models/types/resources/types/object_with_defaults.py +++ b/generators/python/tests/utils/example_models/types/resources/types/object_with_defaults.py @@ -18,7 +18,9 @@ class ObjectWithDefaults(UncheckedBaseModel): required_string: str = "I neeeeeeeeeed this!" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/generators/python/tests/utils/example_models/types/resources/types/object_with_optional_field.py b/generators/python/tests/utils/example_models/types/resources/types/object_with_optional_field.py index a06ad184dda..5d8fce2bfd7 100644 --- a/generators/python/tests/utils/example_models/types/resources/types/object_with_optional_field.py +++ b/generators/python/tests/utils/example_models/types/resources/types/object_with_optional_field.py @@ -24,9 +24,13 @@ class ObjectWithOptionalField(UncheckedBaseModel): date: typing.Optional[dt.date] = None uuid_: typing.Optional[uuid.UUID] = pydantic.Field(alias="uuid", default=None) base_64: typing.Optional[str] = pydantic.Field(alias="base64", default=None) - list_: typing.Optional[typing.List[str]] = pydantic.Field(alias="list", default=None) + list_: typing.Optional[typing.List[str]] = pydantic.Field( + alias="list", default=None + ) set_: typing.Optional[typing.Set[str]] = pydantic.Field(alias="set", default=None) - map_: typing.Optional[typing.Dict[int, str]] = pydantic.Field(alias="map", default=None) + map_: typing.Optional[typing.Dict[int, str]] = pydantic.Field( + alias="map", default=None + ) enum: typing.Optional[Color] = None union: typing.Optional[Shape] = None second_union: typing.Optional[Shape] = None @@ -34,7 +38,9 @@ class ObjectWithOptionalField(UncheckedBaseModel): any: typing.Any if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/generators/python/tests/utils/example_models/types/resources/types/shape.py b/generators/python/tests/utils/example_models/types/resources/types/shape.py index f80a90eb153..9b58bbf8363 100644 --- a/generators/python/tests/utils/example_models/types/resources/types/shape.py +++ b/generators/python/tests/utils/example_models/types/resources/types/shape.py @@ -15,7 +15,9 @@ class Base(UncheckedBaseModel): id: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -27,7 +29,9 @@ class Shape_Circle(Base): radius: float if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -39,11 +43,15 @@ class Shape_Square(Base): length: float if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: extra = pydantic.Extra.allow -Shape = typing_extensions.Annotated[typing.Union[Shape_Circle, Shape_Square], UnionMetadata(discriminant="type")] +Shape = typing_extensions.Annotated[ + typing.Union[Shape_Circle, Shape_Square], UnionMetadata(discriminant="type") +] diff --git a/generators/python/tests/utils/example_models/types/resources/types/square.py b/generators/python/tests/utils/example_models/types/resources/types/square.py index 1ad1d91d3b8..bf9c48b1403 100644 --- a/generators/python/tests/utils/example_models/types/resources/types/square.py +++ b/generators/python/tests/utils/example_models/types/resources/types/square.py @@ -12,7 +12,9 @@ class Square(UncheckedBaseModel): length: float if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/generators/python/tests/utils/test_construct_type.py b/generators/python/tests/utils/test_construct_type.py index e3a2e9c9ad9..44dd3cfb904 100644 --- a/generators/python/tests/utils/test_construct_type.py +++ b/generators/python/tests/utils/test_construct_type.py @@ -1,6 +1,3 @@ - - - from datetime import datetime, date from typing import cast import uuid @@ -8,8 +5,15 @@ import pytest from core_utilities.sdk.unchecked_base_model import construct_type from tests.utils.example_models.types.resources.types.square import Square -from .example_models.manual_types.defaulted_object import ObjectWithDefaultedOptionalFields -from .example_models.types.resources.types import ObjectWithOptionalField, Circle, Shape_Square, Shape_Circle +from .example_models.manual_types.defaulted_object import ( + ObjectWithDefaultedOptionalFields, +) +from .example_models.types.resources.types import ( + ObjectWithOptionalField, + Circle, + Shape_Square, + Shape_Circle, +) def test_construct_valid() -> None: @@ -32,9 +36,12 @@ def test_construct_valid() -> None: "undiscriminated_union": {"id": "string2", "length": 6.7}, "enum": "red", "any": "something here", - "additional_field": "this here" + "additional_field": "this here", } - cast_response = cast(ObjectWithOptionalField, construct_type(type_=ObjectWithOptionalField, object_=response)) + cast_response = cast( + ObjectWithOptionalField, + construct_type(type_=ObjectWithOptionalField, object_=response), + ) assert cast_response.literal == "lit_one" assert cast_response.string == "circle" @@ -56,18 +63,27 @@ def test_construct_valid() -> None: square_expectation = Shape_Square(id="string", length=1.1) assert cast_response.union is not None assert cast_response.union.id == square_expectation.id - assert isinstance(cast_response.union, Shape_Square) and cast_response.union.length == square_expectation.length + assert ( + isinstance(cast_response.union, Shape_Square) + and cast_response.union.length == square_expectation.length + ) assert cast_response.union.type == square_expectation.type circle_expectation = Shape_Circle(id="another_string", radius=2.3) assert cast_response.second_union is not None assert cast_response.second_union.id == circle_expectation.id - assert isinstance(cast_response.second_union, Shape_Circle) and cast_response.second_union.radius == circle_expectation.radius + assert ( + isinstance(cast_response.second_union, Shape_Circle) + and cast_response.second_union.radius == circle_expectation.radius + ) assert cast_response.second_union.type == circle_expectation.type assert cast_response.undiscriminated_union is not None assert cast_response.undiscriminated_union.id == "string2" # type: ignore # Since this is not in the model mypy complains, but it's still fine - assert isinstance(cast_response.undiscriminated_union, Square) and cast_response.undiscriminated_union.length == 6.7 + assert ( + isinstance(cast_response.undiscriminated_union, Square) + and cast_response.undiscriminated_union.length == 6.7 + ) def test_construct_unset() -> None: @@ -88,9 +104,12 @@ def test_construct_unset() -> None: "union": {"type": "square", "id": "string", "length": 1.1}, "undiscriminated_union": {"id": "string2", "length": 6.7}, "enum": "red", - "any": "something here" + "any": "something here", } - cast_response = cast(ObjectWithOptionalField, construct_type(type_=ObjectWithOptionalField, object_=response)) + cast_response = cast( + ObjectWithOptionalField, + construct_type(type_=ObjectWithOptionalField, object_=response), + ) d = cast_response.dict(by_alias=True, exclude_unset=True) assert d == { @@ -110,9 +129,10 @@ def test_construct_unset() -> None: "union": {"type": "square", "id": "string", "length": 1.1}, "undiscriminated_union": {"id": "string2", "length": 6.7}, "enum": "red", - "any": "something here" + "any": "something here", } + def test_construct_invalid() -> None: response = { "literal": "something_else", @@ -130,9 +150,12 @@ def test_construct_invalid() -> None: "map": "hello world", "union": {"id": "123", "length": 1.1}, "undiscriminated_union": {"id": "123", "length": "fifteen"}, - "enum": "bread" + "enum": "bread", } - cast_response = cast(ObjectWithOptionalField, construct_type(type_=ObjectWithOptionalField, object_=response)) + cast_response = cast( + ObjectWithOptionalField, + construct_type(type_=ObjectWithOptionalField, object_=response), + ) assert cast_response.literal == "something_else" assert cast_response.string == 1000000 @@ -149,7 +172,7 @@ def test_construct_invalid() -> None: assert cast_response.map_ == "hello world" assert cast_response.enum == "bread" assert cast_response.any is None - + shape_expectation = Shape_Square(id="123", length=1.1) assert cast_response.union is not None assert cast_response.union.id == shape_expectation.id @@ -164,7 +187,10 @@ def test_construct_invalid() -> None: def test_construct_defaults() -> None: response: object = {} - cast_response = cast(ObjectWithDefaultedOptionalFields, construct_type(type_=ObjectWithDefaultedOptionalFields, object_=response)) + cast_response = cast( + ObjectWithDefaultedOptionalFields, + construct_type(type_=ObjectWithDefaultedOptionalFields, object_=response), + ) assert cast_response.string is None assert cast_response.integer is None @@ -177,10 +203,13 @@ def test_construct_defaults() -> None: def test_construct_defaults_unset() -> None: response: object = {} - cast_response = cast(ObjectWithDefaultedOptionalFields, construct_type(type_=ObjectWithDefaultedOptionalFields, object_=response)) + cast_response = cast( + ObjectWithDefaultedOptionalFields, + construct_type(type_=ObjectWithDefaultedOptionalFields, object_=response), + ) d = cast_response.dict(by_alias=True, exclude_unset=True) - assert d == {'bool': True, 'literal': 'lit_one', 'long': 200000} + assert d == {"bool": True, "literal": "lit_one", "long": 200000} def test_construct_primitives() -> None: @@ -190,12 +219,16 @@ def test_construct_primitives() -> None: assert cast_response_str == response_str response_float = 1.1 - cast_response_float = cast(float, construct_type(type_=float, object_=response_float)) + cast_response_float = cast( + float, construct_type(type_=float, object_=response_float) + ) assert cast_response_float == response_float response_datetime = "2024-01-15T09:30:00Z" - cast_response_datetime = cast(datetime, construct_type(type_=datetime, object_=response_datetime)) + cast_response_datetime = cast( + datetime, construct_type(type_=datetime, object_=response_datetime) + ) assert type(cast_response_datetime) == datetime diff --git a/generators/python/tests/utils/test_defaults.py b/generators/python/tests/utils/test_defaults.py index 9fa1966528f..14b4a6523e7 100644 --- a/generators/python/tests/utils/test_defaults.py +++ b/generators/python/tests/utils/test_defaults.py @@ -1,17 +1,18 @@ -from tests.utils.example_models.types.resources.types.object_with_defaults import ObjectWithDefaults +from tests.utils.example_models.types.resources.types.object_with_defaults import ( + ObjectWithDefaults, +) def test_defaulted_object() -> None: obj_with_none = ObjectWithDefaults( - decimal=None, - string=None, - required_string="something else" + decimal=None, string=None, required_string="something else" ) assert obj_with_none.decimal is None assert obj_with_none.string is None assert obj_with_none.required_string is "something else" + def test_defaulted_object_with_defaults() -> None: obj_with_defaults = ObjectWithDefaults() @@ -19,13 +20,12 @@ def test_defaulted_object_with_defaults() -> None: assert obj_with_defaults.string == "here's a sentence!" assert obj_with_defaults.required_string == "I neeeeeeeeeed this!" + def test_with_non_none_setting() -> None: obj_with_defaults = ObjectWithDefaults( - decimal=3.14, - string="hello", - required_string="something else" + decimal=3.14, string="hello", required_string="something else" ) assert obj_with_defaults.decimal == 3.14 assert obj_with_defaults.string == "hello" - assert obj_with_defaults.required_string == "something else" \ No newline at end of file + assert obj_with_defaults.required_string == "something else" diff --git a/generators/python/tests/utils/test_http_client.py b/generators/python/tests/utils/test_http_client.py index 58feee97c16..c07954aec3b 100644 --- a/generators/python/tests/utils/test_http_client.py +++ b/generators/python/tests/utils/test_http_client.py @@ -1,15 +1,14 @@ from core_utilities.sdk.http_client import get_request_body from core_utilities.sdk.request_options import RequestOptions + def get_request_options() -> RequestOptions: return {"additional_body_parameters": {"see you": "later"}} + def test_get_json_request_body() -> None: json_body, data_body = get_request_body( - json={"hello": "world"}, - data=None, - request_options=None, - omit=None + json={"hello": "world"}, data=None, request_options=None, omit=None ) assert json_body == {"hello": "world"} assert data_body is None @@ -18,18 +17,16 @@ def test_get_json_request_body() -> None: json={"goodbye": "world"}, data=None, request_options=get_request_options(), - omit=None + omit=None, ) assert json_body_extras == {"goodbye": "world", "see you": "later"} assert data_body_extras is None + def test_get_files_request_body() -> None: json_body, data_body = get_request_body( - json=None, - data={"hello": "world"}, - request_options=None, - omit=None + json=None, data={"hello": "world"}, request_options=None, omit=None ) assert data_body == {"hello": "world"} assert json_body is None @@ -38,27 +35,22 @@ def test_get_files_request_body() -> None: json=None, data={"goodbye": "world"}, request_options=get_request_options(), - omit=None + omit=None, ) assert data_body_extras == {"goodbye": "world", "see you": "later"} assert json_body_extras is None + def test_get_none_request_body() -> None: json_body, data_body = get_request_body( - json=None, - data=None, - request_options=None, - omit=None + json=None, data=None, request_options=None, omit=None ) assert data_body is None assert json_body is None json_body_extras, data_body_extras = get_request_body( - json=None, - data=None, - request_options=get_request_options(), - omit=None + json=None, data=None, request_options=get_request_options(), omit=None ) assert json_body_extras == {"see you": "later"} diff --git a/generators/python/tests/utils/test_query_encoding.py b/generators/python/tests/utils/test_query_encoding.py index 903fb25be2d..75522d2c909 100644 --- a/generators/python/tests/utils/test_query_encoding.py +++ b/generators/python/tests/utils/test_query_encoding.py @@ -1,11 +1,21 @@ - from core_utilities.sdk.query_encoder import encode_query def test_query_encoding() -> None: - assert encode_query({"hello world": "hello world"}) == {"hello world": "hello world"} - assert encode_query({"hello_world": {"hello" : "world"}}) == {"hello_world[hello]": "world"} - assert encode_query({"hello_world": {"hello" : {"world" : "today"}, "test": "this"}, "hi": "there"}) == {"hello_world[hello][world]": "today", "hello_world[test]": "this", "hi": "there"} + assert encode_query({"hello world": "hello world"}) == { + "hello world": "hello world" + } + assert encode_query({"hello_world": {"hello": "world"}}) == { + "hello_world[hello]": "world" + } + assert encode_query( + {"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"} + ) == { + "hello_world[hello][world]": "today", + "hello_world[test]": "this", + "hi": "there", + } + def test_encode_query_with_none() -> None: encoded = encode_query(None) diff --git a/generators/python/tests/utils/test_serialization.py b/generators/python/tests/utils/test_serialization.py index bf337a34fb9..a676e4b00e6 100644 --- a/generators/python/tests/utils/test_serialization.py +++ b/generators/python/tests/utils/test_serialization.py @@ -1,41 +1,84 @@ from typing import List, Any -from .typeddict_models.types.core.serialization import convert_and_respect_annotation_metadata +from .typeddict_models.types.core.serialization import ( + convert_and_respect_annotation_metadata, +) from .typeddict_models.types import ShapeParams, ObjectWithOptionalFieldParams UNION_TEST: ShapeParams = {"radius_measurement": 1.0, "shape_type": "circle", "id": "1"} -UNION_TEST_CONVERTED = { - "shapeType": "circle", - "radiusMeasurement": 1.0, - "id": "1" -} +UNION_TEST_CONVERTED = {"shapeType": "circle", "radiusMeasurement": 1.0, "id": "1"} + def test_convert_and_respect_annotation_metadata() -> None: - data: ObjectWithOptionalFieldParams = {"string": "string", "long_": 12345, "bool_": True, "literal": "lit_one", "any": "any"} + data: ObjectWithOptionalFieldParams = { + "string": "string", + "long_": 12345, + "bool_": True, + "literal": "lit_one", + "any": "any", + } converted = convert_and_respect_annotation_metadata( - object_=data, - annotation=ObjectWithOptionalFieldParams + object_=data, annotation=ObjectWithOptionalFieldParams ) - assert converted == {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"} + assert converted == { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + } + def test_convert_and_respect_annotation_metadata_in_list() -> None: - data: List[ObjectWithOptionalFieldParams] = [{"string": "string", "long_": 12345, "bool_": True, "literal": "lit_one", "any": "any"}, {"string": "another string", "long_": 67890, "list_": [], "literal": "lit_one", "any": "any"}] + data: List[ObjectWithOptionalFieldParams] = [ + { + "string": "string", + "long_": 12345, + "bool_": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long_": 67890, + "list_": [], + "literal": "lit_one", + "any": "any", + }, + ] converted = convert_and_respect_annotation_metadata( - object_=data, - annotation=List[ObjectWithOptionalFieldParams] + object_=data, annotation=List[ObjectWithOptionalFieldParams] ) assert converted == [ - {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long": 67890, "list": [], "literal": "lit_one", "any": "any"} + { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long": 67890, + "list": [], + "literal": "lit_one", + "any": "any", + }, ] + def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: - data: ObjectWithOptionalFieldParams = {"string": "string", "long_": 12345, "union": UNION_TEST, "literal": "lit_one", "any": "any"} + data: ObjectWithOptionalFieldParams = { + "string": "string", + "long_": 12345, + "union": UNION_TEST, + "literal": "lit_one", + "any": "any", + } converted = convert_and_respect_annotation_metadata( - object_=data, - annotation=ObjectWithOptionalFieldParams + object_=data, annotation=ObjectWithOptionalFieldParams ) assert converted == { @@ -43,21 +86,21 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: "long": 12345, "union": UNION_TEST_CONVERTED, "literal": "lit_one", - "any": "any" + "any": "any", } + def test_convert_and_respect_annotation_metadata_in_union() -> None: converted = convert_and_respect_annotation_metadata( - object_=UNION_TEST, - annotation=ShapeParams + object_=UNION_TEST, annotation=ShapeParams ) assert converted == UNION_TEST_CONVERTED + def test_convert_and_respect_annotation_metadata_with_empty_object() -> None: data: Any = {} converted = convert_and_respect_annotation_metadata( - object_=data, - annotation=ShapeParams + object_=data, annotation=ShapeParams ) - assert converted == data \ No newline at end of file + assert converted == data diff --git a/generators/python/tests/utils/typeddict_models/types/core/datetime_utils.py b/generators/python/tests/utils/typeddict_models/types/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/generators/python/tests/utils/typeddict_models/types/core/datetime_utils.py +++ b/generators/python/tests/utils/typeddict_models/types/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/generators/python/tests/utils/typeddict_models/types/core/pydantic_utilities.py b/generators/python/tests/utils/typeddict_models/types/core/pydantic_utilities.py index 203567d199c..68c1681d981 100644 --- a/generators/python/tests/utils/typeddict_models/types/core/pydantic_utilities.py +++ b/generators/python/tests/utils/typeddict_models/types/core/pydantic_utilities.py @@ -90,15 +90,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +119,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +160,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,14 +180,18 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: - wrapped_func = pydantic.validator(field_name, pre=pre)(func) # type: ignore # Pydantic v1 + wrapped_func = pydantic.validator(field_name, pre=pre)(func) # type: ignore # Pydantic v1 return wrapped_func(*args, **kwargs) diff --git a/generators/python/tests/utils/typeddict_models/types/core/serialization.py b/generators/python/tests/utils/typeddict_models/types/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/generators/python/tests/utils/typeddict_models/types/core/serialization.py +++ b/generators/python/tests/utils/typeddict_models/types/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/generators/python/tests/utils/typeddict_models/types/core/unchecked_base_model.py b/generators/python/tests/utils/typeddict_models/types/core/unchecked_base_model.py index 401cc513bd1..5a639666364 100644 --- a/generators/python/tests/utils/typeddict_models/types/core/unchecked_base_model.py +++ b/generators/python/tests/utils/typeddict_models/types/core/unchecked_base_model.py @@ -35,7 +35,9 @@ def __init__(self, *, discriminant: str) -> None: class UncheckedBaseModel(UniversalBaseModel): if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -43,7 +45,9 @@ class Config: @classmethod def model_construct( - cls: typing.Type["Model"], _fields_set: typing.Optional[typing.Set[str]] = None, **values: typing.Any + cls: typing.Type["Model"], + _fields_set: typing.Optional[typing.Set[str]] = None, + **values: typing.Any, ) -> "Model": # Fallback construct function to the specified override below. return cls.construct(_fields_set=_fields_set, **values) @@ -52,7 +56,9 @@ def model_construct( # Implementation taken from: https://github.com/pydantic/pydantic/issues/1168#issuecomment-817742836 @classmethod def construct( - cls: typing.Type["Model"], _fields_set: typing.Optional[typing.Set[str]] = None, **values: typing.Any + cls: typing.Type["Model"], + _fields_set: typing.Optional[typing.Set[str]] = None, + **values: typing.Any, ) -> "Model": m = cls.__new__(cls) fields_values = {} @@ -68,7 +74,9 @@ def construct( # you should always use the NAME of the field to for field_values, etc. # because that's how the object is constructed from a pydantic perspective key = field.alias - if key is None or (key not in values and populate_by_name): # Added this to allow population by field name + if key is None or ( + key not in values and populate_by_name + ): # Added this to allow population by field name key = name if key in values: @@ -78,7 +86,9 @@ def construct( type_ = typing.cast(typing.Type, field.outer_type_) # type: ignore # Pydantic < v1.10.15 fields_values[name] = ( - construct_type(object_=values[key], type_=type_) if type_ is not None else values[key] + construct_type(object_=values[key], type_=type_) + if type_ is not None + else values[key] ) _fields_set.add(name) else: @@ -114,14 +124,18 @@ def construct( return m -def _convert_undiscriminated_union_type(union_type: typing.Type[typing.Any], object_: typing.Any) -> typing.Any: +def _convert_undiscriminated_union_type( + union_type: typing.Type[typing.Any], object_: typing.Any +) -> typing.Any: inner_types = get_args(union_type) if typing.Any in inner_types: return object_ for inner_type in inner_types: try: - if inspect.isclass(inner_type) and issubclass(inner_type, pydantic.BaseModel): + if inspect.isclass(inner_type) and issubclass( + inner_type, pydantic.BaseModel + ): # Attempt a validated parse until one works return parse_obj_as(inner_type, object_) except Exception: @@ -135,7 +149,9 @@ def _convert_undiscriminated_union_type(union_type: typing.Type[typing.Any], obj continue -def _convert_union_type(type_: typing.Type[typing.Any], object_: typing.Any) -> typing.Any: +def _convert_union_type( + type_: typing.Type[typing.Any], object_: typing.Any +) -> typing.Any: base_type = get_origin(type_) or type_ union_type = type_ if base_type == typing_extensions.Annotated: @@ -147,10 +163,15 @@ def _convert_union_type(type_: typing.Type[typing.Any], object_: typing.Any) -> # Cast to the correct type, based on the discriminant for inner_type in get_args(union_type): try: - objects_discriminant = getattr(object_, metadata.discriminant) + objects_discriminant = getattr( + object_, metadata.discriminant + ) except: objects_discriminant = object_[metadata.discriminant] - if inner_type.__fields__[metadata.discriminant].default == objects_discriminant: + if ( + inner_type.__fields__[metadata.discriminant].default + == objects_discriminant + ): return construct_type(object_=object_, type_=inner_type) except Exception: # Allow to fall through to our regular union handling @@ -158,7 +179,9 @@ def _convert_union_type(type_: typing.Type[typing.Any], object_: typing.Any) -> return _convert_undiscriminated_union_type(union_type, object_) -def construct_type(*, type_: typing.Type[typing.Any], object_: typing.Any) -> typing.Any: +def construct_type( + *, type_: typing.Type[typing.Any], object_: typing.Any +) -> typing.Any: """ Here we are essentially creating the same `construct` method in spirit as the above, but for all types, not just Pydantic models. @@ -171,7 +194,9 @@ def construct_type(*, type_: typing.Type[typing.Any], object_: typing.Any) -> ty base_type = get_origin(type_) or type_ is_annotated = base_type == typing_extensions.Annotated maybe_annotation_members = get_args(type_) - is_annotated_union = is_annotated and is_union(get_origin(maybe_annotation_members[0])) + is_annotated_union = is_annotated and is_union( + get_origin(maybe_annotation_members[0]) + ) if base_type == typing.Any: return object_ @@ -182,7 +207,9 @@ def construct_type(*, type_: typing.Type[typing.Any], object_: typing.Any) -> ty key_type, items_type = get_args(type_) d = { - construct_type(object_=key, type_=key_type): construct_type(object_=item, type_=items_type) + construct_type(object_=key, type_=key_type): construct_type( + object_=item, type_=items_type + ) for key, item in object_.items() } return d @@ -263,7 +290,9 @@ def _get_is_populate_by_name(model: typing.Type["Model"]) -> bool: # Pydantic V1 swapped the typing of __fields__'s values from ModelField to FieldInfo # And so we try to handle both V1 cases, as well as V2 (FieldInfo from model.model_fields) -def _get_model_fields(model: typing.Type["Model"]) -> typing.Mapping[str, PydanticField]: +def _get_model_fields( + model: typing.Type["Model"], +) -> typing.Mapping[str, PydanticField]: if IS_PYDANTIC_V2: return model.model_fields # type: ignore # Pydantic v2 else: diff --git a/generators/python/tests/utils/typeddict_models/types/resources/types/circle.py b/generators/python/tests/utils/typeddict_models/types/resources/types/circle.py index 6e01c6088eb..b5413ba33d8 100644 --- a/generators/python/tests/utils/typeddict_models/types/resources/types/circle.py +++ b/generators/python/tests/utils/typeddict_models/types/resources/types/circle.py @@ -12,7 +12,9 @@ class Circle(UncheckedBaseModel): radius_measurement: float = pydantic.Field(alias="radiusMeasurement") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/generators/python/tests/utils/typeddict_models/types/resources/types/object_with_defaults.py b/generators/python/tests/utils/typeddict_models/types/resources/types/object_with_defaults.py index 0a59546a07c..790fe57a01d 100644 --- a/generators/python/tests/utils/typeddict_models/types/resources/types/object_with_defaults.py +++ b/generators/python/tests/utils/typeddict_models/types/resources/types/object_with_defaults.py @@ -18,7 +18,9 @@ class ObjectWithDefaults(UncheckedBaseModel): required_string: str = "I neeeeeeeeeed this!" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/generators/python/tests/utils/typeddict_models/types/resources/types/object_with_optional_field.py b/generators/python/tests/utils/typeddict_models/types/resources/types/object_with_optional_field.py index a06ad184dda..5d8fce2bfd7 100644 --- a/generators/python/tests/utils/typeddict_models/types/resources/types/object_with_optional_field.py +++ b/generators/python/tests/utils/typeddict_models/types/resources/types/object_with_optional_field.py @@ -24,9 +24,13 @@ class ObjectWithOptionalField(UncheckedBaseModel): date: typing.Optional[dt.date] = None uuid_: typing.Optional[uuid.UUID] = pydantic.Field(alias="uuid", default=None) base_64: typing.Optional[str] = pydantic.Field(alias="base64", default=None) - list_: typing.Optional[typing.List[str]] = pydantic.Field(alias="list", default=None) + list_: typing.Optional[typing.List[str]] = pydantic.Field( + alias="list", default=None + ) set_: typing.Optional[typing.Set[str]] = pydantic.Field(alias="set", default=None) - map_: typing.Optional[typing.Dict[int, str]] = pydantic.Field(alias="map", default=None) + map_: typing.Optional[typing.Dict[int, str]] = pydantic.Field( + alias="map", default=None + ) enum: typing.Optional[Color] = None union: typing.Optional[Shape] = None second_union: typing.Optional[Shape] = None @@ -34,7 +38,9 @@ class ObjectWithOptionalField(UncheckedBaseModel): any: typing.Any if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/generators/python/tests/utils/typeddict_models/types/resources/types/requests/circle.py b/generators/python/tests/utils/typeddict_models/types/resources/types/requests/circle.py index 32be504e636..060b3b575fb 100644 --- a/generators/python/tests/utils/typeddict_models/types/resources/types/requests/circle.py +++ b/generators/python/tests/utils/typeddict_models/types/resources/types/requests/circle.py @@ -6,4 +6,6 @@ class CircleParams(typing_extensions.TypedDict): - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] diff --git a/generators/python/tests/utils/typeddict_models/types/resources/types/requests/object_with_optional_field.py b/generators/python/tests/utils/typeddict_models/types/resources/types/requests/object_with_optional_field.py index 8c0c9589f10..86b3f54ac59 100644 --- a/generators/python/tests/utils/typeddict_models/types/resources/types/requests/object_with_optional_field.py +++ b/generators/python/tests/utils/typeddict_models/types/resources/types/requests/object_with_optional_field.py @@ -16,16 +16,30 @@ class ObjectWithOptionalFieldParams(typing_extensions.TypedDict): literal: typing.Literal["lit_one"] string: typing_extensions.NotRequired[str] integer: typing_extensions.NotRequired[int] - long_: typing_extensions.NotRequired[typing_extensions.Annotated[int, FieldMetadata(alias="long")]] + long_: typing_extensions.NotRequired[ + typing_extensions.Annotated[int, FieldMetadata(alias="long")] + ] double: typing_extensions.NotRequired[float] - bool_: typing_extensions.NotRequired[typing_extensions.Annotated[bool, FieldMetadata(alias="bool")]] + bool_: typing_extensions.NotRequired[ + typing_extensions.Annotated[bool, FieldMetadata(alias="bool")] + ] datetime: typing_extensions.NotRequired[dt.datetime] date: typing_extensions.NotRequired[dt.date] - uuid_: typing_extensions.NotRequired[typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")]] - base_64: typing_extensions.NotRequired[typing_extensions.Annotated[str, FieldMetadata(alias="base64")]] - list_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")]] - set_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")]] - map_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")]] + uuid_: typing_extensions.NotRequired[ + typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")] + ] + base_64: typing_extensions.NotRequired[ + typing_extensions.Annotated[str, FieldMetadata(alias="base64")] + ] + list_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")] + ] + set_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")] + ] + map_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")] + ] enum: typing_extensions.NotRequired[Color] union: typing_extensions.NotRequired[ShapeParams] second_union: typing_extensions.NotRequired[ShapeParams] diff --git a/generators/python/tests/utils/typeddict_models/types/resources/types/requests/shape.py b/generators/python/tests/utils/typeddict_models/types/resources/types/requests/shape.py index e4e476a9126..9014a803f50 100644 --- a/generators/python/tests/utils/typeddict_models/types/resources/types/requests/shape.py +++ b/generators/python/tests/utils/typeddict_models/types/resources/types/requests/shape.py @@ -14,13 +14,21 @@ class Base(typing_extensions.TypedDict): class Shape_CircleParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["circle"], FieldMetadata(alias="shapeType")] - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["circle"], FieldMetadata(alias="shapeType") + ] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] class Shape_SquareParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["square"], FieldMetadata(alias="shapeType")] - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["square"], FieldMetadata(alias="shapeType") + ] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] ShapeParams = typing.Union[Shape_CircleParams, Shape_SquareParams] diff --git a/generators/python/tests/utils/typeddict_models/types/resources/types/requests/square.py b/generators/python/tests/utils/typeddict_models/types/resources/types/requests/square.py index 1f95b1c8b6f..ab71d01715d 100644 --- a/generators/python/tests/utils/typeddict_models/types/resources/types/requests/square.py +++ b/generators/python/tests/utils/typeddict_models/types/resources/types/requests/square.py @@ -6,4 +6,6 @@ class SquareParams(typing_extensions.TypedDict): - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] diff --git a/generators/python/tests/utils/typeddict_models/types/resources/types/shape.py b/generators/python/tests/utils/typeddict_models/types/resources/types/shape.py index 7eed13b1831..07f01cb2379 100644 --- a/generators/python/tests/utils/typeddict_models/types/resources/types/shape.py +++ b/generators/python/tests/utils/typeddict_models/types/resources/types/shape.py @@ -15,7 +15,9 @@ class Base(UncheckedBaseModel): id: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -23,11 +25,15 @@ class Config: class Shape_Circle(Base): - shape_type: typing.Literal["circle"] = pydantic.Field(alias="shapeType", default="circle") + shape_type: typing.Literal["circle"] = pydantic.Field( + alias="shapeType", default="circle" + ) radius_measurement: float = pydantic.Field(alias="radiusMeasurement") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -35,15 +41,21 @@ class Config: class Shape_Square(Base): - shape_type: typing.Literal["square"] = pydantic.Field(alias="shapeType", default="square") + shape_type: typing.Literal["square"] = pydantic.Field( + alias="shapeType", default="square" + ) length_measurement: float = pydantic.Field(alias="lengthMeasurement") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: extra = pydantic.Extra.allow -Shape = typing_extensions.Annotated[typing.Union[Shape_Circle, Shape_Square], UnionMetadata(discriminant="shapeType")] +Shape = typing_extensions.Annotated[ + typing.Union[Shape_Circle, Shape_Square], UnionMetadata(discriminant="shapeType") +] diff --git a/generators/python/tests/utils/typeddict_models/types/resources/types/square.py b/generators/python/tests/utils/typeddict_models/types/resources/types/square.py index e8a4cc61647..79d691cc08b 100644 --- a/generators/python/tests/utils/typeddict_models/types/resources/types/square.py +++ b/generators/python/tests/utils/typeddict_models/types/resources/types/square.py @@ -12,7 +12,9 @@ class Square(UncheckedBaseModel): length_measurement: float = pydantic.Field(alias="lengthMeasurement") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/alias-extends/core/abstract_fern_service.py b/seed/fastapi/alias-extends/core/abstract_fern_service.py index da7c8dc49c4..9966b4876da 100644 --- a/seed/fastapi/alias-extends/core/abstract_fern_service.py +++ b/seed/fastapi/alias-extends/core/abstract_fern_service.py @@ -7,5 +7,4 @@ class AbstractFernService(abc.ABC): @classmethod - def _init_fern(cls, router: fastapi.APIRouter) -> None: - ... + def _init_fern(cls, router: fastapi.APIRouter) -> None: ... diff --git a/seed/fastapi/alias-extends/core/datetime_utils.py b/seed/fastapi/alias-extends/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/fastapi/alias-extends/core/datetime_utils.py +++ b/seed/fastapi/alias-extends/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/fastapi/alias-extends/core/exceptions/__init__.py b/seed/fastapi/alias-extends/core/exceptions/__init__.py index 297d6e06f5f..dae4b8980c1 100644 --- a/seed/fastapi/alias-extends/core/exceptions/__init__.py +++ b/seed/fastapi/alias-extends/core/exceptions/__init__.py @@ -1,7 +1,11 @@ # This file was auto-generated by Fern from our API Definition. from .fern_http_exception import FernHTTPException -from .handlers import default_exception_handler, fern_http_exception_handler, http_exception_handler +from .handlers import ( + default_exception_handler, + fern_http_exception_handler, + http_exception_handler, +) from .unauthorized import UnauthorizedException __all__ = [ diff --git a/seed/fastapi/alias-extends/core/exceptions/fern_http_exception.py b/seed/fastapi/alias-extends/core/exceptions/fern_http_exception.py index bdf03862487..81610359a7f 100644 --- a/seed/fastapi/alias-extends/core/exceptions/fern_http_exception.py +++ b/seed/fastapi/alias-extends/core/exceptions/fern_http_exception.py @@ -1,14 +1,16 @@ # This file was auto-generated by Fern from our API Definition. import abc -import typing - import fastapi +import typing class FernHTTPException(abc.ABC, fastapi.HTTPException): def __init__( - self, status_code: int, name: typing.Optional[str] = None, content: typing.Optional[typing.Any] = None + self, + status_code: int, + name: typing.Optional[str] = None, + content: typing.Optional[typing.Any] = None, ): super().__init__(status_code=status_code) self.name = name @@ -17,4 +19,6 @@ def __init__( def to_json_response(self) -> fastapi.responses.JSONResponse: content = fastapi.encoders.jsonable_encoder(self.content, exclude_none=True) - return fastapi.responses.JSONResponse(content=content, status_code=self.status_code) + return fastapi.responses.JSONResponse( + content=content, status_code=self.status_code + ) diff --git a/seed/fastapi/alias-extends/core/exceptions/handlers.py b/seed/fastapi/alias-extends/core/exceptions/handlers.py index 6d8c4155c5a..ae1c2741f06 100644 --- a/seed/fastapi/alias-extends/core/exceptions/handlers.py +++ b/seed/fastapi/alias-extends/core/exceptions/handlers.py @@ -2,32 +2,49 @@ import logging -import fastapi import starlette import starlette.exceptions +import fastapi + from .fern_http_exception import FernHTTPException def fern_http_exception_handler( - request: fastapi.requests.Request, exc: FernHTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: FernHTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) return exc.to_json_response() def http_exception_handler( - request: fastapi.requests.Request, exc: starlette.exceptions.HTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: starlette.exceptions.HTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=exc.status_code, content=exc.detail).to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=exc.status_code, content=exc.detail + ).to_json_response() def default_exception_handler( - request: fastapi.requests.Request, exc: Exception, skip_log: bool = False + request: fastapi.requests.Request, + exc: Exception, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=500, content="Internal Server Error").to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=500, content="Internal Server Error" + ).to_json_response() diff --git a/seed/fastapi/alias-extends/core/pydantic_utilities.py b/seed/fastapi/alias-extends/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/fastapi/alias-extends/core/pydantic_utilities.py +++ b/seed/fastapi/alias-extends/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/fastapi/alias-extends/core/route_args.py b/seed/fastapi/alias-extends/core/route_args.py index 4228e2fe05d..bd940bf4ddd 100644 --- a/seed/fastapi/alias-extends/core/route_args.py +++ b/seed/fastapi/alias-extends/core/route_args.py @@ -20,9 +20,15 @@ class RouteArgs(typing_extensions.TypedDict): DEFAULT_ROUTE_ARGS = RouteArgs(openapi_extra=None, tags=None, include_in_schema=True) -def get_route_args(endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str) -> RouteArgs: - unwrapped = inspect.unwrap(endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY))) - route_args = typing.cast(RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS)) +def get_route_args( + endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str +) -> RouteArgs: + unwrapped = inspect.unwrap( + endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY)) + ) + route_args = typing.cast( + RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS) + ) if route_args["tags"] is None: return RouteArgs( openapi_extra=route_args["openapi_extra"], @@ -56,7 +62,11 @@ def decorator(endpoint_function: T) -> T: setattr( endpoint_function, FERN_CONFIG_KEY, - RouteArgs(openapi_extra=openapi_extra, tags=tags, include_in_schema=include_in_schema), + RouteArgs( + openapi_extra=openapi_extra, + tags=tags, + include_in_schema=include_in_schema, + ), ) return endpoint_function diff --git a/seed/fastapi/alias-extends/register.py b/seed/fastapi/alias-extends/register.py index 3b90d0c034f..ce9f38fa412 100644 --- a/seed/fastapi/alias-extends/register.py +++ b/seed/fastapi/alias-extends/register.py @@ -1,31 +1,33 @@ # This file was auto-generated by Fern from our API Definition. -import glob -import importlib -import os -import types -import typing - import fastapi -import starlette.exceptions +from .service.service import AbstractRootService +import typing from fastapi import params - -from .core.abstract_fern_service import AbstractFernService -from .core.exceptions import default_exception_handler, fern_http_exception_handler, http_exception_handler from .core.exceptions.fern_http_exception import FernHTTPException -from .service.service import AbstractRootService +from .core.exceptions import fern_http_exception_handler +import starlette.exceptions +from .core.exceptions import http_exception_handler +from .core.exceptions import default_exception_handler +from .core.abstract_fern_service import AbstractFernService +import types +import os +import glob +import importlib def register( _app: fastapi.FastAPI, *, root: AbstractRootService, - dependencies: typing.Optional[typing.Sequence[params.Depends]] = None + dependencies: typing.Optional[typing.Sequence[params.Depends]] = None, ) -> None: _app.include_router(__register_service(root), dependencies=dependencies) _app.add_exception_handler(FernHTTPException, fern_http_exception_handler) # type: ignore - _app.add_exception_handler(starlette.exceptions.HTTPException, http_exception_handler) # type: ignore + _app.add_exception_handler( + starlette.exceptions.HTTPException, http_exception_handler + ) # type: ignore _app.add_exception_handler(Exception, default_exception_handler) # type: ignore @@ -37,7 +39,9 @@ def __register_service(service: AbstractFernService) -> fastapi.APIRouter: def register_validators(module: types.ModuleType) -> None: validators_directory: str = os.path.dirname(module.__file__) # type: ignore - for path in glob.glob(os.path.join(validators_directory, "**/*.py"), recursive=True): + for path in glob.glob( + os.path.join(validators_directory, "**/*.py"), recursive=True + ): if os.path.isfile(path): relative_path = os.path.relpath(path, start=validators_directory) module_path = ".".join([module.__name__] + relative_path[:-3].split("/")) diff --git a/seed/fastapi/alias-extends/service/inlined_child_request.py b/seed/fastapi/alias-extends/service/inlined_child_request.py index 3de9cdb0bcc..bb64c51d36e 100644 --- a/seed/fastapi/alias-extends/service/inlined_child_request.py +++ b/seed/fastapi/alias-extends/service/inlined_child_request.py @@ -1,18 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ..types.alias_type import AliasType +from ..core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ..core.pydantic_utilities import IS_PYDANTIC_V2 -from ..types.alias_type import AliasType - class InlinedChildRequest(AliasType): child: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/alias-extends/service/service.py b/seed/fastapi/alias-extends/service/service.py index 5a420d73d91..521cc3e39e8 100644 --- a/seed/fastapi/alias-extends/service/service.py +++ b/seed/fastapi/alias-extends/service/service.py @@ -1,18 +1,16 @@ # This file was auto-generated by Fern from our API Definition. +from ..core.abstract_fern_service import AbstractFernService +from .inlined_child_request import InlinedChildRequest import abc -import functools +import fastapi import inspect -import logging import typing - -import fastapi -import starlette - -from ..core.abstract_fern_service import AbstractFernService from ..core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools +import starlette from ..core.route_args import get_route_args -from .inlined_child_request import InlinedChildRequest class AbstractRootService(AbstractFernService): @@ -25,8 +23,7 @@ class AbstractRootService(AbstractFernService): """ @abc.abstractmethod - def extended_inline_request_body(self, *, body: InlinedChildRequest) -> None: - ... + def extended_inline_request_body(self, *, body: InlinedChildRequest) -> None: ... """ Below are internal methods used by Fern to register your implementation. @@ -41,14 +38,20 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_extended_inline_request_body(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.extended_inline_request_body) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) else: new_parameters.append(parameter) - setattr(cls.extended_inline_request_body, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.extended_inline_request_body, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.extended_inline_request_body) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> None: diff --git a/seed/fastapi/alias-extends/types/child.py b/seed/fastapi/alias-extends/types/child.py index 606855407b2..9ab4e88a063 100644 --- a/seed/fastapi/alias-extends/types/child.py +++ b/seed/fastapi/alias-extends/types/child.py @@ -1,12 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from .parent import Parent +from ..core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ..core.pydantic_utilities import IS_PYDANTIC_V2 -from .parent import Parent - class Child(Parent): """ @@ -23,7 +21,9 @@ class Child(Parent): child: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/alias-extends/types/parent.py b/seed/fastapi/alias-extends/types/parent.py index eabf193249b..456ae41837b 100644 --- a/seed/fastapi/alias-extends/types/parent.py +++ b/seed/fastapi/alias-extends/types/parent.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from ..core.pydantic_utilities import UniversalBaseModel +from ..core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class Parent(UniversalBaseModel): """ @@ -21,7 +20,9 @@ class Parent(UniversalBaseModel): parent: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/alias/core/abstract_fern_service.py b/seed/fastapi/alias/core/abstract_fern_service.py index da7c8dc49c4..9966b4876da 100644 --- a/seed/fastapi/alias/core/abstract_fern_service.py +++ b/seed/fastapi/alias/core/abstract_fern_service.py @@ -7,5 +7,4 @@ class AbstractFernService(abc.ABC): @classmethod - def _init_fern(cls, router: fastapi.APIRouter) -> None: - ... + def _init_fern(cls, router: fastapi.APIRouter) -> None: ... diff --git a/seed/fastapi/alias/core/datetime_utils.py b/seed/fastapi/alias/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/fastapi/alias/core/datetime_utils.py +++ b/seed/fastapi/alias/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/fastapi/alias/core/exceptions/__init__.py b/seed/fastapi/alias/core/exceptions/__init__.py index 297d6e06f5f..dae4b8980c1 100644 --- a/seed/fastapi/alias/core/exceptions/__init__.py +++ b/seed/fastapi/alias/core/exceptions/__init__.py @@ -1,7 +1,11 @@ # This file was auto-generated by Fern from our API Definition. from .fern_http_exception import FernHTTPException -from .handlers import default_exception_handler, fern_http_exception_handler, http_exception_handler +from .handlers import ( + default_exception_handler, + fern_http_exception_handler, + http_exception_handler, +) from .unauthorized import UnauthorizedException __all__ = [ diff --git a/seed/fastapi/alias/core/exceptions/fern_http_exception.py b/seed/fastapi/alias/core/exceptions/fern_http_exception.py index bdf03862487..81610359a7f 100644 --- a/seed/fastapi/alias/core/exceptions/fern_http_exception.py +++ b/seed/fastapi/alias/core/exceptions/fern_http_exception.py @@ -1,14 +1,16 @@ # This file was auto-generated by Fern from our API Definition. import abc -import typing - import fastapi +import typing class FernHTTPException(abc.ABC, fastapi.HTTPException): def __init__( - self, status_code: int, name: typing.Optional[str] = None, content: typing.Optional[typing.Any] = None + self, + status_code: int, + name: typing.Optional[str] = None, + content: typing.Optional[typing.Any] = None, ): super().__init__(status_code=status_code) self.name = name @@ -17,4 +19,6 @@ def __init__( def to_json_response(self) -> fastapi.responses.JSONResponse: content = fastapi.encoders.jsonable_encoder(self.content, exclude_none=True) - return fastapi.responses.JSONResponse(content=content, status_code=self.status_code) + return fastapi.responses.JSONResponse( + content=content, status_code=self.status_code + ) diff --git a/seed/fastapi/alias/core/exceptions/handlers.py b/seed/fastapi/alias/core/exceptions/handlers.py index 6d8c4155c5a..ae1c2741f06 100644 --- a/seed/fastapi/alias/core/exceptions/handlers.py +++ b/seed/fastapi/alias/core/exceptions/handlers.py @@ -2,32 +2,49 @@ import logging -import fastapi import starlette import starlette.exceptions +import fastapi + from .fern_http_exception import FernHTTPException def fern_http_exception_handler( - request: fastapi.requests.Request, exc: FernHTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: FernHTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) return exc.to_json_response() def http_exception_handler( - request: fastapi.requests.Request, exc: starlette.exceptions.HTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: starlette.exceptions.HTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=exc.status_code, content=exc.detail).to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=exc.status_code, content=exc.detail + ).to_json_response() def default_exception_handler( - request: fastapi.requests.Request, exc: Exception, skip_log: bool = False + request: fastapi.requests.Request, + exc: Exception, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=500, content="Internal Server Error").to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=500, content="Internal Server Error" + ).to_json_response() diff --git a/seed/fastapi/alias/core/pydantic_utilities.py b/seed/fastapi/alias/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/fastapi/alias/core/pydantic_utilities.py +++ b/seed/fastapi/alias/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/fastapi/alias/core/route_args.py b/seed/fastapi/alias/core/route_args.py index 4228e2fe05d..bd940bf4ddd 100644 --- a/seed/fastapi/alias/core/route_args.py +++ b/seed/fastapi/alias/core/route_args.py @@ -20,9 +20,15 @@ class RouteArgs(typing_extensions.TypedDict): DEFAULT_ROUTE_ARGS = RouteArgs(openapi_extra=None, tags=None, include_in_schema=True) -def get_route_args(endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str) -> RouteArgs: - unwrapped = inspect.unwrap(endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY))) - route_args = typing.cast(RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS)) +def get_route_args( + endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str +) -> RouteArgs: + unwrapped = inspect.unwrap( + endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY)) + ) + route_args = typing.cast( + RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS) + ) if route_args["tags"] is None: return RouteArgs( openapi_extra=route_args["openapi_extra"], @@ -56,7 +62,11 @@ def decorator(endpoint_function: T) -> T: setattr( endpoint_function, FERN_CONFIG_KEY, - RouteArgs(openapi_extra=openapi_extra, tags=tags, include_in_schema=include_in_schema), + RouteArgs( + openapi_extra=openapi_extra, + tags=tags, + include_in_schema=include_in_schema, + ), ) return endpoint_function diff --git a/seed/fastapi/alias/register.py b/seed/fastapi/alias/register.py index 3b90d0c034f..ce9f38fa412 100644 --- a/seed/fastapi/alias/register.py +++ b/seed/fastapi/alias/register.py @@ -1,31 +1,33 @@ # This file was auto-generated by Fern from our API Definition. -import glob -import importlib -import os -import types -import typing - import fastapi -import starlette.exceptions +from .service.service import AbstractRootService +import typing from fastapi import params - -from .core.abstract_fern_service import AbstractFernService -from .core.exceptions import default_exception_handler, fern_http_exception_handler, http_exception_handler from .core.exceptions.fern_http_exception import FernHTTPException -from .service.service import AbstractRootService +from .core.exceptions import fern_http_exception_handler +import starlette.exceptions +from .core.exceptions import http_exception_handler +from .core.exceptions import default_exception_handler +from .core.abstract_fern_service import AbstractFernService +import types +import os +import glob +import importlib def register( _app: fastapi.FastAPI, *, root: AbstractRootService, - dependencies: typing.Optional[typing.Sequence[params.Depends]] = None + dependencies: typing.Optional[typing.Sequence[params.Depends]] = None, ) -> None: _app.include_router(__register_service(root), dependencies=dependencies) _app.add_exception_handler(FernHTTPException, fern_http_exception_handler) # type: ignore - _app.add_exception_handler(starlette.exceptions.HTTPException, http_exception_handler) # type: ignore + _app.add_exception_handler( + starlette.exceptions.HTTPException, http_exception_handler + ) # type: ignore _app.add_exception_handler(Exception, default_exception_handler) # type: ignore @@ -37,7 +39,9 @@ def __register_service(service: AbstractFernService) -> fastapi.APIRouter: def register_validators(module: types.ModuleType) -> None: validators_directory: str = os.path.dirname(module.__file__) # type: ignore - for path in glob.glob(os.path.join(validators_directory, "**/*.py"), recursive=True): + for path in glob.glob( + os.path.join(validators_directory, "**/*.py"), recursive=True + ): if os.path.isfile(path): relative_path = os.path.relpath(path, start=validators_directory) module_path = ".".join([module.__name__] + relative_path[:-3].split("/")) diff --git a/seed/fastapi/alias/service/service.py b/seed/fastapi/alias/service/service.py index 32261b1a8ff..e12877a6599 100644 --- a/seed/fastapi/alias/service/service.py +++ b/seed/fastapi/alias/service/service.py @@ -1,16 +1,14 @@ # This file was auto-generated by Fern from our API Definition. +from ..core.abstract_fern_service import AbstractFernService import abc -import functools +import fastapi import inspect -import logging import typing - -import fastapi -import starlette - -from ..core.abstract_fern_service import AbstractFernService from ..core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools +import starlette from ..core.route_args import get_route_args @@ -24,8 +22,7 @@ class AbstractRootService(AbstractFernService): """ @abc.abstractmethod - def get(self, *, type_id: str) -> None: - ... + def get(self, *, type_id: str) -> None: ... """ Below are internal methods used by Fern to register your implementation. @@ -40,14 +37,20 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_get(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "type_id": new_parameters.append(parameter.replace(default=fastapi.Path(...))) else: new_parameters.append(parameter) - setattr(cls.get, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> None: diff --git a/seed/fastapi/alias/types/type.py b/seed/fastapi/alias/types/type.py index 3b267a36aa4..088835f1f51 100644 --- a/seed/fastapi/alias/types/type.py +++ b/seed/fastapi/alias/types/type.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. +from ..core.pydantic_utilities import UniversalBaseModel +from .type_id import TypeId +from ..core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .type_id import TypeId - class Type(UniversalBaseModel): """ @@ -26,7 +25,9 @@ class Type(UniversalBaseModel): name: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/alias/types/type_id.py b/seed/fastapi/alias/types/type_id.py index 5cd53c920d5..c5f3b3bb32e 100644 --- a/seed/fastapi/alias/types/type_id.py +++ b/seed/fastapi/alias/types/type_id.py @@ -3,4 +3,5 @@ """ "type-kaljhv87" """ + TypeId = str diff --git a/seed/fastapi/api-wide-base-path/core/abstract_fern_service.py b/seed/fastapi/api-wide-base-path/core/abstract_fern_service.py index da7c8dc49c4..9966b4876da 100644 --- a/seed/fastapi/api-wide-base-path/core/abstract_fern_service.py +++ b/seed/fastapi/api-wide-base-path/core/abstract_fern_service.py @@ -7,5 +7,4 @@ class AbstractFernService(abc.ABC): @classmethod - def _init_fern(cls, router: fastapi.APIRouter) -> None: - ... + def _init_fern(cls, router: fastapi.APIRouter) -> None: ... diff --git a/seed/fastapi/api-wide-base-path/core/datetime_utils.py b/seed/fastapi/api-wide-base-path/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/fastapi/api-wide-base-path/core/datetime_utils.py +++ b/seed/fastapi/api-wide-base-path/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/fastapi/api-wide-base-path/core/exceptions/__init__.py b/seed/fastapi/api-wide-base-path/core/exceptions/__init__.py index 297d6e06f5f..dae4b8980c1 100644 --- a/seed/fastapi/api-wide-base-path/core/exceptions/__init__.py +++ b/seed/fastapi/api-wide-base-path/core/exceptions/__init__.py @@ -1,7 +1,11 @@ # This file was auto-generated by Fern from our API Definition. from .fern_http_exception import FernHTTPException -from .handlers import default_exception_handler, fern_http_exception_handler, http_exception_handler +from .handlers import ( + default_exception_handler, + fern_http_exception_handler, + http_exception_handler, +) from .unauthorized import UnauthorizedException __all__ = [ diff --git a/seed/fastapi/api-wide-base-path/core/exceptions/fern_http_exception.py b/seed/fastapi/api-wide-base-path/core/exceptions/fern_http_exception.py index bdf03862487..81610359a7f 100644 --- a/seed/fastapi/api-wide-base-path/core/exceptions/fern_http_exception.py +++ b/seed/fastapi/api-wide-base-path/core/exceptions/fern_http_exception.py @@ -1,14 +1,16 @@ # This file was auto-generated by Fern from our API Definition. import abc -import typing - import fastapi +import typing class FernHTTPException(abc.ABC, fastapi.HTTPException): def __init__( - self, status_code: int, name: typing.Optional[str] = None, content: typing.Optional[typing.Any] = None + self, + status_code: int, + name: typing.Optional[str] = None, + content: typing.Optional[typing.Any] = None, ): super().__init__(status_code=status_code) self.name = name @@ -17,4 +19,6 @@ def __init__( def to_json_response(self) -> fastapi.responses.JSONResponse: content = fastapi.encoders.jsonable_encoder(self.content, exclude_none=True) - return fastapi.responses.JSONResponse(content=content, status_code=self.status_code) + return fastapi.responses.JSONResponse( + content=content, status_code=self.status_code + ) diff --git a/seed/fastapi/api-wide-base-path/core/exceptions/handlers.py b/seed/fastapi/api-wide-base-path/core/exceptions/handlers.py index 6d8c4155c5a..ae1c2741f06 100644 --- a/seed/fastapi/api-wide-base-path/core/exceptions/handlers.py +++ b/seed/fastapi/api-wide-base-path/core/exceptions/handlers.py @@ -2,32 +2,49 @@ import logging -import fastapi import starlette import starlette.exceptions +import fastapi + from .fern_http_exception import FernHTTPException def fern_http_exception_handler( - request: fastapi.requests.Request, exc: FernHTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: FernHTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) return exc.to_json_response() def http_exception_handler( - request: fastapi.requests.Request, exc: starlette.exceptions.HTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: starlette.exceptions.HTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=exc.status_code, content=exc.detail).to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=exc.status_code, content=exc.detail + ).to_json_response() def default_exception_handler( - request: fastapi.requests.Request, exc: Exception, skip_log: bool = False + request: fastapi.requests.Request, + exc: Exception, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=500, content="Internal Server Error").to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=500, content="Internal Server Error" + ).to_json_response() diff --git a/seed/fastapi/api-wide-base-path/core/pydantic_utilities.py b/seed/fastapi/api-wide-base-path/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/fastapi/api-wide-base-path/core/pydantic_utilities.py +++ b/seed/fastapi/api-wide-base-path/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/fastapi/api-wide-base-path/core/route_args.py b/seed/fastapi/api-wide-base-path/core/route_args.py index 4228e2fe05d..bd940bf4ddd 100644 --- a/seed/fastapi/api-wide-base-path/core/route_args.py +++ b/seed/fastapi/api-wide-base-path/core/route_args.py @@ -20,9 +20,15 @@ class RouteArgs(typing_extensions.TypedDict): DEFAULT_ROUTE_ARGS = RouteArgs(openapi_extra=None, tags=None, include_in_schema=True) -def get_route_args(endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str) -> RouteArgs: - unwrapped = inspect.unwrap(endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY))) - route_args = typing.cast(RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS)) +def get_route_args( + endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str +) -> RouteArgs: + unwrapped = inspect.unwrap( + endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY)) + ) + route_args = typing.cast( + RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS) + ) if route_args["tags"] is None: return RouteArgs( openapi_extra=route_args["openapi_extra"], @@ -56,7 +62,11 @@ def decorator(endpoint_function: T) -> T: setattr( endpoint_function, FERN_CONFIG_KEY, - RouteArgs(openapi_extra=openapi_extra, tags=tags, include_in_schema=include_in_schema), + RouteArgs( + openapi_extra=openapi_extra, + tags=tags, + include_in_schema=include_in_schema, + ), ) return endpoint_function diff --git a/seed/fastapi/api-wide-base-path/register.py b/seed/fastapi/api-wide-base-path/register.py index ebdfdf9318d..1d60bbe4d5d 100644 --- a/seed/fastapi/api-wide-base-path/register.py +++ b/seed/fastapi/api-wide-base-path/register.py @@ -1,31 +1,33 @@ # This file was auto-generated by Fern from our API Definition. -import glob -import importlib -import os -import types -import typing - import fastapi -import starlette.exceptions +from .resources.service.service.service import AbstractServiceService +import typing from fastapi import params - -from .core.abstract_fern_service import AbstractFernService -from .core.exceptions import default_exception_handler, fern_http_exception_handler, http_exception_handler from .core.exceptions.fern_http_exception import FernHTTPException -from .resources.service.service.service import AbstractServiceService +from .core.exceptions import fern_http_exception_handler +import starlette.exceptions +from .core.exceptions import http_exception_handler +from .core.exceptions import default_exception_handler +from .core.abstract_fern_service import AbstractFernService +import types +import os +import glob +import importlib def register( _app: fastapi.FastAPI, *, service: AbstractServiceService, - dependencies: typing.Optional[typing.Sequence[params.Depends]] = None + dependencies: typing.Optional[typing.Sequence[params.Depends]] = None, ) -> None: _app.include_router(__register_service(service), dependencies=dependencies) _app.add_exception_handler(FernHTTPException, fern_http_exception_handler) # type: ignore - _app.add_exception_handler(starlette.exceptions.HTTPException, http_exception_handler) # type: ignore + _app.add_exception_handler( + starlette.exceptions.HTTPException, http_exception_handler + ) # type: ignore _app.add_exception_handler(Exception, default_exception_handler) # type: ignore @@ -37,7 +39,9 @@ def __register_service(service: AbstractFernService) -> fastapi.APIRouter: def register_validators(module: types.ModuleType) -> None: validators_directory: str = os.path.dirname(module.__file__) # type: ignore - for path in glob.glob(os.path.join(validators_directory, "**/*.py"), recursive=True): + for path in glob.glob( + os.path.join(validators_directory, "**/*.py"), recursive=True + ): if os.path.isfile(path): relative_path = os.path.relpath(path, start=validators_directory) module_path = ".".join([module.__name__] + relative_path[:-3].split("/")) diff --git a/seed/fastapi/api-wide-base-path/resources/service/service/service.py b/seed/fastapi/api-wide-base-path/resources/service/service/service.py index 1aadc3535c2..57fb598aa03 100644 --- a/seed/fastapi/api-wide-base-path/resources/service/service/service.py +++ b/seed/fastapi/api-wide-base-path/resources/service/service/service.py @@ -1,16 +1,14 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.abstract_fern_service import AbstractFernService import abc -import functools +import fastapi import inspect -import logging import typing - -import fastapi -import starlette - -from ....core.abstract_fern_service import AbstractFernService from ....core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools +import starlette from ....core.route_args import get_route_args @@ -24,8 +22,9 @@ class AbstractServiceService(AbstractFernService): """ @abc.abstractmethod - def post(self, *, service_param: str, resource_param: str, endpoint_param: int) -> None: - ... + def post( + self, *, service_param: str, resource_param: str, endpoint_param: int + ) -> None: ... """ Below are internal methods used by Fern to register your implementation. @@ -40,7 +39,9 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_post(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.post) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "service_param": @@ -51,7 +52,11 @@ def __init_post(cls, router: fastapi.APIRouter) -> None: new_parameters.append(parameter.replace(default=fastapi.Path(...))) else: new_parameters.append(parameter) - setattr(cls.post, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.post, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.post) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> None: diff --git a/seed/fastapi/audiences/core/abstract_fern_service.py b/seed/fastapi/audiences/core/abstract_fern_service.py index da7c8dc49c4..9966b4876da 100644 --- a/seed/fastapi/audiences/core/abstract_fern_service.py +++ b/seed/fastapi/audiences/core/abstract_fern_service.py @@ -7,5 +7,4 @@ class AbstractFernService(abc.ABC): @classmethod - def _init_fern(cls, router: fastapi.APIRouter) -> None: - ... + def _init_fern(cls, router: fastapi.APIRouter) -> None: ... diff --git a/seed/fastapi/audiences/core/datetime_utils.py b/seed/fastapi/audiences/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/fastapi/audiences/core/datetime_utils.py +++ b/seed/fastapi/audiences/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/fastapi/audiences/core/exceptions/__init__.py b/seed/fastapi/audiences/core/exceptions/__init__.py index 297d6e06f5f..dae4b8980c1 100644 --- a/seed/fastapi/audiences/core/exceptions/__init__.py +++ b/seed/fastapi/audiences/core/exceptions/__init__.py @@ -1,7 +1,11 @@ # This file was auto-generated by Fern from our API Definition. from .fern_http_exception import FernHTTPException -from .handlers import default_exception_handler, fern_http_exception_handler, http_exception_handler +from .handlers import ( + default_exception_handler, + fern_http_exception_handler, + http_exception_handler, +) from .unauthorized import UnauthorizedException __all__ = [ diff --git a/seed/fastapi/audiences/core/exceptions/fern_http_exception.py b/seed/fastapi/audiences/core/exceptions/fern_http_exception.py index bdf03862487..81610359a7f 100644 --- a/seed/fastapi/audiences/core/exceptions/fern_http_exception.py +++ b/seed/fastapi/audiences/core/exceptions/fern_http_exception.py @@ -1,14 +1,16 @@ # This file was auto-generated by Fern from our API Definition. import abc -import typing - import fastapi +import typing class FernHTTPException(abc.ABC, fastapi.HTTPException): def __init__( - self, status_code: int, name: typing.Optional[str] = None, content: typing.Optional[typing.Any] = None + self, + status_code: int, + name: typing.Optional[str] = None, + content: typing.Optional[typing.Any] = None, ): super().__init__(status_code=status_code) self.name = name @@ -17,4 +19,6 @@ def __init__( def to_json_response(self) -> fastapi.responses.JSONResponse: content = fastapi.encoders.jsonable_encoder(self.content, exclude_none=True) - return fastapi.responses.JSONResponse(content=content, status_code=self.status_code) + return fastapi.responses.JSONResponse( + content=content, status_code=self.status_code + ) diff --git a/seed/fastapi/audiences/core/exceptions/handlers.py b/seed/fastapi/audiences/core/exceptions/handlers.py index 6d8c4155c5a..ae1c2741f06 100644 --- a/seed/fastapi/audiences/core/exceptions/handlers.py +++ b/seed/fastapi/audiences/core/exceptions/handlers.py @@ -2,32 +2,49 @@ import logging -import fastapi import starlette import starlette.exceptions +import fastapi + from .fern_http_exception import FernHTTPException def fern_http_exception_handler( - request: fastapi.requests.Request, exc: FernHTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: FernHTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) return exc.to_json_response() def http_exception_handler( - request: fastapi.requests.Request, exc: starlette.exceptions.HTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: starlette.exceptions.HTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=exc.status_code, content=exc.detail).to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=exc.status_code, content=exc.detail + ).to_json_response() def default_exception_handler( - request: fastapi.requests.Request, exc: Exception, skip_log: bool = False + request: fastapi.requests.Request, + exc: Exception, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=500, content="Internal Server Error").to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=500, content="Internal Server Error" + ).to_json_response() diff --git a/seed/fastapi/audiences/core/pydantic_utilities.py b/seed/fastapi/audiences/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/fastapi/audiences/core/pydantic_utilities.py +++ b/seed/fastapi/audiences/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/fastapi/audiences/core/route_args.py b/seed/fastapi/audiences/core/route_args.py index 4228e2fe05d..bd940bf4ddd 100644 --- a/seed/fastapi/audiences/core/route_args.py +++ b/seed/fastapi/audiences/core/route_args.py @@ -20,9 +20,15 @@ class RouteArgs(typing_extensions.TypedDict): DEFAULT_ROUTE_ARGS = RouteArgs(openapi_extra=None, tags=None, include_in_schema=True) -def get_route_args(endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str) -> RouteArgs: - unwrapped = inspect.unwrap(endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY))) - route_args = typing.cast(RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS)) +def get_route_args( + endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str +) -> RouteArgs: + unwrapped = inspect.unwrap( + endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY)) + ) + route_args = typing.cast( + RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS) + ) if route_args["tags"] is None: return RouteArgs( openapi_extra=route_args["openapi_extra"], @@ -56,7 +62,11 @@ def decorator(endpoint_function: T) -> T: setattr( endpoint_function, FERN_CONFIG_KEY, - RouteArgs(openapi_extra=openapi_extra, tags=tags, include_in_schema=include_in_schema), + RouteArgs( + openapi_extra=openapi_extra, + tags=tags, + include_in_schema=include_in_schema, + ), ) return endpoint_function diff --git a/seed/fastapi/audiences/register.py b/seed/fastapi/audiences/register.py index 30ba2f5b6ea..03e9ca2629b 100644 --- a/seed/fastapi/audiences/register.py +++ b/seed/fastapi/audiences/register.py @@ -1,20 +1,22 @@ # This file was auto-generated by Fern from our API Definition. -import glob -import importlib -import os -import types -import typing - import fastapi -import starlette.exceptions +from .resources.folder_a.resources.service.service.service import ( + AbstractFolderAServiceService, +) +from .resources.foo.service.service import AbstractFooService +import typing from fastapi import params - -from .core.abstract_fern_service import AbstractFernService -from .core.exceptions import default_exception_handler, fern_http_exception_handler, http_exception_handler from .core.exceptions.fern_http_exception import FernHTTPException -from .resources.folder_a.resources.service.service.service import AbstractFolderAServiceService -from .resources.foo.service.service import AbstractFooService +from .core.exceptions import fern_http_exception_handler +import starlette.exceptions +from .core.exceptions import http_exception_handler +from .core.exceptions import default_exception_handler +from .core.abstract_fern_service import AbstractFernService +import types +import os +import glob +import importlib def register( @@ -22,13 +24,15 @@ def register( *, folder_a_service: AbstractFolderAServiceService, foo: AbstractFooService, - dependencies: typing.Optional[typing.Sequence[params.Depends]] = None + dependencies: typing.Optional[typing.Sequence[params.Depends]] = None, ) -> None: _app.include_router(__register_service(folder_a_service), dependencies=dependencies) _app.include_router(__register_service(foo), dependencies=dependencies) _app.add_exception_handler(FernHTTPException, fern_http_exception_handler) # type: ignore - _app.add_exception_handler(starlette.exceptions.HTTPException, http_exception_handler) # type: ignore + _app.add_exception_handler( + starlette.exceptions.HTTPException, http_exception_handler + ) # type: ignore _app.add_exception_handler(Exception, default_exception_handler) # type: ignore @@ -40,7 +44,9 @@ def __register_service(service: AbstractFernService) -> fastapi.APIRouter: def register_validators(module: types.ModuleType) -> None: validators_directory: str = os.path.dirname(module.__file__) # type: ignore - for path in glob.glob(os.path.join(validators_directory, "**/*.py"), recursive=True): + for path in glob.glob( + os.path.join(validators_directory, "**/*.py"), recursive=True + ): if os.path.isfile(path): relative_path = os.path.relpath(path, start=validators_directory) module_path = ".".join([module.__name__] + relative_path[:-3].split("/")) diff --git a/seed/fastapi/audiences/resources/folder_a/resources/service/service/service.py b/seed/fastapi/audiences/resources/folder_a/resources/service/service/service.py index 8dfe8accde4..2b95f1c4348 100644 --- a/seed/fastapi/audiences/resources/folder_a/resources/service/service/service.py +++ b/seed/fastapi/audiences/resources/folder_a/resources/service/service/service.py @@ -1,17 +1,15 @@ # This file was auto-generated by Fern from our API Definition. +from ......core.abstract_fern_service import AbstractFernService +from ..types.response import Response import abc -import functools +import fastapi import inspect -import logging import typing - -import fastapi - -from ......core.abstract_fern_service import AbstractFernService from ......core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools from ......core.route_args import get_route_args -from ..types.response import Response class AbstractFolderAServiceService(AbstractFernService): @@ -24,8 +22,7 @@ class AbstractFolderAServiceService(AbstractFernService): """ @abc.abstractmethod - def get_direct_thread(self) -> Response: - ... + def get_direct_thread(self) -> Response: ... """ Below are internal methods used by Fern to register your implementation. @@ -40,12 +37,18 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_get_direct_thread(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_direct_thread) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) else: new_parameters.append(parameter) - setattr(cls.get_direct_thread, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_direct_thread, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_direct_thread) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> Response: diff --git a/seed/fastapi/audiences/resources/folder_a/resources/service/types/response.py b/seed/fastapi/audiences/resources/folder_a/resources/service/types/response.py index ebf770c6f8b..f5040a6efec 100644 --- a/seed/fastapi/audiences/resources/folder_a/resources/service/types/response.py +++ b/seed/fastapi/audiences/resources/folder_a/resources/service/types/response.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from ......core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .....folder_b.resources.common.types.foo import Foo +from ......core.pydantic_utilities import IS_PYDANTIC_V2 +import pydantic class Response(UniversalBaseModel): foo: typing.Optional[Foo] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/audiences/resources/folder_b/resources/common/types/foo.py b/seed/fastapi/audiences/resources/folder_b/resources/common/types/foo.py index d95326db7bd..0b12bde7e4e 100644 --- a/seed/fastapi/audiences/resources/folder_b/resources/common/types/foo.py +++ b/seed/fastapi/audiences/resources/folder_b/resources/common/types/foo.py @@ -1,18 +1,21 @@ # This file was auto-generated by Fern from our API Definition. +from ......core.pydantic_utilities import UniversalBaseModel import typing - +from .....folder_c.resources.common.types.foo import ( + Foo as resources_folder_c_resources_common_types_foo_Foo, +) +from ......core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .....folder_c.resources.common.types.foo import Foo as resources_folder_c_resources_common_types_foo_Foo - class Foo(UniversalBaseModel): foo: typing.Optional[resources_folder_c_resources_common_types_foo_Foo] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/audiences/resources/folder_c/resources/common/types/foo.py b/seed/fastapi/audiences/resources/folder_c/resources/common/types/foo.py index 70a0c7e54c5..bad9faeb37b 100644 --- a/seed/fastapi/audiences/resources/folder_c/resources/common/types/foo.py +++ b/seed/fastapi/audiences/resources/folder_c/resources/common/types/foo.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. -import typing +from ......core.pydantic_utilities import UniversalBaseModel import uuid - +from ......core.pydantic_utilities import IS_PYDANTIC_V2 +import typing import pydantic -from ......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class Foo(UniversalBaseModel): bar_property: uuid.UUID if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/audiences/resources/foo/service/find_request.py b/seed/fastapi/audiences/resources/foo/service/find_request.py index 32865fff0f3..0eddaafbd5a 100644 --- a/seed/fastapi/audiences/resources/foo/service/find_request.py +++ b/seed/fastapi/audiences/resources/foo/service/find_request.py @@ -1,18 +1,23 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class FindRequest(UniversalBaseModel): - public_property: typing.Optional[str] = pydantic.Field(alias="publicProperty", default=None) - private_property: typing.Optional[int] = pydantic.Field(alias="privateProperty", default=None) + public_property: typing.Optional[str] = pydantic.Field( + alias="publicProperty", default=None + ) + private_property: typing.Optional[int] = pydantic.Field( + alias="privateProperty", default=None + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/audiences/resources/foo/service/service.py b/seed/fastapi/audiences/resources/foo/service/service.py index 4e67da1848b..ee71d9559af 100644 --- a/seed/fastapi/audiences/resources/foo/service/service.py +++ b/seed/fastapi/audiences/resources/foo/service/service.py @@ -1,18 +1,16 @@ # This file was auto-generated by Fern from our API Definition. -import abc -import functools -import inspect -import logging +from ....core.abstract_fern_service import AbstractFernService +from .find_request import FindRequest import typing - +from ..types.importing_type import ImportingType +import abc import fastapi - -from ....core.abstract_fern_service import AbstractFernService +import inspect from ....core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools from ....core.route_args import get_route_args -from ..types.importing_type import ImportingType -from .find_request import FindRequest class AbstractFooService(AbstractFernService): @@ -25,8 +23,9 @@ class AbstractFooService(AbstractFernService): """ @abc.abstractmethod - def find(self, *, body: FindRequest, optional_string: typing.Optional[str] = None) -> ImportingType: - ... + def find( + self, *, body: FindRequest, optional_string: typing.Optional[str] = None + ) -> ImportingType: ... """ Below are internal methods used by Fern to register your implementation. @@ -41,16 +40,26 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_find(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.find) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "optional_string": - new_parameters.append(parameter.replace(default=fastapi.Query(default=..., alias="optionalString"))) + new_parameters.append( + parameter.replace( + default=fastapi.Query(default=..., alias="optionalString") + ) + ) else: new_parameters.append(parameter) - setattr(cls.find, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.find, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.find) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> ImportingType: diff --git a/seed/fastapi/audiences/resources/foo/types/filtered_type.py b/seed/fastapi/audiences/resources/foo/types/filtered_type.py index ffe14865822..e70e533822c 100644 --- a/seed/fastapi/audiences/resources/foo/types/filtered_type.py +++ b/seed/fastapi/audiences/resources/foo/types/filtered_type.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class FilteredType(UniversalBaseModel): public_property: typing.Optional[str] = None private_property: int if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/audiences/resources/foo/types/importing_type.py b/seed/fastapi/audiences/resources/foo/types/importing_type.py index bec340beb0c..fe72840c7a4 100644 --- a/seed/fastapi/audiences/resources/foo/types/importing_type.py +++ b/seed/fastapi/audiences/resources/foo/types/importing_type.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel +from ...commons.types.imported import Imported +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from ...commons.types.imported import Imported - class ImportingType(UniversalBaseModel): imported: Imported if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/auth-environment-variables/core/abstract_fern_service.py b/seed/fastapi/auth-environment-variables/core/abstract_fern_service.py index da7c8dc49c4..9966b4876da 100644 --- a/seed/fastapi/auth-environment-variables/core/abstract_fern_service.py +++ b/seed/fastapi/auth-environment-variables/core/abstract_fern_service.py @@ -7,5 +7,4 @@ class AbstractFernService(abc.ABC): @classmethod - def _init_fern(cls, router: fastapi.APIRouter) -> None: - ... + def _init_fern(cls, router: fastapi.APIRouter) -> None: ... diff --git a/seed/fastapi/auth-environment-variables/core/datetime_utils.py b/seed/fastapi/auth-environment-variables/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/fastapi/auth-environment-variables/core/datetime_utils.py +++ b/seed/fastapi/auth-environment-variables/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/fastapi/auth-environment-variables/core/exceptions/__init__.py b/seed/fastapi/auth-environment-variables/core/exceptions/__init__.py index 297d6e06f5f..dae4b8980c1 100644 --- a/seed/fastapi/auth-environment-variables/core/exceptions/__init__.py +++ b/seed/fastapi/auth-environment-variables/core/exceptions/__init__.py @@ -1,7 +1,11 @@ # This file was auto-generated by Fern from our API Definition. from .fern_http_exception import FernHTTPException -from .handlers import default_exception_handler, fern_http_exception_handler, http_exception_handler +from .handlers import ( + default_exception_handler, + fern_http_exception_handler, + http_exception_handler, +) from .unauthorized import UnauthorizedException __all__ = [ diff --git a/seed/fastapi/auth-environment-variables/core/exceptions/fern_http_exception.py b/seed/fastapi/auth-environment-variables/core/exceptions/fern_http_exception.py index bdf03862487..81610359a7f 100644 --- a/seed/fastapi/auth-environment-variables/core/exceptions/fern_http_exception.py +++ b/seed/fastapi/auth-environment-variables/core/exceptions/fern_http_exception.py @@ -1,14 +1,16 @@ # This file was auto-generated by Fern from our API Definition. import abc -import typing - import fastapi +import typing class FernHTTPException(abc.ABC, fastapi.HTTPException): def __init__( - self, status_code: int, name: typing.Optional[str] = None, content: typing.Optional[typing.Any] = None + self, + status_code: int, + name: typing.Optional[str] = None, + content: typing.Optional[typing.Any] = None, ): super().__init__(status_code=status_code) self.name = name @@ -17,4 +19,6 @@ def __init__( def to_json_response(self) -> fastapi.responses.JSONResponse: content = fastapi.encoders.jsonable_encoder(self.content, exclude_none=True) - return fastapi.responses.JSONResponse(content=content, status_code=self.status_code) + return fastapi.responses.JSONResponse( + content=content, status_code=self.status_code + ) diff --git a/seed/fastapi/auth-environment-variables/core/exceptions/handlers.py b/seed/fastapi/auth-environment-variables/core/exceptions/handlers.py index 6d8c4155c5a..ae1c2741f06 100644 --- a/seed/fastapi/auth-environment-variables/core/exceptions/handlers.py +++ b/seed/fastapi/auth-environment-variables/core/exceptions/handlers.py @@ -2,32 +2,49 @@ import logging -import fastapi import starlette import starlette.exceptions +import fastapi + from .fern_http_exception import FernHTTPException def fern_http_exception_handler( - request: fastapi.requests.Request, exc: FernHTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: FernHTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) return exc.to_json_response() def http_exception_handler( - request: fastapi.requests.Request, exc: starlette.exceptions.HTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: starlette.exceptions.HTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=exc.status_code, content=exc.detail).to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=exc.status_code, content=exc.detail + ).to_json_response() def default_exception_handler( - request: fastapi.requests.Request, exc: Exception, skip_log: bool = False + request: fastapi.requests.Request, + exc: Exception, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=500, content="Internal Server Error").to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=500, content="Internal Server Error" + ).to_json_response() diff --git a/seed/fastapi/auth-environment-variables/core/pydantic_utilities.py b/seed/fastapi/auth-environment-variables/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/fastapi/auth-environment-variables/core/pydantic_utilities.py +++ b/seed/fastapi/auth-environment-variables/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/fastapi/auth-environment-variables/core/route_args.py b/seed/fastapi/auth-environment-variables/core/route_args.py index 4228e2fe05d..bd940bf4ddd 100644 --- a/seed/fastapi/auth-environment-variables/core/route_args.py +++ b/seed/fastapi/auth-environment-variables/core/route_args.py @@ -20,9 +20,15 @@ class RouteArgs(typing_extensions.TypedDict): DEFAULT_ROUTE_ARGS = RouteArgs(openapi_extra=None, tags=None, include_in_schema=True) -def get_route_args(endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str) -> RouteArgs: - unwrapped = inspect.unwrap(endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY))) - route_args = typing.cast(RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS)) +def get_route_args( + endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str +) -> RouteArgs: + unwrapped = inspect.unwrap( + endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY)) + ) + route_args = typing.cast( + RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS) + ) if route_args["tags"] is None: return RouteArgs( openapi_extra=route_args["openapi_extra"], @@ -56,7 +62,11 @@ def decorator(endpoint_function: T) -> T: setattr( endpoint_function, FERN_CONFIG_KEY, - RouteArgs(openapi_extra=openapi_extra, tags=tags, include_in_schema=include_in_schema), + RouteArgs( + openapi_extra=openapi_extra, + tags=tags, + include_in_schema=include_in_schema, + ), ) return endpoint_function diff --git a/seed/fastapi/auth-environment-variables/register.py b/seed/fastapi/auth-environment-variables/register.py index ebdfdf9318d..1d60bbe4d5d 100644 --- a/seed/fastapi/auth-environment-variables/register.py +++ b/seed/fastapi/auth-environment-variables/register.py @@ -1,31 +1,33 @@ # This file was auto-generated by Fern from our API Definition. -import glob -import importlib -import os -import types -import typing - import fastapi -import starlette.exceptions +from .resources.service.service.service import AbstractServiceService +import typing from fastapi import params - -from .core.abstract_fern_service import AbstractFernService -from .core.exceptions import default_exception_handler, fern_http_exception_handler, http_exception_handler from .core.exceptions.fern_http_exception import FernHTTPException -from .resources.service.service.service import AbstractServiceService +from .core.exceptions import fern_http_exception_handler +import starlette.exceptions +from .core.exceptions import http_exception_handler +from .core.exceptions import default_exception_handler +from .core.abstract_fern_service import AbstractFernService +import types +import os +import glob +import importlib def register( _app: fastapi.FastAPI, *, service: AbstractServiceService, - dependencies: typing.Optional[typing.Sequence[params.Depends]] = None + dependencies: typing.Optional[typing.Sequence[params.Depends]] = None, ) -> None: _app.include_router(__register_service(service), dependencies=dependencies) _app.add_exception_handler(FernHTTPException, fern_http_exception_handler) # type: ignore - _app.add_exception_handler(starlette.exceptions.HTTPException, http_exception_handler) # type: ignore + _app.add_exception_handler( + starlette.exceptions.HTTPException, http_exception_handler + ) # type: ignore _app.add_exception_handler(Exception, default_exception_handler) # type: ignore @@ -37,7 +39,9 @@ def __register_service(service: AbstractFernService) -> fastapi.APIRouter: def register_validators(module: types.ModuleType) -> None: validators_directory: str = os.path.dirname(module.__file__) # type: ignore - for path in glob.glob(os.path.join(validators_directory, "**/*.py"), recursive=True): + for path in glob.glob( + os.path.join(validators_directory, "**/*.py"), recursive=True + ): if os.path.isfile(path): relative_path = os.path.relpath(path, start=validators_directory) module_path = ".".join([module.__name__] + relative_path[:-3].split("/")) diff --git a/seed/fastapi/auth-environment-variables/resources/service/service/service.py b/seed/fastapi/auth-environment-variables/resources/service/service/service.py index c102bc7cc8f..4c19d95a7a8 100644 --- a/seed/fastapi/auth-environment-variables/resources/service/service/service.py +++ b/seed/fastapi/auth-environment-variables/resources/service/service/service.py @@ -1,17 +1,16 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.abstract_fern_service import AbstractFernService +from ....security import ApiAuth import abc -import functools +import fastapi import inspect -import logging import typing - -import fastapi - -from ....core.abstract_fern_service import AbstractFernService +from ....security import FernAuth from ....core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools from ....core.route_args import get_route_args -from ....security import ApiAuth, FernAuth class AbstractServiceService(AbstractFernService): @@ -51,16 +50,26 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_get_with_api_key(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_with_api_key) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "x_another_header": - new_parameters.append(parameter.replace(default=fastapi.Header(alias="X-Another-Header"))) + new_parameters.append( + parameter.replace(default=fastapi.Header(alias="X-Another-Header")) + ) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_with_api_key, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_with_api_key, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_with_api_key) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> str: @@ -89,16 +98,26 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> str: def __init_get_with_header(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_with_header) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "x_endpoint_header": - new_parameters.append(parameter.replace(default=fastapi.Header(alias="X-Endpoint-Header"))) + new_parameters.append( + parameter.replace(default=fastapi.Header(alias="X-Endpoint-Header")) + ) elif parameter_name == "x_another_header": - new_parameters.append(parameter.replace(default=fastapi.Header(alias="X-Another-Header"))) + new_parameters.append( + parameter.replace(default=fastapi.Header(alias="X-Another-Header")) + ) else: new_parameters.append(parameter) - setattr(cls.get_with_header, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_with_header, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_with_header) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> str: diff --git a/seed/fastapi/basic-auth-environment-variables/__init__.py b/seed/fastapi/basic-auth-environment-variables/__init__.py index d1fdab59d75..90a7340f393 100644 --- a/seed/fastapi/basic-auth-environment-variables/__init__.py +++ b/seed/fastapi/basic-auth-environment-variables/__init__.py @@ -1,6 +1,17 @@ # This file was auto-generated by Fern from our API Definition. -from .resources import BadRequest, UnauthorizedRequest, UnauthorizedRequestErrorBody, errors +from .resources import ( + BadRequest, + UnauthorizedRequest, + UnauthorizedRequestErrorBody, + errors, +) from .security import ApiAuth -__all__ = ["ApiAuth", "BadRequest", "UnauthorizedRequest", "UnauthorizedRequestErrorBody", "errors"] +__all__ = [ + "ApiAuth", + "BadRequest", + "UnauthorizedRequest", + "UnauthorizedRequestErrorBody", + "errors", +] diff --git a/seed/fastapi/basic-auth-environment-variables/core/abstract_fern_service.py b/seed/fastapi/basic-auth-environment-variables/core/abstract_fern_service.py index da7c8dc49c4..9966b4876da 100644 --- a/seed/fastapi/basic-auth-environment-variables/core/abstract_fern_service.py +++ b/seed/fastapi/basic-auth-environment-variables/core/abstract_fern_service.py @@ -7,5 +7,4 @@ class AbstractFernService(abc.ABC): @classmethod - def _init_fern(cls, router: fastapi.APIRouter) -> None: - ... + def _init_fern(cls, router: fastapi.APIRouter) -> None: ... diff --git a/seed/fastapi/basic-auth-environment-variables/core/datetime_utils.py b/seed/fastapi/basic-auth-environment-variables/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/fastapi/basic-auth-environment-variables/core/datetime_utils.py +++ b/seed/fastapi/basic-auth-environment-variables/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/fastapi/basic-auth-environment-variables/core/exceptions/__init__.py b/seed/fastapi/basic-auth-environment-variables/core/exceptions/__init__.py index 297d6e06f5f..dae4b8980c1 100644 --- a/seed/fastapi/basic-auth-environment-variables/core/exceptions/__init__.py +++ b/seed/fastapi/basic-auth-environment-variables/core/exceptions/__init__.py @@ -1,7 +1,11 @@ # This file was auto-generated by Fern from our API Definition. from .fern_http_exception import FernHTTPException -from .handlers import default_exception_handler, fern_http_exception_handler, http_exception_handler +from .handlers import ( + default_exception_handler, + fern_http_exception_handler, + http_exception_handler, +) from .unauthorized import UnauthorizedException __all__ = [ diff --git a/seed/fastapi/basic-auth-environment-variables/core/exceptions/fern_http_exception.py b/seed/fastapi/basic-auth-environment-variables/core/exceptions/fern_http_exception.py index bdf03862487..81610359a7f 100644 --- a/seed/fastapi/basic-auth-environment-variables/core/exceptions/fern_http_exception.py +++ b/seed/fastapi/basic-auth-environment-variables/core/exceptions/fern_http_exception.py @@ -1,14 +1,16 @@ # This file was auto-generated by Fern from our API Definition. import abc -import typing - import fastapi +import typing class FernHTTPException(abc.ABC, fastapi.HTTPException): def __init__( - self, status_code: int, name: typing.Optional[str] = None, content: typing.Optional[typing.Any] = None + self, + status_code: int, + name: typing.Optional[str] = None, + content: typing.Optional[typing.Any] = None, ): super().__init__(status_code=status_code) self.name = name @@ -17,4 +19,6 @@ def __init__( def to_json_response(self) -> fastapi.responses.JSONResponse: content = fastapi.encoders.jsonable_encoder(self.content, exclude_none=True) - return fastapi.responses.JSONResponse(content=content, status_code=self.status_code) + return fastapi.responses.JSONResponse( + content=content, status_code=self.status_code + ) diff --git a/seed/fastapi/basic-auth-environment-variables/core/exceptions/handlers.py b/seed/fastapi/basic-auth-environment-variables/core/exceptions/handlers.py index 6d8c4155c5a..ae1c2741f06 100644 --- a/seed/fastapi/basic-auth-environment-variables/core/exceptions/handlers.py +++ b/seed/fastapi/basic-auth-environment-variables/core/exceptions/handlers.py @@ -2,32 +2,49 @@ import logging -import fastapi import starlette import starlette.exceptions +import fastapi + from .fern_http_exception import FernHTTPException def fern_http_exception_handler( - request: fastapi.requests.Request, exc: FernHTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: FernHTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) return exc.to_json_response() def http_exception_handler( - request: fastapi.requests.Request, exc: starlette.exceptions.HTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: starlette.exceptions.HTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=exc.status_code, content=exc.detail).to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=exc.status_code, content=exc.detail + ).to_json_response() def default_exception_handler( - request: fastapi.requests.Request, exc: Exception, skip_log: bool = False + request: fastapi.requests.Request, + exc: Exception, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=500, content="Internal Server Error").to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=500, content="Internal Server Error" + ).to_json_response() diff --git a/seed/fastapi/basic-auth-environment-variables/core/pydantic_utilities.py b/seed/fastapi/basic-auth-environment-variables/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/fastapi/basic-auth-environment-variables/core/pydantic_utilities.py +++ b/seed/fastapi/basic-auth-environment-variables/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/fastapi/basic-auth-environment-variables/core/route_args.py b/seed/fastapi/basic-auth-environment-variables/core/route_args.py index 4228e2fe05d..bd940bf4ddd 100644 --- a/seed/fastapi/basic-auth-environment-variables/core/route_args.py +++ b/seed/fastapi/basic-auth-environment-variables/core/route_args.py @@ -20,9 +20,15 @@ class RouteArgs(typing_extensions.TypedDict): DEFAULT_ROUTE_ARGS = RouteArgs(openapi_extra=None, tags=None, include_in_schema=True) -def get_route_args(endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str) -> RouteArgs: - unwrapped = inspect.unwrap(endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY))) - route_args = typing.cast(RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS)) +def get_route_args( + endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str +) -> RouteArgs: + unwrapped = inspect.unwrap( + endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY)) + ) + route_args = typing.cast( + RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS) + ) if route_args["tags"] is None: return RouteArgs( openapi_extra=route_args["openapi_extra"], @@ -56,7 +62,11 @@ def decorator(endpoint_function: T) -> T: setattr( endpoint_function, FERN_CONFIG_KEY, - RouteArgs(openapi_extra=openapi_extra, tags=tags, include_in_schema=include_in_schema), + RouteArgs( + openapi_extra=openapi_extra, + tags=tags, + include_in_schema=include_in_schema, + ), ) return endpoint_function diff --git a/seed/fastapi/basic-auth-environment-variables/register.py b/seed/fastapi/basic-auth-environment-variables/register.py index 52ab408b6b4..43a8a9ed3c3 100644 --- a/seed/fastapi/basic-auth-environment-variables/register.py +++ b/seed/fastapi/basic-auth-environment-variables/register.py @@ -1,31 +1,33 @@ # This file was auto-generated by Fern from our API Definition. -import glob -import importlib -import os -import types -import typing - import fastapi -import starlette.exceptions +from .resources.basic_auth.service.service import AbstractBasicAuthService +import typing from fastapi import params - -from .core.abstract_fern_service import AbstractFernService -from .core.exceptions import default_exception_handler, fern_http_exception_handler, http_exception_handler from .core.exceptions.fern_http_exception import FernHTTPException -from .resources.basic_auth.service.service import AbstractBasicAuthService +from .core.exceptions import fern_http_exception_handler +import starlette.exceptions +from .core.exceptions import http_exception_handler +from .core.exceptions import default_exception_handler +from .core.abstract_fern_service import AbstractFernService +import types +import os +import glob +import importlib def register( _app: fastapi.FastAPI, *, basic_auth: AbstractBasicAuthService, - dependencies: typing.Optional[typing.Sequence[params.Depends]] = None + dependencies: typing.Optional[typing.Sequence[params.Depends]] = None, ) -> None: _app.include_router(__register_service(basic_auth), dependencies=dependencies) _app.add_exception_handler(FernHTTPException, fern_http_exception_handler) # type: ignore - _app.add_exception_handler(starlette.exceptions.HTTPException, http_exception_handler) # type: ignore + _app.add_exception_handler( + starlette.exceptions.HTTPException, http_exception_handler + ) # type: ignore _app.add_exception_handler(Exception, default_exception_handler) # type: ignore @@ -37,7 +39,9 @@ def __register_service(service: AbstractFernService) -> fastapi.APIRouter: def register_validators(module: types.ModuleType) -> None: validators_directory: str = os.path.dirname(module.__file__) # type: ignore - for path in glob.glob(os.path.join(validators_directory, "**/*.py"), recursive=True): + for path in glob.glob( + os.path.join(validators_directory, "**/*.py"), recursive=True + ): if os.path.isfile(path): relative_path = os.path.relpath(path, start=validators_directory) module_path = ".".join([module.__name__] + relative_path[:-3].split("/")) diff --git a/seed/fastapi/basic-auth-environment-variables/resources/__init__.py b/seed/fastapi/basic-auth-environment-variables/resources/__init__.py index f79f35dadbe..caef920f984 100644 --- a/seed/fastapi/basic-auth-environment-variables/resources/__init__.py +++ b/seed/fastapi/basic-auth-environment-variables/resources/__init__.py @@ -3,4 +3,9 @@ from . import errors from .errors import BadRequest, UnauthorizedRequest, UnauthorizedRequestErrorBody -__all__ = ["BadRequest", "UnauthorizedRequest", "UnauthorizedRequestErrorBody", "errors"] +__all__ = [ + "BadRequest", + "UnauthorizedRequest", + "UnauthorizedRequestErrorBody", + "errors", +] diff --git a/seed/fastapi/basic-auth-environment-variables/resources/basic_auth/service/service.py b/seed/fastapi/basic-auth-environment-variables/resources/basic_auth/service/service.py index ebea7cee667..8bf5c065d59 100644 --- a/seed/fastapi/basic-auth-environment-variables/resources/basic_auth/service/service.py +++ b/seed/fastapi/basic-auth-environment-variables/resources/basic_auth/service/service.py @@ -1,19 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.abstract_fern_service import AbstractFernService +from ....security import ApiAuth import abc -import functools -import inspect -import logging import typing - import fastapi - -from ....core.abstract_fern_service import AbstractFernService +import inspect +from ....security import FernAuth +from ...errors.errors.unauthorized_request import UnauthorizedRequest from ....core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools from ....core.route_args import get_route_args -from ....security import ApiAuth, FernAuth from ...errors.errors.bad_request import BadRequest -from ...errors.errors.unauthorized_request import UnauthorizedRequest class AbstractBasicAuthService(AbstractFernService): @@ -53,14 +52,22 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_get_with_basic_auth(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_with_basic_auth) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_with_basic_auth, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_with_basic_auth, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_with_basic_auth) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> bool: @@ -91,16 +98,24 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> bool: def __init_post_with_basic_auth(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.post_with_basic_auth) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.post_with_basic_auth, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.post_with_basic_auth, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.post_with_basic_auth) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> bool: diff --git a/seed/fastapi/basic-auth-environment-variables/resources/errors/types/unauthorized_request_error_body.py b/seed/fastapi/basic-auth-environment-variables/resources/errors/types/unauthorized_request_error_body.py index d1ad508cd7c..8cb512007db 100644 --- a/seed/fastapi/basic-auth-environment-variables/resources/errors/types/unauthorized_request_error_body.py +++ b/seed/fastapi/basic-auth-environment-variables/resources/errors/types/unauthorized_request_error_body.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class UnauthorizedRequestErrorBody(UniversalBaseModel): message: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/basic-auth/__init__.py b/seed/fastapi/basic-auth/__init__.py index d1fdab59d75..90a7340f393 100644 --- a/seed/fastapi/basic-auth/__init__.py +++ b/seed/fastapi/basic-auth/__init__.py @@ -1,6 +1,17 @@ # This file was auto-generated by Fern from our API Definition. -from .resources import BadRequest, UnauthorizedRequest, UnauthorizedRequestErrorBody, errors +from .resources import ( + BadRequest, + UnauthorizedRequest, + UnauthorizedRequestErrorBody, + errors, +) from .security import ApiAuth -__all__ = ["ApiAuth", "BadRequest", "UnauthorizedRequest", "UnauthorizedRequestErrorBody", "errors"] +__all__ = [ + "ApiAuth", + "BadRequest", + "UnauthorizedRequest", + "UnauthorizedRequestErrorBody", + "errors", +] diff --git a/seed/fastapi/basic-auth/core/abstract_fern_service.py b/seed/fastapi/basic-auth/core/abstract_fern_service.py index da7c8dc49c4..9966b4876da 100644 --- a/seed/fastapi/basic-auth/core/abstract_fern_service.py +++ b/seed/fastapi/basic-auth/core/abstract_fern_service.py @@ -7,5 +7,4 @@ class AbstractFernService(abc.ABC): @classmethod - def _init_fern(cls, router: fastapi.APIRouter) -> None: - ... + def _init_fern(cls, router: fastapi.APIRouter) -> None: ... diff --git a/seed/fastapi/basic-auth/core/datetime_utils.py b/seed/fastapi/basic-auth/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/fastapi/basic-auth/core/datetime_utils.py +++ b/seed/fastapi/basic-auth/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/fastapi/basic-auth/core/exceptions/__init__.py b/seed/fastapi/basic-auth/core/exceptions/__init__.py index 297d6e06f5f..dae4b8980c1 100644 --- a/seed/fastapi/basic-auth/core/exceptions/__init__.py +++ b/seed/fastapi/basic-auth/core/exceptions/__init__.py @@ -1,7 +1,11 @@ # This file was auto-generated by Fern from our API Definition. from .fern_http_exception import FernHTTPException -from .handlers import default_exception_handler, fern_http_exception_handler, http_exception_handler +from .handlers import ( + default_exception_handler, + fern_http_exception_handler, + http_exception_handler, +) from .unauthorized import UnauthorizedException __all__ = [ diff --git a/seed/fastapi/basic-auth/core/exceptions/fern_http_exception.py b/seed/fastapi/basic-auth/core/exceptions/fern_http_exception.py index bdf03862487..81610359a7f 100644 --- a/seed/fastapi/basic-auth/core/exceptions/fern_http_exception.py +++ b/seed/fastapi/basic-auth/core/exceptions/fern_http_exception.py @@ -1,14 +1,16 @@ # This file was auto-generated by Fern from our API Definition. import abc -import typing - import fastapi +import typing class FernHTTPException(abc.ABC, fastapi.HTTPException): def __init__( - self, status_code: int, name: typing.Optional[str] = None, content: typing.Optional[typing.Any] = None + self, + status_code: int, + name: typing.Optional[str] = None, + content: typing.Optional[typing.Any] = None, ): super().__init__(status_code=status_code) self.name = name @@ -17,4 +19,6 @@ def __init__( def to_json_response(self) -> fastapi.responses.JSONResponse: content = fastapi.encoders.jsonable_encoder(self.content, exclude_none=True) - return fastapi.responses.JSONResponse(content=content, status_code=self.status_code) + return fastapi.responses.JSONResponse( + content=content, status_code=self.status_code + ) diff --git a/seed/fastapi/basic-auth/core/exceptions/handlers.py b/seed/fastapi/basic-auth/core/exceptions/handlers.py index 6d8c4155c5a..ae1c2741f06 100644 --- a/seed/fastapi/basic-auth/core/exceptions/handlers.py +++ b/seed/fastapi/basic-auth/core/exceptions/handlers.py @@ -2,32 +2,49 @@ import logging -import fastapi import starlette import starlette.exceptions +import fastapi + from .fern_http_exception import FernHTTPException def fern_http_exception_handler( - request: fastapi.requests.Request, exc: FernHTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: FernHTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) return exc.to_json_response() def http_exception_handler( - request: fastapi.requests.Request, exc: starlette.exceptions.HTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: starlette.exceptions.HTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=exc.status_code, content=exc.detail).to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=exc.status_code, content=exc.detail + ).to_json_response() def default_exception_handler( - request: fastapi.requests.Request, exc: Exception, skip_log: bool = False + request: fastapi.requests.Request, + exc: Exception, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=500, content="Internal Server Error").to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=500, content="Internal Server Error" + ).to_json_response() diff --git a/seed/fastapi/basic-auth/core/pydantic_utilities.py b/seed/fastapi/basic-auth/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/fastapi/basic-auth/core/pydantic_utilities.py +++ b/seed/fastapi/basic-auth/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/fastapi/basic-auth/core/route_args.py b/seed/fastapi/basic-auth/core/route_args.py index 4228e2fe05d..bd940bf4ddd 100644 --- a/seed/fastapi/basic-auth/core/route_args.py +++ b/seed/fastapi/basic-auth/core/route_args.py @@ -20,9 +20,15 @@ class RouteArgs(typing_extensions.TypedDict): DEFAULT_ROUTE_ARGS = RouteArgs(openapi_extra=None, tags=None, include_in_schema=True) -def get_route_args(endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str) -> RouteArgs: - unwrapped = inspect.unwrap(endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY))) - route_args = typing.cast(RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS)) +def get_route_args( + endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str +) -> RouteArgs: + unwrapped = inspect.unwrap( + endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY)) + ) + route_args = typing.cast( + RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS) + ) if route_args["tags"] is None: return RouteArgs( openapi_extra=route_args["openapi_extra"], @@ -56,7 +62,11 @@ def decorator(endpoint_function: T) -> T: setattr( endpoint_function, FERN_CONFIG_KEY, - RouteArgs(openapi_extra=openapi_extra, tags=tags, include_in_schema=include_in_schema), + RouteArgs( + openapi_extra=openapi_extra, + tags=tags, + include_in_schema=include_in_schema, + ), ) return endpoint_function diff --git a/seed/fastapi/basic-auth/register.py b/seed/fastapi/basic-auth/register.py index 52ab408b6b4..43a8a9ed3c3 100644 --- a/seed/fastapi/basic-auth/register.py +++ b/seed/fastapi/basic-auth/register.py @@ -1,31 +1,33 @@ # This file was auto-generated by Fern from our API Definition. -import glob -import importlib -import os -import types -import typing - import fastapi -import starlette.exceptions +from .resources.basic_auth.service.service import AbstractBasicAuthService +import typing from fastapi import params - -from .core.abstract_fern_service import AbstractFernService -from .core.exceptions import default_exception_handler, fern_http_exception_handler, http_exception_handler from .core.exceptions.fern_http_exception import FernHTTPException -from .resources.basic_auth.service.service import AbstractBasicAuthService +from .core.exceptions import fern_http_exception_handler +import starlette.exceptions +from .core.exceptions import http_exception_handler +from .core.exceptions import default_exception_handler +from .core.abstract_fern_service import AbstractFernService +import types +import os +import glob +import importlib def register( _app: fastapi.FastAPI, *, basic_auth: AbstractBasicAuthService, - dependencies: typing.Optional[typing.Sequence[params.Depends]] = None + dependencies: typing.Optional[typing.Sequence[params.Depends]] = None, ) -> None: _app.include_router(__register_service(basic_auth), dependencies=dependencies) _app.add_exception_handler(FernHTTPException, fern_http_exception_handler) # type: ignore - _app.add_exception_handler(starlette.exceptions.HTTPException, http_exception_handler) # type: ignore + _app.add_exception_handler( + starlette.exceptions.HTTPException, http_exception_handler + ) # type: ignore _app.add_exception_handler(Exception, default_exception_handler) # type: ignore @@ -37,7 +39,9 @@ def __register_service(service: AbstractFernService) -> fastapi.APIRouter: def register_validators(module: types.ModuleType) -> None: validators_directory: str = os.path.dirname(module.__file__) # type: ignore - for path in glob.glob(os.path.join(validators_directory, "**/*.py"), recursive=True): + for path in glob.glob( + os.path.join(validators_directory, "**/*.py"), recursive=True + ): if os.path.isfile(path): relative_path = os.path.relpath(path, start=validators_directory) module_path = ".".join([module.__name__] + relative_path[:-3].split("/")) diff --git a/seed/fastapi/basic-auth/resources/__init__.py b/seed/fastapi/basic-auth/resources/__init__.py index f79f35dadbe..caef920f984 100644 --- a/seed/fastapi/basic-auth/resources/__init__.py +++ b/seed/fastapi/basic-auth/resources/__init__.py @@ -3,4 +3,9 @@ from . import errors from .errors import BadRequest, UnauthorizedRequest, UnauthorizedRequestErrorBody -__all__ = ["BadRequest", "UnauthorizedRequest", "UnauthorizedRequestErrorBody", "errors"] +__all__ = [ + "BadRequest", + "UnauthorizedRequest", + "UnauthorizedRequestErrorBody", + "errors", +] diff --git a/seed/fastapi/basic-auth/resources/basic_auth/service/service.py b/seed/fastapi/basic-auth/resources/basic_auth/service/service.py index ebea7cee667..8bf5c065d59 100644 --- a/seed/fastapi/basic-auth/resources/basic_auth/service/service.py +++ b/seed/fastapi/basic-auth/resources/basic_auth/service/service.py @@ -1,19 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.abstract_fern_service import AbstractFernService +from ....security import ApiAuth import abc -import functools -import inspect -import logging import typing - import fastapi - -from ....core.abstract_fern_service import AbstractFernService +import inspect +from ....security import FernAuth +from ...errors.errors.unauthorized_request import UnauthorizedRequest from ....core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools from ....core.route_args import get_route_args -from ....security import ApiAuth, FernAuth from ...errors.errors.bad_request import BadRequest -from ...errors.errors.unauthorized_request import UnauthorizedRequest class AbstractBasicAuthService(AbstractFernService): @@ -53,14 +52,22 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_get_with_basic_auth(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_with_basic_auth) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_with_basic_auth, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_with_basic_auth, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_with_basic_auth) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> bool: @@ -91,16 +98,24 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> bool: def __init_post_with_basic_auth(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.post_with_basic_auth) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.post_with_basic_auth, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.post_with_basic_auth, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.post_with_basic_auth) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> bool: diff --git a/seed/fastapi/basic-auth/resources/errors/types/unauthorized_request_error_body.py b/seed/fastapi/basic-auth/resources/errors/types/unauthorized_request_error_body.py index d1ad508cd7c..8cb512007db 100644 --- a/seed/fastapi/basic-auth/resources/errors/types/unauthorized_request_error_body.py +++ b/seed/fastapi/basic-auth/resources/errors/types/unauthorized_request_error_body.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class UnauthorizedRequestErrorBody(UniversalBaseModel): message: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/bearer-token-environment-variable/core/abstract_fern_service.py b/seed/fastapi/bearer-token-environment-variable/core/abstract_fern_service.py index da7c8dc49c4..9966b4876da 100644 --- a/seed/fastapi/bearer-token-environment-variable/core/abstract_fern_service.py +++ b/seed/fastapi/bearer-token-environment-variable/core/abstract_fern_service.py @@ -7,5 +7,4 @@ class AbstractFernService(abc.ABC): @classmethod - def _init_fern(cls, router: fastapi.APIRouter) -> None: - ... + def _init_fern(cls, router: fastapi.APIRouter) -> None: ... diff --git a/seed/fastapi/bearer-token-environment-variable/core/datetime_utils.py b/seed/fastapi/bearer-token-environment-variable/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/fastapi/bearer-token-environment-variable/core/datetime_utils.py +++ b/seed/fastapi/bearer-token-environment-variable/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/fastapi/bearer-token-environment-variable/core/exceptions/__init__.py b/seed/fastapi/bearer-token-environment-variable/core/exceptions/__init__.py index 297d6e06f5f..dae4b8980c1 100644 --- a/seed/fastapi/bearer-token-environment-variable/core/exceptions/__init__.py +++ b/seed/fastapi/bearer-token-environment-variable/core/exceptions/__init__.py @@ -1,7 +1,11 @@ # This file was auto-generated by Fern from our API Definition. from .fern_http_exception import FernHTTPException -from .handlers import default_exception_handler, fern_http_exception_handler, http_exception_handler +from .handlers import ( + default_exception_handler, + fern_http_exception_handler, + http_exception_handler, +) from .unauthorized import UnauthorizedException __all__ = [ diff --git a/seed/fastapi/bearer-token-environment-variable/core/exceptions/fern_http_exception.py b/seed/fastapi/bearer-token-environment-variable/core/exceptions/fern_http_exception.py index bdf03862487..81610359a7f 100644 --- a/seed/fastapi/bearer-token-environment-variable/core/exceptions/fern_http_exception.py +++ b/seed/fastapi/bearer-token-environment-variable/core/exceptions/fern_http_exception.py @@ -1,14 +1,16 @@ # This file was auto-generated by Fern from our API Definition. import abc -import typing - import fastapi +import typing class FernHTTPException(abc.ABC, fastapi.HTTPException): def __init__( - self, status_code: int, name: typing.Optional[str] = None, content: typing.Optional[typing.Any] = None + self, + status_code: int, + name: typing.Optional[str] = None, + content: typing.Optional[typing.Any] = None, ): super().__init__(status_code=status_code) self.name = name @@ -17,4 +19,6 @@ def __init__( def to_json_response(self) -> fastapi.responses.JSONResponse: content = fastapi.encoders.jsonable_encoder(self.content, exclude_none=True) - return fastapi.responses.JSONResponse(content=content, status_code=self.status_code) + return fastapi.responses.JSONResponse( + content=content, status_code=self.status_code + ) diff --git a/seed/fastapi/bearer-token-environment-variable/core/exceptions/handlers.py b/seed/fastapi/bearer-token-environment-variable/core/exceptions/handlers.py index 6d8c4155c5a..ae1c2741f06 100644 --- a/seed/fastapi/bearer-token-environment-variable/core/exceptions/handlers.py +++ b/seed/fastapi/bearer-token-environment-variable/core/exceptions/handlers.py @@ -2,32 +2,49 @@ import logging -import fastapi import starlette import starlette.exceptions +import fastapi + from .fern_http_exception import FernHTTPException def fern_http_exception_handler( - request: fastapi.requests.Request, exc: FernHTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: FernHTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) return exc.to_json_response() def http_exception_handler( - request: fastapi.requests.Request, exc: starlette.exceptions.HTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: starlette.exceptions.HTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=exc.status_code, content=exc.detail).to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=exc.status_code, content=exc.detail + ).to_json_response() def default_exception_handler( - request: fastapi.requests.Request, exc: Exception, skip_log: bool = False + request: fastapi.requests.Request, + exc: Exception, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=500, content="Internal Server Error").to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=500, content="Internal Server Error" + ).to_json_response() diff --git a/seed/fastapi/bearer-token-environment-variable/core/pydantic_utilities.py b/seed/fastapi/bearer-token-environment-variable/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/fastapi/bearer-token-environment-variable/core/pydantic_utilities.py +++ b/seed/fastapi/bearer-token-environment-variable/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/fastapi/bearer-token-environment-variable/core/route_args.py b/seed/fastapi/bearer-token-environment-variable/core/route_args.py index 4228e2fe05d..bd940bf4ddd 100644 --- a/seed/fastapi/bearer-token-environment-variable/core/route_args.py +++ b/seed/fastapi/bearer-token-environment-variable/core/route_args.py @@ -20,9 +20,15 @@ class RouteArgs(typing_extensions.TypedDict): DEFAULT_ROUTE_ARGS = RouteArgs(openapi_extra=None, tags=None, include_in_schema=True) -def get_route_args(endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str) -> RouteArgs: - unwrapped = inspect.unwrap(endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY))) - route_args = typing.cast(RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS)) +def get_route_args( + endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str +) -> RouteArgs: + unwrapped = inspect.unwrap( + endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY)) + ) + route_args = typing.cast( + RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS) + ) if route_args["tags"] is None: return RouteArgs( openapi_extra=route_args["openapi_extra"], @@ -56,7 +62,11 @@ def decorator(endpoint_function: T) -> T: setattr( endpoint_function, FERN_CONFIG_KEY, - RouteArgs(openapi_extra=openapi_extra, tags=tags, include_in_schema=include_in_schema), + RouteArgs( + openapi_extra=openapi_extra, + tags=tags, + include_in_schema=include_in_schema, + ), ) return endpoint_function diff --git a/seed/fastapi/bearer-token-environment-variable/register.py b/seed/fastapi/bearer-token-environment-variable/register.py index ebdfdf9318d..1d60bbe4d5d 100644 --- a/seed/fastapi/bearer-token-environment-variable/register.py +++ b/seed/fastapi/bearer-token-environment-variable/register.py @@ -1,31 +1,33 @@ # This file was auto-generated by Fern from our API Definition. -import glob -import importlib -import os -import types -import typing - import fastapi -import starlette.exceptions +from .resources.service.service.service import AbstractServiceService +import typing from fastapi import params - -from .core.abstract_fern_service import AbstractFernService -from .core.exceptions import default_exception_handler, fern_http_exception_handler, http_exception_handler from .core.exceptions.fern_http_exception import FernHTTPException -from .resources.service.service.service import AbstractServiceService +from .core.exceptions import fern_http_exception_handler +import starlette.exceptions +from .core.exceptions import http_exception_handler +from .core.exceptions import default_exception_handler +from .core.abstract_fern_service import AbstractFernService +import types +import os +import glob +import importlib def register( _app: fastapi.FastAPI, *, service: AbstractServiceService, - dependencies: typing.Optional[typing.Sequence[params.Depends]] = None + dependencies: typing.Optional[typing.Sequence[params.Depends]] = None, ) -> None: _app.include_router(__register_service(service), dependencies=dependencies) _app.add_exception_handler(FernHTTPException, fern_http_exception_handler) # type: ignore - _app.add_exception_handler(starlette.exceptions.HTTPException, http_exception_handler) # type: ignore + _app.add_exception_handler( + starlette.exceptions.HTTPException, http_exception_handler + ) # type: ignore _app.add_exception_handler(Exception, default_exception_handler) # type: ignore @@ -37,7 +39,9 @@ def __register_service(service: AbstractFernService) -> fastapi.APIRouter: def register_validators(module: types.ModuleType) -> None: validators_directory: str = os.path.dirname(module.__file__) # type: ignore - for path in glob.glob(os.path.join(validators_directory, "**/*.py"), recursive=True): + for path in glob.glob( + os.path.join(validators_directory, "**/*.py"), recursive=True + ): if os.path.isfile(path): relative_path = os.path.relpath(path, start=validators_directory) module_path = ".".join([module.__name__] + relative_path[:-3].split("/")) diff --git a/seed/fastapi/bearer-token-environment-variable/resources/service/service/service.py b/seed/fastapi/bearer-token-environment-variable/resources/service/service/service.py index 64796ce6ac1..e4fbf5d4f37 100644 --- a/seed/fastapi/bearer-token-environment-variable/resources/service/service/service.py +++ b/seed/fastapi/bearer-token-environment-variable/resources/service/service/service.py @@ -1,17 +1,16 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.abstract_fern_service import AbstractFernService +from ....security import ApiAuth import abc -import functools +import fastapi import inspect -import logging import typing - -import fastapi - -from ....core.abstract_fern_service import AbstractFernService +from ....security import FernAuth from ....core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools from ....core.route_args import get_route_args -from ....security import ApiAuth, FernAuth class AbstractServiceService(AbstractFernService): @@ -43,14 +42,22 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_get_with_bearer_token(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_with_bearer_token) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_with_bearer_token, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_with_bearer_token, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_with_bearer_token) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> str: diff --git a/seed/fastapi/bearer-token-environment-variable/security.py b/seed/fastapi/bearer-token-environment-variable/security.py index bab014441e1..4ccabc21106 100644 --- a/seed/fastapi/bearer-token-environment-variable/security.py +++ b/seed/fastapi/bearer-token-environment-variable/security.py @@ -1,8 +1,8 @@ # This file was auto-generated by Fern from our API Definition. +from .core.security.bearer import BearerToken import fastapi - -from .core.security.bearer import BearerToken, HTTPBearer +from .core.security.bearer import HTTPBearer ApiAuth = BearerToken diff --git a/seed/fastapi/circular-references-advanced/__init__.py b/seed/fastapi/circular-references-advanced/__init__.py index 4d306681bf5..3950c426090 100644 --- a/seed/fastapi/circular-references-advanced/__init__.py +++ b/seed/fastapi/circular-references-advanced/__init__.py @@ -1,6 +1,16 @@ # This file was auto-generated by Fern from our API Definition. -from .resources import A, ContainerValue, FieldName, FieldValue, ObjectFieldValue, ObjectValue, PrimitiveValue, a, ast +from .resources import ( + A, + ContainerValue, + FieldName, + FieldValue, + ObjectFieldValue, + ObjectValue, + PrimitiveValue, + a, + ast, +) from .types import ImportingA, RootType __all__ = [ diff --git a/seed/fastapi/circular-references-advanced/core/abstract_fern_service.py b/seed/fastapi/circular-references-advanced/core/abstract_fern_service.py index da7c8dc49c4..9966b4876da 100644 --- a/seed/fastapi/circular-references-advanced/core/abstract_fern_service.py +++ b/seed/fastapi/circular-references-advanced/core/abstract_fern_service.py @@ -7,5 +7,4 @@ class AbstractFernService(abc.ABC): @classmethod - def _init_fern(cls, router: fastapi.APIRouter) -> None: - ... + def _init_fern(cls, router: fastapi.APIRouter) -> None: ... diff --git a/seed/fastapi/circular-references-advanced/core/datetime_utils.py b/seed/fastapi/circular-references-advanced/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/fastapi/circular-references-advanced/core/datetime_utils.py +++ b/seed/fastapi/circular-references-advanced/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/fastapi/circular-references-advanced/core/exceptions/__init__.py b/seed/fastapi/circular-references-advanced/core/exceptions/__init__.py index 297d6e06f5f..dae4b8980c1 100644 --- a/seed/fastapi/circular-references-advanced/core/exceptions/__init__.py +++ b/seed/fastapi/circular-references-advanced/core/exceptions/__init__.py @@ -1,7 +1,11 @@ # This file was auto-generated by Fern from our API Definition. from .fern_http_exception import FernHTTPException -from .handlers import default_exception_handler, fern_http_exception_handler, http_exception_handler +from .handlers import ( + default_exception_handler, + fern_http_exception_handler, + http_exception_handler, +) from .unauthorized import UnauthorizedException __all__ = [ diff --git a/seed/fastapi/circular-references-advanced/core/exceptions/fern_http_exception.py b/seed/fastapi/circular-references-advanced/core/exceptions/fern_http_exception.py index bdf03862487..81610359a7f 100644 --- a/seed/fastapi/circular-references-advanced/core/exceptions/fern_http_exception.py +++ b/seed/fastapi/circular-references-advanced/core/exceptions/fern_http_exception.py @@ -1,14 +1,16 @@ # This file was auto-generated by Fern from our API Definition. import abc -import typing - import fastapi +import typing class FernHTTPException(abc.ABC, fastapi.HTTPException): def __init__( - self, status_code: int, name: typing.Optional[str] = None, content: typing.Optional[typing.Any] = None + self, + status_code: int, + name: typing.Optional[str] = None, + content: typing.Optional[typing.Any] = None, ): super().__init__(status_code=status_code) self.name = name @@ -17,4 +19,6 @@ def __init__( def to_json_response(self) -> fastapi.responses.JSONResponse: content = fastapi.encoders.jsonable_encoder(self.content, exclude_none=True) - return fastapi.responses.JSONResponse(content=content, status_code=self.status_code) + return fastapi.responses.JSONResponse( + content=content, status_code=self.status_code + ) diff --git a/seed/fastapi/circular-references-advanced/core/exceptions/handlers.py b/seed/fastapi/circular-references-advanced/core/exceptions/handlers.py index 6d8c4155c5a..ae1c2741f06 100644 --- a/seed/fastapi/circular-references-advanced/core/exceptions/handlers.py +++ b/seed/fastapi/circular-references-advanced/core/exceptions/handlers.py @@ -2,32 +2,49 @@ import logging -import fastapi import starlette import starlette.exceptions +import fastapi + from .fern_http_exception import FernHTTPException def fern_http_exception_handler( - request: fastapi.requests.Request, exc: FernHTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: FernHTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) return exc.to_json_response() def http_exception_handler( - request: fastapi.requests.Request, exc: starlette.exceptions.HTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: starlette.exceptions.HTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=exc.status_code, content=exc.detail).to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=exc.status_code, content=exc.detail + ).to_json_response() def default_exception_handler( - request: fastapi.requests.Request, exc: Exception, skip_log: bool = False + request: fastapi.requests.Request, + exc: Exception, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=500, content="Internal Server Error").to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=500, content="Internal Server Error" + ).to_json_response() diff --git a/seed/fastapi/circular-references-advanced/core/pydantic_utilities.py b/seed/fastapi/circular-references-advanced/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/fastapi/circular-references-advanced/core/pydantic_utilities.py +++ b/seed/fastapi/circular-references-advanced/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/fastapi/circular-references-advanced/core/route_args.py b/seed/fastapi/circular-references-advanced/core/route_args.py index 4228e2fe05d..bd940bf4ddd 100644 --- a/seed/fastapi/circular-references-advanced/core/route_args.py +++ b/seed/fastapi/circular-references-advanced/core/route_args.py @@ -20,9 +20,15 @@ class RouteArgs(typing_extensions.TypedDict): DEFAULT_ROUTE_ARGS = RouteArgs(openapi_extra=None, tags=None, include_in_schema=True) -def get_route_args(endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str) -> RouteArgs: - unwrapped = inspect.unwrap(endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY))) - route_args = typing.cast(RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS)) +def get_route_args( + endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str +) -> RouteArgs: + unwrapped = inspect.unwrap( + endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY)) + ) + route_args = typing.cast( + RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS) + ) if route_args["tags"] is None: return RouteArgs( openapi_extra=route_args["openapi_extra"], @@ -56,7 +62,11 @@ def decorator(endpoint_function: T) -> T: setattr( endpoint_function, FERN_CONFIG_KEY, - RouteArgs(openapi_extra=openapi_extra, tags=tags, include_in_schema=include_in_schema), + RouteArgs( + openapi_extra=openapi_extra, + tags=tags, + include_in_schema=include_in_schema, + ), ) return endpoint_function diff --git a/seed/fastapi/circular-references-advanced/register.py b/seed/fastapi/circular-references-advanced/register.py index 6f6e6707f03..a536c0ce4e4 100644 --- a/seed/fastapi/circular-references-advanced/register.py +++ b/seed/fastapi/circular-references-advanced/register.py @@ -1,23 +1,29 @@ # This file was auto-generated by Fern from our API Definition. -import glob -import importlib -import os -import types -import typing - import fastapi -import starlette.exceptions +import typing from fastapi import params - -from .core.abstract_fern_service import AbstractFernService -from .core.exceptions import default_exception_handler, fern_http_exception_handler, http_exception_handler from .core.exceptions.fern_http_exception import FernHTTPException +from .core.exceptions import fern_http_exception_handler +import starlette.exceptions +from .core.exceptions import http_exception_handler +from .core.exceptions import default_exception_handler +from .core.abstract_fern_service import AbstractFernService +import types +import os +import glob +import importlib -def register(_app: fastapi.FastAPI, *, dependencies: typing.Optional[typing.Sequence[params.Depends]] = None) -> None: +def register( + _app: fastapi.FastAPI, + *, + dependencies: typing.Optional[typing.Sequence[params.Depends]] = None, +) -> None: _app.add_exception_handler(FernHTTPException, fern_http_exception_handler) # type: ignore - _app.add_exception_handler(starlette.exceptions.HTTPException, http_exception_handler) # type: ignore + _app.add_exception_handler( + starlette.exceptions.HTTPException, http_exception_handler + ) # type: ignore _app.add_exception_handler(Exception, default_exception_handler) # type: ignore @@ -29,7 +35,9 @@ def __register_service(service: AbstractFernService) -> fastapi.APIRouter: def register_validators(module: types.ModuleType) -> None: validators_directory: str = os.path.dirname(module.__file__) # type: ignore - for path in glob.glob(os.path.join(validators_directory, "**/*.py"), recursive=True): + for path in glob.glob( + os.path.join(validators_directory, "**/*.py"), recursive=True + ): if os.path.isfile(path): relative_path = os.path.relpath(path, start=validators_directory) module_path = ".".join([module.__name__] + relative_path[:-3].split("/")) diff --git a/seed/fastapi/circular-references-advanced/resources/__init__.py b/seed/fastapi/circular-references-advanced/resources/__init__.py index f6b1eb525a7..5d7a95c56dd 100644 --- a/seed/fastapi/circular-references-advanced/resources/__init__.py +++ b/seed/fastapi/circular-references-advanced/resources/__init__.py @@ -2,7 +2,14 @@ from . import a, ast from .a import A -from .ast import ContainerValue, FieldName, FieldValue, ObjectFieldValue, ObjectValue, PrimitiveValue +from .ast import ( + ContainerValue, + FieldName, + FieldValue, + ObjectFieldValue, + ObjectValue, + PrimitiveValue, +) __all__ = [ "A", diff --git a/seed/fastapi/circular-references-advanced/resources/a/types/a.py b/seed/fastapi/circular-references-advanced/resources/a/types/a.py index 0dc67089d18..0205033683c 100644 --- a/seed/fastapi/circular-references-advanced/resources/a/types/a.py +++ b/seed/fastapi/circular-references-advanced/resources/a/types/a.py @@ -1,16 +1,16 @@ # This file was auto-generated by Fern from our API Definition. +from ....types.root_type import RootType +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2 -from ....types.root_type import RootType - class A(RootType): if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/circular-references-advanced/resources/ast/__init__.py b/seed/fastapi/circular-references-advanced/resources/ast/__init__.py index 772839cd218..78c33bc0e58 100644 --- a/seed/fastapi/circular-references-advanced/resources/ast/__init__.py +++ b/seed/fastapi/circular-references-advanced/resources/ast/__init__.py @@ -1,5 +1,19 @@ # This file was auto-generated by Fern from our API Definition. -from .types import ContainerValue, FieldName, FieldValue, ObjectFieldValue, ObjectValue, PrimitiveValue +from .types import ( + ContainerValue, + FieldName, + FieldValue, + ObjectFieldValue, + ObjectValue, + PrimitiveValue, +) -__all__ = ["ContainerValue", "FieldName", "FieldValue", "ObjectFieldValue", "ObjectValue", "PrimitiveValue"] +__all__ = [ + "ContainerValue", + "FieldName", + "FieldValue", + "ObjectFieldValue", + "ObjectValue", + "PrimitiveValue", +] diff --git a/seed/fastapi/circular-references-advanced/resources/ast/types/__init__.py b/seed/fastapi/circular-references-advanced/resources/ast/types/__init__.py index 1b46ecbb7ae..fc2f7ad7524 100644 --- a/seed/fastapi/circular-references-advanced/resources/ast/types/__init__.py +++ b/seed/fastapi/circular-references-advanced/resources/ast/types/__init__.py @@ -7,4 +7,11 @@ from .object_value import ObjectValue from .primitive_value import PrimitiveValue -__all__ = ["ContainerValue", "FieldName", "FieldValue", "ObjectFieldValue", "ObjectValue", "PrimitiveValue"] +__all__ = [ + "ContainerValue", + "FieldName", + "FieldValue", + "ObjectFieldValue", + "ObjectValue", + "PrimitiveValue", +] diff --git a/seed/fastapi/circular-references-advanced/resources/ast/types/container_value.py b/seed/fastapi/circular-references-advanced/resources/ast/types/container_value.py index fd6906fe08f..b56bf7c924d 100644 --- a/seed/fastapi/circular-references-advanced/resources/ast/types/container_value.py +++ b/seed/fastapi/circular-references-advanced/resources/ast/types/container_value.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - import typing - -import pydantic +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +from ....core.pydantic_utilities import UniversalRootModel import typing_extensions - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel, UniversalRootModel, update_forward_refs +import pydantic +from ....core.pydantic_utilities import UniversalBaseModel +from ....core.pydantic_utilities import update_forward_refs T_Result = typing.TypeVar("T_Result") @@ -17,13 +17,19 @@ def list_(self, value: typing.List[FieldValue]) -> ContainerValue: if IS_PYDANTIC_V2: return ContainerValue(root=_ContainerValue.List(type="list", value=value)) else: - return ContainerValue(__root__=_ContainerValue.List(type="list", value=value)) + return ContainerValue( + __root__=_ContainerValue.List(type="list", value=value) + ) def optional(self, value: typing.Optional[FieldValue]) -> ContainerValue: if IS_PYDANTIC_V2: - return ContainerValue(root=_ContainerValue.Optional(type="optional", value=value)) + return ContainerValue( + root=_ContainerValue.Optional(type="optional", value=value) + ) else: - return ContainerValue(__root__=_ContainerValue.Optional(type="optional", value=value)) + return ContainerValue( + __root__=_ContainerValue.Optional(type="optional", value=value) + ) class ContainerValue(UniversalRootModel): @@ -31,18 +37,23 @@ class ContainerValue(UniversalRootModel): if IS_PYDANTIC_V2: root: typing_extensions.Annotated[ - typing.Union[_ContainerValue.List, _ContainerValue.Optional], pydantic.Field(discriminator="type") + typing.Union[_ContainerValue.List, _ContainerValue.Optional], + pydantic.Field(discriminator="type"), ] - def get_as_union(self) -> typing.Union[_ContainerValue.List, _ContainerValue.Optional]: + def get_as_union( + self, + ) -> typing.Union[_ContainerValue.List, _ContainerValue.Optional]: return self.root - else: __root__: typing_extensions.Annotated[ - typing.Union[_ContainerValue.List, _ContainerValue.Optional], pydantic.Field(discriminator="type") + typing.Union[_ContainerValue.List, _ContainerValue.Optional], + pydantic.Field(discriminator="type"), ] - def get_as_union(self) -> typing.Union[_ContainerValue.List, _ContainerValue.Optional]: + def get_as_union( + self, + ) -> typing.Union[_ContainerValue.List, _ContainerValue.Optional]: return self.__root__ def visit( @@ -70,6 +81,10 @@ class Optional(UniversalBaseModel): value: typing.Optional[FieldValue] = None -update_forward_refs(_ContainerValue.List, ContainerValue=ContainerValue, FieldValue=FieldValue) -update_forward_refs(_ContainerValue.Optional, ContainerValue=ContainerValue, FieldValue=FieldValue) +update_forward_refs( + _ContainerValue.List, ContainerValue=ContainerValue, FieldValue=FieldValue +) +update_forward_refs( + _ContainerValue.Optional, ContainerValue=ContainerValue, FieldValue=FieldValue +) update_forward_refs(ContainerValue) diff --git a/seed/fastapi/circular-references-advanced/resources/ast/types/field_value.py b/seed/fastapi/circular-references-advanced/resources/ast/types/field_value.py index 4307e20e517..5513cd17b4e 100644 --- a/seed/fastapi/circular-references-advanced/resources/ast/types/field_value.py +++ b/seed/fastapi/circular-references-advanced/resources/ast/types/field_value.py @@ -1,37 +1,61 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from .primitive_value import ( + PrimitiveValue as resources_ast_types_primitive_value_PrimitiveValue, +) +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +from .object_value import ObjectValue as resources_ast_types_object_value_ObjectValue +from ....core.pydantic_utilities import UniversalRootModel import typing - -import pydantic import typing_extensions - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel, UniversalRootModel, update_forward_refs -from .object_value import ObjectValue as resources_ast_types_object_value_ObjectValue -from .primitive_value import PrimitiveValue as resources_ast_types_primitive_value_PrimitiveValue +import pydantic +from ....core.pydantic_utilities import UniversalBaseModel +from ....core.pydantic_utilities import update_forward_refs T_Result = typing.TypeVar("T_Result") class _Factory: - def primitive_value(self, value: resources_ast_types_primitive_value_PrimitiveValue) -> FieldValue: + def primitive_value( + self, value: resources_ast_types_primitive_value_PrimitiveValue + ) -> FieldValue: if IS_PYDANTIC_V2: - return FieldValue(root=_FieldValue.PrimitiveValue(type="primitive_value", value=value)) + return FieldValue( + root=_FieldValue.PrimitiveValue(type="primitive_value", value=value) + ) else: - return FieldValue(__root__=_FieldValue.PrimitiveValue(type="primitive_value", value=value)) + return FieldValue( + __root__=_FieldValue.PrimitiveValue(type="primitive_value", value=value) + ) - def object_value(self, value: resources_ast_types_object_value_ObjectValue) -> FieldValue: + def object_value( + self, value: resources_ast_types_object_value_ObjectValue + ) -> FieldValue: if IS_PYDANTIC_V2: - return FieldValue(root=_FieldValue.ObjectValue(**value.dict(exclude_unset=True), type="object_value")) + return FieldValue( + root=_FieldValue.ObjectValue( + **value.dict(exclude_unset=True), type="object_value" + ) + ) else: - return FieldValue(__root__=_FieldValue.ObjectValue(**value.dict(exclude_unset=True), type="object_value")) + return FieldValue( + __root__=_FieldValue.ObjectValue( + **value.dict(exclude_unset=True), type="object_value" + ) + ) - def container_value(self, value: resources_ast_types_container_value_ContainerValue) -> FieldValue: + def container_value( + self, value: resources_ast_types_container_value_ContainerValue + ) -> FieldValue: if IS_PYDANTIC_V2: - return FieldValue(root=_FieldValue.ContainerValue(type="container_value", value=value)) + return FieldValue( + root=_FieldValue.ContainerValue(type="container_value", value=value) + ) else: - return FieldValue(__root__=_FieldValue.ContainerValue(type="container_value", value=value)) + return FieldValue( + __root__=_FieldValue.ContainerValue(type="container_value", value=value) + ) class FieldValue(UniversalRootModel): @@ -39,44 +63,69 @@ class FieldValue(UniversalRootModel): if IS_PYDANTIC_V2: root: typing_extensions.Annotated[ - typing.Union[_FieldValue.PrimitiveValue, _FieldValue.ObjectValue, _FieldValue.ContainerValue], + typing.Union[ + _FieldValue.PrimitiveValue, + _FieldValue.ObjectValue, + _FieldValue.ContainerValue, + ], pydantic.Field(discriminator="type"), ] def get_as_union( self, - ) -> typing.Union[_FieldValue.PrimitiveValue, _FieldValue.ObjectValue, _FieldValue.ContainerValue]: + ) -> typing.Union[ + _FieldValue.PrimitiveValue, + _FieldValue.ObjectValue, + _FieldValue.ContainerValue, + ]: return self.root - else: __root__: typing_extensions.Annotated[ - typing.Union[_FieldValue.PrimitiveValue, _FieldValue.ObjectValue, _FieldValue.ContainerValue], + typing.Union[ + _FieldValue.PrimitiveValue, + _FieldValue.ObjectValue, + _FieldValue.ContainerValue, + ], pydantic.Field(discriminator="type"), ] def get_as_union( self, - ) -> typing.Union[_FieldValue.PrimitiveValue, _FieldValue.ObjectValue, _FieldValue.ContainerValue]: + ) -> typing.Union[ + _FieldValue.PrimitiveValue, + _FieldValue.ObjectValue, + _FieldValue.ContainerValue, + ]: return self.__root__ def visit( self, - primitive_value: typing.Callable[[resources_ast_types_primitive_value_PrimitiveValue], T_Result], - object_value: typing.Callable[[resources_ast_types_object_value_ObjectValue], T_Result], - container_value: typing.Callable[[resources_ast_types_container_value_ContainerValue], T_Result], + primitive_value: typing.Callable[ + [resources_ast_types_primitive_value_PrimitiveValue], T_Result + ], + object_value: typing.Callable[ + [resources_ast_types_object_value_ObjectValue], T_Result + ], + container_value: typing.Callable[ + [resources_ast_types_container_value_ContainerValue], T_Result + ], ) -> T_Result: unioned_value = self.get_as_union() if unioned_value.type == "primitive_value": return primitive_value(unioned_value.value) if unioned_value.type == "object_value": return object_value( - resources_ast_types_object_value_ObjectValue(**unioned_value.dict(exclude_unset=True, exclude={"type"})) + resources_ast_types_object_value_ObjectValue( + **unioned_value.dict(exclude_unset=True, exclude={"type"}) + ) ) if unioned_value.type == "container_value": return container_value(unioned_value.value) -from .container_value import ContainerValue as resources_ast_types_container_value_ContainerValue # noqa: E402 +from .container_value import ( + ContainerValue as resources_ast_types_container_value_ContainerValue, +) # noqa: E402 class _FieldValue: @@ -93,6 +142,8 @@ class ContainerValue(UniversalBaseModel): update_forward_refs( - _FieldValue.ContainerValue, ContainerValue=resources_ast_types_container_value_ContainerValue, FieldValue=FieldValue + _FieldValue.ContainerValue, + ContainerValue=resources_ast_types_container_value_ContainerValue, + FieldValue=FieldValue, ) update_forward_refs(FieldValue) diff --git a/seed/fastapi/circular-references-advanced/resources/ast/types/object_field_value.py b/seed/fastapi/circular-references-advanced/resources/ast/types/object_field_value.py index b8febaf77a3..7c20d76a5db 100644 --- a/seed/fastapi/circular-references-advanced/resources/ast/types/object_field_value.py +++ b/seed/fastapi/circular-references-advanced/resources/ast/types/object_field_value.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import UniversalBaseModel from .field_name import FieldName from .field_value import FieldValue +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing +import pydantic class ObjectFieldValue(UniversalBaseModel): @@ -18,7 +17,9 @@ class ObjectFieldValue(UniversalBaseModel): value: FieldValue if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/circular-references-advanced/resources/ast/types/object_value.py b/seed/fastapi/circular-references-advanced/resources/ast/types/object_value.py index fcfe1bdc0c9..436913dc835 100644 --- a/seed/fastapi/circular-references-advanced/resources/ast/types/object_value.py +++ b/seed/fastapi/circular-references-advanced/resources/ast/types/object_value.py @@ -1,15 +1,16 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class ObjectValue(UniversalBaseModel): if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/circular-references-advanced/resources/ast/types/primitive_value.py b/seed/fastapi/circular-references-advanced/resources/ast/types/primitive_value.py index 94133770391..2b98b423352 100644 --- a/seed/fastapi/circular-references-advanced/resources/ast/types/primitive_value.py +++ b/seed/fastapi/circular-references-advanced/resources/ast/types/primitive_value.py @@ -10,7 +10,11 @@ class PrimitiveValue(str, enum.Enum): STRING = "STRING" NUMBER = "NUMBER" - def visit(self, string: typing.Callable[[], T_Result], number: typing.Callable[[], T_Result]) -> T_Result: + def visit( + self, + string: typing.Callable[[], T_Result], + number: typing.Callable[[], T_Result], + ) -> T_Result: if self is PrimitiveValue.STRING: return string() if self is PrimitiveValue.NUMBER: diff --git a/seed/fastapi/circular-references-advanced/types/importing_a.py b/seed/fastapi/circular-references-advanced/types/importing_a.py index b8a7b66a757..c715bebeabc 100644 --- a/seed/fastapi/circular-references-advanced/types/importing_a.py +++ b/seed/fastapi/circular-references-advanced/types/importing_a.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from ..core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from ..resources.a.types.a import A +from ..core.pydantic_utilities import IS_PYDANTIC_V2 +import pydantic class ImportingA(UniversalBaseModel): a: typing.Optional[A] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/circular-references-advanced/types/root_type.py b/seed/fastapi/circular-references-advanced/types/root_type.py index a16a6315525..1e0ee944f87 100644 --- a/seed/fastapi/circular-references-advanced/types/root_type.py +++ b/seed/fastapi/circular-references-advanced/types/root_type.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ..core.pydantic_utilities import UniversalBaseModel +from ..core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class RootType(UniversalBaseModel): s: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/circular-references/__init__.py b/seed/fastapi/circular-references/__init__.py index 27066086273..4b66a1fe37f 100644 --- a/seed/fastapi/circular-references/__init__.py +++ b/seed/fastapi/circular-references/__init__.py @@ -1,6 +1,24 @@ # This file was auto-generated by Fern from our API Definition. -from .resources import A, ContainerValue, FieldValue, ObjectValue, PrimitiveValue, a, ast +from .resources import ( + A, + ContainerValue, + FieldValue, + ObjectValue, + PrimitiveValue, + a, + ast, +) from .types import ImportingA, RootType -__all__ = ["A", "ContainerValue", "FieldValue", "ImportingA", "ObjectValue", "PrimitiveValue", "RootType", "a", "ast"] +__all__ = [ + "A", + "ContainerValue", + "FieldValue", + "ImportingA", + "ObjectValue", + "PrimitiveValue", + "RootType", + "a", + "ast", +] diff --git a/seed/fastapi/circular-references/core/abstract_fern_service.py b/seed/fastapi/circular-references/core/abstract_fern_service.py index da7c8dc49c4..9966b4876da 100644 --- a/seed/fastapi/circular-references/core/abstract_fern_service.py +++ b/seed/fastapi/circular-references/core/abstract_fern_service.py @@ -7,5 +7,4 @@ class AbstractFernService(abc.ABC): @classmethod - def _init_fern(cls, router: fastapi.APIRouter) -> None: - ... + def _init_fern(cls, router: fastapi.APIRouter) -> None: ... diff --git a/seed/fastapi/circular-references/core/datetime_utils.py b/seed/fastapi/circular-references/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/fastapi/circular-references/core/datetime_utils.py +++ b/seed/fastapi/circular-references/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/fastapi/circular-references/core/exceptions/__init__.py b/seed/fastapi/circular-references/core/exceptions/__init__.py index 297d6e06f5f..dae4b8980c1 100644 --- a/seed/fastapi/circular-references/core/exceptions/__init__.py +++ b/seed/fastapi/circular-references/core/exceptions/__init__.py @@ -1,7 +1,11 @@ # This file was auto-generated by Fern from our API Definition. from .fern_http_exception import FernHTTPException -from .handlers import default_exception_handler, fern_http_exception_handler, http_exception_handler +from .handlers import ( + default_exception_handler, + fern_http_exception_handler, + http_exception_handler, +) from .unauthorized import UnauthorizedException __all__ = [ diff --git a/seed/fastapi/circular-references/core/exceptions/fern_http_exception.py b/seed/fastapi/circular-references/core/exceptions/fern_http_exception.py index bdf03862487..81610359a7f 100644 --- a/seed/fastapi/circular-references/core/exceptions/fern_http_exception.py +++ b/seed/fastapi/circular-references/core/exceptions/fern_http_exception.py @@ -1,14 +1,16 @@ # This file was auto-generated by Fern from our API Definition. import abc -import typing - import fastapi +import typing class FernHTTPException(abc.ABC, fastapi.HTTPException): def __init__( - self, status_code: int, name: typing.Optional[str] = None, content: typing.Optional[typing.Any] = None + self, + status_code: int, + name: typing.Optional[str] = None, + content: typing.Optional[typing.Any] = None, ): super().__init__(status_code=status_code) self.name = name @@ -17,4 +19,6 @@ def __init__( def to_json_response(self) -> fastapi.responses.JSONResponse: content = fastapi.encoders.jsonable_encoder(self.content, exclude_none=True) - return fastapi.responses.JSONResponse(content=content, status_code=self.status_code) + return fastapi.responses.JSONResponse( + content=content, status_code=self.status_code + ) diff --git a/seed/fastapi/circular-references/core/exceptions/handlers.py b/seed/fastapi/circular-references/core/exceptions/handlers.py index 6d8c4155c5a..ae1c2741f06 100644 --- a/seed/fastapi/circular-references/core/exceptions/handlers.py +++ b/seed/fastapi/circular-references/core/exceptions/handlers.py @@ -2,32 +2,49 @@ import logging -import fastapi import starlette import starlette.exceptions +import fastapi + from .fern_http_exception import FernHTTPException def fern_http_exception_handler( - request: fastapi.requests.Request, exc: FernHTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: FernHTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) return exc.to_json_response() def http_exception_handler( - request: fastapi.requests.Request, exc: starlette.exceptions.HTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: starlette.exceptions.HTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=exc.status_code, content=exc.detail).to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=exc.status_code, content=exc.detail + ).to_json_response() def default_exception_handler( - request: fastapi.requests.Request, exc: Exception, skip_log: bool = False + request: fastapi.requests.Request, + exc: Exception, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=500, content="Internal Server Error").to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=500, content="Internal Server Error" + ).to_json_response() diff --git a/seed/fastapi/circular-references/core/pydantic_utilities.py b/seed/fastapi/circular-references/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/fastapi/circular-references/core/pydantic_utilities.py +++ b/seed/fastapi/circular-references/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/fastapi/circular-references/core/route_args.py b/seed/fastapi/circular-references/core/route_args.py index 4228e2fe05d..bd940bf4ddd 100644 --- a/seed/fastapi/circular-references/core/route_args.py +++ b/seed/fastapi/circular-references/core/route_args.py @@ -20,9 +20,15 @@ class RouteArgs(typing_extensions.TypedDict): DEFAULT_ROUTE_ARGS = RouteArgs(openapi_extra=None, tags=None, include_in_schema=True) -def get_route_args(endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str) -> RouteArgs: - unwrapped = inspect.unwrap(endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY))) - route_args = typing.cast(RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS)) +def get_route_args( + endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str +) -> RouteArgs: + unwrapped = inspect.unwrap( + endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY)) + ) + route_args = typing.cast( + RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS) + ) if route_args["tags"] is None: return RouteArgs( openapi_extra=route_args["openapi_extra"], @@ -56,7 +62,11 @@ def decorator(endpoint_function: T) -> T: setattr( endpoint_function, FERN_CONFIG_KEY, - RouteArgs(openapi_extra=openapi_extra, tags=tags, include_in_schema=include_in_schema), + RouteArgs( + openapi_extra=openapi_extra, + tags=tags, + include_in_schema=include_in_schema, + ), ) return endpoint_function diff --git a/seed/fastapi/circular-references/register.py b/seed/fastapi/circular-references/register.py index 6f6e6707f03..a536c0ce4e4 100644 --- a/seed/fastapi/circular-references/register.py +++ b/seed/fastapi/circular-references/register.py @@ -1,23 +1,29 @@ # This file was auto-generated by Fern from our API Definition. -import glob -import importlib -import os -import types -import typing - import fastapi -import starlette.exceptions +import typing from fastapi import params - -from .core.abstract_fern_service import AbstractFernService -from .core.exceptions import default_exception_handler, fern_http_exception_handler, http_exception_handler from .core.exceptions.fern_http_exception import FernHTTPException +from .core.exceptions import fern_http_exception_handler +import starlette.exceptions +from .core.exceptions import http_exception_handler +from .core.exceptions import default_exception_handler +from .core.abstract_fern_service import AbstractFernService +import types +import os +import glob +import importlib -def register(_app: fastapi.FastAPI, *, dependencies: typing.Optional[typing.Sequence[params.Depends]] = None) -> None: +def register( + _app: fastapi.FastAPI, + *, + dependencies: typing.Optional[typing.Sequence[params.Depends]] = None, +) -> None: _app.add_exception_handler(FernHTTPException, fern_http_exception_handler) # type: ignore - _app.add_exception_handler(starlette.exceptions.HTTPException, http_exception_handler) # type: ignore + _app.add_exception_handler( + starlette.exceptions.HTTPException, http_exception_handler + ) # type: ignore _app.add_exception_handler(Exception, default_exception_handler) # type: ignore @@ -29,7 +35,9 @@ def __register_service(service: AbstractFernService) -> fastapi.APIRouter: def register_validators(module: types.ModuleType) -> None: validators_directory: str = os.path.dirname(module.__file__) # type: ignore - for path in glob.glob(os.path.join(validators_directory, "**/*.py"), recursive=True): + for path in glob.glob( + os.path.join(validators_directory, "**/*.py"), recursive=True + ): if os.path.isfile(path): relative_path = os.path.relpath(path, start=validators_directory) module_path = ".".join([module.__name__] + relative_path[:-3].split("/")) diff --git a/seed/fastapi/circular-references/resources/__init__.py b/seed/fastapi/circular-references/resources/__init__.py index 447ec55a767..77789d0d362 100644 --- a/seed/fastapi/circular-references/resources/__init__.py +++ b/seed/fastapi/circular-references/resources/__init__.py @@ -4,4 +4,12 @@ from .a import A from .ast import ContainerValue, FieldValue, ObjectValue, PrimitiveValue -__all__ = ["A", "ContainerValue", "FieldValue", "ObjectValue", "PrimitiveValue", "a", "ast"] +__all__ = [ + "A", + "ContainerValue", + "FieldValue", + "ObjectValue", + "PrimitiveValue", + "a", + "ast", +] diff --git a/seed/fastapi/circular-references/resources/a/types/a.py b/seed/fastapi/circular-references/resources/a/types/a.py index 0dc67089d18..0205033683c 100644 --- a/seed/fastapi/circular-references/resources/a/types/a.py +++ b/seed/fastapi/circular-references/resources/a/types/a.py @@ -1,16 +1,16 @@ # This file was auto-generated by Fern from our API Definition. +from ....types.root_type import RootType +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2 -from ....types.root_type import RootType - class A(RootType): if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/circular-references/resources/ast/types/container_value.py b/seed/fastapi/circular-references/resources/ast/types/container_value.py index fd6906fe08f..b56bf7c924d 100644 --- a/seed/fastapi/circular-references/resources/ast/types/container_value.py +++ b/seed/fastapi/circular-references/resources/ast/types/container_value.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - import typing - -import pydantic +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +from ....core.pydantic_utilities import UniversalRootModel import typing_extensions - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel, UniversalRootModel, update_forward_refs +import pydantic +from ....core.pydantic_utilities import UniversalBaseModel +from ....core.pydantic_utilities import update_forward_refs T_Result = typing.TypeVar("T_Result") @@ -17,13 +17,19 @@ def list_(self, value: typing.List[FieldValue]) -> ContainerValue: if IS_PYDANTIC_V2: return ContainerValue(root=_ContainerValue.List(type="list", value=value)) else: - return ContainerValue(__root__=_ContainerValue.List(type="list", value=value)) + return ContainerValue( + __root__=_ContainerValue.List(type="list", value=value) + ) def optional(self, value: typing.Optional[FieldValue]) -> ContainerValue: if IS_PYDANTIC_V2: - return ContainerValue(root=_ContainerValue.Optional(type="optional", value=value)) + return ContainerValue( + root=_ContainerValue.Optional(type="optional", value=value) + ) else: - return ContainerValue(__root__=_ContainerValue.Optional(type="optional", value=value)) + return ContainerValue( + __root__=_ContainerValue.Optional(type="optional", value=value) + ) class ContainerValue(UniversalRootModel): @@ -31,18 +37,23 @@ class ContainerValue(UniversalRootModel): if IS_PYDANTIC_V2: root: typing_extensions.Annotated[ - typing.Union[_ContainerValue.List, _ContainerValue.Optional], pydantic.Field(discriminator="type") + typing.Union[_ContainerValue.List, _ContainerValue.Optional], + pydantic.Field(discriminator="type"), ] - def get_as_union(self) -> typing.Union[_ContainerValue.List, _ContainerValue.Optional]: + def get_as_union( + self, + ) -> typing.Union[_ContainerValue.List, _ContainerValue.Optional]: return self.root - else: __root__: typing_extensions.Annotated[ - typing.Union[_ContainerValue.List, _ContainerValue.Optional], pydantic.Field(discriminator="type") + typing.Union[_ContainerValue.List, _ContainerValue.Optional], + pydantic.Field(discriminator="type"), ] - def get_as_union(self) -> typing.Union[_ContainerValue.List, _ContainerValue.Optional]: + def get_as_union( + self, + ) -> typing.Union[_ContainerValue.List, _ContainerValue.Optional]: return self.__root__ def visit( @@ -70,6 +81,10 @@ class Optional(UniversalBaseModel): value: typing.Optional[FieldValue] = None -update_forward_refs(_ContainerValue.List, ContainerValue=ContainerValue, FieldValue=FieldValue) -update_forward_refs(_ContainerValue.Optional, ContainerValue=ContainerValue, FieldValue=FieldValue) +update_forward_refs( + _ContainerValue.List, ContainerValue=ContainerValue, FieldValue=FieldValue +) +update_forward_refs( + _ContainerValue.Optional, ContainerValue=ContainerValue, FieldValue=FieldValue +) update_forward_refs(ContainerValue) diff --git a/seed/fastapi/circular-references/resources/ast/types/field_value.py b/seed/fastapi/circular-references/resources/ast/types/field_value.py index 4307e20e517..5513cd17b4e 100644 --- a/seed/fastapi/circular-references/resources/ast/types/field_value.py +++ b/seed/fastapi/circular-references/resources/ast/types/field_value.py @@ -1,37 +1,61 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from .primitive_value import ( + PrimitiveValue as resources_ast_types_primitive_value_PrimitiveValue, +) +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +from .object_value import ObjectValue as resources_ast_types_object_value_ObjectValue +from ....core.pydantic_utilities import UniversalRootModel import typing - -import pydantic import typing_extensions - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel, UniversalRootModel, update_forward_refs -from .object_value import ObjectValue as resources_ast_types_object_value_ObjectValue -from .primitive_value import PrimitiveValue as resources_ast_types_primitive_value_PrimitiveValue +import pydantic +from ....core.pydantic_utilities import UniversalBaseModel +from ....core.pydantic_utilities import update_forward_refs T_Result = typing.TypeVar("T_Result") class _Factory: - def primitive_value(self, value: resources_ast_types_primitive_value_PrimitiveValue) -> FieldValue: + def primitive_value( + self, value: resources_ast_types_primitive_value_PrimitiveValue + ) -> FieldValue: if IS_PYDANTIC_V2: - return FieldValue(root=_FieldValue.PrimitiveValue(type="primitive_value", value=value)) + return FieldValue( + root=_FieldValue.PrimitiveValue(type="primitive_value", value=value) + ) else: - return FieldValue(__root__=_FieldValue.PrimitiveValue(type="primitive_value", value=value)) + return FieldValue( + __root__=_FieldValue.PrimitiveValue(type="primitive_value", value=value) + ) - def object_value(self, value: resources_ast_types_object_value_ObjectValue) -> FieldValue: + def object_value( + self, value: resources_ast_types_object_value_ObjectValue + ) -> FieldValue: if IS_PYDANTIC_V2: - return FieldValue(root=_FieldValue.ObjectValue(**value.dict(exclude_unset=True), type="object_value")) + return FieldValue( + root=_FieldValue.ObjectValue( + **value.dict(exclude_unset=True), type="object_value" + ) + ) else: - return FieldValue(__root__=_FieldValue.ObjectValue(**value.dict(exclude_unset=True), type="object_value")) + return FieldValue( + __root__=_FieldValue.ObjectValue( + **value.dict(exclude_unset=True), type="object_value" + ) + ) - def container_value(self, value: resources_ast_types_container_value_ContainerValue) -> FieldValue: + def container_value( + self, value: resources_ast_types_container_value_ContainerValue + ) -> FieldValue: if IS_PYDANTIC_V2: - return FieldValue(root=_FieldValue.ContainerValue(type="container_value", value=value)) + return FieldValue( + root=_FieldValue.ContainerValue(type="container_value", value=value) + ) else: - return FieldValue(__root__=_FieldValue.ContainerValue(type="container_value", value=value)) + return FieldValue( + __root__=_FieldValue.ContainerValue(type="container_value", value=value) + ) class FieldValue(UniversalRootModel): @@ -39,44 +63,69 @@ class FieldValue(UniversalRootModel): if IS_PYDANTIC_V2: root: typing_extensions.Annotated[ - typing.Union[_FieldValue.PrimitiveValue, _FieldValue.ObjectValue, _FieldValue.ContainerValue], + typing.Union[ + _FieldValue.PrimitiveValue, + _FieldValue.ObjectValue, + _FieldValue.ContainerValue, + ], pydantic.Field(discriminator="type"), ] def get_as_union( self, - ) -> typing.Union[_FieldValue.PrimitiveValue, _FieldValue.ObjectValue, _FieldValue.ContainerValue]: + ) -> typing.Union[ + _FieldValue.PrimitiveValue, + _FieldValue.ObjectValue, + _FieldValue.ContainerValue, + ]: return self.root - else: __root__: typing_extensions.Annotated[ - typing.Union[_FieldValue.PrimitiveValue, _FieldValue.ObjectValue, _FieldValue.ContainerValue], + typing.Union[ + _FieldValue.PrimitiveValue, + _FieldValue.ObjectValue, + _FieldValue.ContainerValue, + ], pydantic.Field(discriminator="type"), ] def get_as_union( self, - ) -> typing.Union[_FieldValue.PrimitiveValue, _FieldValue.ObjectValue, _FieldValue.ContainerValue]: + ) -> typing.Union[ + _FieldValue.PrimitiveValue, + _FieldValue.ObjectValue, + _FieldValue.ContainerValue, + ]: return self.__root__ def visit( self, - primitive_value: typing.Callable[[resources_ast_types_primitive_value_PrimitiveValue], T_Result], - object_value: typing.Callable[[resources_ast_types_object_value_ObjectValue], T_Result], - container_value: typing.Callable[[resources_ast_types_container_value_ContainerValue], T_Result], + primitive_value: typing.Callable[ + [resources_ast_types_primitive_value_PrimitiveValue], T_Result + ], + object_value: typing.Callable[ + [resources_ast_types_object_value_ObjectValue], T_Result + ], + container_value: typing.Callable[ + [resources_ast_types_container_value_ContainerValue], T_Result + ], ) -> T_Result: unioned_value = self.get_as_union() if unioned_value.type == "primitive_value": return primitive_value(unioned_value.value) if unioned_value.type == "object_value": return object_value( - resources_ast_types_object_value_ObjectValue(**unioned_value.dict(exclude_unset=True, exclude={"type"})) + resources_ast_types_object_value_ObjectValue( + **unioned_value.dict(exclude_unset=True, exclude={"type"}) + ) ) if unioned_value.type == "container_value": return container_value(unioned_value.value) -from .container_value import ContainerValue as resources_ast_types_container_value_ContainerValue # noqa: E402 +from .container_value import ( + ContainerValue as resources_ast_types_container_value_ContainerValue, +) # noqa: E402 class _FieldValue: @@ -93,6 +142,8 @@ class ContainerValue(UniversalBaseModel): update_forward_refs( - _FieldValue.ContainerValue, ContainerValue=resources_ast_types_container_value_ContainerValue, FieldValue=FieldValue + _FieldValue.ContainerValue, + ContainerValue=resources_ast_types_container_value_ContainerValue, + FieldValue=FieldValue, ) update_forward_refs(FieldValue) diff --git a/seed/fastapi/circular-references/resources/ast/types/object_value.py b/seed/fastapi/circular-references/resources/ast/types/object_value.py index fcfe1bdc0c9..436913dc835 100644 --- a/seed/fastapi/circular-references/resources/ast/types/object_value.py +++ b/seed/fastapi/circular-references/resources/ast/types/object_value.py @@ -1,15 +1,16 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class ObjectValue(UniversalBaseModel): if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/circular-references/resources/ast/types/primitive_value.py b/seed/fastapi/circular-references/resources/ast/types/primitive_value.py index 94133770391..2b98b423352 100644 --- a/seed/fastapi/circular-references/resources/ast/types/primitive_value.py +++ b/seed/fastapi/circular-references/resources/ast/types/primitive_value.py @@ -10,7 +10,11 @@ class PrimitiveValue(str, enum.Enum): STRING = "STRING" NUMBER = "NUMBER" - def visit(self, string: typing.Callable[[], T_Result], number: typing.Callable[[], T_Result]) -> T_Result: + def visit( + self, + string: typing.Callable[[], T_Result], + number: typing.Callable[[], T_Result], + ) -> T_Result: if self is PrimitiveValue.STRING: return string() if self is PrimitiveValue.NUMBER: diff --git a/seed/fastapi/circular-references/types/importing_a.py b/seed/fastapi/circular-references/types/importing_a.py index b8a7b66a757..c715bebeabc 100644 --- a/seed/fastapi/circular-references/types/importing_a.py +++ b/seed/fastapi/circular-references/types/importing_a.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from ..core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from ..resources.a.types.a import A +from ..core.pydantic_utilities import IS_PYDANTIC_V2 +import pydantic class ImportingA(UniversalBaseModel): a: typing.Optional[A] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/circular-references/types/root_type.py b/seed/fastapi/circular-references/types/root_type.py index a16a6315525..1e0ee944f87 100644 --- a/seed/fastapi/circular-references/types/root_type.py +++ b/seed/fastapi/circular-references/types/root_type.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ..core.pydantic_utilities import UniversalBaseModel +from ..core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class RootType(UniversalBaseModel): s: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/code-samples/core/abstract_fern_service.py b/seed/fastapi/code-samples/core/abstract_fern_service.py index da7c8dc49c4..9966b4876da 100644 --- a/seed/fastapi/code-samples/core/abstract_fern_service.py +++ b/seed/fastapi/code-samples/core/abstract_fern_service.py @@ -7,5 +7,4 @@ class AbstractFernService(abc.ABC): @classmethod - def _init_fern(cls, router: fastapi.APIRouter) -> None: - ... + def _init_fern(cls, router: fastapi.APIRouter) -> None: ... diff --git a/seed/fastapi/code-samples/core/datetime_utils.py b/seed/fastapi/code-samples/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/fastapi/code-samples/core/datetime_utils.py +++ b/seed/fastapi/code-samples/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/fastapi/code-samples/core/exceptions/__init__.py b/seed/fastapi/code-samples/core/exceptions/__init__.py index 297d6e06f5f..dae4b8980c1 100644 --- a/seed/fastapi/code-samples/core/exceptions/__init__.py +++ b/seed/fastapi/code-samples/core/exceptions/__init__.py @@ -1,7 +1,11 @@ # This file was auto-generated by Fern from our API Definition. from .fern_http_exception import FernHTTPException -from .handlers import default_exception_handler, fern_http_exception_handler, http_exception_handler +from .handlers import ( + default_exception_handler, + fern_http_exception_handler, + http_exception_handler, +) from .unauthorized import UnauthorizedException __all__ = [ diff --git a/seed/fastapi/code-samples/core/exceptions/fern_http_exception.py b/seed/fastapi/code-samples/core/exceptions/fern_http_exception.py index bdf03862487..81610359a7f 100644 --- a/seed/fastapi/code-samples/core/exceptions/fern_http_exception.py +++ b/seed/fastapi/code-samples/core/exceptions/fern_http_exception.py @@ -1,14 +1,16 @@ # This file was auto-generated by Fern from our API Definition. import abc -import typing - import fastapi +import typing class FernHTTPException(abc.ABC, fastapi.HTTPException): def __init__( - self, status_code: int, name: typing.Optional[str] = None, content: typing.Optional[typing.Any] = None + self, + status_code: int, + name: typing.Optional[str] = None, + content: typing.Optional[typing.Any] = None, ): super().__init__(status_code=status_code) self.name = name @@ -17,4 +19,6 @@ def __init__( def to_json_response(self) -> fastapi.responses.JSONResponse: content = fastapi.encoders.jsonable_encoder(self.content, exclude_none=True) - return fastapi.responses.JSONResponse(content=content, status_code=self.status_code) + return fastapi.responses.JSONResponse( + content=content, status_code=self.status_code + ) diff --git a/seed/fastapi/code-samples/core/exceptions/handlers.py b/seed/fastapi/code-samples/core/exceptions/handlers.py index 6d8c4155c5a..ae1c2741f06 100644 --- a/seed/fastapi/code-samples/core/exceptions/handlers.py +++ b/seed/fastapi/code-samples/core/exceptions/handlers.py @@ -2,32 +2,49 @@ import logging -import fastapi import starlette import starlette.exceptions +import fastapi + from .fern_http_exception import FernHTTPException def fern_http_exception_handler( - request: fastapi.requests.Request, exc: FernHTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: FernHTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) return exc.to_json_response() def http_exception_handler( - request: fastapi.requests.Request, exc: starlette.exceptions.HTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: starlette.exceptions.HTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=exc.status_code, content=exc.detail).to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=exc.status_code, content=exc.detail + ).to_json_response() def default_exception_handler( - request: fastapi.requests.Request, exc: Exception, skip_log: bool = False + request: fastapi.requests.Request, + exc: Exception, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=500, content="Internal Server Error").to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=500, content="Internal Server Error" + ).to_json_response() diff --git a/seed/fastapi/code-samples/core/pydantic_utilities.py b/seed/fastapi/code-samples/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/fastapi/code-samples/core/pydantic_utilities.py +++ b/seed/fastapi/code-samples/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/fastapi/code-samples/core/route_args.py b/seed/fastapi/code-samples/core/route_args.py index 4228e2fe05d..bd940bf4ddd 100644 --- a/seed/fastapi/code-samples/core/route_args.py +++ b/seed/fastapi/code-samples/core/route_args.py @@ -20,9 +20,15 @@ class RouteArgs(typing_extensions.TypedDict): DEFAULT_ROUTE_ARGS = RouteArgs(openapi_extra=None, tags=None, include_in_schema=True) -def get_route_args(endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str) -> RouteArgs: - unwrapped = inspect.unwrap(endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY))) - route_args = typing.cast(RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS)) +def get_route_args( + endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str +) -> RouteArgs: + unwrapped = inspect.unwrap( + endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY)) + ) + route_args = typing.cast( + RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS) + ) if route_args["tags"] is None: return RouteArgs( openapi_extra=route_args["openapi_extra"], @@ -56,7 +62,11 @@ def decorator(endpoint_function: T) -> T: setattr( endpoint_function, FERN_CONFIG_KEY, - RouteArgs(openapi_extra=openapi_extra, tags=tags, include_in_schema=include_in_schema), + RouteArgs( + openapi_extra=openapi_extra, + tags=tags, + include_in_schema=include_in_schema, + ), ) return endpoint_function diff --git a/seed/fastapi/code-samples/register.py b/seed/fastapi/code-samples/register.py index ebdfdf9318d..1d60bbe4d5d 100644 --- a/seed/fastapi/code-samples/register.py +++ b/seed/fastapi/code-samples/register.py @@ -1,31 +1,33 @@ # This file was auto-generated by Fern from our API Definition. -import glob -import importlib -import os -import types -import typing - import fastapi -import starlette.exceptions +from .resources.service.service.service import AbstractServiceService +import typing from fastapi import params - -from .core.abstract_fern_service import AbstractFernService -from .core.exceptions import default_exception_handler, fern_http_exception_handler, http_exception_handler from .core.exceptions.fern_http_exception import FernHTTPException -from .resources.service.service.service import AbstractServiceService +from .core.exceptions import fern_http_exception_handler +import starlette.exceptions +from .core.exceptions import http_exception_handler +from .core.exceptions import default_exception_handler +from .core.abstract_fern_service import AbstractFernService +import types +import os +import glob +import importlib def register( _app: fastapi.FastAPI, *, service: AbstractServiceService, - dependencies: typing.Optional[typing.Sequence[params.Depends]] = None + dependencies: typing.Optional[typing.Sequence[params.Depends]] = None, ) -> None: _app.include_router(__register_service(service), dependencies=dependencies) _app.add_exception_handler(FernHTTPException, fern_http_exception_handler) # type: ignore - _app.add_exception_handler(starlette.exceptions.HTTPException, http_exception_handler) # type: ignore + _app.add_exception_handler( + starlette.exceptions.HTTPException, http_exception_handler + ) # type: ignore _app.add_exception_handler(Exception, default_exception_handler) # type: ignore @@ -37,7 +39,9 @@ def __register_service(service: AbstractFernService) -> fastapi.APIRouter: def register_validators(module: types.ModuleType) -> None: validators_directory: str = os.path.dirname(module.__file__) # type: ignore - for path in glob.glob(os.path.join(validators_directory, "**/*.py"), recursive=True): + for path in glob.glob( + os.path.join(validators_directory, "**/*.py"), recursive=True + ): if os.path.isfile(path): relative_path = os.path.relpath(path, start=validators_directory) module_path = ".".join([module.__name__] + relative_path[:-3].split("/")) diff --git a/seed/fastapi/code-samples/resources/service/service/my_request.py b/seed/fastapi/code-samples/resources/service/service/my_request.py index 74947344e6f..174823d3dbd 100644 --- a/seed/fastapi/code-samples/resources/service/service/my_request.py +++ b/seed/fastapi/code-samples/resources/service/service/my_request.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class MyRequest(UniversalBaseModel): num_events: int if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/code-samples/resources/service/service/service.py b/seed/fastapi/code-samples/resources/service/service/service.py index 662bf17effa..c6fd26f2328 100644 --- a/seed/fastapi/code-samples/resources/service/service/service.py +++ b/seed/fastapi/code-samples/resources/service/service/service.py @@ -1,18 +1,16 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.abstract_fern_service import AbstractFernService +from .my_request import MyRequest +from ..types.my_response import MyResponse import abc -import functools +import fastapi import inspect -import logging import typing - -import fastapi - -from ....core.abstract_fern_service import AbstractFernService from ....core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools from ....core.route_args import get_route_args -from ..types.my_response import MyResponse -from .my_request import MyRequest class AbstractServiceService(AbstractFernService): @@ -25,8 +23,7 @@ class AbstractServiceService(AbstractFernService): """ @abc.abstractmethod - def hello(self, *, body: MyRequest) -> MyResponse: - ... + def hello(self, *, body: MyRequest) -> MyResponse: ... """ Below are internal methods used by Fern to register your implementation. @@ -41,14 +38,20 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_hello(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.hello) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) else: new_parameters.append(parameter) - setattr(cls.hello, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.hello, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.hello) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> MyResponse: diff --git a/seed/fastapi/code-samples/resources/service/types/my_response.py b/seed/fastapi/code-samples/resources/service/types/my_response.py index 3022fe47b63..a65702b2bd1 100644 --- a/seed/fastapi/code-samples/resources/service/types/my_response.py +++ b/seed/fastapi/code-samples/resources/service/types/my_response.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class MyResponse(UniversalBaseModel): id: str name: typing.Optional[str] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/custom-auth/__init__.py b/seed/fastapi/custom-auth/__init__.py index d1fdab59d75..90a7340f393 100644 --- a/seed/fastapi/custom-auth/__init__.py +++ b/seed/fastapi/custom-auth/__init__.py @@ -1,6 +1,17 @@ # This file was auto-generated by Fern from our API Definition. -from .resources import BadRequest, UnauthorizedRequest, UnauthorizedRequestErrorBody, errors +from .resources import ( + BadRequest, + UnauthorizedRequest, + UnauthorizedRequestErrorBody, + errors, +) from .security import ApiAuth -__all__ = ["ApiAuth", "BadRequest", "UnauthorizedRequest", "UnauthorizedRequestErrorBody", "errors"] +__all__ = [ + "ApiAuth", + "BadRequest", + "UnauthorizedRequest", + "UnauthorizedRequestErrorBody", + "errors", +] diff --git a/seed/fastapi/custom-auth/core/abstract_fern_service.py b/seed/fastapi/custom-auth/core/abstract_fern_service.py index da7c8dc49c4..9966b4876da 100644 --- a/seed/fastapi/custom-auth/core/abstract_fern_service.py +++ b/seed/fastapi/custom-auth/core/abstract_fern_service.py @@ -7,5 +7,4 @@ class AbstractFernService(abc.ABC): @classmethod - def _init_fern(cls, router: fastapi.APIRouter) -> None: - ... + def _init_fern(cls, router: fastapi.APIRouter) -> None: ... diff --git a/seed/fastapi/custom-auth/core/datetime_utils.py b/seed/fastapi/custom-auth/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/fastapi/custom-auth/core/datetime_utils.py +++ b/seed/fastapi/custom-auth/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/fastapi/custom-auth/core/exceptions/__init__.py b/seed/fastapi/custom-auth/core/exceptions/__init__.py index 297d6e06f5f..dae4b8980c1 100644 --- a/seed/fastapi/custom-auth/core/exceptions/__init__.py +++ b/seed/fastapi/custom-auth/core/exceptions/__init__.py @@ -1,7 +1,11 @@ # This file was auto-generated by Fern from our API Definition. from .fern_http_exception import FernHTTPException -from .handlers import default_exception_handler, fern_http_exception_handler, http_exception_handler +from .handlers import ( + default_exception_handler, + fern_http_exception_handler, + http_exception_handler, +) from .unauthorized import UnauthorizedException __all__ = [ diff --git a/seed/fastapi/custom-auth/core/exceptions/fern_http_exception.py b/seed/fastapi/custom-auth/core/exceptions/fern_http_exception.py index bdf03862487..81610359a7f 100644 --- a/seed/fastapi/custom-auth/core/exceptions/fern_http_exception.py +++ b/seed/fastapi/custom-auth/core/exceptions/fern_http_exception.py @@ -1,14 +1,16 @@ # This file was auto-generated by Fern from our API Definition. import abc -import typing - import fastapi +import typing class FernHTTPException(abc.ABC, fastapi.HTTPException): def __init__( - self, status_code: int, name: typing.Optional[str] = None, content: typing.Optional[typing.Any] = None + self, + status_code: int, + name: typing.Optional[str] = None, + content: typing.Optional[typing.Any] = None, ): super().__init__(status_code=status_code) self.name = name @@ -17,4 +19,6 @@ def __init__( def to_json_response(self) -> fastapi.responses.JSONResponse: content = fastapi.encoders.jsonable_encoder(self.content, exclude_none=True) - return fastapi.responses.JSONResponse(content=content, status_code=self.status_code) + return fastapi.responses.JSONResponse( + content=content, status_code=self.status_code + ) diff --git a/seed/fastapi/custom-auth/core/exceptions/handlers.py b/seed/fastapi/custom-auth/core/exceptions/handlers.py index 6d8c4155c5a..ae1c2741f06 100644 --- a/seed/fastapi/custom-auth/core/exceptions/handlers.py +++ b/seed/fastapi/custom-auth/core/exceptions/handlers.py @@ -2,32 +2,49 @@ import logging -import fastapi import starlette import starlette.exceptions +import fastapi + from .fern_http_exception import FernHTTPException def fern_http_exception_handler( - request: fastapi.requests.Request, exc: FernHTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: FernHTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) return exc.to_json_response() def http_exception_handler( - request: fastapi.requests.Request, exc: starlette.exceptions.HTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: starlette.exceptions.HTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=exc.status_code, content=exc.detail).to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=exc.status_code, content=exc.detail + ).to_json_response() def default_exception_handler( - request: fastapi.requests.Request, exc: Exception, skip_log: bool = False + request: fastapi.requests.Request, + exc: Exception, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=500, content="Internal Server Error").to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=500, content="Internal Server Error" + ).to_json_response() diff --git a/seed/fastapi/custom-auth/core/pydantic_utilities.py b/seed/fastapi/custom-auth/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/fastapi/custom-auth/core/pydantic_utilities.py +++ b/seed/fastapi/custom-auth/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/fastapi/custom-auth/core/route_args.py b/seed/fastapi/custom-auth/core/route_args.py index 4228e2fe05d..bd940bf4ddd 100644 --- a/seed/fastapi/custom-auth/core/route_args.py +++ b/seed/fastapi/custom-auth/core/route_args.py @@ -20,9 +20,15 @@ class RouteArgs(typing_extensions.TypedDict): DEFAULT_ROUTE_ARGS = RouteArgs(openapi_extra=None, tags=None, include_in_schema=True) -def get_route_args(endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str) -> RouteArgs: - unwrapped = inspect.unwrap(endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY))) - route_args = typing.cast(RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS)) +def get_route_args( + endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str +) -> RouteArgs: + unwrapped = inspect.unwrap( + endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY)) + ) + route_args = typing.cast( + RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS) + ) if route_args["tags"] is None: return RouteArgs( openapi_extra=route_args["openapi_extra"], @@ -56,7 +62,11 @@ def decorator(endpoint_function: T) -> T: setattr( endpoint_function, FERN_CONFIG_KEY, - RouteArgs(openapi_extra=openapi_extra, tags=tags, include_in_schema=include_in_schema), + RouteArgs( + openapi_extra=openapi_extra, + tags=tags, + include_in_schema=include_in_schema, + ), ) return endpoint_function diff --git a/seed/fastapi/custom-auth/register.py b/seed/fastapi/custom-auth/register.py index 5238629a333..edab583de1b 100644 --- a/seed/fastapi/custom-auth/register.py +++ b/seed/fastapi/custom-auth/register.py @@ -1,31 +1,33 @@ # This file was auto-generated by Fern from our API Definition. -import glob -import importlib -import os -import types -import typing - import fastapi -import starlette.exceptions +from .resources.custom_auth.service.service import AbstractCustomAuthService +import typing from fastapi import params - -from .core.abstract_fern_service import AbstractFernService -from .core.exceptions import default_exception_handler, fern_http_exception_handler, http_exception_handler from .core.exceptions.fern_http_exception import FernHTTPException -from .resources.custom_auth.service.service import AbstractCustomAuthService +from .core.exceptions import fern_http_exception_handler +import starlette.exceptions +from .core.exceptions import http_exception_handler +from .core.exceptions import default_exception_handler +from .core.abstract_fern_service import AbstractFernService +import types +import os +import glob +import importlib def register( _app: fastapi.FastAPI, *, custom_auth: AbstractCustomAuthService, - dependencies: typing.Optional[typing.Sequence[params.Depends]] = None + dependencies: typing.Optional[typing.Sequence[params.Depends]] = None, ) -> None: _app.include_router(__register_service(custom_auth), dependencies=dependencies) _app.add_exception_handler(FernHTTPException, fern_http_exception_handler) # type: ignore - _app.add_exception_handler(starlette.exceptions.HTTPException, http_exception_handler) # type: ignore + _app.add_exception_handler( + starlette.exceptions.HTTPException, http_exception_handler + ) # type: ignore _app.add_exception_handler(Exception, default_exception_handler) # type: ignore @@ -37,7 +39,9 @@ def __register_service(service: AbstractFernService) -> fastapi.APIRouter: def register_validators(module: types.ModuleType) -> None: validators_directory: str = os.path.dirname(module.__file__) # type: ignore - for path in glob.glob(os.path.join(validators_directory, "**/*.py"), recursive=True): + for path in glob.glob( + os.path.join(validators_directory, "**/*.py"), recursive=True + ): if os.path.isfile(path): relative_path = os.path.relpath(path, start=validators_directory) module_path = ".".join([module.__name__] + relative_path[:-3].split("/")) diff --git a/seed/fastapi/custom-auth/resources/__init__.py b/seed/fastapi/custom-auth/resources/__init__.py index f79f35dadbe..caef920f984 100644 --- a/seed/fastapi/custom-auth/resources/__init__.py +++ b/seed/fastapi/custom-auth/resources/__init__.py @@ -3,4 +3,9 @@ from . import errors from .errors import BadRequest, UnauthorizedRequest, UnauthorizedRequestErrorBody -__all__ = ["BadRequest", "UnauthorizedRequest", "UnauthorizedRequestErrorBody", "errors"] +__all__ = [ + "BadRequest", + "UnauthorizedRequest", + "UnauthorizedRequestErrorBody", + "errors", +] diff --git a/seed/fastapi/custom-auth/resources/custom_auth/service/service.py b/seed/fastapi/custom-auth/resources/custom_auth/service/service.py index 63968b5c697..45d26ed2fc0 100644 --- a/seed/fastapi/custom-auth/resources/custom_auth/service/service.py +++ b/seed/fastapi/custom-auth/resources/custom_auth/service/service.py @@ -1,19 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.abstract_fern_service import AbstractFernService +from ....security import ApiAuth import abc -import functools -import inspect -import logging import typing - import fastapi - -from ....core.abstract_fern_service import AbstractFernService +import inspect +from ....security import FernAuth +from ...errors.errors.unauthorized_request import UnauthorizedRequest from ....core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools from ....core.route_args import get_route_args -from ....security import ApiAuth, FernAuth from ...errors.errors.bad_request import BadRequest -from ...errors.errors.unauthorized_request import UnauthorizedRequest class AbstractCustomAuthService(AbstractFernService): @@ -53,14 +52,22 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_get_with_custom_auth(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_with_custom_auth) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_with_custom_auth, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_with_custom_auth, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_with_custom_auth) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> bool: @@ -91,16 +98,24 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> bool: def __init_post_with_custom_auth(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.post_with_custom_auth) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.post_with_custom_auth, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.post_with_custom_auth, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.post_with_custom_auth) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> bool: diff --git a/seed/fastapi/custom-auth/resources/errors/types/unauthorized_request_error_body.py b/seed/fastapi/custom-auth/resources/errors/types/unauthorized_request_error_body.py index d1ad508cd7c..8cb512007db 100644 --- a/seed/fastapi/custom-auth/resources/errors/types/unauthorized_request_error_body.py +++ b/seed/fastapi/custom-auth/resources/errors/types/unauthorized_request_error_body.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class UnauthorizedRequestErrorBody(UniversalBaseModel): message: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/enum-query-params/core/abstract_fern_service.py b/seed/fastapi/enum-query-params/core/abstract_fern_service.py index da7c8dc49c4..9966b4876da 100644 --- a/seed/fastapi/enum-query-params/core/abstract_fern_service.py +++ b/seed/fastapi/enum-query-params/core/abstract_fern_service.py @@ -7,5 +7,4 @@ class AbstractFernService(abc.ABC): @classmethod - def _init_fern(cls, router: fastapi.APIRouter) -> None: - ... + def _init_fern(cls, router: fastapi.APIRouter) -> None: ... diff --git a/seed/fastapi/enum-query-params/core/datetime_utils.py b/seed/fastapi/enum-query-params/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/fastapi/enum-query-params/core/datetime_utils.py +++ b/seed/fastapi/enum-query-params/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/fastapi/enum-query-params/core/exceptions/__init__.py b/seed/fastapi/enum-query-params/core/exceptions/__init__.py index 297d6e06f5f..dae4b8980c1 100644 --- a/seed/fastapi/enum-query-params/core/exceptions/__init__.py +++ b/seed/fastapi/enum-query-params/core/exceptions/__init__.py @@ -1,7 +1,11 @@ # This file was auto-generated by Fern from our API Definition. from .fern_http_exception import FernHTTPException -from .handlers import default_exception_handler, fern_http_exception_handler, http_exception_handler +from .handlers import ( + default_exception_handler, + fern_http_exception_handler, + http_exception_handler, +) from .unauthorized import UnauthorizedException __all__ = [ diff --git a/seed/fastapi/enum-query-params/core/exceptions/fern_http_exception.py b/seed/fastapi/enum-query-params/core/exceptions/fern_http_exception.py index bdf03862487..a5925c21510 100644 --- a/seed/fastapi/enum-query-params/core/exceptions/fern_http_exception.py +++ b/seed/fastapi/enum-query-params/core/exceptions/fern_http_exception.py @@ -8,7 +8,10 @@ class FernHTTPException(abc.ABC, fastapi.HTTPException): def __init__( - self, status_code: int, name: typing.Optional[str] = None, content: typing.Optional[typing.Any] = None + self, + status_code: int, + name: typing.Optional[str] = None, + content: typing.Optional[typing.Any] = None, ): super().__init__(status_code=status_code) self.name = name @@ -17,4 +20,6 @@ def __init__( def to_json_response(self) -> fastapi.responses.JSONResponse: content = fastapi.encoders.jsonable_encoder(self.content, exclude_none=True) - return fastapi.responses.JSONResponse(content=content, status_code=self.status_code) + return fastapi.responses.JSONResponse( + content=content, status_code=self.status_code + ) diff --git a/seed/fastapi/enum-query-params/core/exceptions/handlers.py b/seed/fastapi/enum-query-params/core/exceptions/handlers.py index fe5ac5419c7..6e7a82773f6 100644 --- a/seed/fastapi/enum-query-params/core/exceptions/handlers.py +++ b/seed/fastapi/enum-query-params/core/exceptions/handlers.py @@ -12,21 +12,33 @@ def fern_http_exception_handler( request: fastapi.requests.Request, exc: FernHTTPException, skip_log: bool = False ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) return exc.to_json_response() def http_exception_handler( - request: fastapi.requests.Request, exc: starlette.exceptions.HTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: starlette.exceptions.HTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=exc.status_code, content=exc.detail).to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=exc.status_code, content=exc.detail + ).to_json_response() def default_exception_handler( request: fastapi.requests.Request, exc: Exception, skip_log: bool = False ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=500, content="Internal Server Error").to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=500, content="Internal Server Error" + ).to_json_response() diff --git a/seed/fastapi/enum-query-params/core/route_args.py b/seed/fastapi/enum-query-params/core/route_args.py index 4228e2fe05d..bd940bf4ddd 100644 --- a/seed/fastapi/enum-query-params/core/route_args.py +++ b/seed/fastapi/enum-query-params/core/route_args.py @@ -20,9 +20,15 @@ class RouteArgs(typing_extensions.TypedDict): DEFAULT_ROUTE_ARGS = RouteArgs(openapi_extra=None, tags=None, include_in_schema=True) -def get_route_args(endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str) -> RouteArgs: - unwrapped = inspect.unwrap(endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY))) - route_args = typing.cast(RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS)) +def get_route_args( + endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str +) -> RouteArgs: + unwrapped = inspect.unwrap( + endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY)) + ) + route_args = typing.cast( + RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS) + ) if route_args["tags"] is None: return RouteArgs( openapi_extra=route_args["openapi_extra"], @@ -56,7 +62,11 @@ def decorator(endpoint_function: T) -> T: setattr( endpoint_function, FERN_CONFIG_KEY, - RouteArgs(openapi_extra=openapi_extra, tags=tags, include_in_schema=include_in_schema), + RouteArgs( + openapi_extra=openapi_extra, + tags=tags, + include_in_schema=include_in_schema, + ), ) return endpoint_function diff --git a/seed/fastapi/enum-query-params/register.py b/seed/fastapi/enum-query-params/register.py index eaa49359484..924372c4ac3 100644 --- a/seed/fastapi/enum-query-params/register.py +++ b/seed/fastapi/enum-query-params/register.py @@ -11,7 +11,11 @@ from fastapi import params from .core.abstract_fern_service import AbstractFernService -from .core.exceptions import default_exception_handler, fern_http_exception_handler, http_exception_handler +from .core.exceptions import ( + default_exception_handler, + fern_http_exception_handler, + http_exception_handler, +) from .core.exceptions.fern_http_exception import FernHTTPException from .resources.svc.service.service import AbstractSvcService @@ -20,12 +24,14 @@ def register( _app: fastapi.FastAPI, *, svc: AbstractSvcService, - dependencies: typing.Optional[typing.Sequence[params.Depends]] = None + dependencies: typing.Optional[typing.Sequence[params.Depends]] = None, ) -> None: _app.include_router(__register_service(svc), dependencies=dependencies) _app.add_exception_handler(FernHTTPException, fern_http_exception_handler) - _app.add_exception_handler(starlette.exceptions.HTTPException, http_exception_handler) + _app.add_exception_handler( + starlette.exceptions.HTTPException, http_exception_handler + ) _app.add_exception_handler(Exception, default_exception_handler) @@ -37,7 +43,9 @@ def __register_service(service: AbstractFernService) -> fastapi.APIRouter: def register_validators(module: types.ModuleType) -> None: validators_directory: str = os.path.dirname(module.__file__) # type: ignore - for path in glob.glob(os.path.join(validators_directory, "**/*.py"), recursive=True): + for path in glob.glob( + os.path.join(validators_directory, "**/*.py"), recursive=True + ): if os.path.isfile(path): relative_path = os.path.relpath(path, start=validators_directory) module_path = ".".join([module.__name__] + relative_path[:-3].split("/")) diff --git a/seed/fastapi/enum-query-params/resources/svc/service/service.py b/seed/fastapi/enum-query-params/resources/svc/service/service.py index a41b314dab1..320d9da8235 100644 --- a/seed/fastapi/enum-query-params/resources/svc/service/service.py +++ b/seed/fastapi/enum-query-params/resources/svc/service/service.py @@ -24,8 +24,9 @@ class AbstractSvcService(AbstractFernService): """ @abc.abstractmethod - def test(self, *, some_enum: typing.Optional[typing.List[MyEnum]] = None) -> str: - ... + def test( + self, *, some_enum: typing.Optional[typing.List[MyEnum]] = None + ) -> str: ... """ Below are internal methods used by Fern to register your implementation. @@ -40,14 +41,24 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_test(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.test) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "some_enum": - new_parameters.append(parameter.replace(default=fastapi.Query(default=None, alias="some-enum"))) + new_parameters.append( + parameter.replace( + default=fastapi.Query(default=None, alias="some-enum") + ) + ) else: new_parameters.append(parameter) - setattr(cls.test, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.test, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.test) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> str: diff --git a/seed/fastapi/enum/core/abstract_fern_service.py b/seed/fastapi/enum/core/abstract_fern_service.py index da7c8dc49c4..9966b4876da 100644 --- a/seed/fastapi/enum/core/abstract_fern_service.py +++ b/seed/fastapi/enum/core/abstract_fern_service.py @@ -7,5 +7,4 @@ class AbstractFernService(abc.ABC): @classmethod - def _init_fern(cls, router: fastapi.APIRouter) -> None: - ... + def _init_fern(cls, router: fastapi.APIRouter) -> None: ... diff --git a/seed/fastapi/enum/core/datetime_utils.py b/seed/fastapi/enum/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/fastapi/enum/core/datetime_utils.py +++ b/seed/fastapi/enum/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/fastapi/enum/core/exceptions/__init__.py b/seed/fastapi/enum/core/exceptions/__init__.py index 297d6e06f5f..dae4b8980c1 100644 --- a/seed/fastapi/enum/core/exceptions/__init__.py +++ b/seed/fastapi/enum/core/exceptions/__init__.py @@ -1,7 +1,11 @@ # This file was auto-generated by Fern from our API Definition. from .fern_http_exception import FernHTTPException -from .handlers import default_exception_handler, fern_http_exception_handler, http_exception_handler +from .handlers import ( + default_exception_handler, + fern_http_exception_handler, + http_exception_handler, +) from .unauthorized import UnauthorizedException __all__ = [ diff --git a/seed/fastapi/enum/core/exceptions/fern_http_exception.py b/seed/fastapi/enum/core/exceptions/fern_http_exception.py index bdf03862487..a5925c21510 100644 --- a/seed/fastapi/enum/core/exceptions/fern_http_exception.py +++ b/seed/fastapi/enum/core/exceptions/fern_http_exception.py @@ -8,7 +8,10 @@ class FernHTTPException(abc.ABC, fastapi.HTTPException): def __init__( - self, status_code: int, name: typing.Optional[str] = None, content: typing.Optional[typing.Any] = None + self, + status_code: int, + name: typing.Optional[str] = None, + content: typing.Optional[typing.Any] = None, ): super().__init__(status_code=status_code) self.name = name @@ -17,4 +20,6 @@ def __init__( def to_json_response(self) -> fastapi.responses.JSONResponse: content = fastapi.encoders.jsonable_encoder(self.content, exclude_none=True) - return fastapi.responses.JSONResponse(content=content, status_code=self.status_code) + return fastapi.responses.JSONResponse( + content=content, status_code=self.status_code + ) diff --git a/seed/fastapi/enum/core/exceptions/handlers.py b/seed/fastapi/enum/core/exceptions/handlers.py index fe5ac5419c7..6e7a82773f6 100644 --- a/seed/fastapi/enum/core/exceptions/handlers.py +++ b/seed/fastapi/enum/core/exceptions/handlers.py @@ -12,21 +12,33 @@ def fern_http_exception_handler( request: fastapi.requests.Request, exc: FernHTTPException, skip_log: bool = False ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) return exc.to_json_response() def http_exception_handler( - request: fastapi.requests.Request, exc: starlette.exceptions.HTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: starlette.exceptions.HTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=exc.status_code, content=exc.detail).to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=exc.status_code, content=exc.detail + ).to_json_response() def default_exception_handler( request: fastapi.requests.Request, exc: Exception, skip_log: bool = False ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=500, content="Internal Server Error").to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=500, content="Internal Server Error" + ).to_json_response() diff --git a/seed/fastapi/enum/core/route_args.py b/seed/fastapi/enum/core/route_args.py index 4228e2fe05d..bd940bf4ddd 100644 --- a/seed/fastapi/enum/core/route_args.py +++ b/seed/fastapi/enum/core/route_args.py @@ -20,9 +20,15 @@ class RouteArgs(typing_extensions.TypedDict): DEFAULT_ROUTE_ARGS = RouteArgs(openapi_extra=None, tags=None, include_in_schema=True) -def get_route_args(endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str) -> RouteArgs: - unwrapped = inspect.unwrap(endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY))) - route_args = typing.cast(RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS)) +def get_route_args( + endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str +) -> RouteArgs: + unwrapped = inspect.unwrap( + endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY)) + ) + route_args = typing.cast( + RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS) + ) if route_args["tags"] is None: return RouteArgs( openapi_extra=route_args["openapi_extra"], @@ -56,7 +62,11 @@ def decorator(endpoint_function: T) -> T: setattr( endpoint_function, FERN_CONFIG_KEY, - RouteArgs(openapi_extra=openapi_extra, tags=tags, include_in_schema=include_in_schema), + RouteArgs( + openapi_extra=openapi_extra, + tags=tags, + include_in_schema=include_in_schema, + ), ) return endpoint_function diff --git a/seed/fastapi/enum/register.py b/seed/fastapi/enum/register.py index 77241986c6c..1156a4994a5 100644 --- a/seed/fastapi/enum/register.py +++ b/seed/fastapi/enum/register.py @@ -11,7 +11,11 @@ from fastapi import params from .core.abstract_fern_service import AbstractFernService -from .core.exceptions import default_exception_handler, fern_http_exception_handler, http_exception_handler +from .core.exceptions import ( + default_exception_handler, + fern_http_exception_handler, + http_exception_handler, +) from .core.exceptions.fern_http_exception import FernHTTPException from .resources.inlined_request.service.service import AbstractInlinedRequestService from .resources.path_param.service.service import AbstractPathParamService @@ -24,14 +28,16 @@ def register( inlined_request: AbstractInlinedRequestService, path_param: AbstractPathParamService, query_param: AbstractQueryParamService, - dependencies: typing.Optional[typing.Sequence[params.Depends]] = None + dependencies: typing.Optional[typing.Sequence[params.Depends]] = None, ) -> None: _app.include_router(__register_service(inlined_request), dependencies=dependencies) _app.include_router(__register_service(path_param), dependencies=dependencies) _app.include_router(__register_service(query_param), dependencies=dependencies) _app.add_exception_handler(FernHTTPException, fern_http_exception_handler) - _app.add_exception_handler(starlette.exceptions.HTTPException, http_exception_handler) + _app.add_exception_handler( + starlette.exceptions.HTTPException, http_exception_handler + ) _app.add_exception_handler(Exception, default_exception_handler) @@ -43,7 +49,9 @@ def __register_service(service: AbstractFernService) -> fastapi.APIRouter: def register_validators(module: types.ModuleType) -> None: validators_directory: str = os.path.dirname(module.__file__) # type: ignore - for path in glob.glob(os.path.join(validators_directory, "**/*.py"), recursive=True): + for path in glob.glob( + os.path.join(validators_directory, "**/*.py"), recursive=True + ): if os.path.isfile(path): relative_path = os.path.relpath(path, start=validators_directory) module_path = ".".join([module.__name__] + relative_path[:-3].split("/")) diff --git a/seed/fastapi/enum/resources/inlined_request/service/send_enum_inlined_request.py b/seed/fastapi/enum/resources/inlined_request/service/send_enum_inlined_request.py index 95b40bcb66b..a080230fea1 100644 --- a/seed/fastapi/enum/resources/inlined_request/service/send_enum_inlined_request.py +++ b/seed/fastapi/enum/resources/inlined_request/service/send_enum_inlined_request.py @@ -16,11 +16,19 @@ class SendEnumInlinedRequest(pydantic.BaseModel): operand: typing.Optional[Operand] def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/fastapi/enum/resources/inlined_request/service/service.py b/seed/fastapi/enum/resources/inlined_request/service/service.py index e8573f6733c..cc8fdbf56fd 100644 --- a/seed/fastapi/enum/resources/inlined_request/service/service.py +++ b/seed/fastapi/enum/resources/inlined_request/service/service.py @@ -25,8 +25,7 @@ class AbstractInlinedRequestService(AbstractFernService): """ @abc.abstractmethod - def send(self, *, body: SendEnumInlinedRequest) -> None: - ... + def send(self, *, body: SendEnumInlinedRequest) -> None: ... """ Below are internal methods used by Fern to register your implementation. @@ -41,14 +40,20 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_send(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.send) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) else: new_parameters.append(parameter) - setattr(cls.send, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.send, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.send) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> None: diff --git a/seed/fastapi/enum/resources/path_param/service/service.py b/seed/fastapi/enum/resources/path_param/service/service.py index 2c63c18a674..f2affa92365 100644 --- a/seed/fastapi/enum/resources/path_param/service/service.py +++ b/seed/fastapi/enum/resources/path_param/service/service.py @@ -25,8 +25,7 @@ class AbstractPathParamService(AbstractFernService): """ @abc.abstractmethod - def send(self, *, operand: Operand) -> None: - ... + def send(self, *, operand: Operand) -> None: ... """ Below are internal methods used by Fern to register your implementation. @@ -41,14 +40,20 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_send(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.send) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "operand": new_parameters.append(parameter.replace(default=fastapi.Path(...))) else: new_parameters.append(parameter) - setattr(cls.send, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.send, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.send) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> None: diff --git a/seed/fastapi/enum/resources/query_param/service/service.py b/seed/fastapi/enum/resources/query_param/service/service.py index 3a0ad638f21..13b44e9410b 100644 --- a/seed/fastapi/enum/resources/query_param/service/service.py +++ b/seed/fastapi/enum/resources/query_param/service/service.py @@ -25,12 +25,12 @@ class AbstractQueryParamService(AbstractFernService): """ @abc.abstractmethod - def send(self, *, operand: typing.Optional[Operand] = None) -> None: - ... + def send(self, *, operand: typing.Optional[Operand] = None) -> None: ... @abc.abstractmethod - def send_list(self, *, operand: typing.Optional[typing.List[Operand]] = None) -> None: - ... + def send_list( + self, *, operand: typing.Optional[typing.List[Operand]] = None + ) -> None: ... """ Below are internal methods used by Fern to register your implementation. @@ -46,14 +46,22 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_send(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.send) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "operand": - new_parameters.append(parameter.replace(default=fastapi.Query(default=None))) + new_parameters.append( + parameter.replace(default=fastapi.Query(default=None)) + ) else: new_parameters.append(parameter) - setattr(cls.send, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.send, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.send) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> None: @@ -83,14 +91,22 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> None: def __init_send_list(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.send_list) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "operand": - new_parameters.append(parameter.replace(default=fastapi.Query(default=None))) + new_parameters.append( + parameter.replace(default=fastapi.Query(default=None)) + ) else: new_parameters.append(parameter) - setattr(cls.send_list, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.send_list, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.send_list) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> None: diff --git a/seed/fastapi/error-property/core/abstract_fern_service.py b/seed/fastapi/error-property/core/abstract_fern_service.py index da7c8dc49c4..9966b4876da 100644 --- a/seed/fastapi/error-property/core/abstract_fern_service.py +++ b/seed/fastapi/error-property/core/abstract_fern_service.py @@ -7,5 +7,4 @@ class AbstractFernService(abc.ABC): @classmethod - def _init_fern(cls, router: fastapi.APIRouter) -> None: - ... + def _init_fern(cls, router: fastapi.APIRouter) -> None: ... diff --git a/seed/fastapi/error-property/core/datetime_utils.py b/seed/fastapi/error-property/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/fastapi/error-property/core/datetime_utils.py +++ b/seed/fastapi/error-property/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/fastapi/error-property/core/exceptions/__init__.py b/seed/fastapi/error-property/core/exceptions/__init__.py index 297d6e06f5f..dae4b8980c1 100644 --- a/seed/fastapi/error-property/core/exceptions/__init__.py +++ b/seed/fastapi/error-property/core/exceptions/__init__.py @@ -1,7 +1,11 @@ # This file was auto-generated by Fern from our API Definition. from .fern_http_exception import FernHTTPException -from .handlers import default_exception_handler, fern_http_exception_handler, http_exception_handler +from .handlers import ( + default_exception_handler, + fern_http_exception_handler, + http_exception_handler, +) from .unauthorized import UnauthorizedException __all__ = [ diff --git a/seed/fastapi/error-property/core/exceptions/fern_http_exception.py b/seed/fastapi/error-property/core/exceptions/fern_http_exception.py index 0770211f75c..24ee7b0cc25 100644 --- a/seed/fastapi/error-property/core/exceptions/fern_http_exception.py +++ b/seed/fastapi/error-property/core/exceptions/fern_http_exception.py @@ -1,21 +1,21 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - import abc -import http -import typing -import uuid - import fastapi -import pydantic - +import typing from ..pydantic_utilities import UniversalBaseModel +import pydantic +import uuid +import http class FernHTTPException(abc.ABC, fastapi.HTTPException): def __init__( - self, status_code: int, name: typing.Optional[str] = None, content: typing.Optional[typing.Any] = None + self, + status_code: int, + name: typing.Optional[str] = None, + content: typing.Optional[typing.Any] = None, ): super().__init__(status_code=status_code) self.name = name @@ -23,13 +23,20 @@ def __init__( self.content = content class Body(UniversalBaseModel): - error_name: typing.Optional[str] = pydantic.Field(alias="errorName", default=None) - error_instance_id: uuid.UUID = pydantic.Field(alias="errorInstanceId", default_factory=uuid.uuid4) + error_name: typing.Optional[str] = pydantic.Field( + alias="errorName", default=None + ) + error_instance_id: uuid.UUID = pydantic.Field( + alias="errorInstanceId", default_factory=uuid.uuid4 + ) content: typing.Optional[typing.Any] = None def to_json_response(self) -> fastapi.responses.JSONResponse: body = FernHTTPException.Body( - error_name=self.name, content=self.content or http.HTTPStatus(self.status_code).phrase + error_name=self.name, + content=self.content or http.HTTPStatus(self.status_code).phrase, ) content = fastapi.encoders.jsonable_encoder(body, exclude_none=True) - return fastapi.responses.JSONResponse(content=content, status_code=self.status_code) + return fastapi.responses.JSONResponse( + content=content, status_code=self.status_code + ) diff --git a/seed/fastapi/error-property/core/exceptions/handlers.py b/seed/fastapi/error-property/core/exceptions/handlers.py index 6d8c4155c5a..ae1c2741f06 100644 --- a/seed/fastapi/error-property/core/exceptions/handlers.py +++ b/seed/fastapi/error-property/core/exceptions/handlers.py @@ -2,32 +2,49 @@ import logging -import fastapi import starlette import starlette.exceptions +import fastapi + from .fern_http_exception import FernHTTPException def fern_http_exception_handler( - request: fastapi.requests.Request, exc: FernHTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: FernHTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) return exc.to_json_response() def http_exception_handler( - request: fastapi.requests.Request, exc: starlette.exceptions.HTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: starlette.exceptions.HTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=exc.status_code, content=exc.detail).to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=exc.status_code, content=exc.detail + ).to_json_response() def default_exception_handler( - request: fastapi.requests.Request, exc: Exception, skip_log: bool = False + request: fastapi.requests.Request, + exc: Exception, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=500, content="Internal Server Error").to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=500, content="Internal Server Error" + ).to_json_response() diff --git a/seed/fastapi/error-property/core/pydantic_utilities.py b/seed/fastapi/error-property/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/fastapi/error-property/core/pydantic_utilities.py +++ b/seed/fastapi/error-property/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/fastapi/error-property/core/route_args.py b/seed/fastapi/error-property/core/route_args.py index 4228e2fe05d..bd940bf4ddd 100644 --- a/seed/fastapi/error-property/core/route_args.py +++ b/seed/fastapi/error-property/core/route_args.py @@ -20,9 +20,15 @@ class RouteArgs(typing_extensions.TypedDict): DEFAULT_ROUTE_ARGS = RouteArgs(openapi_extra=None, tags=None, include_in_schema=True) -def get_route_args(endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str) -> RouteArgs: - unwrapped = inspect.unwrap(endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY))) - route_args = typing.cast(RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS)) +def get_route_args( + endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str +) -> RouteArgs: + unwrapped = inspect.unwrap( + endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY)) + ) + route_args = typing.cast( + RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS) + ) if route_args["tags"] is None: return RouteArgs( openapi_extra=route_args["openapi_extra"], @@ -56,7 +62,11 @@ def decorator(endpoint_function: T) -> T: setattr( endpoint_function, FERN_CONFIG_KEY, - RouteArgs(openapi_extra=openapi_extra, tags=tags, include_in_schema=include_in_schema), + RouteArgs( + openapi_extra=openapi_extra, + tags=tags, + include_in_schema=include_in_schema, + ), ) return endpoint_function diff --git a/seed/fastapi/error-property/register.py b/seed/fastapi/error-property/register.py index dcf94c5befa..57bd81f4b80 100644 --- a/seed/fastapi/error-property/register.py +++ b/seed/fastapi/error-property/register.py @@ -1,31 +1,37 @@ # This file was auto-generated by Fern from our API Definition. -import glob -import importlib -import os -import types -import typing - import fastapi -import starlette.exceptions +from .resources.property_based_error.service.service import ( + AbstractPropertyBasedErrorService, +) +import typing from fastapi import params - -from .core.abstract_fern_service import AbstractFernService -from .core.exceptions import default_exception_handler, fern_http_exception_handler, http_exception_handler from .core.exceptions.fern_http_exception import FernHTTPException -from .resources.property_based_error.service.service import AbstractPropertyBasedErrorService +from .core.exceptions import fern_http_exception_handler +import starlette.exceptions +from .core.exceptions import http_exception_handler +from .core.exceptions import default_exception_handler +from .core.abstract_fern_service import AbstractFernService +import types +import os +import glob +import importlib def register( _app: fastapi.FastAPI, *, property_based_error: AbstractPropertyBasedErrorService, - dependencies: typing.Optional[typing.Sequence[params.Depends]] = None + dependencies: typing.Optional[typing.Sequence[params.Depends]] = None, ) -> None: - _app.include_router(__register_service(property_based_error), dependencies=dependencies) + _app.include_router( + __register_service(property_based_error), dependencies=dependencies + ) _app.add_exception_handler(FernHTTPException, fern_http_exception_handler) # type: ignore - _app.add_exception_handler(starlette.exceptions.HTTPException, http_exception_handler) # type: ignore + _app.add_exception_handler( + starlette.exceptions.HTTPException, http_exception_handler + ) # type: ignore _app.add_exception_handler(Exception, default_exception_handler) # type: ignore @@ -37,7 +43,9 @@ def __register_service(service: AbstractFernService) -> fastapi.APIRouter: def register_validators(module: types.ModuleType) -> None: validators_directory: str = os.path.dirname(module.__file__) # type: ignore - for path in glob.glob(os.path.join(validators_directory, "**/*.py"), recursive=True): + for path in glob.glob( + os.path.join(validators_directory, "**/*.py"), recursive=True + ): if os.path.isfile(path): relative_path = os.path.relpath(path, start=validators_directory) module_path = ".".join([module.__name__] + relative_path[:-3].split("/")) diff --git a/seed/fastapi/error-property/resources/errors/types/property_based_error_test_body.py b/seed/fastapi/error-property/resources/errors/types/property_based_error_test_body.py index 69b30fd2772..a5e888c969c 100644 --- a/seed/fastapi/error-property/resources/errors/types/property_based_error_test_body.py +++ b/seed/fastapi/error-property/resources/errors/types/property_based_error_test_body.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class PropertyBasedErrorTestBody(UniversalBaseModel): message: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/error-property/resources/property_based_error/service/service.py b/seed/fastapi/error-property/resources/property_based_error/service/service.py index 3cecff90dbd..f5a0b8a4e34 100644 --- a/seed/fastapi/error-property/resources/property_based_error/service/service.py +++ b/seed/fastapi/error-property/resources/property_based_error/service/service.py @@ -1,17 +1,15 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.abstract_fern_service import AbstractFernService import abc -import functools +import fastapi import inspect -import logging import typing - -import fastapi - -from ....core.abstract_fern_service import AbstractFernService +from ...errors.errors.property_based_error_test import PropertyBasedErrorTest from ....core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools from ....core.route_args import get_route_args -from ...errors.errors.property_based_error_test import PropertyBasedErrorTest class AbstractPropertyBasedErrorService(AbstractFernService): @@ -43,12 +41,18 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_throw_error(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.throw_error) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) else: new_parameters.append(parameter) - setattr(cls.throw_error, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.throw_error, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.throw_error) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> str: diff --git a/seed/fastapi/examples/core/abstract_fern_service.py b/seed/fastapi/examples/core/abstract_fern_service.py index da7c8dc49c4..9966b4876da 100644 --- a/seed/fastapi/examples/core/abstract_fern_service.py +++ b/seed/fastapi/examples/core/abstract_fern_service.py @@ -7,5 +7,4 @@ class AbstractFernService(abc.ABC): @classmethod - def _init_fern(cls, router: fastapi.APIRouter) -> None: - ... + def _init_fern(cls, router: fastapi.APIRouter) -> None: ... diff --git a/seed/fastapi/examples/core/datetime_utils.py b/seed/fastapi/examples/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/fastapi/examples/core/datetime_utils.py +++ b/seed/fastapi/examples/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/fastapi/examples/core/exceptions/__init__.py b/seed/fastapi/examples/core/exceptions/__init__.py index 297d6e06f5f..dae4b8980c1 100644 --- a/seed/fastapi/examples/core/exceptions/__init__.py +++ b/seed/fastapi/examples/core/exceptions/__init__.py @@ -1,7 +1,11 @@ # This file was auto-generated by Fern from our API Definition. from .fern_http_exception import FernHTTPException -from .handlers import default_exception_handler, fern_http_exception_handler, http_exception_handler +from .handlers import ( + default_exception_handler, + fern_http_exception_handler, + http_exception_handler, +) from .unauthorized import UnauthorizedException __all__ = [ diff --git a/seed/fastapi/examples/core/exceptions/fern_http_exception.py b/seed/fastapi/examples/core/exceptions/fern_http_exception.py index bdf03862487..81610359a7f 100644 --- a/seed/fastapi/examples/core/exceptions/fern_http_exception.py +++ b/seed/fastapi/examples/core/exceptions/fern_http_exception.py @@ -1,14 +1,16 @@ # This file was auto-generated by Fern from our API Definition. import abc -import typing - import fastapi +import typing class FernHTTPException(abc.ABC, fastapi.HTTPException): def __init__( - self, status_code: int, name: typing.Optional[str] = None, content: typing.Optional[typing.Any] = None + self, + status_code: int, + name: typing.Optional[str] = None, + content: typing.Optional[typing.Any] = None, ): super().__init__(status_code=status_code) self.name = name @@ -17,4 +19,6 @@ def __init__( def to_json_response(self) -> fastapi.responses.JSONResponse: content = fastapi.encoders.jsonable_encoder(self.content, exclude_none=True) - return fastapi.responses.JSONResponse(content=content, status_code=self.status_code) + return fastapi.responses.JSONResponse( + content=content, status_code=self.status_code + ) diff --git a/seed/fastapi/examples/core/exceptions/handlers.py b/seed/fastapi/examples/core/exceptions/handlers.py index 6d8c4155c5a..ae1c2741f06 100644 --- a/seed/fastapi/examples/core/exceptions/handlers.py +++ b/seed/fastapi/examples/core/exceptions/handlers.py @@ -2,32 +2,49 @@ import logging -import fastapi import starlette import starlette.exceptions +import fastapi + from .fern_http_exception import FernHTTPException def fern_http_exception_handler( - request: fastapi.requests.Request, exc: FernHTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: FernHTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) return exc.to_json_response() def http_exception_handler( - request: fastapi.requests.Request, exc: starlette.exceptions.HTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: starlette.exceptions.HTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=exc.status_code, content=exc.detail).to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=exc.status_code, content=exc.detail + ).to_json_response() def default_exception_handler( - request: fastapi.requests.Request, exc: Exception, skip_log: bool = False + request: fastapi.requests.Request, + exc: Exception, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=500, content="Internal Server Error").to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=500, content="Internal Server Error" + ).to_json_response() diff --git a/seed/fastapi/examples/core/pydantic_utilities.py b/seed/fastapi/examples/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/fastapi/examples/core/pydantic_utilities.py +++ b/seed/fastapi/examples/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/fastapi/examples/core/route_args.py b/seed/fastapi/examples/core/route_args.py index 4228e2fe05d..bd940bf4ddd 100644 --- a/seed/fastapi/examples/core/route_args.py +++ b/seed/fastapi/examples/core/route_args.py @@ -20,9 +20,15 @@ class RouteArgs(typing_extensions.TypedDict): DEFAULT_ROUTE_ARGS = RouteArgs(openapi_extra=None, tags=None, include_in_schema=True) -def get_route_args(endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str) -> RouteArgs: - unwrapped = inspect.unwrap(endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY))) - route_args = typing.cast(RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS)) +def get_route_args( + endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str +) -> RouteArgs: + unwrapped = inspect.unwrap( + endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY)) + ) + route_args = typing.cast( + RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS) + ) if route_args["tags"] is None: return RouteArgs( openapi_extra=route_args["openapi_extra"], @@ -56,7 +62,11 @@ def decorator(endpoint_function: T) -> T: setattr( endpoint_function, FERN_CONFIG_KEY, - RouteArgs(openapi_extra=openapi_extra, tags=tags, include_in_schema=include_in_schema), + RouteArgs( + openapi_extra=openapi_extra, + tags=tags, + include_in_schema=include_in_schema, + ), ) return endpoint_function diff --git a/seed/fastapi/examples/register.py b/seed/fastapi/examples/register.py index 622a8b5dd34..734b4393a6f 100644 --- a/seed/fastapi/examples/register.py +++ b/seed/fastapi/examples/register.py @@ -1,25 +1,27 @@ # This file was auto-generated by Fern from our API Definition. -import glob -import importlib -import os -import types -import typing - import fastapi -import starlette.exceptions -from fastapi import params - -from .core.abstract_fern_service import AbstractFernService -from .core.exceptions import default_exception_handler, fern_http_exception_handler, http_exception_handler -from .core.exceptions.fern_http_exception import FernHTTPException +from .service.service import AbstractRootService from .resources.file.resources.notification.resources.service.service.service import ( AbstractFileNotificationServiceService, ) from .resources.file.resources.service.service.service import AbstractFileServiceService -from .resources.health.resources.service.service.service import AbstractHealthServiceService +from .resources.health.resources.service.service.service import ( + AbstractHealthServiceService, +) from .resources.service.service.service import AbstractServiceService -from .service.service import AbstractRootService +import typing +from fastapi import params +from .core.exceptions.fern_http_exception import FernHTTPException +from .core.exceptions import fern_http_exception_handler +import starlette.exceptions +from .core.exceptions import http_exception_handler +from .core.exceptions import default_exception_handler +from .core.abstract_fern_service import AbstractFernService +import types +import os +import glob +import importlib def register( @@ -30,16 +32,20 @@ def register( file_service: AbstractFileServiceService, health_service: AbstractHealthServiceService, service: AbstractServiceService, - dependencies: typing.Optional[typing.Sequence[params.Depends]] = None + dependencies: typing.Optional[typing.Sequence[params.Depends]] = None, ) -> None: _app.include_router(__register_service(root), dependencies=dependencies) - _app.include_router(__register_service(file_notification_service), dependencies=dependencies) + _app.include_router( + __register_service(file_notification_service), dependencies=dependencies + ) _app.include_router(__register_service(file_service), dependencies=dependencies) _app.include_router(__register_service(health_service), dependencies=dependencies) _app.include_router(__register_service(service), dependencies=dependencies) _app.add_exception_handler(FernHTTPException, fern_http_exception_handler) # type: ignore - _app.add_exception_handler(starlette.exceptions.HTTPException, http_exception_handler) # type: ignore + _app.add_exception_handler( + starlette.exceptions.HTTPException, http_exception_handler + ) # type: ignore _app.add_exception_handler(Exception, default_exception_handler) # type: ignore @@ -51,7 +57,9 @@ def __register_service(service: AbstractFernService) -> fastapi.APIRouter: def register_validators(module: types.ModuleType) -> None: validators_directory: str = os.path.dirname(module.__file__) # type: ignore - for path in glob.glob(os.path.join(validators_directory, "**/*.py"), recursive=True): + for path in glob.glob( + os.path.join(validators_directory, "**/*.py"), recursive=True + ): if os.path.isfile(path): relative_path = os.path.relpath(path, start=validators_directory) module_path = ".".join([module.__name__] + relative_path[:-3].split("/")) diff --git a/seed/fastapi/examples/resources/commons/resources/types/types/data.py b/seed/fastapi/examples/resources/commons/resources/types/types/data.py index 9d50a16b7b1..bd8d42cc657 100644 --- a/seed/fastapi/examples/resources/commons/resources/types/types/data.py +++ b/seed/fastapi/examples/resources/commons/resources/types/types/data.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ......core.pydantic_utilities import IS_PYDANTIC_V2 +from ......core.pydantic_utilities import UniversalRootModel import typing - -import pydantic import typing_extensions - -from ......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel, UniversalRootModel, update_forward_refs +import pydantic +from ......core.pydantic_utilities import UniversalBaseModel +from ......core.pydantic_utilities import update_forward_refs T_Result = typing.TypeVar("T_Result") @@ -39,21 +39,26 @@ class Data(UniversalRootModel): if IS_PYDANTIC_V2: root: typing_extensions.Annotated[ - typing.Union[_Data.String, _Data.Base64], pydantic.Field(discriminator="type") + typing.Union[_Data.String, _Data.Base64], + pydantic.Field(discriminator="type"), ] def get_as_union(self) -> typing.Union[_Data.String, _Data.Base64]: return self.root - else: __root__: typing_extensions.Annotated[ - typing.Union[_Data.String, _Data.Base64], pydantic.Field(discriminator="type") + typing.Union[_Data.String, _Data.Base64], + pydantic.Field(discriminator="type"), ] def get_as_union(self) -> typing.Union[_Data.String, _Data.Base64]: return self.__root__ - def visit(self, string: typing.Callable[[str], T_Result], base_64: typing.Callable[[str], T_Result]) -> T_Result: + def visit( + self, + string: typing.Callable[[str], T_Result], + base_64: typing.Callable[[str], T_Result], + ) -> T_Result: unioned_value = self.get_as_union() if unioned_value.type == "string": return string(unioned_value.value) diff --git a/seed/fastapi/examples/resources/commons/resources/types/types/event_info.py b/seed/fastapi/examples/resources/commons/resources/types/types/event_info.py index 03ea9c7b933..e7b8bb5a7d6 100644 --- a/seed/fastapi/examples/resources/commons/resources/types/types/event_info.py +++ b/seed/fastapi/examples/resources/commons/resources/types/types/event_info.py @@ -1,25 +1,37 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from .metadata import ( + Metadata as resources_commons_resources_types_types_metadata_Metadata, +) +from ......core.pydantic_utilities import IS_PYDANTIC_V2 +from .tag import Tag as resources_commons_resources_types_types_tag_Tag +from ......core.pydantic_utilities import UniversalRootModel import typing - -import pydantic import typing_extensions - -from ......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel, UniversalRootModel, update_forward_refs -from .metadata import Metadata as resources_commons_resources_types_types_metadata_Metadata -from .tag import Tag as resources_commons_resources_types_types_tag_Tag +import pydantic +from ......core.pydantic_utilities import UniversalBaseModel +from ......core.pydantic_utilities import update_forward_refs T_Result = typing.TypeVar("T_Result") class _Factory: - def metadata(self, value: resources_commons_resources_types_types_metadata_Metadata) -> EventInfo: + def metadata( + self, value: resources_commons_resources_types_types_metadata_Metadata + ) -> EventInfo: if IS_PYDANTIC_V2: - return EventInfo(root=_EventInfo.Metadata(**value.dict(exclude_unset=True), type="metadata")) + return EventInfo( + root=_EventInfo.Metadata( + **value.dict(exclude_unset=True), type="metadata" + ) + ) else: - return EventInfo(__root__=_EventInfo.Metadata(**value.dict(exclude_unset=True), type="metadata")) + return EventInfo( + __root__=_EventInfo.Metadata( + **value.dict(exclude_unset=True), type="metadata" + ) + ) def tag(self, value: resources_commons_resources_types_types_tag_Tag) -> EventInfo: if IS_PYDANTIC_V2: @@ -45,15 +57,16 @@ class EventInfo(UniversalRootModel): if IS_PYDANTIC_V2: root: typing_extensions.Annotated[ - typing.Union[_EventInfo.Metadata, _EventInfo.Tag], pydantic.Field(discriminator="type") + typing.Union[_EventInfo.Metadata, _EventInfo.Tag], + pydantic.Field(discriminator="type"), ] def get_as_union(self) -> typing.Union[_EventInfo.Metadata, _EventInfo.Tag]: return self.root - else: __root__: typing_extensions.Annotated[ - typing.Union[_EventInfo.Metadata, _EventInfo.Tag], pydantic.Field(discriminator="type") + typing.Union[_EventInfo.Metadata, _EventInfo.Tag], + pydantic.Field(discriminator="type"), ] def get_as_union(self) -> typing.Union[_EventInfo.Metadata, _EventInfo.Tag]: @@ -61,8 +74,12 @@ def get_as_union(self) -> typing.Union[_EventInfo.Metadata, _EventInfo.Tag]: def visit( self, - metadata: typing.Callable[[resources_commons_resources_types_types_metadata_Metadata], T_Result], - tag: typing.Callable[[resources_commons_resources_types_types_tag_Tag], T_Result], + metadata: typing.Callable[ + [resources_commons_resources_types_types_metadata_Metadata], T_Result + ], + tag: typing.Callable[ + [resources_commons_resources_types_types_tag_Tag], T_Result + ], ) -> T_Result: unioned_value = self.get_as_union() if unioned_value.type == "metadata": diff --git a/seed/fastapi/examples/resources/commons/resources/types/types/metadata.py b/seed/fastapi/examples/resources/commons/resources/types/types/metadata.py index 936d40ae63c..6bd315cf9ae 100644 --- a/seed/fastapi/examples/resources/commons/resources/types/types/metadata.py +++ b/seed/fastapi/examples/resources/commons/resources/types/types/metadata.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. +from ......core.pydantic_utilities import UniversalBaseModel import typing - import pydantic - -from ......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ......core.pydantic_utilities import IS_PYDANTIC_V2 class Metadata(UniversalBaseModel): @@ -25,7 +24,9 @@ class Metadata(UniversalBaseModel): json_string: typing.Optional[str] = pydantic.Field(alias="jsonString", default=None) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/examples/resources/commons/resources/types/types/tag.py b/seed/fastapi/examples/resources/commons/resources/types/types/tag.py index ae576888232..ad97a39db4c 100644 --- a/seed/fastapi/examples/resources/commons/resources/types/types/tag.py +++ b/seed/fastapi/examples/resources/commons/resources/types/types/tag.py @@ -3,4 +3,5 @@ """ "tag-wf9as23d" """ + Tag = str diff --git a/seed/fastapi/examples/resources/file/resources/notification/resources/service/service/service.py b/seed/fastapi/examples/resources/file/resources/notification/resources/service/service/service.py index b5e33abaac4..3fe2af8ceeb 100644 --- a/seed/fastapi/examples/resources/file/resources/notification/resources/service/service/service.py +++ b/seed/fastapi/examples/resources/file/resources/notification/resources/service/service/service.py @@ -1,18 +1,17 @@ # This file was auto-generated by Fern from our API Definition. +from ........core.abstract_fern_service import AbstractFernService +from ........security import ApiAuth +from .......types.types.exception import Exception import abc -import functools +import fastapi import inspect -import logging import typing - -import fastapi - -from ........core.abstract_fern_service import AbstractFernService +from ........security import FernAuth from ........core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools from ........core.route_args import get_route_args -from ........security import ApiAuth, FernAuth -from .......types.types.exception import Exception class AbstractFileNotificationServiceService(AbstractFernService): @@ -25,8 +24,7 @@ class AbstractFileNotificationServiceService(AbstractFernService): """ @abc.abstractmethod - def get_exception(self, *, notification_id: str, auth: ApiAuth) -> Exception: - ... + def get_exception(self, *, notification_id: str, auth: ApiAuth) -> Exception: ... """ Below are internal methods used by Fern to register your implementation. @@ -41,16 +39,24 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_get_exception(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_exception) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "notification_id": new_parameters.append(parameter.replace(default=fastapi.Path(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_exception, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_exception, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_exception) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> Exception: @@ -72,5 +78,7 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> Exception: path="/file/notification/{notification_id}", response_model=Exception, description=AbstractFileNotificationServiceService.get_exception.__doc__, - **get_route_args(cls.get_exception, default_tag="file.notification.service"), + **get_route_args( + cls.get_exception, default_tag="file.notification.service" + ), )(wrapper) diff --git a/seed/fastapi/examples/resources/file/resources/service/service/service.py b/seed/fastapi/examples/resources/file/resources/service/service/service.py index a0d9c4f3574..aec67207dfa 100644 --- a/seed/fastapi/examples/resources/file/resources/service/service/service.py +++ b/seed/fastapi/examples/resources/file/resources/service/service/service.py @@ -1,19 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ......core.abstract_fern_service import AbstractFernService +from ......security import ApiAuth +from .....types.types.file import File import abc -import functools +import fastapi import inspect -import logging import typing - -import fastapi - -from ......core.abstract_fern_service import AbstractFernService +from ......security import FernAuth +from .....types.errors.not_found_error import NotFoundError from ......core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools from ......core.route_args import get_route_args -from ......security import ApiAuth, FernAuth -from .....types.errors.not_found_error import NotFoundError -from .....types.types.file import File class AbstractFileServiceService(AbstractFernService): @@ -45,16 +44,24 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_get_file(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_file) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "filename": new_parameters.append(parameter.replace(default=fastapi.Path(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_file, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_file, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_file) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> File: diff --git a/seed/fastapi/examples/resources/file/resources/service/types/filename.py b/seed/fastapi/examples/resources/file/resources/service/types/filename.py index add91706b10..2531edee925 100644 --- a/seed/fastapi/examples/resources/file/resources/service/types/filename.py +++ b/seed/fastapi/examples/resources/file/resources/service/types/filename.py @@ -3,4 +3,5 @@ """ "file.txt" """ + Filename = str diff --git a/seed/fastapi/examples/resources/health/resources/service/service/service.py b/seed/fastapi/examples/resources/health/resources/service/service/service.py index 46d9c278939..a24cf9baec9 100644 --- a/seed/fastapi/examples/resources/health/resources/service/service/service.py +++ b/seed/fastapi/examples/resources/health/resources/service/service/service.py @@ -1,18 +1,17 @@ # This file was auto-generated by Fern from our API Definition. +from ......core.abstract_fern_service import AbstractFernService +from ......security import ApiAuth import abc -import functools +import fastapi import inspect -import logging import typing - -import fastapi -import starlette - -from ......core.abstract_fern_service import AbstractFernService +from ......security import FernAuth from ......core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools +import starlette from ......core.route_args import get_route_args -from ......security import ApiAuth, FernAuth class AbstractHealthServiceService(AbstractFernService): @@ -52,16 +51,24 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_check(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.check) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "id": new_parameters.append(parameter.replace(default=fastapi.Path(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.check, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.check, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.check) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> None: @@ -91,14 +98,22 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> None: def __init_ping(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.ping) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.ping, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.ping, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.ping) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> bool: diff --git a/seed/fastapi/examples/resources/service/service/service.py b/seed/fastapi/examples/resources/service/service/service.py index be115dc8b49..3dc171af5e5 100644 --- a/seed/fastapi/examples/resources/service/service/service.py +++ b/seed/fastapi/examples/resources/service/service/service.py @@ -1,20 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.abstract_fern_service import AbstractFernService +from ...types.types.movie import Movie import abc -import functools -import inspect -import logging +from ...types.types.movie_id import MovieId import typing - +from ...types.types.metadata import Metadata +from ...types.types.response import Response import fastapi - -from ....core.abstract_fern_service import AbstractFernService +import inspect from ....core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools from ....core.route_args import get_route_args -from ...types.types.metadata import Metadata -from ...types.types.movie import Movie -from ...types.types.movie_id import MovieId -from ...types.types.response import Response class AbstractServiceService(AbstractFernService): @@ -27,12 +25,10 @@ class AbstractServiceService(AbstractFernService): """ @abc.abstractmethod - def get_movie(self, *, movie_id: str) -> Movie: - ... + def get_movie(self, *, movie_id: str) -> Movie: ... @abc.abstractmethod - def create_movie(self, *, body: Movie) -> MovieId: - ... + def create_movie(self, *, body: Movie) -> MovieId: ... @abc.abstractmethod def get_metadata( @@ -41,12 +37,10 @@ def get_metadata( shallow: typing.Optional[bool] = None, tag: typing.Optional[typing.List[str]] = None, x_api_version: str, - ) -> Metadata: - ... + ) -> Metadata: ... @abc.abstractmethod - def get_response(self) -> Response: - ... + def get_response(self) -> Response: ... """ Below are internal methods used by Fern to register your implementation. @@ -64,14 +58,20 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_get_movie(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_movie) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "movie_id": new_parameters.append(parameter.replace(default=fastapi.Path(...))) else: new_parameters.append(parameter) - setattr(cls.get_movie, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_movie, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_movie) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> Movie: @@ -100,14 +100,20 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> Movie: def __init_create_movie(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.create_movie) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) else: new_parameters.append(parameter) - setattr(cls.create_movie, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.create_movie, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.create_movie) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> MovieId: @@ -136,18 +142,30 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> MovieId: def __init_get_metadata(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_metadata) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "shallow": - new_parameters.append(parameter.replace(default=fastapi.Query(default=None))) + new_parameters.append( + parameter.replace(default=fastapi.Query(default=None)) + ) elif parameter_name == "tag": - new_parameters.append(parameter.replace(default=fastapi.Query(default=None))) + new_parameters.append( + parameter.replace(default=fastapi.Query(default=None)) + ) elif parameter_name == "x_api_version": - new_parameters.append(parameter.replace(default=fastapi.Header(alias="X-API-Version"))) + new_parameters.append( + parameter.replace(default=fastapi.Header(alias="X-API-Version")) + ) else: new_parameters.append(parameter) - setattr(cls.get_metadata, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_metadata, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_metadata) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> Metadata: @@ -176,12 +194,18 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> Metadata: def __init_get_response(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_response) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) else: new_parameters.append(parameter) - setattr(cls.get_response, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_response, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_response) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> Response: diff --git a/seed/fastapi/examples/resources/types/types/actor.py b/seed/fastapi/examples/resources/types/types/actor.py index d11a753f7fb..e743af6d337 100644 --- a/seed/fastapi/examples/resources/types/types/actor.py +++ b/seed/fastapi/examples/resources/types/types/actor.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class Actor(UniversalBaseModel): name: str id: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/examples/resources/types/types/actress.py b/seed/fastapi/examples/resources/types/types/actress.py index 19b0ccf3f44..bed464a7e2a 100644 --- a/seed/fastapi/examples/resources/types/types/actress.py +++ b/seed/fastapi/examples/resources/types/types/actress.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class Actress(UniversalBaseModel): """ @@ -23,7 +22,9 @@ class Actress(UniversalBaseModel): id: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/examples/resources/types/types/cast_member.py b/seed/fastapi/examples/resources/types/types/cast_member.py index d73c89864e1..8be1a0b0a2a 100644 --- a/seed/fastapi/examples/resources/types/types/cast_member.py +++ b/seed/fastapi/examples/resources/types/types/cast_member.py @@ -1,7 +1,6 @@ # This file was auto-generated by Fern from our API Definition. import typing - from .actor import Actor from .actress import Actress from .stunt_double import StuntDouble diff --git a/seed/fastapi/examples/resources/types/types/directory.py b/seed/fastapi/examples/resources/types/types/directory.py index ac858e745dc..699ad545971 100644 --- a/seed/fastapi/examples/resources/types/types/directory.py +++ b/seed/fastapi/examples/resources/types/types/directory.py @@ -1,13 +1,12 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ....core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel, update_forward_refs from .file import File +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import pydantic +from ....core.pydantic_utilities import update_forward_refs class Directory(UniversalBaseModel): @@ -43,7 +42,9 @@ class Directory(UniversalBaseModel): directories: typing.Optional[typing.List[Directory]] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/examples/resources/types/types/entity.py b/seed/fastapi/examples/resources/types/types/entity.py index 7b387913073..030605e7fe1 100644 --- a/seed/fastapi/examples/resources/types/types/entity.py +++ b/seed/fastapi/examples/resources/types/types/entity.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel +from ....types.type import Type +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from ....types.type import Type - class Entity(UniversalBaseModel): """ @@ -25,7 +24,9 @@ class Entity(UniversalBaseModel): name: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/examples/resources/types/types/exception.py b/seed/fastapi/examples/resources/types/types/exception.py index 423f730cc1d..4b8ddfa86cc 100644 --- a/seed/fastapi/examples/resources/types/types/exception.py +++ b/seed/fastapi/examples/resources/types/types/exception.py @@ -1,14 +1,14 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from .exception_info import ExceptionInfo +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +from ....core.pydantic_utilities import UniversalRootModel import typing - -import pydantic import typing_extensions - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel, UniversalRootModel, update_forward_refs -from .exception_info import ExceptionInfo +import pydantic +from ....core.pydantic_utilities import UniversalBaseModel +from ....core.pydantic_utilities import update_forward_refs T_Result = typing.TypeVar("T_Result") @@ -16,9 +16,17 @@ class _Factory: def generic(self, value: ExceptionInfo) -> Exception: if IS_PYDANTIC_V2: - return Exception(root=_Exception.Generic(**value.dict(exclude_unset=True), type="generic")) + return Exception( + root=_Exception.Generic( + **value.dict(exclude_unset=True), type="generic" + ) + ) else: - return Exception(__root__=_Exception.Generic(**value.dict(exclude_unset=True), type="generic")) + return Exception( + __root__=_Exception.Generic( + **value.dict(exclude_unset=True), type="generic" + ) + ) def timeout(self) -> Exception: if IS_PYDANTIC_V2: @@ -44,26 +52,33 @@ class Exception(UniversalRootModel): if IS_PYDANTIC_V2: root: typing_extensions.Annotated[ - typing.Union[_Exception.Generic, _Exception.Timeout], pydantic.Field(discriminator="type") + typing.Union[_Exception.Generic, _Exception.Timeout], + pydantic.Field(discriminator="type"), ] def get_as_union(self) -> typing.Union[_Exception.Generic, _Exception.Timeout]: return self.root - else: __root__: typing_extensions.Annotated[ - typing.Union[_Exception.Generic, _Exception.Timeout], pydantic.Field(discriminator="type") + typing.Union[_Exception.Generic, _Exception.Timeout], + pydantic.Field(discriminator="type"), ] def get_as_union(self) -> typing.Union[_Exception.Generic, _Exception.Timeout]: return self.__root__ def visit( - self, generic: typing.Callable[[ExceptionInfo], T_Result], timeout: typing.Callable[[], T_Result] + self, + generic: typing.Callable[[ExceptionInfo], T_Result], + timeout: typing.Callable[[], T_Result], ) -> T_Result: unioned_value = self.get_as_union() if unioned_value.type == "generic": - return generic(ExceptionInfo(**unioned_value.dict(exclude_unset=True, exclude={"type"}))) + return generic( + ExceptionInfo( + **unioned_value.dict(exclude_unset=True, exclude={"type"}) + ) + ) if unioned_value.type == "timeout": return timeout() diff --git a/seed/fastapi/examples/resources/types/types/exception_info.py b/seed/fastapi/examples/resources/types/types/exception_info.py index 54cd54eeae4..f3042e91bd2 100644 --- a/seed/fastapi/examples/resources/types/types/exception_info.py +++ b/seed/fastapi/examples/resources/types/types/exception_info.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ....core.pydantic_utilities import UniversalBaseModel import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class ExceptionInfo(UniversalBaseModel): @@ -25,7 +24,9 @@ class ExceptionInfo(UniversalBaseModel): exception_stacktrace: str = pydantic.Field(alias="exceptionStacktrace") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/examples/resources/types/types/extended_movie.py b/seed/fastapi/examples/resources/types/types/extended_movie.py index c9920e9d65b..413a5b39bbd 100644 --- a/seed/fastapi/examples/resources/types/types/extended_movie.py +++ b/seed/fastapi/examples/resources/types/types/extended_movie.py @@ -1,11 +1,9 @@ # This file was auto-generated by Fern from our API Definition. +from .movie import Movie import typing - -import pydantic - from ....core.pydantic_utilities import IS_PYDANTIC_V2 -from .movie import Movie +import pydantic class ExtendedMovie(Movie): @@ -32,7 +30,9 @@ class ExtendedMovie(Movie): cast: typing.List[str] if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/examples/resources/types/types/file.py b/seed/fastapi/examples/resources/types/types/file.py index 19513bc7bde..16d490114e6 100644 --- a/seed/fastapi/examples/resources/types/types/file.py +++ b/seed/fastapi/examples/resources/types/types/file.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class File(UniversalBaseModel): """ @@ -23,7 +22,9 @@ class File(UniversalBaseModel): contents: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/examples/resources/types/types/metadata.py b/seed/fastapi/examples/resources/types/types/metadata.py index 74da2acaef8..6761fd25a93 100644 --- a/seed/fastapi/examples/resources/types/types/metadata.py +++ b/seed/fastapi/examples/resources/types/types/metadata.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +from ....core.pydantic_utilities import UniversalRootModel import typing - -import pydantic import typing_extensions - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel, UniversalRootModel, update_forward_refs +import pydantic +from ....core.pydantic_utilities import UniversalBaseModel +from ....core.pydantic_utilities import update_forward_refs T_Result = typing.TypeVar("T_Result") @@ -39,21 +39,26 @@ class Metadata(UniversalRootModel): if IS_PYDANTIC_V2: root: typing_extensions.Annotated[ - typing.Union[_Metadata.Html, _Metadata.Markdown], pydantic.Field(discriminator="type") + typing.Union[_Metadata.Html, _Metadata.Markdown], + pydantic.Field(discriminator="type"), ] def get_as_union(self) -> typing.Union[_Metadata.Html, _Metadata.Markdown]: return self.root - else: __root__: typing_extensions.Annotated[ - typing.Union[_Metadata.Html, _Metadata.Markdown], pydantic.Field(discriminator="type") + typing.Union[_Metadata.Html, _Metadata.Markdown], + pydantic.Field(discriminator="type"), ] def get_as_union(self) -> typing.Union[_Metadata.Html, _Metadata.Markdown]: return self.__root__ - def visit(self, html: typing.Callable[[str], T_Result], markdown: typing.Callable[[str], T_Result]) -> T_Result: + def visit( + self, + html: typing.Callable[[str], T_Result], + markdown: typing.Callable[[str], T_Result], + ) -> T_Result: unioned_value = self.get_as_union() if unioned_value.type == "html": return html(unioned_value.value) diff --git a/seed/fastapi/examples/resources/types/types/migration.py b/seed/fastapi/examples/resources/types/types/migration.py index 00574ed4ae4..e3b807074a6 100644 --- a/seed/fastapi/examples/resources/types/types/migration.py +++ b/seed/fastapi/examples/resources/types/types/migration.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel +from .migration_status import MigrationStatus +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .migration_status import MigrationStatus - class Migration(UniversalBaseModel): """ @@ -24,7 +23,9 @@ class Migration(UniversalBaseModel): status: MigrationStatus if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/examples/resources/types/types/moment.py b/seed/fastapi/examples/resources/types/types/moment.py index 89c72e9cda5..f8d2aa482cb 100644 --- a/seed/fastapi/examples/resources/types/types/moment.py +++ b/seed/fastapi/examples/resources/types/types/moment.py @@ -1,13 +1,12 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel +import uuid import datetime as dt +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import typing -import uuid - import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class Moment(UniversalBaseModel): """ @@ -36,7 +35,9 @@ class Moment(UniversalBaseModel): datetime: dt.datetime if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/examples/resources/types/types/movie.py b/seed/fastapi/examples/resources/types/types/movie.py index 44fbc6a8441..8bb860f4fd5 100644 --- a/seed/fastapi/examples/resources/types/types/movie.py +++ b/seed/fastapi/examples/resources/types/types/movie.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel +from .movie_id import MovieId import typing - import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from ...commons.resources.types.types.tag import Tag -from .movie_id import MovieId +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class Movie(UniversalBaseModel): @@ -45,7 +44,9 @@ class Movie(UniversalBaseModel): metadata: typing.Dict[str, typing.Any] if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/examples/resources/types/types/movie_id.py b/seed/fastapi/examples/resources/types/types/movie_id.py index 86f7a4f4651..86945f3b676 100644 --- a/seed/fastapi/examples/resources/types/types/movie_id.py +++ b/seed/fastapi/examples/resources/types/types/movie_id.py @@ -3,4 +3,5 @@ """ "movie-c06a4ad7" """ + MovieId = str diff --git a/seed/fastapi/examples/resources/types/types/node.py b/seed/fastapi/examples/resources/types/types/node.py index 2c4c76ce62d..15c390c81c7 100644 --- a/seed/fastapi/examples/resources/types/types/node.py +++ b/seed/fastapi/examples/resources/types/types/node.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ....core.pydantic_utilities import UniversalBaseModel import typing - +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel, update_forward_refs +from ....core.pydantic_utilities import update_forward_refs class Node(UniversalBaseModel): @@ -45,7 +44,9 @@ class Node(UniversalBaseModel): trees: typing.Optional[typing.List[Tree]] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/examples/resources/types/types/request.py b/seed/fastapi/examples/resources/types/types/request.py index c168a492afd..6064764f9f4 100644 --- a/seed/fastapi/examples/resources/types/types/request.py +++ b/seed/fastapi/examples/resources/types/types/request.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class Request(UniversalBaseModel): """ @@ -21,7 +20,9 @@ class Request(UniversalBaseModel): request: typing.Any if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/examples/resources/types/types/response.py b/seed/fastapi/examples/resources/types/types/response.py index e00a0080225..dabc6171758 100644 --- a/seed/fastapi/examples/resources/types/types/response.py +++ b/seed/fastapi/examples/resources/types/types/response.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from ....types.identifier import Identifier +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import pydantic class Response(UniversalBaseModel): @@ -36,7 +35,9 @@ class Response(UniversalBaseModel): identifiers: typing.List[Identifier] if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/examples/resources/types/types/response_type.py b/seed/fastapi/examples/resources/types/types/response_type.py index 289bb6f34d0..00f9b4fa73b 100644 --- a/seed/fastapi/examples/resources/types/types/response_type.py +++ b/seed/fastapi/examples/resources/types/types/response_type.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel +from ....types.type import Type +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from ....types.type import Type - class ResponseType(UniversalBaseModel): type: Type if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/examples/resources/types/types/stunt_double.py b/seed/fastapi/examples/resources/types/types/stunt_double.py index 14ef619fada..a47b54732b0 100644 --- a/seed/fastapi/examples/resources/types/types/stunt_double.py +++ b/seed/fastapi/examples/resources/types/types/stunt_double.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ....core.pydantic_utilities import UniversalBaseModel import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class StuntDouble(UniversalBaseModel): @@ -12,7 +11,9 @@ class StuntDouble(UniversalBaseModel): actor_or_actress_id: str = pydantic.Field(alias="actorOrActressId") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/examples/resources/types/types/test.py b/seed/fastapi/examples/resources/types/types/test.py index b2e1f60df69..b5655173944 100644 --- a/seed/fastapi/examples/resources/types/types/test.py +++ b/seed/fastapi/examples/resources/types/types/test.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +from ....core.pydantic_utilities import UniversalRootModel import typing - -import pydantic import typing_extensions - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel, UniversalRootModel, update_forward_refs +import pydantic +from ....core.pydantic_utilities import UniversalBaseModel +from ....core.pydantic_utilities import update_forward_refs T_Result = typing.TypeVar("T_Result") @@ -38,18 +38,25 @@ class Test(UniversalRootModel): factory: typing.ClassVar[_Factory] = _Factory() if IS_PYDANTIC_V2: - root: typing_extensions.Annotated[typing.Union[_Test.And, _Test.Or], pydantic.Field(discriminator="type")] + root: typing_extensions.Annotated[ + typing.Union[_Test.And, _Test.Or], pydantic.Field(discriminator="type") + ] def get_as_union(self) -> typing.Union[_Test.And, _Test.Or]: return self.root - else: - __root__: typing_extensions.Annotated[typing.Union[_Test.And, _Test.Or], pydantic.Field(discriminator="type")] + __root__: typing_extensions.Annotated[ + typing.Union[_Test.And, _Test.Or], pydantic.Field(discriminator="type") + ] def get_as_union(self) -> typing.Union[_Test.And, _Test.Or]: return self.__root__ - def visit(self, and_: typing.Callable[[bool], T_Result], or_: typing.Callable[[bool], T_Result]) -> T_Result: + def visit( + self, + and_: typing.Callable[[bool], T_Result], + or_: typing.Callable[[bool], T_Result], + ) -> T_Result: unioned_value = self.get_as_union() if unioned_value.type == "and": return and_(unioned_value.value) diff --git a/seed/fastapi/examples/resources/types/types/tree.py b/seed/fastapi/examples/resources/types/types/tree.py index 25c9102f193..3c5296117ad 100644 --- a/seed/fastapi/examples/resources/types/types/tree.py +++ b/seed/fastapi/examples/resources/types/types/tree.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ....core.pydantic_utilities import UniversalBaseModel import typing - +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel, update_forward_refs +from ....core.pydantic_utilities import update_forward_refs class Tree(UniversalBaseModel): @@ -30,7 +29,9 @@ class Tree(UniversalBaseModel): nodes: typing.Optional[typing.List[Node]] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/examples/security.py b/seed/fastapi/examples/security.py index bab014441e1..4ccabc21106 100644 --- a/seed/fastapi/examples/security.py +++ b/seed/fastapi/examples/security.py @@ -1,8 +1,8 @@ # This file was auto-generated by Fern from our API Definition. +from .core.security.bearer import BearerToken import fastapi - -from .core.security.bearer import BearerToken, HTTPBearer +from .core.security.bearer import HTTPBearer ApiAuth = BearerToken diff --git a/seed/fastapi/examples/service/service.py b/seed/fastapi/examples/service/service.py index 5a0f02fc4d2..d74792a23f6 100644 --- a/seed/fastapi/examples/service/service.py +++ b/seed/fastapi/examples/service/service.py @@ -1,15 +1,13 @@ # This file was auto-generated by Fern from our API Definition. +from ..core.abstract_fern_service import AbstractFernService import abc -import functools +import fastapi import inspect -import logging import typing - -import fastapi - -from ..core.abstract_fern_service import AbstractFernService from ..core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools from ..core.route_args import get_route_args @@ -23,8 +21,7 @@ class AbstractRootService(AbstractFernService): """ @abc.abstractmethod - def echo(self, *, body: str) -> str: - ... + def echo(self, *, body: str) -> str: ... """ Below are internal methods used by Fern to register your implementation. @@ -39,14 +36,20 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_echo(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.echo) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) else: new_parameters.append(parameter) - setattr(cls.echo, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.echo, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.echo) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> str: diff --git a/seed/fastapi/examples/types/basic_type.py b/seed/fastapi/examples/types/basic_type.py index 139f5bd3263..fd451272682 100644 --- a/seed/fastapi/examples/types/basic_type.py +++ b/seed/fastapi/examples/types/basic_type.py @@ -10,7 +10,11 @@ class BasicType(str, enum.Enum): PRIMITIVE = "primitive" LITERAL = "literal" - def visit(self, primitive: typing.Callable[[], T_Result], literal: typing.Callable[[], T_Result]) -> T_Result: + def visit( + self, + primitive: typing.Callable[[], T_Result], + literal: typing.Callable[[], T_Result], + ) -> T_Result: if self is BasicType.PRIMITIVE: return primitive() if self is BasicType.LITERAL: diff --git a/seed/fastapi/examples/types/identifier.py b/seed/fastapi/examples/types/identifier.py index 8020aa09f26..50df5eb723f 100644 --- a/seed/fastapi/examples/types/identifier.py +++ b/seed/fastapi/examples/types/identifier.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. +from ..core.pydantic_utilities import UniversalBaseModel +from .type import Type +from ..core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .type import Type - class Identifier(UniversalBaseModel): type: Type @@ -14,7 +13,9 @@ class Identifier(UniversalBaseModel): label: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/examples/types/type.py b/seed/fastapi/examples/types/type.py index 09d1c916dfd..e77e5e18b15 100644 --- a/seed/fastapi/examples/types/type.py +++ b/seed/fastapi/examples/types/type.py @@ -1,7 +1,6 @@ # This file was auto-generated by Fern from our API Definition. import typing - from .basic_type import BasicType from .complex_type import ComplexType diff --git a/seed/fastapi/exhaustive/no-custom-config/__init__.py b/seed/fastapi/exhaustive/no-custom-config/__init__.py index 2679cde4830..6eda4b194c2 100644 --- a/seed/fastapi/exhaustive/no-custom-config/__init__.py +++ b/seed/fastapi/exhaustive/no-custom-config/__init__.py @@ -1,6 +1,13 @@ # This file was auto-generated by Fern from our API Definition. -from .resources import BadObjectRequestInfo, BadRequestBody, PostWithObjectBody, general_errors, inlined_requests, types +from .resources import ( + BadObjectRequestInfo, + BadRequestBody, + PostWithObjectBody, + general_errors, + inlined_requests, + types, +) from .security import ApiAuth __all__ = [ diff --git a/seed/fastapi/exhaustive/no-custom-config/core/abstract_fern_service.py b/seed/fastapi/exhaustive/no-custom-config/core/abstract_fern_service.py index da7c8dc49c4..9966b4876da 100644 --- a/seed/fastapi/exhaustive/no-custom-config/core/abstract_fern_service.py +++ b/seed/fastapi/exhaustive/no-custom-config/core/abstract_fern_service.py @@ -7,5 +7,4 @@ class AbstractFernService(abc.ABC): @classmethod - def _init_fern(cls, router: fastapi.APIRouter) -> None: - ... + def _init_fern(cls, router: fastapi.APIRouter) -> None: ... diff --git a/seed/fastapi/exhaustive/no-custom-config/core/datetime_utils.py b/seed/fastapi/exhaustive/no-custom-config/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/fastapi/exhaustive/no-custom-config/core/datetime_utils.py +++ b/seed/fastapi/exhaustive/no-custom-config/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/fastapi/exhaustive/no-custom-config/core/exceptions/__init__.py b/seed/fastapi/exhaustive/no-custom-config/core/exceptions/__init__.py index 297d6e06f5f..dae4b8980c1 100644 --- a/seed/fastapi/exhaustive/no-custom-config/core/exceptions/__init__.py +++ b/seed/fastapi/exhaustive/no-custom-config/core/exceptions/__init__.py @@ -1,7 +1,11 @@ # This file was auto-generated by Fern from our API Definition. from .fern_http_exception import FernHTTPException -from .handlers import default_exception_handler, fern_http_exception_handler, http_exception_handler +from .handlers import ( + default_exception_handler, + fern_http_exception_handler, + http_exception_handler, +) from .unauthorized import UnauthorizedException __all__ = [ diff --git a/seed/fastapi/exhaustive/no-custom-config/core/exceptions/fern_http_exception.py b/seed/fastapi/exhaustive/no-custom-config/core/exceptions/fern_http_exception.py index bdf03862487..81610359a7f 100644 --- a/seed/fastapi/exhaustive/no-custom-config/core/exceptions/fern_http_exception.py +++ b/seed/fastapi/exhaustive/no-custom-config/core/exceptions/fern_http_exception.py @@ -1,14 +1,16 @@ # This file was auto-generated by Fern from our API Definition. import abc -import typing - import fastapi +import typing class FernHTTPException(abc.ABC, fastapi.HTTPException): def __init__( - self, status_code: int, name: typing.Optional[str] = None, content: typing.Optional[typing.Any] = None + self, + status_code: int, + name: typing.Optional[str] = None, + content: typing.Optional[typing.Any] = None, ): super().__init__(status_code=status_code) self.name = name @@ -17,4 +19,6 @@ def __init__( def to_json_response(self) -> fastapi.responses.JSONResponse: content = fastapi.encoders.jsonable_encoder(self.content, exclude_none=True) - return fastapi.responses.JSONResponse(content=content, status_code=self.status_code) + return fastapi.responses.JSONResponse( + content=content, status_code=self.status_code + ) diff --git a/seed/fastapi/exhaustive/no-custom-config/core/exceptions/handlers.py b/seed/fastapi/exhaustive/no-custom-config/core/exceptions/handlers.py index 6d8c4155c5a..ae1c2741f06 100644 --- a/seed/fastapi/exhaustive/no-custom-config/core/exceptions/handlers.py +++ b/seed/fastapi/exhaustive/no-custom-config/core/exceptions/handlers.py @@ -2,32 +2,49 @@ import logging -import fastapi import starlette import starlette.exceptions +import fastapi + from .fern_http_exception import FernHTTPException def fern_http_exception_handler( - request: fastapi.requests.Request, exc: FernHTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: FernHTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) return exc.to_json_response() def http_exception_handler( - request: fastapi.requests.Request, exc: starlette.exceptions.HTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: starlette.exceptions.HTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=exc.status_code, content=exc.detail).to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=exc.status_code, content=exc.detail + ).to_json_response() def default_exception_handler( - request: fastapi.requests.Request, exc: Exception, skip_log: bool = False + request: fastapi.requests.Request, + exc: Exception, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=500, content="Internal Server Error").to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=500, content="Internal Server Error" + ).to_json_response() diff --git a/seed/fastapi/exhaustive/no-custom-config/core/pydantic_utilities.py b/seed/fastapi/exhaustive/no-custom-config/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/fastapi/exhaustive/no-custom-config/core/pydantic_utilities.py +++ b/seed/fastapi/exhaustive/no-custom-config/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/fastapi/exhaustive/no-custom-config/core/route_args.py b/seed/fastapi/exhaustive/no-custom-config/core/route_args.py index 4228e2fe05d..bd940bf4ddd 100644 --- a/seed/fastapi/exhaustive/no-custom-config/core/route_args.py +++ b/seed/fastapi/exhaustive/no-custom-config/core/route_args.py @@ -20,9 +20,15 @@ class RouteArgs(typing_extensions.TypedDict): DEFAULT_ROUTE_ARGS = RouteArgs(openapi_extra=None, tags=None, include_in_schema=True) -def get_route_args(endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str) -> RouteArgs: - unwrapped = inspect.unwrap(endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY))) - route_args = typing.cast(RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS)) +def get_route_args( + endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str +) -> RouteArgs: + unwrapped = inspect.unwrap( + endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY)) + ) + route_args = typing.cast( + RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS) + ) if route_args["tags"] is None: return RouteArgs( openapi_extra=route_args["openapi_extra"], @@ -56,7 +62,11 @@ def decorator(endpoint_function: T) -> T: setattr( endpoint_function, FERN_CONFIG_KEY, - RouteArgs(openapi_extra=openapi_extra, tags=tags, include_in_schema=include_in_schema), + RouteArgs( + openapi_extra=openapi_extra, + tags=tags, + include_in_schema=include_in_schema, + ), ) return endpoint_function diff --git a/seed/fastapi/exhaustive/no-custom-config/register.py b/seed/fastapi/exhaustive/no-custom-config/register.py index be0c42bf3f9..1f804567f73 100644 --- a/seed/fastapi/exhaustive/no-custom-config/register.py +++ b/seed/fastapi/exhaustive/no-custom-config/register.py @@ -1,29 +1,43 @@ # This file was auto-generated by Fern from our API Definition. -import glob -import importlib -import os -import types -import typing - import fastapi -import starlette.exceptions -from fastapi import params - -from .core.abstract_fern_service import AbstractFernService -from .core.exceptions import default_exception_handler, fern_http_exception_handler, http_exception_handler -from .core.exceptions.fern_http_exception import FernHTTPException -from .resources.endpoints.resources.container.service.service import AbstractEndpointsContainerService -from .resources.endpoints.resources.enum.service.service import AbstractEndpointsEnumService -from .resources.endpoints.resources.http_methods.service.service import AbstractEndpointsHttpMethodsService -from .resources.endpoints.resources.object.service.service import AbstractEndpointsObjectService -from .resources.endpoints.resources.params.service.service import AbstractEndpointsParamsService -from .resources.endpoints.resources.primitive.service.service import AbstractEndpointsPrimitiveService -from .resources.endpoints.resources.union.service.service import AbstractEndpointsUnionService +from .resources.endpoints.resources.container.service.service import ( + AbstractEndpointsContainerService, +) +from .resources.endpoints.resources.enum.service.service import ( + AbstractEndpointsEnumService, +) +from .resources.endpoints.resources.http_methods.service.service import ( + AbstractEndpointsHttpMethodsService, +) +from .resources.endpoints.resources.object.service.service import ( + AbstractEndpointsObjectService, +) +from .resources.endpoints.resources.params.service.service import ( + AbstractEndpointsParamsService, +) +from .resources.endpoints.resources.primitive.service.service import ( + AbstractEndpointsPrimitiveService, +) +from .resources.endpoints.resources.union.service.service import ( + AbstractEndpointsUnionService, +) from .resources.inlined_requests.service.service import AbstractInlinedRequestsService from .resources.no_auth.service.service import AbstractNoAuthService from .resources.no_req_body.service.service import AbstractNoReqBodyService from .resources.req_with_headers.service.service import AbstractReqWithHeadersService +import typing +from fastapi import params +from .core.exceptions.fern_http_exception import FernHTTPException +from .core.exceptions import fern_http_exception_handler +import starlette.exceptions +from .core.exceptions import http_exception_handler +from .core.exceptions import default_exception_handler +from .core.abstract_fern_service import AbstractFernService +import types +import os +import glob +import importlib def register( @@ -40,14 +54,20 @@ def register( no_auth: AbstractNoAuthService, no_req_body: AbstractNoReqBodyService, req_with_headers: AbstractReqWithHeadersService, - dependencies: typing.Optional[typing.Sequence[params.Depends]] = None + dependencies: typing.Optional[typing.Sequence[params.Depends]] = None, ) -> None: - _app.include_router(__register_service(endpoints_container), dependencies=dependencies) + _app.include_router( + __register_service(endpoints_container), dependencies=dependencies + ) _app.include_router(__register_service(endpoints_enum), dependencies=dependencies) - _app.include_router(__register_service(endpoints_http_methods), dependencies=dependencies) + _app.include_router( + __register_service(endpoints_http_methods), dependencies=dependencies + ) _app.include_router(__register_service(endpoints_object), dependencies=dependencies) _app.include_router(__register_service(endpoints_params), dependencies=dependencies) - _app.include_router(__register_service(endpoints_primitive), dependencies=dependencies) + _app.include_router( + __register_service(endpoints_primitive), dependencies=dependencies + ) _app.include_router(__register_service(endpoints_union), dependencies=dependencies) _app.include_router(__register_service(inlined_requests), dependencies=dependencies) _app.include_router(__register_service(no_auth), dependencies=dependencies) @@ -55,7 +75,9 @@ def register( _app.include_router(__register_service(req_with_headers), dependencies=dependencies) _app.add_exception_handler(FernHTTPException, fern_http_exception_handler) # type: ignore - _app.add_exception_handler(starlette.exceptions.HTTPException, http_exception_handler) # type: ignore + _app.add_exception_handler( + starlette.exceptions.HTTPException, http_exception_handler + ) # type: ignore _app.add_exception_handler(Exception, default_exception_handler) # type: ignore @@ -67,7 +89,9 @@ def __register_service(service: AbstractFernService) -> fastapi.APIRouter: def register_validators(module: types.ModuleType) -> None: validators_directory: str = os.path.dirname(module.__file__) # type: ignore - for path in glob.glob(os.path.join(validators_directory, "**/*.py"), recursive=True): + for path in glob.glob( + os.path.join(validators_directory, "**/*.py"), recursive=True + ): if os.path.isfile(path): relative_path = os.path.relpath(path, start=validators_directory) module_path = ".".join([module.__name__] + relative_path[:-3].split("/")) diff --git a/seed/fastapi/exhaustive/no-custom-config/resources/endpoints/resources/container/service/service.py b/seed/fastapi/exhaustive/no-custom-config/resources/endpoints/resources/container/service/service.py index af2cbf4be28..79da48ea0cc 100644 --- a/seed/fastapi/exhaustive/no-custom-config/resources/endpoints/resources/container/service/service.py +++ b/seed/fastapi/exhaustive/no-custom-config/resources/endpoints/resources/container/service/service.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. -import abc -import functools -import inspect -import logging +from ......core.abstract_fern_service import AbstractFernService import typing - +from ......security import ApiAuth +import abc +from .....types.resources.object.types.object_with_required_field import ( + ObjectWithRequiredField, +) import fastapi - -from ......core.abstract_fern_service import AbstractFernService +import inspect +from ......security import FernAuth from ......core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools from ......core.route_args import get_route_args -from ......security import ApiAuth, FernAuth -from .....types.resources.object.types.object_with_required_field import ObjectWithRequiredField class AbstractEndpointsContainerService(AbstractFernService): @@ -25,40 +26,39 @@ class AbstractEndpointsContainerService(AbstractFernService): """ @abc.abstractmethod - def get_and_return_list_of_primitives(self, *, body: typing.List[str], auth: ApiAuth) -> typing.Sequence[str]: - ... + def get_and_return_list_of_primitives( + self, *, body: typing.List[str], auth: ApiAuth + ) -> typing.Sequence[str]: ... @abc.abstractmethod def get_and_return_list_of_objects( self, *, body: typing.List[ObjectWithRequiredField], auth: ApiAuth - ) -> typing.Sequence[ObjectWithRequiredField]: - ... + ) -> typing.Sequence[ObjectWithRequiredField]: ... @abc.abstractmethod - def get_and_return_set_of_primitives(self, *, body: typing.Set[str], auth: ApiAuth) -> typing.Set[str]: - ... + def get_and_return_set_of_primitives( + self, *, body: typing.Set[str], auth: ApiAuth + ) -> typing.Set[str]: ... @abc.abstractmethod def get_and_return_set_of_objects( self, *, body: typing.List[ObjectWithRequiredField], auth: ApiAuth - ) -> typing.Sequence[ObjectWithRequiredField]: - ... + ) -> typing.Sequence[ObjectWithRequiredField]: ... @abc.abstractmethod - def get_and_return_map_prim_to_prim(self, *, body: typing.Dict[str, str], auth: ApiAuth) -> typing.Dict[str, str]: - ... + def get_and_return_map_prim_to_prim( + self, *, body: typing.Dict[str, str], auth: ApiAuth + ) -> typing.Dict[str, str]: ... @abc.abstractmethod def get_and_return_map_of_prim_to_object( self, *, body: typing.Dict[str, ObjectWithRequiredField], auth: ApiAuth - ) -> typing.Dict[str, ObjectWithRequiredField]: - ... + ) -> typing.Dict[str, ObjectWithRequiredField]: ... @abc.abstractmethod def get_and_return_optional( self, *, body: typing.Optional[ObjectWithRequiredField] = None, auth: ApiAuth - ) -> typing.Optional[ObjectWithRequiredField]: - ... + ) -> typing.Optional[ObjectWithRequiredField]: ... """ Below are internal methods used by Fern to register your implementation. @@ -76,20 +76,28 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: cls.__init_get_and_return_optional(router=router) @classmethod - def __init_get_and_return_list_of_primitives(cls, router: fastapi.APIRouter) -> None: + def __init_get_and_return_list_of_primitives( + cls, router: fastapi.APIRouter + ) -> None: endpoint_function = inspect.signature(cls.get_and_return_list_of_primitives) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) setattr( - cls.get_and_return_list_of_primitives, "__signature__", endpoint_function.replace(parameters=new_parameters) + cls.get_and_return_list_of_primitives, + "__signature__", + endpoint_function.replace(parameters=new_parameters), ) @functools.wraps(cls.get_and_return_list_of_primitives) @@ -112,28 +120,38 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> typing.Sequence[str]: path="/container/list-of-primitives", response_model=typing.Sequence[str], description=AbstractEndpointsContainerService.get_and_return_list_of_primitives.__doc__, - **get_route_args(cls.get_and_return_list_of_primitives, default_tag="endpoints.container"), + **get_route_args( + cls.get_and_return_list_of_primitives, default_tag="endpoints.container" + ), )(wrapper) @classmethod def __init_get_and_return_list_of_objects(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_and_return_list_of_objects) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) setattr( - cls.get_and_return_list_of_objects, "__signature__", endpoint_function.replace(parameters=new_parameters) + cls.get_and_return_list_of_objects, + "__signature__", + endpoint_function.replace(parameters=new_parameters), ) @functools.wraps(cls.get_and_return_list_of_objects) - def wrapper(*args: typing.Any, **kwargs: typing.Any) -> typing.Sequence[ObjectWithRequiredField]: + def wrapper( + *args: typing.Any, **kwargs: typing.Any + ) -> typing.Sequence[ObjectWithRequiredField]: try: return cls.get_and_return_list_of_objects(*args, **kwargs) except FernHTTPException as e: @@ -152,24 +170,32 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> typing.Sequence[ObjectWi path="/container/list-of-objects", response_model=typing.Sequence[ObjectWithRequiredField], description=AbstractEndpointsContainerService.get_and_return_list_of_objects.__doc__, - **get_route_args(cls.get_and_return_list_of_objects, default_tag="endpoints.container"), + **get_route_args( + cls.get_and_return_list_of_objects, default_tag="endpoints.container" + ), )(wrapper) @classmethod def __init_get_and_return_set_of_primitives(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_and_return_set_of_primitives) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) setattr( - cls.get_and_return_set_of_primitives, "__signature__", endpoint_function.replace(parameters=new_parameters) + cls.get_and_return_set_of_primitives, + "__signature__", + endpoint_function.replace(parameters=new_parameters), ) @functools.wraps(cls.get_and_return_set_of_primitives) @@ -192,28 +218,38 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> typing.Set[str]: path="/container/set-of-primitives", response_model=typing.Set[str], description=AbstractEndpointsContainerService.get_and_return_set_of_primitives.__doc__, - **get_route_args(cls.get_and_return_set_of_primitives, default_tag="endpoints.container"), + **get_route_args( + cls.get_and_return_set_of_primitives, default_tag="endpoints.container" + ), )(wrapper) @classmethod def __init_get_and_return_set_of_objects(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_and_return_set_of_objects) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) setattr( - cls.get_and_return_set_of_objects, "__signature__", endpoint_function.replace(parameters=new_parameters) + cls.get_and_return_set_of_objects, + "__signature__", + endpoint_function.replace(parameters=new_parameters), ) @functools.wraps(cls.get_and_return_set_of_objects) - def wrapper(*args: typing.Any, **kwargs: typing.Any) -> typing.Sequence[ObjectWithRequiredField]: + def wrapper( + *args: typing.Any, **kwargs: typing.Any + ) -> typing.Sequence[ObjectWithRequiredField]: try: return cls.get_and_return_set_of_objects(*args, **kwargs) except FernHTTPException as e: @@ -232,24 +268,32 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> typing.Sequence[ObjectWi path="/container/set-of-objects", response_model=typing.Sequence[ObjectWithRequiredField], description=AbstractEndpointsContainerService.get_and_return_set_of_objects.__doc__, - **get_route_args(cls.get_and_return_set_of_objects, default_tag="endpoints.container"), + **get_route_args( + cls.get_and_return_set_of_objects, default_tag="endpoints.container" + ), )(wrapper) @classmethod def __init_get_and_return_map_prim_to_prim(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_and_return_map_prim_to_prim) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) setattr( - cls.get_and_return_map_prim_to_prim, "__signature__", endpoint_function.replace(parameters=new_parameters) + cls.get_and_return_map_prim_to_prim, + "__signature__", + endpoint_function.replace(parameters=new_parameters), ) @functools.wraps(cls.get_and_return_map_prim_to_prim) @@ -272,20 +316,28 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> typing.Dict[str, str]: path="/container/map-prim-to-prim", response_model=typing.Dict[str, str], description=AbstractEndpointsContainerService.get_and_return_map_prim_to_prim.__doc__, - **get_route_args(cls.get_and_return_map_prim_to_prim, default_tag="endpoints.container"), + **get_route_args( + cls.get_and_return_map_prim_to_prim, default_tag="endpoints.container" + ), )(wrapper) @classmethod - def __init_get_and_return_map_of_prim_to_object(cls, router: fastapi.APIRouter) -> None: + def __init_get_and_return_map_of_prim_to_object( + cls, router: fastapi.APIRouter + ) -> None: endpoint_function = inspect.signature(cls.get_and_return_map_of_prim_to_object) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) setattr( @@ -295,7 +347,9 @@ def __init_get_and_return_map_of_prim_to_object(cls, router: fastapi.APIRouter) ) @functools.wraps(cls.get_and_return_map_of_prim_to_object) - def wrapper(*args: typing.Any, **kwargs: typing.Any) -> typing.Dict[str, ObjectWithRequiredField]: + def wrapper( + *args: typing.Any, **kwargs: typing.Any + ) -> typing.Dict[str, ObjectWithRequiredField]: try: return cls.get_and_return_map_of_prim_to_object(*args, **kwargs) except FernHTTPException as e: @@ -314,26 +368,39 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> typing.Dict[str, ObjectW path="/container/map-prim-to-object", response_model=typing.Dict[str, ObjectWithRequiredField], description=AbstractEndpointsContainerService.get_and_return_map_of_prim_to_object.__doc__, - **get_route_args(cls.get_and_return_map_of_prim_to_object, default_tag="endpoints.container"), + **get_route_args( + cls.get_and_return_map_of_prim_to_object, + default_tag="endpoints.container", + ), )(wrapper) @classmethod def __init_get_and_return_optional(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_and_return_optional) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_and_return_optional, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_and_return_optional, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_and_return_optional) - def wrapper(*args: typing.Any, **kwargs: typing.Any) -> typing.Optional[ObjectWithRequiredField]: + def wrapper( + *args: typing.Any, **kwargs: typing.Any + ) -> typing.Optional[ObjectWithRequiredField]: try: return cls.get_and_return_optional(*args, **kwargs) except FernHTTPException as e: @@ -352,5 +419,7 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> typing.Optional[ObjectWi path="/container/opt-objects", response_model=typing.Optional[ObjectWithRequiredField], description=AbstractEndpointsContainerService.get_and_return_optional.__doc__, - **get_route_args(cls.get_and_return_optional, default_tag="endpoints.container"), + **get_route_args( + cls.get_and_return_optional, default_tag="endpoints.container" + ), )(wrapper) diff --git a/seed/fastapi/exhaustive/no-custom-config/resources/endpoints/resources/enum/service/service.py b/seed/fastapi/exhaustive/no-custom-config/resources/endpoints/resources/enum/service/service.py index a279991058b..4c665920e0b 100644 --- a/seed/fastapi/exhaustive/no-custom-config/resources/endpoints/resources/enum/service/service.py +++ b/seed/fastapi/exhaustive/no-custom-config/resources/endpoints/resources/enum/service/service.py @@ -1,18 +1,17 @@ # This file was auto-generated by Fern from our API Definition. +from ......core.abstract_fern_service import AbstractFernService +from .....types.resources.enum.types.weather_report import WeatherReport +from ......security import ApiAuth import abc -import functools +import fastapi import inspect -import logging import typing - -import fastapi - -from ......core.abstract_fern_service import AbstractFernService +from ......security import FernAuth from ......core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools from ......core.route_args import get_route_args -from ......security import ApiAuth, FernAuth -from .....types.resources.enum.types.weather_report import WeatherReport class AbstractEndpointsEnumService(AbstractFernService): @@ -25,8 +24,9 @@ class AbstractEndpointsEnumService(AbstractFernService): """ @abc.abstractmethod - def get_and_return_enum(self, *, body: WeatherReport, auth: ApiAuth) -> WeatherReport: - ... + def get_and_return_enum( + self, *, body: WeatherReport, auth: ApiAuth + ) -> WeatherReport: ... """ Below are internal methods used by Fern to register your implementation. @@ -41,16 +41,24 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_get_and_return_enum(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_and_return_enum) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_and_return_enum, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_and_return_enum, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_and_return_enum) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> WeatherReport: diff --git a/seed/fastapi/exhaustive/no-custom-config/resources/endpoints/resources/http_methods/service/service.py b/seed/fastapi/exhaustive/no-custom-config/resources/endpoints/resources/http_methods/service/service.py index 4ec18085f84..73b65270c55 100644 --- a/seed/fastapi/exhaustive/no-custom-config/resources/endpoints/resources/http_methods/service/service.py +++ b/seed/fastapi/exhaustive/no-custom-config/resources/endpoints/resources/http_methods/service/service.py @@ -1,19 +1,22 @@ # This file was auto-generated by Fern from our API Definition. +from ......core.abstract_fern_service import AbstractFernService +from ......security import ApiAuth import abc -import functools +from .....types.resources.object.types.object_with_required_field import ( + ObjectWithRequiredField, +) +from .....types.resources.object.types.object_with_optional_field import ( + ObjectWithOptionalField, +) +import fastapi import inspect -import logging import typing - -import fastapi - -from ......core.abstract_fern_service import AbstractFernService +from ......security import FernAuth from ......core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools from ......core.route_args import get_route_args -from ......security import ApiAuth, FernAuth -from .....types.resources.object.types.object_with_optional_field import ObjectWithOptionalField -from .....types.resources.object.types.object_with_required_field import ObjectWithRequiredField class AbstractEndpointsHttpMethodsService(AbstractFernService): @@ -26,24 +29,25 @@ class AbstractEndpointsHttpMethodsService(AbstractFernService): """ @abc.abstractmethod - def test_get(self, *, id: str, auth: ApiAuth) -> str: - ... + def test_get(self, *, id: str, auth: ApiAuth) -> str: ... @abc.abstractmethod - def test_post(self, *, body: ObjectWithRequiredField, auth: ApiAuth) -> ObjectWithOptionalField: - ... + def test_post( + self, *, body: ObjectWithRequiredField, auth: ApiAuth + ) -> ObjectWithOptionalField: ... @abc.abstractmethod - def test_put(self, *, body: ObjectWithRequiredField, id: str, auth: ApiAuth) -> ObjectWithOptionalField: - ... + def test_put( + self, *, body: ObjectWithRequiredField, id: str, auth: ApiAuth + ) -> ObjectWithOptionalField: ... @abc.abstractmethod - def test_patch(self, *, body: ObjectWithOptionalField, id: str, auth: ApiAuth) -> ObjectWithOptionalField: - ... + def test_patch( + self, *, body: ObjectWithOptionalField, id: str, auth: ApiAuth + ) -> ObjectWithOptionalField: ... @abc.abstractmethod - def test_delete(self, *, id: str, auth: ApiAuth) -> bool: - ... + def test_delete(self, *, id: str, auth: ApiAuth) -> bool: ... """ Below are internal methods used by Fern to register your implementation. @@ -62,16 +66,24 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_test_get(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.test_get) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "id": new_parameters.append(parameter.replace(default=fastapi.Path(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.test_get, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.test_get, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.test_get) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> str: @@ -100,16 +112,24 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> str: def __init_test_post(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.test_post) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.test_post, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.test_post, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.test_post) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> ObjectWithOptionalField: @@ -138,7 +158,9 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> ObjectWithOptionalField: def __init_test_put(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.test_put) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": @@ -146,10 +168,16 @@ def __init_test_put(cls, router: fastapi.APIRouter) -> None: elif parameter_name == "id": new_parameters.append(parameter.replace(default=fastapi.Path(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.test_put, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.test_put, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.test_put) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> ObjectWithOptionalField: @@ -178,7 +206,9 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> ObjectWithOptionalField: def __init_test_patch(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.test_patch) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": @@ -186,10 +216,16 @@ def __init_test_patch(cls, router: fastapi.APIRouter) -> None: elif parameter_name == "id": new_parameters.append(parameter.replace(default=fastapi.Path(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.test_patch, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.test_patch, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.test_patch) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> ObjectWithOptionalField: @@ -218,16 +254,24 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> ObjectWithOptionalField: def __init_test_delete(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.test_delete) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "id": new_parameters.append(parameter.replace(default=fastapi.Path(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.test_delete, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.test_delete, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.test_delete) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> bool: diff --git a/seed/fastapi/exhaustive/no-custom-config/resources/endpoints/resources/object/service/service.py b/seed/fastapi/exhaustive/no-custom-config/resources/endpoints/resources/object/service/service.py index b3f2bc65b51..8b73109a788 100644 --- a/seed/fastapi/exhaustive/no-custom-config/resources/endpoints/resources/object/service/service.py +++ b/seed/fastapi/exhaustive/no-custom-config/resources/endpoints/resources/object/service/service.py @@ -1,22 +1,29 @@ # This file was auto-generated by Fern from our API Definition. +from ......core.abstract_fern_service import AbstractFernService +from .....types.resources.object.types.object_with_optional_field import ( + ObjectWithOptionalField, +) +from ......security import ApiAuth import abc -import functools -import inspect -import logging +from .....types.resources.object.types.object_with_required_field import ( + ObjectWithRequiredField, +) +from .....types.resources.object.types.object_with_map_of_map import ObjectWithMapOfMap +from .....types.resources.object.types.nested_object_with_optional_field import ( + NestedObjectWithOptionalField, +) +from .....types.resources.object.types.nested_object_with_required_field import ( + NestedObjectWithRequiredField, +) import typing - import fastapi - -from ......core.abstract_fern_service import AbstractFernService +import inspect +from ......security import FernAuth from ......core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools from ......core.route_args import get_route_args -from ......security import ApiAuth, FernAuth -from .....types.resources.object.types.nested_object_with_optional_field import NestedObjectWithOptionalField -from .....types.resources.object.types.nested_object_with_required_field import NestedObjectWithRequiredField -from .....types.resources.object.types.object_with_map_of_map import ObjectWithMapOfMap -from .....types.resources.object.types.object_with_optional_field import ObjectWithOptionalField -from .....types.resources.object.types.object_with_required_field import ObjectWithRequiredField class AbstractEndpointsObjectService(AbstractFernService): @@ -31,36 +38,32 @@ class AbstractEndpointsObjectService(AbstractFernService): @abc.abstractmethod def get_and_return_with_optional_field( self, *, body: ObjectWithOptionalField, auth: ApiAuth - ) -> ObjectWithOptionalField: - ... + ) -> ObjectWithOptionalField: ... @abc.abstractmethod def get_and_return_with_required_field( self, *, body: ObjectWithRequiredField, auth: ApiAuth - ) -> ObjectWithRequiredField: - ... + ) -> ObjectWithRequiredField: ... @abc.abstractmethod - def get_and_return_with_map_of_map(self, *, body: ObjectWithMapOfMap, auth: ApiAuth) -> ObjectWithMapOfMap: - ... + def get_and_return_with_map_of_map( + self, *, body: ObjectWithMapOfMap, auth: ApiAuth + ) -> ObjectWithMapOfMap: ... @abc.abstractmethod def get_and_return_nested_with_optional_field( self, *, body: NestedObjectWithOptionalField, auth: ApiAuth - ) -> NestedObjectWithOptionalField: - ... + ) -> NestedObjectWithOptionalField: ... @abc.abstractmethod def get_and_return_nested_with_required_field( self, *, body: NestedObjectWithRequiredField, string: str, auth: ApiAuth - ) -> NestedObjectWithRequiredField: - ... + ) -> NestedObjectWithRequiredField: ... @abc.abstractmethod def get_and_return_nested_with_required_field_as_list( self, *, body: typing.List[NestedObjectWithRequiredField], auth: ApiAuth - ) -> NestedObjectWithRequiredField: - ... + ) -> NestedObjectWithRequiredField: ... """ Below are internal methods used by Fern to register your implementation. @@ -77,16 +80,22 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: cls.__init_get_and_return_nested_with_required_field_as_list(router=router) @classmethod - def __init_get_and_return_with_optional_field(cls, router: fastapi.APIRouter) -> None: + def __init_get_and_return_with_optional_field( + cls, router: fastapi.APIRouter + ) -> None: endpoint_function = inspect.signature(cls.get_and_return_with_optional_field) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) setattr( @@ -115,20 +124,28 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> ObjectWithOptionalField: path="/object/get-and-return-with-optional-field", response_model=ObjectWithOptionalField, description=AbstractEndpointsObjectService.get_and_return_with_optional_field.__doc__, - **get_route_args(cls.get_and_return_with_optional_field, default_tag="endpoints.object"), + **get_route_args( + cls.get_and_return_with_optional_field, default_tag="endpoints.object" + ), )(wrapper) @classmethod - def __init_get_and_return_with_required_field(cls, router: fastapi.APIRouter) -> None: + def __init_get_and_return_with_required_field( + cls, router: fastapi.APIRouter + ) -> None: endpoint_function = inspect.signature(cls.get_and_return_with_required_field) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) setattr( @@ -157,24 +174,32 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> ObjectWithRequiredField: path="/object/get-and-return-with-required-field", response_model=ObjectWithRequiredField, description=AbstractEndpointsObjectService.get_and_return_with_required_field.__doc__, - **get_route_args(cls.get_and_return_with_required_field, default_tag="endpoints.object"), + **get_route_args( + cls.get_and_return_with_required_field, default_tag="endpoints.object" + ), )(wrapper) @classmethod def __init_get_and_return_with_map_of_map(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_and_return_with_map_of_map) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) setattr( - cls.get_and_return_with_map_of_map, "__signature__", endpoint_function.replace(parameters=new_parameters) + cls.get_and_return_with_map_of_map, + "__signature__", + endpoint_function.replace(parameters=new_parameters), ) @functools.wraps(cls.get_and_return_with_map_of_map) @@ -197,20 +222,30 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> ObjectWithMapOfMap: path="/object/get-and-return-with-map-of-map", response_model=ObjectWithMapOfMap, description=AbstractEndpointsObjectService.get_and_return_with_map_of_map.__doc__, - **get_route_args(cls.get_and_return_with_map_of_map, default_tag="endpoints.object"), + **get_route_args( + cls.get_and_return_with_map_of_map, default_tag="endpoints.object" + ), )(wrapper) @classmethod - def __init_get_and_return_nested_with_optional_field(cls, router: fastapi.APIRouter) -> None: - endpoint_function = inspect.signature(cls.get_and_return_nested_with_optional_field) + def __init_get_and_return_nested_with_optional_field( + cls, router: fastapi.APIRouter + ) -> None: + endpoint_function = inspect.signature( + cls.get_and_return_nested_with_optional_field + ) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) setattr( @@ -220,7 +255,9 @@ def __init_get_and_return_nested_with_optional_field(cls, router: fastapi.APIRou ) @functools.wraps(cls.get_and_return_nested_with_optional_field) - def wrapper(*args: typing.Any, **kwargs: typing.Any) -> NestedObjectWithOptionalField: + def wrapper( + *args: typing.Any, **kwargs: typing.Any + ) -> NestedObjectWithOptionalField: try: return cls.get_and_return_nested_with_optional_field(*args, **kwargs) except FernHTTPException as e: @@ -233,20 +270,31 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> NestedObjectWithOptional # this is necessary for FastAPI to find forward-ref'ed type hints. # https://github.com/tiangolo/fastapi/pull/5077 - wrapper.__globals__.update(cls.get_and_return_nested_with_optional_field.__globals__) + wrapper.__globals__.update( + cls.get_and_return_nested_with_optional_field.__globals__ + ) router.post( path="/object/get-and-return-nested-with-optional-field", response_model=NestedObjectWithOptionalField, description=AbstractEndpointsObjectService.get_and_return_nested_with_optional_field.__doc__, - **get_route_args(cls.get_and_return_nested_with_optional_field, default_tag="endpoints.object"), + **get_route_args( + cls.get_and_return_nested_with_optional_field, + default_tag="endpoints.object", + ), )(wrapper) @classmethod - def __init_get_and_return_nested_with_required_field(cls, router: fastapi.APIRouter) -> None: - endpoint_function = inspect.signature(cls.get_and_return_nested_with_required_field) + def __init_get_and_return_nested_with_required_field( + cls, router: fastapi.APIRouter + ) -> None: + endpoint_function = inspect.signature( + cls.get_and_return_nested_with_required_field + ) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": @@ -254,7 +302,9 @@ def __init_get_and_return_nested_with_required_field(cls, router: fastapi.APIRou elif parameter_name == "string": new_parameters.append(parameter.replace(default=fastapi.Path(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) setattr( @@ -264,7 +314,9 @@ def __init_get_and_return_nested_with_required_field(cls, router: fastapi.APIRou ) @functools.wraps(cls.get_and_return_nested_with_required_field) - def wrapper(*args: typing.Any, **kwargs: typing.Any) -> NestedObjectWithRequiredField: + def wrapper( + *args: typing.Any, **kwargs: typing.Any + ) -> NestedObjectWithRequiredField: try: return cls.get_and_return_nested_with_required_field(*args, **kwargs) except FernHTTPException as e: @@ -277,26 +329,39 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> NestedObjectWithRequired # this is necessary for FastAPI to find forward-ref'ed type hints. # https://github.com/tiangolo/fastapi/pull/5077 - wrapper.__globals__.update(cls.get_and_return_nested_with_required_field.__globals__) + wrapper.__globals__.update( + cls.get_and_return_nested_with_required_field.__globals__ + ) router.post( path="/object/get-and-return-nested-with-required-field/{string}", response_model=NestedObjectWithRequiredField, description=AbstractEndpointsObjectService.get_and_return_nested_with_required_field.__doc__, - **get_route_args(cls.get_and_return_nested_with_required_field, default_tag="endpoints.object"), + **get_route_args( + cls.get_and_return_nested_with_required_field, + default_tag="endpoints.object", + ), )(wrapper) @classmethod - def __init_get_and_return_nested_with_required_field_as_list(cls, router: fastapi.APIRouter) -> None: - endpoint_function = inspect.signature(cls.get_and_return_nested_with_required_field_as_list) + def __init_get_and_return_nested_with_required_field_as_list( + cls, router: fastapi.APIRouter + ) -> None: + endpoint_function = inspect.signature( + cls.get_and_return_nested_with_required_field_as_list + ) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) setattr( @@ -306,9 +371,13 @@ def __init_get_and_return_nested_with_required_field_as_list(cls, router: fastap ) @functools.wraps(cls.get_and_return_nested_with_required_field_as_list) - def wrapper(*args: typing.Any, **kwargs: typing.Any) -> NestedObjectWithRequiredField: + def wrapper( + *args: typing.Any, **kwargs: typing.Any + ) -> NestedObjectWithRequiredField: try: - return cls.get_and_return_nested_with_required_field_as_list(*args, **kwargs) + return cls.get_and_return_nested_with_required_field_as_list( + *args, **kwargs + ) except FernHTTPException as e: logging.getLogger(f"{cls.__module__}.{cls.__name__}").warn( f"Endpoint 'get_and_return_nested_with_required_field_as_list' unexpectedly threw {e.__class__.__name__}. " @@ -319,11 +388,16 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> NestedObjectWithRequired # this is necessary for FastAPI to find forward-ref'ed type hints. # https://github.com/tiangolo/fastapi/pull/5077 - wrapper.__globals__.update(cls.get_and_return_nested_with_required_field_as_list.__globals__) + wrapper.__globals__.update( + cls.get_and_return_nested_with_required_field_as_list.__globals__ + ) router.post( path="/object/get-and-return-nested-with-required-field-list", response_model=NestedObjectWithRequiredField, description=AbstractEndpointsObjectService.get_and_return_nested_with_required_field_as_list.__doc__, - **get_route_args(cls.get_and_return_nested_with_required_field_as_list, default_tag="endpoints.object"), + **get_route_args( + cls.get_and_return_nested_with_required_field_as_list, + default_tag="endpoints.object", + ), )(wrapper) diff --git a/seed/fastapi/exhaustive/no-custom-config/resources/endpoints/resources/params/service/service.py b/seed/fastapi/exhaustive/no-custom-config/resources/endpoints/resources/params/service/service.py index a7ae7b277b2..93c809bd4e7 100644 --- a/seed/fastapi/exhaustive/no-custom-config/resources/endpoints/resources/params/service/service.py +++ b/seed/fastapi/exhaustive/no-custom-config/resources/endpoints/resources/params/service/service.py @@ -1,18 +1,17 @@ # This file was auto-generated by Fern from our API Definition. +from ......core.abstract_fern_service import AbstractFernService +from ......security import ApiAuth import abc -import functools -import inspect -import logging import typing - import fastapi -import starlette - -from ......core.abstract_fern_service import AbstractFernService +import inspect +from ......security import FernAuth from ......core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools from ......core.route_args import get_route_args -from ......security import ApiAuth, FernAuth +import starlette class AbstractEndpointsParamsService(AbstractFernService): @@ -39,7 +38,9 @@ def get_with_query(self, *, query: str, number: int, auth: ApiAuth) -> None: ... @abc.abstractmethod - def get_with_allow_multiple_query(self, *, query: typing.List[str], numer: typing.List[int], auth: ApiAuth) -> None: + def get_with_allow_multiple_query( + self, *, query: typing.List[str], numer: typing.List[int], auth: ApiAuth + ) -> None: """ GET with multiple of same query param """ @@ -76,16 +77,24 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_get_with_path(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_with_path) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "param": new_parameters.append(parameter.replace(default=fastapi.Path(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_with_path, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_with_path, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_with_path) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> str: @@ -114,18 +123,30 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> str: def __init_get_with_query(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_with_query) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "query": - new_parameters.append(parameter.replace(default=fastapi.Query(default=...))) + new_parameters.append( + parameter.replace(default=fastapi.Query(default=...)) + ) elif parameter_name == "number": - new_parameters.append(parameter.replace(default=fastapi.Query(default=...))) + new_parameters.append( + parameter.replace(default=fastapi.Query(default=...)) + ) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_with_query, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_with_query, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_with_query) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> None: @@ -155,19 +176,29 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> None: def __init_get_with_allow_multiple_query(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_with_allow_multiple_query) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "query": - new_parameters.append(parameter.replace(default=fastapi.Query(default=[]))) + new_parameters.append( + parameter.replace(default=fastapi.Query(default=[])) + ) elif parameter_name == "numer": - new_parameters.append(parameter.replace(default=fastapi.Query(default=[]))) + new_parameters.append( + parameter.replace(default=fastapi.Query(default=[])) + ) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) setattr( - cls.get_with_allow_multiple_query, "__signature__", endpoint_function.replace(parameters=new_parameters) + cls.get_with_allow_multiple_query, + "__signature__", + endpoint_function.replace(parameters=new_parameters), ) @functools.wraps(cls.get_with_allow_multiple_query) @@ -191,25 +222,37 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> None: response_model=None, status_code=starlette.status.HTTP_204_NO_CONTENT, description=AbstractEndpointsParamsService.get_with_allow_multiple_query.__doc__, - **get_route_args(cls.get_with_allow_multiple_query, default_tag="endpoints.params"), + **get_route_args( + cls.get_with_allow_multiple_query, default_tag="endpoints.params" + ), )(wrapper) @classmethod def __init_get_with_path_and_query(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_with_path_and_query) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "param": new_parameters.append(parameter.replace(default=fastapi.Path(...))) elif parameter_name == "query": - new_parameters.append(parameter.replace(default=fastapi.Query(default=...))) + new_parameters.append( + parameter.replace(default=fastapi.Query(default=...)) + ) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_with_path_and_query, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_with_path_and_query, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_with_path_and_query) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> None: @@ -232,14 +275,18 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> None: response_model=None, status_code=starlette.status.HTTP_204_NO_CONTENT, description=AbstractEndpointsParamsService.get_with_path_and_query.__doc__, - **get_route_args(cls.get_with_path_and_query, default_tag="endpoints.params"), + **get_route_args( + cls.get_with_path_and_query, default_tag="endpoints.params" + ), )(wrapper) @classmethod def __init_modify_with_path(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.modify_with_path) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": @@ -247,10 +294,16 @@ def __init_modify_with_path(cls, router: fastapi.APIRouter) -> None: elif parameter_name == "param": new_parameters.append(parameter.replace(default=fastapi.Path(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.modify_with_path, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.modify_with_path, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.modify_with_path) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> str: diff --git a/seed/fastapi/exhaustive/no-custom-config/resources/endpoints/resources/primitive/service/service.py b/seed/fastapi/exhaustive/no-custom-config/resources/endpoints/resources/primitive/service/service.py index db7ef44676c..78b3526b630 100644 --- a/seed/fastapi/exhaustive/no-custom-config/resources/endpoints/resources/primitive/service/service.py +++ b/seed/fastapi/exhaustive/no-custom-config/resources/endpoints/resources/primitive/service/service.py @@ -1,19 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ......core.abstract_fern_service import AbstractFernService +from ......security import ApiAuth import abc import datetime as dt -import functools -import inspect -import logging -import typing import uuid - import fastapi - -from ......core.abstract_fern_service import AbstractFernService +import inspect +import typing +from ......security import FernAuth from ......core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools from ......core.route_args import get_route_args -from ......security import ApiAuth, FernAuth class AbstractEndpointsPrimitiveService(AbstractFernService): @@ -26,40 +25,33 @@ class AbstractEndpointsPrimitiveService(AbstractFernService): """ @abc.abstractmethod - def get_and_return_string(self, *, body: str, auth: ApiAuth) -> str: - ... + def get_and_return_string(self, *, body: str, auth: ApiAuth) -> str: ... @abc.abstractmethod - def get_and_return_int(self, *, body: int, auth: ApiAuth) -> int: - ... + def get_and_return_int(self, *, body: int, auth: ApiAuth) -> int: ... @abc.abstractmethod - def get_and_return_long(self, *, body: int, auth: ApiAuth) -> int: - ... + def get_and_return_long(self, *, body: int, auth: ApiAuth) -> int: ... @abc.abstractmethod - def get_and_return_double(self, *, body: float, auth: ApiAuth) -> float: - ... + def get_and_return_double(self, *, body: float, auth: ApiAuth) -> float: ... @abc.abstractmethod - def get_and_return_bool(self, *, body: bool, auth: ApiAuth) -> bool: - ... + def get_and_return_bool(self, *, body: bool, auth: ApiAuth) -> bool: ... @abc.abstractmethod - def get_and_return_datetime(self, *, body: dt.datetime, auth: ApiAuth) -> dt.datetime: - ... + def get_and_return_datetime( + self, *, body: dt.datetime, auth: ApiAuth + ) -> dt.datetime: ... @abc.abstractmethod - def get_and_return_date(self, *, body: dt.date, auth: ApiAuth) -> dt.date: - ... + def get_and_return_date(self, *, body: dt.date, auth: ApiAuth) -> dt.date: ... @abc.abstractmethod - def get_and_return_uuid(self, *, body: uuid.UUID, auth: ApiAuth) -> uuid.UUID: - ... + def get_and_return_uuid(self, *, body: uuid.UUID, auth: ApiAuth) -> uuid.UUID: ... @abc.abstractmethod - def get_and_return_base_64(self, *, body: str, auth: ApiAuth) -> str: - ... + def get_and_return_base_64(self, *, body: str, auth: ApiAuth) -> str: ... """ Below are internal methods used by Fern to register your implementation. @@ -82,16 +74,24 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_get_and_return_string(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_and_return_string) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_and_return_string, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_and_return_string, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_and_return_string) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> str: @@ -113,23 +113,33 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> str: path="/primitive/string", response_model=str, description=AbstractEndpointsPrimitiveService.get_and_return_string.__doc__, - **get_route_args(cls.get_and_return_string, default_tag="endpoints.primitive"), + **get_route_args( + cls.get_and_return_string, default_tag="endpoints.primitive" + ), )(wrapper) @classmethod def __init_get_and_return_int(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_and_return_int) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_and_return_int, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_and_return_int, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_and_return_int) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> int: @@ -158,16 +168,24 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> int: def __init_get_and_return_long(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_and_return_long) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_and_return_long, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_and_return_long, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_and_return_long) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> int: @@ -189,23 +207,33 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> int: path="/primitive/long", response_model=int, description=AbstractEndpointsPrimitiveService.get_and_return_long.__doc__, - **get_route_args(cls.get_and_return_long, default_tag="endpoints.primitive"), + **get_route_args( + cls.get_and_return_long, default_tag="endpoints.primitive" + ), )(wrapper) @classmethod def __init_get_and_return_double(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_and_return_double) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_and_return_double, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_and_return_double, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_and_return_double) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> float: @@ -227,23 +255,33 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> float: path="/primitive/double", response_model=float, description=AbstractEndpointsPrimitiveService.get_and_return_double.__doc__, - **get_route_args(cls.get_and_return_double, default_tag="endpoints.primitive"), + **get_route_args( + cls.get_and_return_double, default_tag="endpoints.primitive" + ), )(wrapper) @classmethod def __init_get_and_return_bool(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_and_return_bool) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_and_return_bool, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_and_return_bool, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_and_return_bool) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> bool: @@ -265,23 +303,33 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> bool: path="/primitive/boolean", response_model=bool, description=AbstractEndpointsPrimitiveService.get_and_return_bool.__doc__, - **get_route_args(cls.get_and_return_bool, default_tag="endpoints.primitive"), + **get_route_args( + cls.get_and_return_bool, default_tag="endpoints.primitive" + ), )(wrapper) @classmethod def __init_get_and_return_datetime(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_and_return_datetime) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_and_return_datetime, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_and_return_datetime, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_and_return_datetime) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> dt.datetime: @@ -303,23 +351,33 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> dt.datetime: path="/primitive/datetime", response_model=dt.datetime, description=AbstractEndpointsPrimitiveService.get_and_return_datetime.__doc__, - **get_route_args(cls.get_and_return_datetime, default_tag="endpoints.primitive"), + **get_route_args( + cls.get_and_return_datetime, default_tag="endpoints.primitive" + ), )(wrapper) @classmethod def __init_get_and_return_date(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_and_return_date) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_and_return_date, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_and_return_date, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_and_return_date) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> dt.date: @@ -341,23 +399,33 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> dt.date: path="/primitive/date", response_model=dt.date, description=AbstractEndpointsPrimitiveService.get_and_return_date.__doc__, - **get_route_args(cls.get_and_return_date, default_tag="endpoints.primitive"), + **get_route_args( + cls.get_and_return_date, default_tag="endpoints.primitive" + ), )(wrapper) @classmethod def __init_get_and_return_uuid(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_and_return_uuid) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_and_return_uuid, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_and_return_uuid, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_and_return_uuid) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> uuid.UUID: @@ -379,23 +447,33 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> uuid.UUID: path="/primitive/uuid", response_model=uuid.UUID, description=AbstractEndpointsPrimitiveService.get_and_return_uuid.__doc__, - **get_route_args(cls.get_and_return_uuid, default_tag="endpoints.primitive"), + **get_route_args( + cls.get_and_return_uuid, default_tag="endpoints.primitive" + ), )(wrapper) @classmethod def __init_get_and_return_base_64(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_and_return_base_64) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_and_return_base_64, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_and_return_base_64, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_and_return_base_64) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> str: @@ -417,5 +495,7 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> str: path="/primitive/base64", response_model=str, description=AbstractEndpointsPrimitiveService.get_and_return_base_64.__doc__, - **get_route_args(cls.get_and_return_base_64, default_tag="endpoints.primitive"), + **get_route_args( + cls.get_and_return_base_64, default_tag="endpoints.primitive" + ), )(wrapper) diff --git a/seed/fastapi/exhaustive/no-custom-config/resources/endpoints/resources/union/service/service.py b/seed/fastapi/exhaustive/no-custom-config/resources/endpoints/resources/union/service/service.py index 5c026188aca..cc962963db9 100644 --- a/seed/fastapi/exhaustive/no-custom-config/resources/endpoints/resources/union/service/service.py +++ b/seed/fastapi/exhaustive/no-custom-config/resources/endpoints/resources/union/service/service.py @@ -1,18 +1,17 @@ # This file was auto-generated by Fern from our API Definition. +from ......core.abstract_fern_service import AbstractFernService +from .....types.resources.union.types.animal import Animal +from ......security import ApiAuth import abc -import functools +import fastapi import inspect -import logging import typing - -import fastapi - -from ......core.abstract_fern_service import AbstractFernService +from ......security import FernAuth from ......core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools from ......core.route_args import get_route_args -from ......security import ApiAuth, FernAuth -from .....types.resources.union.types.animal import Animal class AbstractEndpointsUnionService(AbstractFernService): @@ -25,8 +24,7 @@ class AbstractEndpointsUnionService(AbstractFernService): """ @abc.abstractmethod - def get_and_return_union(self, *, body: Animal, auth: ApiAuth) -> Animal: - ... + def get_and_return_union(self, *, body: Animal, auth: ApiAuth) -> Animal: ... """ Below are internal methods used by Fern to register your implementation. @@ -41,16 +39,24 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_get_and_return_union(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_and_return_union) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_and_return_union, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_and_return_union, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_and_return_union) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> Animal: diff --git a/seed/fastapi/exhaustive/no-custom-config/resources/general_errors/types/bad_object_request_info.py b/seed/fastapi/exhaustive/no-custom-config/resources/general_errors/types/bad_object_request_info.py index 08402f7e618..3b4b5d03362 100644 --- a/seed/fastapi/exhaustive/no-custom-config/resources/general_errors/types/bad_object_request_info.py +++ b/seed/fastapi/exhaustive/no-custom-config/resources/general_errors/types/bad_object_request_info.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class BadObjectRequestInfo(UniversalBaseModel): message: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/exhaustive/no-custom-config/resources/inlined_requests/service/post_with_object_body.py b/seed/fastapi/exhaustive/no-custom-config/resources/inlined_requests/service/post_with_object_body.py index b62587f8d32..647905603ee 100644 --- a/seed/fastapi/exhaustive/no-custom-config/resources/inlined_requests/service/post_with_object_body.py +++ b/seed/fastapi/exhaustive/no-custom-config/resources/inlined_requests/service/post_with_object_body.py @@ -1,11 +1,12 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ....core.pydantic_utilities import UniversalBaseModel +from ...types.resources.object.types.object_with_optional_field import ( + ObjectWithOptionalField, +) import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from ...types.resources.object.types.object_with_optional_field import ObjectWithOptionalField +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class PostWithObjectBody(UniversalBaseModel): @@ -14,7 +15,9 @@ class PostWithObjectBody(UniversalBaseModel): nested_object: ObjectWithOptionalField = pydantic.Field(alias="NestedObject") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/exhaustive/no-custom-config/resources/inlined_requests/service/service.py b/seed/fastapi/exhaustive/no-custom-config/resources/inlined_requests/service/service.py index 24b6ac5ff85..9894c433149 100644 --- a/seed/fastapi/exhaustive/no-custom-config/resources/inlined_requests/service/service.py +++ b/seed/fastapi/exhaustive/no-custom-config/resources/inlined_requests/service/service.py @@ -1,19 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.abstract_fern_service import AbstractFernService +from .post_with_object_body import PostWithObjectBody +from ...types.resources.object.types.object_with_optional_field import ( + ObjectWithOptionalField, +) import abc -import functools +import fastapi import inspect -import logging import typing - -import fastapi - -from ....core.abstract_fern_service import AbstractFernService +from ...general_errors.errors.bad_request_body import BadRequestBody from ....core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools from ....core.route_args import get_route_args -from ...general_errors.errors.bad_request_body import BadRequestBody -from ...types.resources.object.types.object_with_optional_field import ObjectWithOptionalField -from .post_with_object_body import PostWithObjectBody class AbstractInlinedRequestsService(AbstractFernService): @@ -26,7 +26,9 @@ class AbstractInlinedRequestsService(AbstractFernService): """ @abc.abstractmethod - def post_with_object_bodyand_response(self, *, body: PostWithObjectBody) -> ObjectWithOptionalField: + def post_with_object_bodyand_response( + self, *, body: PostWithObjectBody + ) -> ObjectWithOptionalField: """ POST with custom object in request body, response is an object """ @@ -42,10 +44,14 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: cls.__init_post_with_object_bodyand_response(router=router) @classmethod - def __init_post_with_object_bodyand_response(cls, router: fastapi.APIRouter) -> None: + def __init_post_with_object_bodyand_response( + cls, router: fastapi.APIRouter + ) -> None: endpoint_function = inspect.signature(cls.post_with_object_bodyand_response) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": @@ -53,7 +59,9 @@ def __init_post_with_object_bodyand_response(cls, router: fastapi.APIRouter) -> else: new_parameters.append(parameter) setattr( - cls.post_with_object_bodyand_response, "__signature__", endpoint_function.replace(parameters=new_parameters) + cls.post_with_object_bodyand_response, + "__signature__", + endpoint_function.replace(parameters=new_parameters), ) @functools.wraps(cls.post_with_object_bodyand_response) @@ -78,5 +86,7 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> ObjectWithOptionalField: path="/req-bodies/object", response_model=ObjectWithOptionalField, description=AbstractInlinedRequestsService.post_with_object_bodyand_response.__doc__, - **get_route_args(cls.post_with_object_bodyand_response, default_tag="inlined_requests"), + **get_route_args( + cls.post_with_object_bodyand_response, default_tag="inlined_requests" + ), )(wrapper) diff --git a/seed/fastapi/exhaustive/no-custom-config/resources/no_auth/service/service.py b/seed/fastapi/exhaustive/no-custom-config/resources/no_auth/service/service.py index 952a7322d89..b0984ae6360 100644 --- a/seed/fastapi/exhaustive/no-custom-config/resources/no_auth/service/service.py +++ b/seed/fastapi/exhaustive/no-custom-config/resources/no_auth/service/service.py @@ -1,17 +1,15 @@ # This file was auto-generated by Fern from our API Definition. -import abc -import functools -import inspect -import logging +from ....core.abstract_fern_service import AbstractFernService import typing - +import abc import fastapi - -from ....core.abstract_fern_service import AbstractFernService +import inspect +from ...general_errors.errors.bad_request_body import BadRequestBody from ....core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools from ....core.route_args import get_route_args -from ...general_errors.errors.bad_request_body import BadRequestBody class AbstractNoAuthService(AbstractFernService): @@ -43,14 +41,20 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_post_with_no_auth(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.post_with_no_auth) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) else: new_parameters.append(parameter) - setattr(cls.post_with_no_auth, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.post_with_no_auth, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.post_with_no_auth) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> bool: diff --git a/seed/fastapi/exhaustive/no-custom-config/resources/no_req_body/service/service.py b/seed/fastapi/exhaustive/no-custom-config/resources/no_req_body/service/service.py index 09c805cc1c7..40b96353e2d 100644 --- a/seed/fastapi/exhaustive/no-custom-config/resources/no_req_body/service/service.py +++ b/seed/fastapi/exhaustive/no-custom-config/resources/no_req_body/service/service.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.abstract_fern_service import AbstractFernService +from ....security import ApiAuth +from ...types.resources.object.types.object_with_optional_field import ( + ObjectWithOptionalField, +) import abc -import functools +import fastapi import inspect -import logging import typing - -import fastapi - -from ....core.abstract_fern_service import AbstractFernService +from ....security import FernAuth from ....core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools from ....core.route_args import get_route_args -from ....security import ApiAuth, FernAuth -from ...types.resources.object.types.object_with_optional_field import ObjectWithOptionalField class AbstractNoReqBodyService(AbstractFernService): @@ -25,12 +26,10 @@ class AbstractNoReqBodyService(AbstractFernService): """ @abc.abstractmethod - def get_with_no_request_body(self, *, auth: ApiAuth) -> ObjectWithOptionalField: - ... + def get_with_no_request_body(self, *, auth: ApiAuth) -> ObjectWithOptionalField: ... @abc.abstractmethod - def post_with_no_request_body(self, *, auth: ApiAuth) -> str: - ... + def post_with_no_request_body(self, *, auth: ApiAuth) -> str: ... """ Below are internal methods used by Fern to register your implementation. @@ -46,14 +45,22 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_get_with_no_request_body(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_with_no_request_body) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_with_no_request_body, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_with_no_request_body, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_with_no_request_body) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> ObjectWithOptionalField: @@ -82,14 +89,22 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> ObjectWithOptionalField: def __init_post_with_no_request_body(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.post_with_no_request_body) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.post_with_no_request_body, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.post_with_no_request_body, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.post_with_no_request_body) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> str: diff --git a/seed/fastapi/exhaustive/no-custom-config/resources/req_with_headers/service/service.py b/seed/fastapi/exhaustive/no-custom-config/resources/req_with_headers/service/service.py index 7b31e8311b8..0bb5ea5b04c 100644 --- a/seed/fastapi/exhaustive/no-custom-config/resources/req_with_headers/service/service.py +++ b/seed/fastapi/exhaustive/no-custom-config/resources/req_with_headers/service/service.py @@ -1,18 +1,17 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.abstract_fern_service import AbstractFernService +from ....security import ApiAuth import abc -import functools +import fastapi import inspect -import logging import typing - -import fastapi -import starlette - -from ....core.abstract_fern_service import AbstractFernService +from ....security import FernAuth from ....core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools +import starlette from ....core.route_args import get_route_args -from ....security import ApiAuth, FernAuth class AbstractReqWithHeadersService(AbstractFernService): @@ -25,8 +24,9 @@ class AbstractReqWithHeadersService(AbstractFernService): """ @abc.abstractmethod - def get_with_custom_header(self, *, body: str, x_test_endpoint_header: str, auth: ApiAuth) -> None: - ... + def get_with_custom_header( + self, *, body: str, x_test_endpoint_header: str, auth: ApiAuth + ) -> None: ... """ Below are internal methods used by Fern to register your implementation. @@ -41,18 +41,30 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_get_with_custom_header(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_with_custom_header) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "x_test_endpoint_header": - new_parameters.append(parameter.replace(default=fastapi.Header(alias="X-TEST-ENDPOINT-HEADER"))) + new_parameters.append( + parameter.replace( + default=fastapi.Header(alias="X-TEST-ENDPOINT-HEADER") + ) + ) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_with_custom_header, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_with_custom_header, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_with_custom_header) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> None: @@ -75,5 +87,7 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> None: response_model=None, status_code=starlette.status.HTTP_204_NO_CONTENT, description=AbstractReqWithHeadersService.get_with_custom_header.__doc__, - **get_route_args(cls.get_with_custom_header, default_tag="req_with_headers"), + **get_route_args( + cls.get_with_custom_header, default_tag="req_with_headers" + ), )(wrapper) diff --git a/seed/fastapi/exhaustive/no-custom-config/resources/types/resources/object/errors/nested_object_with_optional_field_error.py b/seed/fastapi/exhaustive/no-custom-config/resources/types/resources/object/errors/nested_object_with_optional_field_error.py index 3ba440b272a..8ccad4823e1 100644 --- a/seed/fastapi/exhaustive/no-custom-config/resources/types/resources/object/errors/nested_object_with_optional_field_error.py +++ b/seed/fastapi/exhaustive/no-custom-config/resources/types/resources/object/errors/nested_object_with_optional_field_error.py @@ -6,4 +6,6 @@ class NestedObjectWithOptionalFieldError(FernHTTPException): def __init__(self, error: NestedObjectWithOptionalField): - super().__init__(status_code=400, name="NestedObjectWithOptionalFieldError", content=error) + super().__init__( + status_code=400, name="NestedObjectWithOptionalFieldError", content=error + ) diff --git a/seed/fastapi/exhaustive/no-custom-config/resources/types/resources/object/errors/nested_object_with_required_field_error.py b/seed/fastapi/exhaustive/no-custom-config/resources/types/resources/object/errors/nested_object_with_required_field_error.py index 10b5e850066..d328ecaf35e 100644 --- a/seed/fastapi/exhaustive/no-custom-config/resources/types/resources/object/errors/nested_object_with_required_field_error.py +++ b/seed/fastapi/exhaustive/no-custom-config/resources/types/resources/object/errors/nested_object_with_required_field_error.py @@ -6,4 +6,6 @@ class NestedObjectWithRequiredFieldError(FernHTTPException): def __init__(self, error: NestedObjectWithRequiredField): - super().__init__(status_code=400, name="NestedObjectWithRequiredFieldError", content=error) + super().__init__( + status_code=400, name="NestedObjectWithRequiredFieldError", content=error + ) diff --git a/seed/fastapi/exhaustive/no-custom-config/resources/types/resources/object/errors/object_with_optional_field_error.py b/seed/fastapi/exhaustive/no-custom-config/resources/types/resources/object/errors/object_with_optional_field_error.py index 09a92f4c466..1205d252c69 100644 --- a/seed/fastapi/exhaustive/no-custom-config/resources/types/resources/object/errors/object_with_optional_field_error.py +++ b/seed/fastapi/exhaustive/no-custom-config/resources/types/resources/object/errors/object_with_optional_field_error.py @@ -6,4 +6,6 @@ class ObjectWithOptionalFieldError(FernHTTPException): def __init__(self, error: ObjectWithOptionalField): - super().__init__(status_code=400, name="ObjectWithOptionalFieldError", content=error) + super().__init__( + status_code=400, name="ObjectWithOptionalFieldError", content=error + ) diff --git a/seed/fastapi/exhaustive/no-custom-config/resources/types/resources/object/errors/object_with_required_field_error.py b/seed/fastapi/exhaustive/no-custom-config/resources/types/resources/object/errors/object_with_required_field_error.py index c0c5cc11812..53045a6279e 100644 --- a/seed/fastapi/exhaustive/no-custom-config/resources/types/resources/object/errors/object_with_required_field_error.py +++ b/seed/fastapi/exhaustive/no-custom-config/resources/types/resources/object/errors/object_with_required_field_error.py @@ -6,4 +6,6 @@ class ObjectWithRequiredFieldError(FernHTTPException): def __init__(self, error: ObjectWithRequiredField): - super().__init__(status_code=400, name="ObjectWithRequiredFieldError", content=error) + super().__init__( + status_code=400, name="ObjectWithRequiredFieldError", content=error + ) diff --git a/seed/fastapi/exhaustive/no-custom-config/resources/types/resources/object/types/double_optional.py b/seed/fastapi/exhaustive/no-custom-config/resources/types/resources/object/types/double_optional.py index 496516e1c7e..055935ee32e 100644 --- a/seed/fastapi/exhaustive/no-custom-config/resources/types/resources/object/types/double_optional.py +++ b/seed/fastapi/exhaustive/no-custom-config/resources/types/resources/object/types/double_optional.py @@ -1,18 +1,21 @@ # This file was auto-generated by Fern from our API Definition. +from ......core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .optional_alias import OptionalAlias +import pydantic +from ......core.pydantic_utilities import IS_PYDANTIC_V2 class DoubleOptional(UniversalBaseModel): - optional_alias: typing.Optional[OptionalAlias] = pydantic.Field(alias="optionalAlias", default=None) + optional_alias: typing.Optional[OptionalAlias] = pydantic.Field( + alias="optionalAlias", default=None + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/exhaustive/no-custom-config/resources/types/resources/object/types/nested_object_with_optional_field.py b/seed/fastapi/exhaustive/no-custom-config/resources/types/resources/object/types/nested_object_with_optional_field.py index ed1a24559d4..15fff182ee9 100644 --- a/seed/fastapi/exhaustive/no-custom-config/resources/types/resources/object/types/nested_object_with_optional_field.py +++ b/seed/fastapi/exhaustive/no-custom-config/resources/types/resources/object/types/nested_object_with_optional_field.py @@ -1,19 +1,22 @@ # This file was auto-generated by Fern from our API Definition. +from ......core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .object_with_optional_field import ObjectWithOptionalField +import pydantic +from ......core.pydantic_utilities import IS_PYDANTIC_V2 class NestedObjectWithOptionalField(UniversalBaseModel): string: typing.Optional[str] = None - nested_object: typing.Optional[ObjectWithOptionalField] = pydantic.Field(alias="NestedObject", default=None) + nested_object: typing.Optional[ObjectWithOptionalField] = pydantic.Field( + alias="NestedObject", default=None + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/exhaustive/no-custom-config/resources/types/resources/object/types/nested_object_with_required_field.py b/seed/fastapi/exhaustive/no-custom-config/resources/types/resources/object/types/nested_object_with_required_field.py index 9f1da7f2b69..c152f7caf34 100644 --- a/seed/fastapi/exhaustive/no-custom-config/resources/types/resources/object/types/nested_object_with_required_field.py +++ b/seed/fastapi/exhaustive/no-custom-config/resources/types/resources/object/types/nested_object_with_required_field.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ......core.pydantic_utilities import UniversalBaseModel from .object_with_optional_field import ObjectWithOptionalField +import pydantic +from ......core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class NestedObjectWithRequiredField(UniversalBaseModel): @@ -13,7 +12,9 @@ class NestedObjectWithRequiredField(UniversalBaseModel): nested_object: ObjectWithOptionalField = pydantic.Field(alias="NestedObject") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/exhaustive/no-custom-config/resources/types/resources/object/types/object_with_map_of_map.py b/seed/fastapi/exhaustive/no-custom-config/resources/types/resources/object/types/object_with_map_of_map.py index aba295a1e88..259d15f900b 100644 --- a/seed/fastapi/exhaustive/no-custom-config/resources/types/resources/object/types/object_with_map_of_map.py +++ b/seed/fastapi/exhaustive/no-custom-config/resources/types/resources/object/types/object_with_map_of_map.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ......core.pydantic_utilities import UniversalBaseModel import typing - import pydantic - -from ......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ......core.pydantic_utilities import IS_PYDANTIC_V2 class ObjectWithMapOfMap(UniversalBaseModel): map_: typing.Dict[str, typing.Dict[str, str]] = pydantic.Field(alias="map") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/exhaustive/no-custom-config/resources/types/resources/object/types/object_with_optional_field.py b/seed/fastapi/exhaustive/no-custom-config/resources/types/resources/object/types/object_with_optional_field.py index eb3565c51a2..b8d37eb85ef 100644 --- a/seed/fastapi/exhaustive/no-custom-config/resources/types/resources/object/types/object_with_optional_field.py +++ b/seed/fastapi/exhaustive/no-custom-config/resources/types/resources/object/types/object_with_optional_field.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. -import datetime as dt +from ......core.pydantic_utilities import UniversalBaseModel import typing -import uuid - import pydantic - -from ......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +import datetime as dt +import uuid +from ......core.pydantic_utilities import IS_PYDANTIC_V2 class ObjectWithOptionalField(UniversalBaseModel): @@ -23,13 +22,19 @@ class ObjectWithOptionalField(UniversalBaseModel): date: typing.Optional[dt.date] = None uuid_: typing.Optional[uuid.UUID] = pydantic.Field(alias="uuid", default=None) base_64: typing.Optional[str] = pydantic.Field(alias="base64", default=None) - list_: typing.Optional[typing.List[str]] = pydantic.Field(alias="list", default=None) + list_: typing.Optional[typing.List[str]] = pydantic.Field( + alias="list", default=None + ) set_: typing.Optional[typing.Set[str]] = pydantic.Field(alias="set", default=None) - map_: typing.Optional[typing.Dict[int, str]] = pydantic.Field(alias="map", default=None) + map_: typing.Optional[typing.Dict[int, str]] = pydantic.Field( + alias="map", default=None + ) bigint: typing.Optional[str] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/exhaustive/no-custom-config/resources/types/resources/object/types/object_with_required_field.py b/seed/fastapi/exhaustive/no-custom-config/resources/types/resources/object/types/object_with_required_field.py index 20aee4fa01f..460dec359be 100644 --- a/seed/fastapi/exhaustive/no-custom-config/resources/types/resources/object/types/object_with_required_field.py +++ b/seed/fastapi/exhaustive/no-custom-config/resources/types/resources/object/types/object_with_required_field.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ......core.pydantic_utilities import UniversalBaseModel +from ......core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class ObjectWithRequiredField(UniversalBaseModel): string: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/exhaustive/no-custom-config/resources/types/resources/union/types/animal.py b/seed/fastapi/exhaustive/no-custom-config/resources/types/resources/union/types/animal.py index 74285020765..a8ee74c09ed 100644 --- a/seed/fastapi/exhaustive/no-custom-config/resources/types/resources/union/types/animal.py +++ b/seed/fastapi/exhaustive/no-custom-config/resources/types/resources/union/types/animal.py @@ -1,15 +1,14 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from .dog import Dog as resources_types_resources_union_types_dog_Dog +from ......core.pydantic_utilities import IS_PYDANTIC_V2 +from .cat import Cat as resources_types_resources_union_types_cat_Cat +from ......core.pydantic_utilities import UniversalRootModel import typing - -import pydantic import typing_extensions - -from ......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalRootModel, update_forward_refs -from .cat import Cat as resources_types_resources_union_types_cat_Cat -from .dog import Dog as resources_types_resources_union_types_dog_Dog +import pydantic +from ......core.pydantic_utilities import update_forward_refs T_Result = typing.TypeVar("T_Result") @@ -17,15 +16,23 @@ class _Factory: def dog(self, value: resources_types_resources_union_types_dog_Dog) -> Animal: if IS_PYDANTIC_V2: - return Animal(root=_Animal.Dog(**value.dict(exclude_unset=True), animal="dog")) + return Animal( + root=_Animal.Dog(**value.dict(exclude_unset=True), animal="dog") + ) else: - return Animal(__root__=_Animal.Dog(**value.dict(exclude_unset=True), animal="dog")) + return Animal( + __root__=_Animal.Dog(**value.dict(exclude_unset=True), animal="dog") + ) def cat(self, value: resources_types_resources_union_types_cat_Cat) -> Animal: if IS_PYDANTIC_V2: - return Animal(root=_Animal.Cat(**value.dict(exclude_unset=True), animal="cat")) + return Animal( + root=_Animal.Cat(**value.dict(exclude_unset=True), animal="cat") + ) else: - return Animal(__root__=_Animal.Cat(**value.dict(exclude_unset=True), animal="cat")) + return Animal( + __root__=_Animal.Cat(**value.dict(exclude_unset=True), animal="cat") + ) class Animal(UniversalRootModel): @@ -33,15 +40,16 @@ class Animal(UniversalRootModel): if IS_PYDANTIC_V2: root: typing_extensions.Annotated[ - typing.Union[_Animal.Dog, _Animal.Cat], pydantic.Field(discriminator="animal") + typing.Union[_Animal.Dog, _Animal.Cat], + pydantic.Field(discriminator="animal"), ] def get_as_union(self) -> typing.Union[_Animal.Dog, _Animal.Cat]: return self.root - else: __root__: typing_extensions.Annotated[ - typing.Union[_Animal.Dog, _Animal.Cat], pydantic.Field(discriminator="animal") + typing.Union[_Animal.Dog, _Animal.Cat], + pydantic.Field(discriminator="animal"), ] def get_as_union(self) -> typing.Union[_Animal.Dog, _Animal.Cat]: diff --git a/seed/fastapi/exhaustive/no-custom-config/resources/types/resources/union/types/cat.py b/seed/fastapi/exhaustive/no-custom-config/resources/types/resources/union/types/cat.py index 2436a0fd384..cdcfe7a1d25 100644 --- a/seed/fastapi/exhaustive/no-custom-config/resources/types/resources/union/types/cat.py +++ b/seed/fastapi/exhaustive/no-custom-config/resources/types/resources/union/types/cat.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ......core.pydantic_utilities import UniversalBaseModel import pydantic - -from ......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ......core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class Cat(UniversalBaseModel): @@ -12,7 +11,9 @@ class Cat(UniversalBaseModel): likes_to_meow: bool = pydantic.Field(alias="likesToMeow") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/exhaustive/no-custom-config/resources/types/resources/union/types/dog.py b/seed/fastapi/exhaustive/no-custom-config/resources/types/resources/union/types/dog.py index 3afc51b5137..b5feda1e61c 100644 --- a/seed/fastapi/exhaustive/no-custom-config/resources/types/resources/union/types/dog.py +++ b/seed/fastapi/exhaustive/no-custom-config/resources/types/resources/union/types/dog.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ......core.pydantic_utilities import UniversalBaseModel import pydantic - -from ......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ......core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class Dog(UniversalBaseModel): @@ -12,7 +11,9 @@ class Dog(UniversalBaseModel): likes_to_woof: bool = pydantic.Field(alias="likesToWoof") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/exhaustive/no-custom-config/security.py b/seed/fastapi/exhaustive/no-custom-config/security.py index bab014441e1..4ccabc21106 100644 --- a/seed/fastapi/exhaustive/no-custom-config/security.py +++ b/seed/fastapi/exhaustive/no-custom-config/security.py @@ -1,8 +1,8 @@ # This file was auto-generated by Fern from our API Definition. +from .core.security.bearer import BearerToken import fastapi - -from .core.security.bearer import BearerToken, HTTPBearer +from .core.security.bearer import HTTPBearer ApiAuth = BearerToken diff --git a/seed/fastapi/exhaustive/pydantic-v1/__init__.py b/seed/fastapi/exhaustive/pydantic-v1/__init__.py index 2679cde4830..6eda4b194c2 100644 --- a/seed/fastapi/exhaustive/pydantic-v1/__init__.py +++ b/seed/fastapi/exhaustive/pydantic-v1/__init__.py @@ -1,6 +1,13 @@ # This file was auto-generated by Fern from our API Definition. -from .resources import BadObjectRequestInfo, BadRequestBody, PostWithObjectBody, general_errors, inlined_requests, types +from .resources import ( + BadObjectRequestInfo, + BadRequestBody, + PostWithObjectBody, + general_errors, + inlined_requests, + types, +) from .security import ApiAuth __all__ = [ diff --git a/seed/fastapi/exhaustive/pydantic-v1/core/abstract_fern_service.py b/seed/fastapi/exhaustive/pydantic-v1/core/abstract_fern_service.py index da7c8dc49c4..9966b4876da 100644 --- a/seed/fastapi/exhaustive/pydantic-v1/core/abstract_fern_service.py +++ b/seed/fastapi/exhaustive/pydantic-v1/core/abstract_fern_service.py @@ -7,5 +7,4 @@ class AbstractFernService(abc.ABC): @classmethod - def _init_fern(cls, router: fastapi.APIRouter) -> None: - ... + def _init_fern(cls, router: fastapi.APIRouter) -> None: ... diff --git a/seed/fastapi/exhaustive/pydantic-v1/core/datetime_utils.py b/seed/fastapi/exhaustive/pydantic-v1/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/fastapi/exhaustive/pydantic-v1/core/datetime_utils.py +++ b/seed/fastapi/exhaustive/pydantic-v1/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/fastapi/exhaustive/pydantic-v1/core/exceptions/__init__.py b/seed/fastapi/exhaustive/pydantic-v1/core/exceptions/__init__.py index 297d6e06f5f..dae4b8980c1 100644 --- a/seed/fastapi/exhaustive/pydantic-v1/core/exceptions/__init__.py +++ b/seed/fastapi/exhaustive/pydantic-v1/core/exceptions/__init__.py @@ -1,7 +1,11 @@ # This file was auto-generated by Fern from our API Definition. from .fern_http_exception import FernHTTPException -from .handlers import default_exception_handler, fern_http_exception_handler, http_exception_handler +from .handlers import ( + default_exception_handler, + fern_http_exception_handler, + http_exception_handler, +) from .unauthorized import UnauthorizedException __all__ = [ diff --git a/seed/fastapi/exhaustive/pydantic-v1/core/exceptions/fern_http_exception.py b/seed/fastapi/exhaustive/pydantic-v1/core/exceptions/fern_http_exception.py index bdf03862487..81610359a7f 100644 --- a/seed/fastapi/exhaustive/pydantic-v1/core/exceptions/fern_http_exception.py +++ b/seed/fastapi/exhaustive/pydantic-v1/core/exceptions/fern_http_exception.py @@ -1,14 +1,16 @@ # This file was auto-generated by Fern from our API Definition. import abc -import typing - import fastapi +import typing class FernHTTPException(abc.ABC, fastapi.HTTPException): def __init__( - self, status_code: int, name: typing.Optional[str] = None, content: typing.Optional[typing.Any] = None + self, + status_code: int, + name: typing.Optional[str] = None, + content: typing.Optional[typing.Any] = None, ): super().__init__(status_code=status_code) self.name = name @@ -17,4 +19,6 @@ def __init__( def to_json_response(self) -> fastapi.responses.JSONResponse: content = fastapi.encoders.jsonable_encoder(self.content, exclude_none=True) - return fastapi.responses.JSONResponse(content=content, status_code=self.status_code) + return fastapi.responses.JSONResponse( + content=content, status_code=self.status_code + ) diff --git a/seed/fastapi/exhaustive/pydantic-v1/core/exceptions/handlers.py b/seed/fastapi/exhaustive/pydantic-v1/core/exceptions/handlers.py index 6d8c4155c5a..ae1c2741f06 100644 --- a/seed/fastapi/exhaustive/pydantic-v1/core/exceptions/handlers.py +++ b/seed/fastapi/exhaustive/pydantic-v1/core/exceptions/handlers.py @@ -2,32 +2,49 @@ import logging -import fastapi import starlette import starlette.exceptions +import fastapi + from .fern_http_exception import FernHTTPException def fern_http_exception_handler( - request: fastapi.requests.Request, exc: FernHTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: FernHTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) return exc.to_json_response() def http_exception_handler( - request: fastapi.requests.Request, exc: starlette.exceptions.HTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: starlette.exceptions.HTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=exc.status_code, content=exc.detail).to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=exc.status_code, content=exc.detail + ).to_json_response() def default_exception_handler( - request: fastapi.requests.Request, exc: Exception, skip_log: bool = False + request: fastapi.requests.Request, + exc: Exception, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=500, content="Internal Server Error").to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=500, content="Internal Server Error" + ).to_json_response() diff --git a/seed/fastapi/exhaustive/pydantic-v1/core/pydantic_utilities.py b/seed/fastapi/exhaustive/pydantic-v1/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/fastapi/exhaustive/pydantic-v1/core/pydantic_utilities.py +++ b/seed/fastapi/exhaustive/pydantic-v1/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/fastapi/exhaustive/pydantic-v1/core/route_args.py b/seed/fastapi/exhaustive/pydantic-v1/core/route_args.py index 4228e2fe05d..bd940bf4ddd 100644 --- a/seed/fastapi/exhaustive/pydantic-v1/core/route_args.py +++ b/seed/fastapi/exhaustive/pydantic-v1/core/route_args.py @@ -20,9 +20,15 @@ class RouteArgs(typing_extensions.TypedDict): DEFAULT_ROUTE_ARGS = RouteArgs(openapi_extra=None, tags=None, include_in_schema=True) -def get_route_args(endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str) -> RouteArgs: - unwrapped = inspect.unwrap(endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY))) - route_args = typing.cast(RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS)) +def get_route_args( + endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str +) -> RouteArgs: + unwrapped = inspect.unwrap( + endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY)) + ) + route_args = typing.cast( + RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS) + ) if route_args["tags"] is None: return RouteArgs( openapi_extra=route_args["openapi_extra"], @@ -56,7 +62,11 @@ def decorator(endpoint_function: T) -> T: setattr( endpoint_function, FERN_CONFIG_KEY, - RouteArgs(openapi_extra=openapi_extra, tags=tags, include_in_schema=include_in_schema), + RouteArgs( + openapi_extra=openapi_extra, + tags=tags, + include_in_schema=include_in_schema, + ), ) return endpoint_function diff --git a/seed/fastapi/exhaustive/pydantic-v1/register.py b/seed/fastapi/exhaustive/pydantic-v1/register.py index be0c42bf3f9..1f804567f73 100644 --- a/seed/fastapi/exhaustive/pydantic-v1/register.py +++ b/seed/fastapi/exhaustive/pydantic-v1/register.py @@ -1,29 +1,43 @@ # This file was auto-generated by Fern from our API Definition. -import glob -import importlib -import os -import types -import typing - import fastapi -import starlette.exceptions -from fastapi import params - -from .core.abstract_fern_service import AbstractFernService -from .core.exceptions import default_exception_handler, fern_http_exception_handler, http_exception_handler -from .core.exceptions.fern_http_exception import FernHTTPException -from .resources.endpoints.resources.container.service.service import AbstractEndpointsContainerService -from .resources.endpoints.resources.enum.service.service import AbstractEndpointsEnumService -from .resources.endpoints.resources.http_methods.service.service import AbstractEndpointsHttpMethodsService -from .resources.endpoints.resources.object.service.service import AbstractEndpointsObjectService -from .resources.endpoints.resources.params.service.service import AbstractEndpointsParamsService -from .resources.endpoints.resources.primitive.service.service import AbstractEndpointsPrimitiveService -from .resources.endpoints.resources.union.service.service import AbstractEndpointsUnionService +from .resources.endpoints.resources.container.service.service import ( + AbstractEndpointsContainerService, +) +from .resources.endpoints.resources.enum.service.service import ( + AbstractEndpointsEnumService, +) +from .resources.endpoints.resources.http_methods.service.service import ( + AbstractEndpointsHttpMethodsService, +) +from .resources.endpoints.resources.object.service.service import ( + AbstractEndpointsObjectService, +) +from .resources.endpoints.resources.params.service.service import ( + AbstractEndpointsParamsService, +) +from .resources.endpoints.resources.primitive.service.service import ( + AbstractEndpointsPrimitiveService, +) +from .resources.endpoints.resources.union.service.service import ( + AbstractEndpointsUnionService, +) from .resources.inlined_requests.service.service import AbstractInlinedRequestsService from .resources.no_auth.service.service import AbstractNoAuthService from .resources.no_req_body.service.service import AbstractNoReqBodyService from .resources.req_with_headers.service.service import AbstractReqWithHeadersService +import typing +from fastapi import params +from .core.exceptions.fern_http_exception import FernHTTPException +from .core.exceptions import fern_http_exception_handler +import starlette.exceptions +from .core.exceptions import http_exception_handler +from .core.exceptions import default_exception_handler +from .core.abstract_fern_service import AbstractFernService +import types +import os +import glob +import importlib def register( @@ -40,14 +54,20 @@ def register( no_auth: AbstractNoAuthService, no_req_body: AbstractNoReqBodyService, req_with_headers: AbstractReqWithHeadersService, - dependencies: typing.Optional[typing.Sequence[params.Depends]] = None + dependencies: typing.Optional[typing.Sequence[params.Depends]] = None, ) -> None: - _app.include_router(__register_service(endpoints_container), dependencies=dependencies) + _app.include_router( + __register_service(endpoints_container), dependencies=dependencies + ) _app.include_router(__register_service(endpoints_enum), dependencies=dependencies) - _app.include_router(__register_service(endpoints_http_methods), dependencies=dependencies) + _app.include_router( + __register_service(endpoints_http_methods), dependencies=dependencies + ) _app.include_router(__register_service(endpoints_object), dependencies=dependencies) _app.include_router(__register_service(endpoints_params), dependencies=dependencies) - _app.include_router(__register_service(endpoints_primitive), dependencies=dependencies) + _app.include_router( + __register_service(endpoints_primitive), dependencies=dependencies + ) _app.include_router(__register_service(endpoints_union), dependencies=dependencies) _app.include_router(__register_service(inlined_requests), dependencies=dependencies) _app.include_router(__register_service(no_auth), dependencies=dependencies) @@ -55,7 +75,9 @@ def register( _app.include_router(__register_service(req_with_headers), dependencies=dependencies) _app.add_exception_handler(FernHTTPException, fern_http_exception_handler) # type: ignore - _app.add_exception_handler(starlette.exceptions.HTTPException, http_exception_handler) # type: ignore + _app.add_exception_handler( + starlette.exceptions.HTTPException, http_exception_handler + ) # type: ignore _app.add_exception_handler(Exception, default_exception_handler) # type: ignore @@ -67,7 +89,9 @@ def __register_service(service: AbstractFernService) -> fastapi.APIRouter: def register_validators(module: types.ModuleType) -> None: validators_directory: str = os.path.dirname(module.__file__) # type: ignore - for path in glob.glob(os.path.join(validators_directory, "**/*.py"), recursive=True): + for path in glob.glob( + os.path.join(validators_directory, "**/*.py"), recursive=True + ): if os.path.isfile(path): relative_path = os.path.relpath(path, start=validators_directory) module_path = ".".join([module.__name__] + relative_path[:-3].split("/")) diff --git a/seed/fastapi/exhaustive/pydantic-v1/resources/endpoints/resources/container/service/service.py b/seed/fastapi/exhaustive/pydantic-v1/resources/endpoints/resources/container/service/service.py index af2cbf4be28..79da48ea0cc 100644 --- a/seed/fastapi/exhaustive/pydantic-v1/resources/endpoints/resources/container/service/service.py +++ b/seed/fastapi/exhaustive/pydantic-v1/resources/endpoints/resources/container/service/service.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. -import abc -import functools -import inspect -import logging +from ......core.abstract_fern_service import AbstractFernService import typing - +from ......security import ApiAuth +import abc +from .....types.resources.object.types.object_with_required_field import ( + ObjectWithRequiredField, +) import fastapi - -from ......core.abstract_fern_service import AbstractFernService +import inspect +from ......security import FernAuth from ......core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools from ......core.route_args import get_route_args -from ......security import ApiAuth, FernAuth -from .....types.resources.object.types.object_with_required_field import ObjectWithRequiredField class AbstractEndpointsContainerService(AbstractFernService): @@ -25,40 +26,39 @@ class AbstractEndpointsContainerService(AbstractFernService): """ @abc.abstractmethod - def get_and_return_list_of_primitives(self, *, body: typing.List[str], auth: ApiAuth) -> typing.Sequence[str]: - ... + def get_and_return_list_of_primitives( + self, *, body: typing.List[str], auth: ApiAuth + ) -> typing.Sequence[str]: ... @abc.abstractmethod def get_and_return_list_of_objects( self, *, body: typing.List[ObjectWithRequiredField], auth: ApiAuth - ) -> typing.Sequence[ObjectWithRequiredField]: - ... + ) -> typing.Sequence[ObjectWithRequiredField]: ... @abc.abstractmethod - def get_and_return_set_of_primitives(self, *, body: typing.Set[str], auth: ApiAuth) -> typing.Set[str]: - ... + def get_and_return_set_of_primitives( + self, *, body: typing.Set[str], auth: ApiAuth + ) -> typing.Set[str]: ... @abc.abstractmethod def get_and_return_set_of_objects( self, *, body: typing.List[ObjectWithRequiredField], auth: ApiAuth - ) -> typing.Sequence[ObjectWithRequiredField]: - ... + ) -> typing.Sequence[ObjectWithRequiredField]: ... @abc.abstractmethod - def get_and_return_map_prim_to_prim(self, *, body: typing.Dict[str, str], auth: ApiAuth) -> typing.Dict[str, str]: - ... + def get_and_return_map_prim_to_prim( + self, *, body: typing.Dict[str, str], auth: ApiAuth + ) -> typing.Dict[str, str]: ... @abc.abstractmethod def get_and_return_map_of_prim_to_object( self, *, body: typing.Dict[str, ObjectWithRequiredField], auth: ApiAuth - ) -> typing.Dict[str, ObjectWithRequiredField]: - ... + ) -> typing.Dict[str, ObjectWithRequiredField]: ... @abc.abstractmethod def get_and_return_optional( self, *, body: typing.Optional[ObjectWithRequiredField] = None, auth: ApiAuth - ) -> typing.Optional[ObjectWithRequiredField]: - ... + ) -> typing.Optional[ObjectWithRequiredField]: ... """ Below are internal methods used by Fern to register your implementation. @@ -76,20 +76,28 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: cls.__init_get_and_return_optional(router=router) @classmethod - def __init_get_and_return_list_of_primitives(cls, router: fastapi.APIRouter) -> None: + def __init_get_and_return_list_of_primitives( + cls, router: fastapi.APIRouter + ) -> None: endpoint_function = inspect.signature(cls.get_and_return_list_of_primitives) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) setattr( - cls.get_and_return_list_of_primitives, "__signature__", endpoint_function.replace(parameters=new_parameters) + cls.get_and_return_list_of_primitives, + "__signature__", + endpoint_function.replace(parameters=new_parameters), ) @functools.wraps(cls.get_and_return_list_of_primitives) @@ -112,28 +120,38 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> typing.Sequence[str]: path="/container/list-of-primitives", response_model=typing.Sequence[str], description=AbstractEndpointsContainerService.get_and_return_list_of_primitives.__doc__, - **get_route_args(cls.get_and_return_list_of_primitives, default_tag="endpoints.container"), + **get_route_args( + cls.get_and_return_list_of_primitives, default_tag="endpoints.container" + ), )(wrapper) @classmethod def __init_get_and_return_list_of_objects(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_and_return_list_of_objects) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) setattr( - cls.get_and_return_list_of_objects, "__signature__", endpoint_function.replace(parameters=new_parameters) + cls.get_and_return_list_of_objects, + "__signature__", + endpoint_function.replace(parameters=new_parameters), ) @functools.wraps(cls.get_and_return_list_of_objects) - def wrapper(*args: typing.Any, **kwargs: typing.Any) -> typing.Sequence[ObjectWithRequiredField]: + def wrapper( + *args: typing.Any, **kwargs: typing.Any + ) -> typing.Sequence[ObjectWithRequiredField]: try: return cls.get_and_return_list_of_objects(*args, **kwargs) except FernHTTPException as e: @@ -152,24 +170,32 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> typing.Sequence[ObjectWi path="/container/list-of-objects", response_model=typing.Sequence[ObjectWithRequiredField], description=AbstractEndpointsContainerService.get_and_return_list_of_objects.__doc__, - **get_route_args(cls.get_and_return_list_of_objects, default_tag="endpoints.container"), + **get_route_args( + cls.get_and_return_list_of_objects, default_tag="endpoints.container" + ), )(wrapper) @classmethod def __init_get_and_return_set_of_primitives(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_and_return_set_of_primitives) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) setattr( - cls.get_and_return_set_of_primitives, "__signature__", endpoint_function.replace(parameters=new_parameters) + cls.get_and_return_set_of_primitives, + "__signature__", + endpoint_function.replace(parameters=new_parameters), ) @functools.wraps(cls.get_and_return_set_of_primitives) @@ -192,28 +218,38 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> typing.Set[str]: path="/container/set-of-primitives", response_model=typing.Set[str], description=AbstractEndpointsContainerService.get_and_return_set_of_primitives.__doc__, - **get_route_args(cls.get_and_return_set_of_primitives, default_tag="endpoints.container"), + **get_route_args( + cls.get_and_return_set_of_primitives, default_tag="endpoints.container" + ), )(wrapper) @classmethod def __init_get_and_return_set_of_objects(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_and_return_set_of_objects) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) setattr( - cls.get_and_return_set_of_objects, "__signature__", endpoint_function.replace(parameters=new_parameters) + cls.get_and_return_set_of_objects, + "__signature__", + endpoint_function.replace(parameters=new_parameters), ) @functools.wraps(cls.get_and_return_set_of_objects) - def wrapper(*args: typing.Any, **kwargs: typing.Any) -> typing.Sequence[ObjectWithRequiredField]: + def wrapper( + *args: typing.Any, **kwargs: typing.Any + ) -> typing.Sequence[ObjectWithRequiredField]: try: return cls.get_and_return_set_of_objects(*args, **kwargs) except FernHTTPException as e: @@ -232,24 +268,32 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> typing.Sequence[ObjectWi path="/container/set-of-objects", response_model=typing.Sequence[ObjectWithRequiredField], description=AbstractEndpointsContainerService.get_and_return_set_of_objects.__doc__, - **get_route_args(cls.get_and_return_set_of_objects, default_tag="endpoints.container"), + **get_route_args( + cls.get_and_return_set_of_objects, default_tag="endpoints.container" + ), )(wrapper) @classmethod def __init_get_and_return_map_prim_to_prim(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_and_return_map_prim_to_prim) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) setattr( - cls.get_and_return_map_prim_to_prim, "__signature__", endpoint_function.replace(parameters=new_parameters) + cls.get_and_return_map_prim_to_prim, + "__signature__", + endpoint_function.replace(parameters=new_parameters), ) @functools.wraps(cls.get_and_return_map_prim_to_prim) @@ -272,20 +316,28 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> typing.Dict[str, str]: path="/container/map-prim-to-prim", response_model=typing.Dict[str, str], description=AbstractEndpointsContainerService.get_and_return_map_prim_to_prim.__doc__, - **get_route_args(cls.get_and_return_map_prim_to_prim, default_tag="endpoints.container"), + **get_route_args( + cls.get_and_return_map_prim_to_prim, default_tag="endpoints.container" + ), )(wrapper) @classmethod - def __init_get_and_return_map_of_prim_to_object(cls, router: fastapi.APIRouter) -> None: + def __init_get_and_return_map_of_prim_to_object( + cls, router: fastapi.APIRouter + ) -> None: endpoint_function = inspect.signature(cls.get_and_return_map_of_prim_to_object) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) setattr( @@ -295,7 +347,9 @@ def __init_get_and_return_map_of_prim_to_object(cls, router: fastapi.APIRouter) ) @functools.wraps(cls.get_and_return_map_of_prim_to_object) - def wrapper(*args: typing.Any, **kwargs: typing.Any) -> typing.Dict[str, ObjectWithRequiredField]: + def wrapper( + *args: typing.Any, **kwargs: typing.Any + ) -> typing.Dict[str, ObjectWithRequiredField]: try: return cls.get_and_return_map_of_prim_to_object(*args, **kwargs) except FernHTTPException as e: @@ -314,26 +368,39 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> typing.Dict[str, ObjectW path="/container/map-prim-to-object", response_model=typing.Dict[str, ObjectWithRequiredField], description=AbstractEndpointsContainerService.get_and_return_map_of_prim_to_object.__doc__, - **get_route_args(cls.get_and_return_map_of_prim_to_object, default_tag="endpoints.container"), + **get_route_args( + cls.get_and_return_map_of_prim_to_object, + default_tag="endpoints.container", + ), )(wrapper) @classmethod def __init_get_and_return_optional(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_and_return_optional) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_and_return_optional, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_and_return_optional, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_and_return_optional) - def wrapper(*args: typing.Any, **kwargs: typing.Any) -> typing.Optional[ObjectWithRequiredField]: + def wrapper( + *args: typing.Any, **kwargs: typing.Any + ) -> typing.Optional[ObjectWithRequiredField]: try: return cls.get_and_return_optional(*args, **kwargs) except FernHTTPException as e: @@ -352,5 +419,7 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> typing.Optional[ObjectWi path="/container/opt-objects", response_model=typing.Optional[ObjectWithRequiredField], description=AbstractEndpointsContainerService.get_and_return_optional.__doc__, - **get_route_args(cls.get_and_return_optional, default_tag="endpoints.container"), + **get_route_args( + cls.get_and_return_optional, default_tag="endpoints.container" + ), )(wrapper) diff --git a/seed/fastapi/exhaustive/pydantic-v1/resources/endpoints/resources/enum/service/service.py b/seed/fastapi/exhaustive/pydantic-v1/resources/endpoints/resources/enum/service/service.py index a279991058b..4c665920e0b 100644 --- a/seed/fastapi/exhaustive/pydantic-v1/resources/endpoints/resources/enum/service/service.py +++ b/seed/fastapi/exhaustive/pydantic-v1/resources/endpoints/resources/enum/service/service.py @@ -1,18 +1,17 @@ # This file was auto-generated by Fern from our API Definition. +from ......core.abstract_fern_service import AbstractFernService +from .....types.resources.enum.types.weather_report import WeatherReport +from ......security import ApiAuth import abc -import functools +import fastapi import inspect -import logging import typing - -import fastapi - -from ......core.abstract_fern_service import AbstractFernService +from ......security import FernAuth from ......core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools from ......core.route_args import get_route_args -from ......security import ApiAuth, FernAuth -from .....types.resources.enum.types.weather_report import WeatherReport class AbstractEndpointsEnumService(AbstractFernService): @@ -25,8 +24,9 @@ class AbstractEndpointsEnumService(AbstractFernService): """ @abc.abstractmethod - def get_and_return_enum(self, *, body: WeatherReport, auth: ApiAuth) -> WeatherReport: - ... + def get_and_return_enum( + self, *, body: WeatherReport, auth: ApiAuth + ) -> WeatherReport: ... """ Below are internal methods used by Fern to register your implementation. @@ -41,16 +41,24 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_get_and_return_enum(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_and_return_enum) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_and_return_enum, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_and_return_enum, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_and_return_enum) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> WeatherReport: diff --git a/seed/fastapi/exhaustive/pydantic-v1/resources/endpoints/resources/http_methods/service/service.py b/seed/fastapi/exhaustive/pydantic-v1/resources/endpoints/resources/http_methods/service/service.py index 4ec18085f84..73b65270c55 100644 --- a/seed/fastapi/exhaustive/pydantic-v1/resources/endpoints/resources/http_methods/service/service.py +++ b/seed/fastapi/exhaustive/pydantic-v1/resources/endpoints/resources/http_methods/service/service.py @@ -1,19 +1,22 @@ # This file was auto-generated by Fern from our API Definition. +from ......core.abstract_fern_service import AbstractFernService +from ......security import ApiAuth import abc -import functools +from .....types.resources.object.types.object_with_required_field import ( + ObjectWithRequiredField, +) +from .....types.resources.object.types.object_with_optional_field import ( + ObjectWithOptionalField, +) +import fastapi import inspect -import logging import typing - -import fastapi - -from ......core.abstract_fern_service import AbstractFernService +from ......security import FernAuth from ......core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools from ......core.route_args import get_route_args -from ......security import ApiAuth, FernAuth -from .....types.resources.object.types.object_with_optional_field import ObjectWithOptionalField -from .....types.resources.object.types.object_with_required_field import ObjectWithRequiredField class AbstractEndpointsHttpMethodsService(AbstractFernService): @@ -26,24 +29,25 @@ class AbstractEndpointsHttpMethodsService(AbstractFernService): """ @abc.abstractmethod - def test_get(self, *, id: str, auth: ApiAuth) -> str: - ... + def test_get(self, *, id: str, auth: ApiAuth) -> str: ... @abc.abstractmethod - def test_post(self, *, body: ObjectWithRequiredField, auth: ApiAuth) -> ObjectWithOptionalField: - ... + def test_post( + self, *, body: ObjectWithRequiredField, auth: ApiAuth + ) -> ObjectWithOptionalField: ... @abc.abstractmethod - def test_put(self, *, body: ObjectWithRequiredField, id: str, auth: ApiAuth) -> ObjectWithOptionalField: - ... + def test_put( + self, *, body: ObjectWithRequiredField, id: str, auth: ApiAuth + ) -> ObjectWithOptionalField: ... @abc.abstractmethod - def test_patch(self, *, body: ObjectWithOptionalField, id: str, auth: ApiAuth) -> ObjectWithOptionalField: - ... + def test_patch( + self, *, body: ObjectWithOptionalField, id: str, auth: ApiAuth + ) -> ObjectWithOptionalField: ... @abc.abstractmethod - def test_delete(self, *, id: str, auth: ApiAuth) -> bool: - ... + def test_delete(self, *, id: str, auth: ApiAuth) -> bool: ... """ Below are internal methods used by Fern to register your implementation. @@ -62,16 +66,24 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_test_get(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.test_get) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "id": new_parameters.append(parameter.replace(default=fastapi.Path(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.test_get, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.test_get, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.test_get) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> str: @@ -100,16 +112,24 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> str: def __init_test_post(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.test_post) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.test_post, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.test_post, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.test_post) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> ObjectWithOptionalField: @@ -138,7 +158,9 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> ObjectWithOptionalField: def __init_test_put(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.test_put) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": @@ -146,10 +168,16 @@ def __init_test_put(cls, router: fastapi.APIRouter) -> None: elif parameter_name == "id": new_parameters.append(parameter.replace(default=fastapi.Path(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.test_put, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.test_put, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.test_put) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> ObjectWithOptionalField: @@ -178,7 +206,9 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> ObjectWithOptionalField: def __init_test_patch(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.test_patch) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": @@ -186,10 +216,16 @@ def __init_test_patch(cls, router: fastapi.APIRouter) -> None: elif parameter_name == "id": new_parameters.append(parameter.replace(default=fastapi.Path(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.test_patch, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.test_patch, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.test_patch) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> ObjectWithOptionalField: @@ -218,16 +254,24 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> ObjectWithOptionalField: def __init_test_delete(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.test_delete) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "id": new_parameters.append(parameter.replace(default=fastapi.Path(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.test_delete, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.test_delete, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.test_delete) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> bool: diff --git a/seed/fastapi/exhaustive/pydantic-v1/resources/endpoints/resources/object/service/service.py b/seed/fastapi/exhaustive/pydantic-v1/resources/endpoints/resources/object/service/service.py index b3f2bc65b51..8b73109a788 100644 --- a/seed/fastapi/exhaustive/pydantic-v1/resources/endpoints/resources/object/service/service.py +++ b/seed/fastapi/exhaustive/pydantic-v1/resources/endpoints/resources/object/service/service.py @@ -1,22 +1,29 @@ # This file was auto-generated by Fern from our API Definition. +from ......core.abstract_fern_service import AbstractFernService +from .....types.resources.object.types.object_with_optional_field import ( + ObjectWithOptionalField, +) +from ......security import ApiAuth import abc -import functools -import inspect -import logging +from .....types.resources.object.types.object_with_required_field import ( + ObjectWithRequiredField, +) +from .....types.resources.object.types.object_with_map_of_map import ObjectWithMapOfMap +from .....types.resources.object.types.nested_object_with_optional_field import ( + NestedObjectWithOptionalField, +) +from .....types.resources.object.types.nested_object_with_required_field import ( + NestedObjectWithRequiredField, +) import typing - import fastapi - -from ......core.abstract_fern_service import AbstractFernService +import inspect +from ......security import FernAuth from ......core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools from ......core.route_args import get_route_args -from ......security import ApiAuth, FernAuth -from .....types.resources.object.types.nested_object_with_optional_field import NestedObjectWithOptionalField -from .....types.resources.object.types.nested_object_with_required_field import NestedObjectWithRequiredField -from .....types.resources.object.types.object_with_map_of_map import ObjectWithMapOfMap -from .....types.resources.object.types.object_with_optional_field import ObjectWithOptionalField -from .....types.resources.object.types.object_with_required_field import ObjectWithRequiredField class AbstractEndpointsObjectService(AbstractFernService): @@ -31,36 +38,32 @@ class AbstractEndpointsObjectService(AbstractFernService): @abc.abstractmethod def get_and_return_with_optional_field( self, *, body: ObjectWithOptionalField, auth: ApiAuth - ) -> ObjectWithOptionalField: - ... + ) -> ObjectWithOptionalField: ... @abc.abstractmethod def get_and_return_with_required_field( self, *, body: ObjectWithRequiredField, auth: ApiAuth - ) -> ObjectWithRequiredField: - ... + ) -> ObjectWithRequiredField: ... @abc.abstractmethod - def get_and_return_with_map_of_map(self, *, body: ObjectWithMapOfMap, auth: ApiAuth) -> ObjectWithMapOfMap: - ... + def get_and_return_with_map_of_map( + self, *, body: ObjectWithMapOfMap, auth: ApiAuth + ) -> ObjectWithMapOfMap: ... @abc.abstractmethod def get_and_return_nested_with_optional_field( self, *, body: NestedObjectWithOptionalField, auth: ApiAuth - ) -> NestedObjectWithOptionalField: - ... + ) -> NestedObjectWithOptionalField: ... @abc.abstractmethod def get_and_return_nested_with_required_field( self, *, body: NestedObjectWithRequiredField, string: str, auth: ApiAuth - ) -> NestedObjectWithRequiredField: - ... + ) -> NestedObjectWithRequiredField: ... @abc.abstractmethod def get_and_return_nested_with_required_field_as_list( self, *, body: typing.List[NestedObjectWithRequiredField], auth: ApiAuth - ) -> NestedObjectWithRequiredField: - ... + ) -> NestedObjectWithRequiredField: ... """ Below are internal methods used by Fern to register your implementation. @@ -77,16 +80,22 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: cls.__init_get_and_return_nested_with_required_field_as_list(router=router) @classmethod - def __init_get_and_return_with_optional_field(cls, router: fastapi.APIRouter) -> None: + def __init_get_and_return_with_optional_field( + cls, router: fastapi.APIRouter + ) -> None: endpoint_function = inspect.signature(cls.get_and_return_with_optional_field) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) setattr( @@ -115,20 +124,28 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> ObjectWithOptionalField: path="/object/get-and-return-with-optional-field", response_model=ObjectWithOptionalField, description=AbstractEndpointsObjectService.get_and_return_with_optional_field.__doc__, - **get_route_args(cls.get_and_return_with_optional_field, default_tag="endpoints.object"), + **get_route_args( + cls.get_and_return_with_optional_field, default_tag="endpoints.object" + ), )(wrapper) @classmethod - def __init_get_and_return_with_required_field(cls, router: fastapi.APIRouter) -> None: + def __init_get_and_return_with_required_field( + cls, router: fastapi.APIRouter + ) -> None: endpoint_function = inspect.signature(cls.get_and_return_with_required_field) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) setattr( @@ -157,24 +174,32 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> ObjectWithRequiredField: path="/object/get-and-return-with-required-field", response_model=ObjectWithRequiredField, description=AbstractEndpointsObjectService.get_and_return_with_required_field.__doc__, - **get_route_args(cls.get_and_return_with_required_field, default_tag="endpoints.object"), + **get_route_args( + cls.get_and_return_with_required_field, default_tag="endpoints.object" + ), )(wrapper) @classmethod def __init_get_and_return_with_map_of_map(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_and_return_with_map_of_map) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) setattr( - cls.get_and_return_with_map_of_map, "__signature__", endpoint_function.replace(parameters=new_parameters) + cls.get_and_return_with_map_of_map, + "__signature__", + endpoint_function.replace(parameters=new_parameters), ) @functools.wraps(cls.get_and_return_with_map_of_map) @@ -197,20 +222,30 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> ObjectWithMapOfMap: path="/object/get-and-return-with-map-of-map", response_model=ObjectWithMapOfMap, description=AbstractEndpointsObjectService.get_and_return_with_map_of_map.__doc__, - **get_route_args(cls.get_and_return_with_map_of_map, default_tag="endpoints.object"), + **get_route_args( + cls.get_and_return_with_map_of_map, default_tag="endpoints.object" + ), )(wrapper) @classmethod - def __init_get_and_return_nested_with_optional_field(cls, router: fastapi.APIRouter) -> None: - endpoint_function = inspect.signature(cls.get_and_return_nested_with_optional_field) + def __init_get_and_return_nested_with_optional_field( + cls, router: fastapi.APIRouter + ) -> None: + endpoint_function = inspect.signature( + cls.get_and_return_nested_with_optional_field + ) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) setattr( @@ -220,7 +255,9 @@ def __init_get_and_return_nested_with_optional_field(cls, router: fastapi.APIRou ) @functools.wraps(cls.get_and_return_nested_with_optional_field) - def wrapper(*args: typing.Any, **kwargs: typing.Any) -> NestedObjectWithOptionalField: + def wrapper( + *args: typing.Any, **kwargs: typing.Any + ) -> NestedObjectWithOptionalField: try: return cls.get_and_return_nested_with_optional_field(*args, **kwargs) except FernHTTPException as e: @@ -233,20 +270,31 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> NestedObjectWithOptional # this is necessary for FastAPI to find forward-ref'ed type hints. # https://github.com/tiangolo/fastapi/pull/5077 - wrapper.__globals__.update(cls.get_and_return_nested_with_optional_field.__globals__) + wrapper.__globals__.update( + cls.get_and_return_nested_with_optional_field.__globals__ + ) router.post( path="/object/get-and-return-nested-with-optional-field", response_model=NestedObjectWithOptionalField, description=AbstractEndpointsObjectService.get_and_return_nested_with_optional_field.__doc__, - **get_route_args(cls.get_and_return_nested_with_optional_field, default_tag="endpoints.object"), + **get_route_args( + cls.get_and_return_nested_with_optional_field, + default_tag="endpoints.object", + ), )(wrapper) @classmethod - def __init_get_and_return_nested_with_required_field(cls, router: fastapi.APIRouter) -> None: - endpoint_function = inspect.signature(cls.get_and_return_nested_with_required_field) + def __init_get_and_return_nested_with_required_field( + cls, router: fastapi.APIRouter + ) -> None: + endpoint_function = inspect.signature( + cls.get_and_return_nested_with_required_field + ) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": @@ -254,7 +302,9 @@ def __init_get_and_return_nested_with_required_field(cls, router: fastapi.APIRou elif parameter_name == "string": new_parameters.append(parameter.replace(default=fastapi.Path(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) setattr( @@ -264,7 +314,9 @@ def __init_get_and_return_nested_with_required_field(cls, router: fastapi.APIRou ) @functools.wraps(cls.get_and_return_nested_with_required_field) - def wrapper(*args: typing.Any, **kwargs: typing.Any) -> NestedObjectWithRequiredField: + def wrapper( + *args: typing.Any, **kwargs: typing.Any + ) -> NestedObjectWithRequiredField: try: return cls.get_and_return_nested_with_required_field(*args, **kwargs) except FernHTTPException as e: @@ -277,26 +329,39 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> NestedObjectWithRequired # this is necessary for FastAPI to find forward-ref'ed type hints. # https://github.com/tiangolo/fastapi/pull/5077 - wrapper.__globals__.update(cls.get_and_return_nested_with_required_field.__globals__) + wrapper.__globals__.update( + cls.get_and_return_nested_with_required_field.__globals__ + ) router.post( path="/object/get-and-return-nested-with-required-field/{string}", response_model=NestedObjectWithRequiredField, description=AbstractEndpointsObjectService.get_and_return_nested_with_required_field.__doc__, - **get_route_args(cls.get_and_return_nested_with_required_field, default_tag="endpoints.object"), + **get_route_args( + cls.get_and_return_nested_with_required_field, + default_tag="endpoints.object", + ), )(wrapper) @classmethod - def __init_get_and_return_nested_with_required_field_as_list(cls, router: fastapi.APIRouter) -> None: - endpoint_function = inspect.signature(cls.get_and_return_nested_with_required_field_as_list) + def __init_get_and_return_nested_with_required_field_as_list( + cls, router: fastapi.APIRouter + ) -> None: + endpoint_function = inspect.signature( + cls.get_and_return_nested_with_required_field_as_list + ) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) setattr( @@ -306,9 +371,13 @@ def __init_get_and_return_nested_with_required_field_as_list(cls, router: fastap ) @functools.wraps(cls.get_and_return_nested_with_required_field_as_list) - def wrapper(*args: typing.Any, **kwargs: typing.Any) -> NestedObjectWithRequiredField: + def wrapper( + *args: typing.Any, **kwargs: typing.Any + ) -> NestedObjectWithRequiredField: try: - return cls.get_and_return_nested_with_required_field_as_list(*args, **kwargs) + return cls.get_and_return_nested_with_required_field_as_list( + *args, **kwargs + ) except FernHTTPException as e: logging.getLogger(f"{cls.__module__}.{cls.__name__}").warn( f"Endpoint 'get_and_return_nested_with_required_field_as_list' unexpectedly threw {e.__class__.__name__}. " @@ -319,11 +388,16 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> NestedObjectWithRequired # this is necessary for FastAPI to find forward-ref'ed type hints. # https://github.com/tiangolo/fastapi/pull/5077 - wrapper.__globals__.update(cls.get_and_return_nested_with_required_field_as_list.__globals__) + wrapper.__globals__.update( + cls.get_and_return_nested_with_required_field_as_list.__globals__ + ) router.post( path="/object/get-and-return-nested-with-required-field-list", response_model=NestedObjectWithRequiredField, description=AbstractEndpointsObjectService.get_and_return_nested_with_required_field_as_list.__doc__, - **get_route_args(cls.get_and_return_nested_with_required_field_as_list, default_tag="endpoints.object"), + **get_route_args( + cls.get_and_return_nested_with_required_field_as_list, + default_tag="endpoints.object", + ), )(wrapper) diff --git a/seed/fastapi/exhaustive/pydantic-v1/resources/endpoints/resources/params/service/service.py b/seed/fastapi/exhaustive/pydantic-v1/resources/endpoints/resources/params/service/service.py index a7ae7b277b2..93c809bd4e7 100644 --- a/seed/fastapi/exhaustive/pydantic-v1/resources/endpoints/resources/params/service/service.py +++ b/seed/fastapi/exhaustive/pydantic-v1/resources/endpoints/resources/params/service/service.py @@ -1,18 +1,17 @@ # This file was auto-generated by Fern from our API Definition. +from ......core.abstract_fern_service import AbstractFernService +from ......security import ApiAuth import abc -import functools -import inspect -import logging import typing - import fastapi -import starlette - -from ......core.abstract_fern_service import AbstractFernService +import inspect +from ......security import FernAuth from ......core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools from ......core.route_args import get_route_args -from ......security import ApiAuth, FernAuth +import starlette class AbstractEndpointsParamsService(AbstractFernService): @@ -39,7 +38,9 @@ def get_with_query(self, *, query: str, number: int, auth: ApiAuth) -> None: ... @abc.abstractmethod - def get_with_allow_multiple_query(self, *, query: typing.List[str], numer: typing.List[int], auth: ApiAuth) -> None: + def get_with_allow_multiple_query( + self, *, query: typing.List[str], numer: typing.List[int], auth: ApiAuth + ) -> None: """ GET with multiple of same query param """ @@ -76,16 +77,24 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_get_with_path(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_with_path) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "param": new_parameters.append(parameter.replace(default=fastapi.Path(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_with_path, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_with_path, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_with_path) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> str: @@ -114,18 +123,30 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> str: def __init_get_with_query(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_with_query) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "query": - new_parameters.append(parameter.replace(default=fastapi.Query(default=...))) + new_parameters.append( + parameter.replace(default=fastapi.Query(default=...)) + ) elif parameter_name == "number": - new_parameters.append(parameter.replace(default=fastapi.Query(default=...))) + new_parameters.append( + parameter.replace(default=fastapi.Query(default=...)) + ) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_with_query, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_with_query, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_with_query) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> None: @@ -155,19 +176,29 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> None: def __init_get_with_allow_multiple_query(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_with_allow_multiple_query) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "query": - new_parameters.append(parameter.replace(default=fastapi.Query(default=[]))) + new_parameters.append( + parameter.replace(default=fastapi.Query(default=[])) + ) elif parameter_name == "numer": - new_parameters.append(parameter.replace(default=fastapi.Query(default=[]))) + new_parameters.append( + parameter.replace(default=fastapi.Query(default=[])) + ) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) setattr( - cls.get_with_allow_multiple_query, "__signature__", endpoint_function.replace(parameters=new_parameters) + cls.get_with_allow_multiple_query, + "__signature__", + endpoint_function.replace(parameters=new_parameters), ) @functools.wraps(cls.get_with_allow_multiple_query) @@ -191,25 +222,37 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> None: response_model=None, status_code=starlette.status.HTTP_204_NO_CONTENT, description=AbstractEndpointsParamsService.get_with_allow_multiple_query.__doc__, - **get_route_args(cls.get_with_allow_multiple_query, default_tag="endpoints.params"), + **get_route_args( + cls.get_with_allow_multiple_query, default_tag="endpoints.params" + ), )(wrapper) @classmethod def __init_get_with_path_and_query(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_with_path_and_query) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "param": new_parameters.append(parameter.replace(default=fastapi.Path(...))) elif parameter_name == "query": - new_parameters.append(parameter.replace(default=fastapi.Query(default=...))) + new_parameters.append( + parameter.replace(default=fastapi.Query(default=...)) + ) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_with_path_and_query, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_with_path_and_query, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_with_path_and_query) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> None: @@ -232,14 +275,18 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> None: response_model=None, status_code=starlette.status.HTTP_204_NO_CONTENT, description=AbstractEndpointsParamsService.get_with_path_and_query.__doc__, - **get_route_args(cls.get_with_path_and_query, default_tag="endpoints.params"), + **get_route_args( + cls.get_with_path_and_query, default_tag="endpoints.params" + ), )(wrapper) @classmethod def __init_modify_with_path(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.modify_with_path) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": @@ -247,10 +294,16 @@ def __init_modify_with_path(cls, router: fastapi.APIRouter) -> None: elif parameter_name == "param": new_parameters.append(parameter.replace(default=fastapi.Path(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.modify_with_path, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.modify_with_path, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.modify_with_path) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> str: diff --git a/seed/fastapi/exhaustive/pydantic-v1/resources/endpoints/resources/primitive/service/service.py b/seed/fastapi/exhaustive/pydantic-v1/resources/endpoints/resources/primitive/service/service.py index db7ef44676c..78b3526b630 100644 --- a/seed/fastapi/exhaustive/pydantic-v1/resources/endpoints/resources/primitive/service/service.py +++ b/seed/fastapi/exhaustive/pydantic-v1/resources/endpoints/resources/primitive/service/service.py @@ -1,19 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ......core.abstract_fern_service import AbstractFernService +from ......security import ApiAuth import abc import datetime as dt -import functools -import inspect -import logging -import typing import uuid - import fastapi - -from ......core.abstract_fern_service import AbstractFernService +import inspect +import typing +from ......security import FernAuth from ......core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools from ......core.route_args import get_route_args -from ......security import ApiAuth, FernAuth class AbstractEndpointsPrimitiveService(AbstractFernService): @@ -26,40 +25,33 @@ class AbstractEndpointsPrimitiveService(AbstractFernService): """ @abc.abstractmethod - def get_and_return_string(self, *, body: str, auth: ApiAuth) -> str: - ... + def get_and_return_string(self, *, body: str, auth: ApiAuth) -> str: ... @abc.abstractmethod - def get_and_return_int(self, *, body: int, auth: ApiAuth) -> int: - ... + def get_and_return_int(self, *, body: int, auth: ApiAuth) -> int: ... @abc.abstractmethod - def get_and_return_long(self, *, body: int, auth: ApiAuth) -> int: - ... + def get_and_return_long(self, *, body: int, auth: ApiAuth) -> int: ... @abc.abstractmethod - def get_and_return_double(self, *, body: float, auth: ApiAuth) -> float: - ... + def get_and_return_double(self, *, body: float, auth: ApiAuth) -> float: ... @abc.abstractmethod - def get_and_return_bool(self, *, body: bool, auth: ApiAuth) -> bool: - ... + def get_and_return_bool(self, *, body: bool, auth: ApiAuth) -> bool: ... @abc.abstractmethod - def get_and_return_datetime(self, *, body: dt.datetime, auth: ApiAuth) -> dt.datetime: - ... + def get_and_return_datetime( + self, *, body: dt.datetime, auth: ApiAuth + ) -> dt.datetime: ... @abc.abstractmethod - def get_and_return_date(self, *, body: dt.date, auth: ApiAuth) -> dt.date: - ... + def get_and_return_date(self, *, body: dt.date, auth: ApiAuth) -> dt.date: ... @abc.abstractmethod - def get_and_return_uuid(self, *, body: uuid.UUID, auth: ApiAuth) -> uuid.UUID: - ... + def get_and_return_uuid(self, *, body: uuid.UUID, auth: ApiAuth) -> uuid.UUID: ... @abc.abstractmethod - def get_and_return_base_64(self, *, body: str, auth: ApiAuth) -> str: - ... + def get_and_return_base_64(self, *, body: str, auth: ApiAuth) -> str: ... """ Below are internal methods used by Fern to register your implementation. @@ -82,16 +74,24 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_get_and_return_string(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_and_return_string) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_and_return_string, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_and_return_string, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_and_return_string) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> str: @@ -113,23 +113,33 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> str: path="/primitive/string", response_model=str, description=AbstractEndpointsPrimitiveService.get_and_return_string.__doc__, - **get_route_args(cls.get_and_return_string, default_tag="endpoints.primitive"), + **get_route_args( + cls.get_and_return_string, default_tag="endpoints.primitive" + ), )(wrapper) @classmethod def __init_get_and_return_int(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_and_return_int) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_and_return_int, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_and_return_int, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_and_return_int) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> int: @@ -158,16 +168,24 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> int: def __init_get_and_return_long(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_and_return_long) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_and_return_long, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_and_return_long, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_and_return_long) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> int: @@ -189,23 +207,33 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> int: path="/primitive/long", response_model=int, description=AbstractEndpointsPrimitiveService.get_and_return_long.__doc__, - **get_route_args(cls.get_and_return_long, default_tag="endpoints.primitive"), + **get_route_args( + cls.get_and_return_long, default_tag="endpoints.primitive" + ), )(wrapper) @classmethod def __init_get_and_return_double(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_and_return_double) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_and_return_double, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_and_return_double, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_and_return_double) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> float: @@ -227,23 +255,33 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> float: path="/primitive/double", response_model=float, description=AbstractEndpointsPrimitiveService.get_and_return_double.__doc__, - **get_route_args(cls.get_and_return_double, default_tag="endpoints.primitive"), + **get_route_args( + cls.get_and_return_double, default_tag="endpoints.primitive" + ), )(wrapper) @classmethod def __init_get_and_return_bool(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_and_return_bool) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_and_return_bool, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_and_return_bool, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_and_return_bool) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> bool: @@ -265,23 +303,33 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> bool: path="/primitive/boolean", response_model=bool, description=AbstractEndpointsPrimitiveService.get_and_return_bool.__doc__, - **get_route_args(cls.get_and_return_bool, default_tag="endpoints.primitive"), + **get_route_args( + cls.get_and_return_bool, default_tag="endpoints.primitive" + ), )(wrapper) @classmethod def __init_get_and_return_datetime(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_and_return_datetime) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_and_return_datetime, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_and_return_datetime, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_and_return_datetime) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> dt.datetime: @@ -303,23 +351,33 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> dt.datetime: path="/primitive/datetime", response_model=dt.datetime, description=AbstractEndpointsPrimitiveService.get_and_return_datetime.__doc__, - **get_route_args(cls.get_and_return_datetime, default_tag="endpoints.primitive"), + **get_route_args( + cls.get_and_return_datetime, default_tag="endpoints.primitive" + ), )(wrapper) @classmethod def __init_get_and_return_date(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_and_return_date) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_and_return_date, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_and_return_date, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_and_return_date) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> dt.date: @@ -341,23 +399,33 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> dt.date: path="/primitive/date", response_model=dt.date, description=AbstractEndpointsPrimitiveService.get_and_return_date.__doc__, - **get_route_args(cls.get_and_return_date, default_tag="endpoints.primitive"), + **get_route_args( + cls.get_and_return_date, default_tag="endpoints.primitive" + ), )(wrapper) @classmethod def __init_get_and_return_uuid(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_and_return_uuid) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_and_return_uuid, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_and_return_uuid, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_and_return_uuid) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> uuid.UUID: @@ -379,23 +447,33 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> uuid.UUID: path="/primitive/uuid", response_model=uuid.UUID, description=AbstractEndpointsPrimitiveService.get_and_return_uuid.__doc__, - **get_route_args(cls.get_and_return_uuid, default_tag="endpoints.primitive"), + **get_route_args( + cls.get_and_return_uuid, default_tag="endpoints.primitive" + ), )(wrapper) @classmethod def __init_get_and_return_base_64(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_and_return_base_64) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_and_return_base_64, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_and_return_base_64, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_and_return_base_64) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> str: @@ -417,5 +495,7 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> str: path="/primitive/base64", response_model=str, description=AbstractEndpointsPrimitiveService.get_and_return_base_64.__doc__, - **get_route_args(cls.get_and_return_base_64, default_tag="endpoints.primitive"), + **get_route_args( + cls.get_and_return_base_64, default_tag="endpoints.primitive" + ), )(wrapper) diff --git a/seed/fastapi/exhaustive/pydantic-v1/resources/endpoints/resources/union/service/service.py b/seed/fastapi/exhaustive/pydantic-v1/resources/endpoints/resources/union/service/service.py index 5c026188aca..cc962963db9 100644 --- a/seed/fastapi/exhaustive/pydantic-v1/resources/endpoints/resources/union/service/service.py +++ b/seed/fastapi/exhaustive/pydantic-v1/resources/endpoints/resources/union/service/service.py @@ -1,18 +1,17 @@ # This file was auto-generated by Fern from our API Definition. +from ......core.abstract_fern_service import AbstractFernService +from .....types.resources.union.types.animal import Animal +from ......security import ApiAuth import abc -import functools +import fastapi import inspect -import logging import typing - -import fastapi - -from ......core.abstract_fern_service import AbstractFernService +from ......security import FernAuth from ......core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools from ......core.route_args import get_route_args -from ......security import ApiAuth, FernAuth -from .....types.resources.union.types.animal import Animal class AbstractEndpointsUnionService(AbstractFernService): @@ -25,8 +24,7 @@ class AbstractEndpointsUnionService(AbstractFernService): """ @abc.abstractmethod - def get_and_return_union(self, *, body: Animal, auth: ApiAuth) -> Animal: - ... + def get_and_return_union(self, *, body: Animal, auth: ApiAuth) -> Animal: ... """ Below are internal methods used by Fern to register your implementation. @@ -41,16 +39,24 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_get_and_return_union(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_and_return_union) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_and_return_union, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_and_return_union, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_and_return_union) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> Animal: diff --git a/seed/fastapi/exhaustive/pydantic-v1/resources/general_errors/types/bad_object_request_info.py b/seed/fastapi/exhaustive/pydantic-v1/resources/general_errors/types/bad_object_request_info.py index 08402f7e618..3b4b5d03362 100644 --- a/seed/fastapi/exhaustive/pydantic-v1/resources/general_errors/types/bad_object_request_info.py +++ b/seed/fastapi/exhaustive/pydantic-v1/resources/general_errors/types/bad_object_request_info.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class BadObjectRequestInfo(UniversalBaseModel): message: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/exhaustive/pydantic-v1/resources/inlined_requests/service/post_with_object_body.py b/seed/fastapi/exhaustive/pydantic-v1/resources/inlined_requests/service/post_with_object_body.py index b62587f8d32..647905603ee 100644 --- a/seed/fastapi/exhaustive/pydantic-v1/resources/inlined_requests/service/post_with_object_body.py +++ b/seed/fastapi/exhaustive/pydantic-v1/resources/inlined_requests/service/post_with_object_body.py @@ -1,11 +1,12 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ....core.pydantic_utilities import UniversalBaseModel +from ...types.resources.object.types.object_with_optional_field import ( + ObjectWithOptionalField, +) import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from ...types.resources.object.types.object_with_optional_field import ObjectWithOptionalField +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class PostWithObjectBody(UniversalBaseModel): @@ -14,7 +15,9 @@ class PostWithObjectBody(UniversalBaseModel): nested_object: ObjectWithOptionalField = pydantic.Field(alias="NestedObject") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/exhaustive/pydantic-v1/resources/inlined_requests/service/service.py b/seed/fastapi/exhaustive/pydantic-v1/resources/inlined_requests/service/service.py index 24b6ac5ff85..9894c433149 100644 --- a/seed/fastapi/exhaustive/pydantic-v1/resources/inlined_requests/service/service.py +++ b/seed/fastapi/exhaustive/pydantic-v1/resources/inlined_requests/service/service.py @@ -1,19 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.abstract_fern_service import AbstractFernService +from .post_with_object_body import PostWithObjectBody +from ...types.resources.object.types.object_with_optional_field import ( + ObjectWithOptionalField, +) import abc -import functools +import fastapi import inspect -import logging import typing - -import fastapi - -from ....core.abstract_fern_service import AbstractFernService +from ...general_errors.errors.bad_request_body import BadRequestBody from ....core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools from ....core.route_args import get_route_args -from ...general_errors.errors.bad_request_body import BadRequestBody -from ...types.resources.object.types.object_with_optional_field import ObjectWithOptionalField -from .post_with_object_body import PostWithObjectBody class AbstractInlinedRequestsService(AbstractFernService): @@ -26,7 +26,9 @@ class AbstractInlinedRequestsService(AbstractFernService): """ @abc.abstractmethod - def post_with_object_bodyand_response(self, *, body: PostWithObjectBody) -> ObjectWithOptionalField: + def post_with_object_bodyand_response( + self, *, body: PostWithObjectBody + ) -> ObjectWithOptionalField: """ POST with custom object in request body, response is an object """ @@ -42,10 +44,14 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: cls.__init_post_with_object_bodyand_response(router=router) @classmethod - def __init_post_with_object_bodyand_response(cls, router: fastapi.APIRouter) -> None: + def __init_post_with_object_bodyand_response( + cls, router: fastapi.APIRouter + ) -> None: endpoint_function = inspect.signature(cls.post_with_object_bodyand_response) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": @@ -53,7 +59,9 @@ def __init_post_with_object_bodyand_response(cls, router: fastapi.APIRouter) -> else: new_parameters.append(parameter) setattr( - cls.post_with_object_bodyand_response, "__signature__", endpoint_function.replace(parameters=new_parameters) + cls.post_with_object_bodyand_response, + "__signature__", + endpoint_function.replace(parameters=new_parameters), ) @functools.wraps(cls.post_with_object_bodyand_response) @@ -78,5 +86,7 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> ObjectWithOptionalField: path="/req-bodies/object", response_model=ObjectWithOptionalField, description=AbstractInlinedRequestsService.post_with_object_bodyand_response.__doc__, - **get_route_args(cls.post_with_object_bodyand_response, default_tag="inlined_requests"), + **get_route_args( + cls.post_with_object_bodyand_response, default_tag="inlined_requests" + ), )(wrapper) diff --git a/seed/fastapi/exhaustive/pydantic-v1/resources/no_auth/service/service.py b/seed/fastapi/exhaustive/pydantic-v1/resources/no_auth/service/service.py index 952a7322d89..b0984ae6360 100644 --- a/seed/fastapi/exhaustive/pydantic-v1/resources/no_auth/service/service.py +++ b/seed/fastapi/exhaustive/pydantic-v1/resources/no_auth/service/service.py @@ -1,17 +1,15 @@ # This file was auto-generated by Fern from our API Definition. -import abc -import functools -import inspect -import logging +from ....core.abstract_fern_service import AbstractFernService import typing - +import abc import fastapi - -from ....core.abstract_fern_service import AbstractFernService +import inspect +from ...general_errors.errors.bad_request_body import BadRequestBody from ....core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools from ....core.route_args import get_route_args -from ...general_errors.errors.bad_request_body import BadRequestBody class AbstractNoAuthService(AbstractFernService): @@ -43,14 +41,20 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_post_with_no_auth(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.post_with_no_auth) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) else: new_parameters.append(parameter) - setattr(cls.post_with_no_auth, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.post_with_no_auth, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.post_with_no_auth) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> bool: diff --git a/seed/fastapi/exhaustive/pydantic-v1/resources/no_req_body/service/service.py b/seed/fastapi/exhaustive/pydantic-v1/resources/no_req_body/service/service.py index 09c805cc1c7..40b96353e2d 100644 --- a/seed/fastapi/exhaustive/pydantic-v1/resources/no_req_body/service/service.py +++ b/seed/fastapi/exhaustive/pydantic-v1/resources/no_req_body/service/service.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.abstract_fern_service import AbstractFernService +from ....security import ApiAuth +from ...types.resources.object.types.object_with_optional_field import ( + ObjectWithOptionalField, +) import abc -import functools +import fastapi import inspect -import logging import typing - -import fastapi - -from ....core.abstract_fern_service import AbstractFernService +from ....security import FernAuth from ....core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools from ....core.route_args import get_route_args -from ....security import ApiAuth, FernAuth -from ...types.resources.object.types.object_with_optional_field import ObjectWithOptionalField class AbstractNoReqBodyService(AbstractFernService): @@ -25,12 +26,10 @@ class AbstractNoReqBodyService(AbstractFernService): """ @abc.abstractmethod - def get_with_no_request_body(self, *, auth: ApiAuth) -> ObjectWithOptionalField: - ... + def get_with_no_request_body(self, *, auth: ApiAuth) -> ObjectWithOptionalField: ... @abc.abstractmethod - def post_with_no_request_body(self, *, auth: ApiAuth) -> str: - ... + def post_with_no_request_body(self, *, auth: ApiAuth) -> str: ... """ Below are internal methods used by Fern to register your implementation. @@ -46,14 +45,22 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_get_with_no_request_body(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_with_no_request_body) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_with_no_request_body, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_with_no_request_body, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_with_no_request_body) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> ObjectWithOptionalField: @@ -82,14 +89,22 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> ObjectWithOptionalField: def __init_post_with_no_request_body(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.post_with_no_request_body) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.post_with_no_request_body, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.post_with_no_request_body, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.post_with_no_request_body) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> str: diff --git a/seed/fastapi/exhaustive/pydantic-v1/resources/req_with_headers/service/service.py b/seed/fastapi/exhaustive/pydantic-v1/resources/req_with_headers/service/service.py index 7b31e8311b8..0bb5ea5b04c 100644 --- a/seed/fastapi/exhaustive/pydantic-v1/resources/req_with_headers/service/service.py +++ b/seed/fastapi/exhaustive/pydantic-v1/resources/req_with_headers/service/service.py @@ -1,18 +1,17 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.abstract_fern_service import AbstractFernService +from ....security import ApiAuth import abc -import functools +import fastapi import inspect -import logging import typing - -import fastapi -import starlette - -from ....core.abstract_fern_service import AbstractFernService +from ....security import FernAuth from ....core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools +import starlette from ....core.route_args import get_route_args -from ....security import ApiAuth, FernAuth class AbstractReqWithHeadersService(AbstractFernService): @@ -25,8 +24,9 @@ class AbstractReqWithHeadersService(AbstractFernService): """ @abc.abstractmethod - def get_with_custom_header(self, *, body: str, x_test_endpoint_header: str, auth: ApiAuth) -> None: - ... + def get_with_custom_header( + self, *, body: str, x_test_endpoint_header: str, auth: ApiAuth + ) -> None: ... """ Below are internal methods used by Fern to register your implementation. @@ -41,18 +41,30 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_get_with_custom_header(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_with_custom_header) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "x_test_endpoint_header": - new_parameters.append(parameter.replace(default=fastapi.Header(alias="X-TEST-ENDPOINT-HEADER"))) + new_parameters.append( + parameter.replace( + default=fastapi.Header(alias="X-TEST-ENDPOINT-HEADER") + ) + ) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_with_custom_header, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_with_custom_header, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_with_custom_header) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> None: @@ -75,5 +87,7 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> None: response_model=None, status_code=starlette.status.HTTP_204_NO_CONTENT, description=AbstractReqWithHeadersService.get_with_custom_header.__doc__, - **get_route_args(cls.get_with_custom_header, default_tag="req_with_headers"), + **get_route_args( + cls.get_with_custom_header, default_tag="req_with_headers" + ), )(wrapper) diff --git a/seed/fastapi/exhaustive/pydantic-v1/resources/types/resources/object/errors/nested_object_with_optional_field_error.py b/seed/fastapi/exhaustive/pydantic-v1/resources/types/resources/object/errors/nested_object_with_optional_field_error.py index 3ba440b272a..8ccad4823e1 100644 --- a/seed/fastapi/exhaustive/pydantic-v1/resources/types/resources/object/errors/nested_object_with_optional_field_error.py +++ b/seed/fastapi/exhaustive/pydantic-v1/resources/types/resources/object/errors/nested_object_with_optional_field_error.py @@ -6,4 +6,6 @@ class NestedObjectWithOptionalFieldError(FernHTTPException): def __init__(self, error: NestedObjectWithOptionalField): - super().__init__(status_code=400, name="NestedObjectWithOptionalFieldError", content=error) + super().__init__( + status_code=400, name="NestedObjectWithOptionalFieldError", content=error + ) diff --git a/seed/fastapi/exhaustive/pydantic-v1/resources/types/resources/object/errors/nested_object_with_required_field_error.py b/seed/fastapi/exhaustive/pydantic-v1/resources/types/resources/object/errors/nested_object_with_required_field_error.py index 10b5e850066..d328ecaf35e 100644 --- a/seed/fastapi/exhaustive/pydantic-v1/resources/types/resources/object/errors/nested_object_with_required_field_error.py +++ b/seed/fastapi/exhaustive/pydantic-v1/resources/types/resources/object/errors/nested_object_with_required_field_error.py @@ -6,4 +6,6 @@ class NestedObjectWithRequiredFieldError(FernHTTPException): def __init__(self, error: NestedObjectWithRequiredField): - super().__init__(status_code=400, name="NestedObjectWithRequiredFieldError", content=error) + super().__init__( + status_code=400, name="NestedObjectWithRequiredFieldError", content=error + ) diff --git a/seed/fastapi/exhaustive/pydantic-v1/resources/types/resources/object/errors/object_with_optional_field_error.py b/seed/fastapi/exhaustive/pydantic-v1/resources/types/resources/object/errors/object_with_optional_field_error.py index 09a92f4c466..1205d252c69 100644 --- a/seed/fastapi/exhaustive/pydantic-v1/resources/types/resources/object/errors/object_with_optional_field_error.py +++ b/seed/fastapi/exhaustive/pydantic-v1/resources/types/resources/object/errors/object_with_optional_field_error.py @@ -6,4 +6,6 @@ class ObjectWithOptionalFieldError(FernHTTPException): def __init__(self, error: ObjectWithOptionalField): - super().__init__(status_code=400, name="ObjectWithOptionalFieldError", content=error) + super().__init__( + status_code=400, name="ObjectWithOptionalFieldError", content=error + ) diff --git a/seed/fastapi/exhaustive/pydantic-v1/resources/types/resources/object/errors/object_with_required_field_error.py b/seed/fastapi/exhaustive/pydantic-v1/resources/types/resources/object/errors/object_with_required_field_error.py index c0c5cc11812..53045a6279e 100644 --- a/seed/fastapi/exhaustive/pydantic-v1/resources/types/resources/object/errors/object_with_required_field_error.py +++ b/seed/fastapi/exhaustive/pydantic-v1/resources/types/resources/object/errors/object_with_required_field_error.py @@ -6,4 +6,6 @@ class ObjectWithRequiredFieldError(FernHTTPException): def __init__(self, error: ObjectWithRequiredField): - super().__init__(status_code=400, name="ObjectWithRequiredFieldError", content=error) + super().__init__( + status_code=400, name="ObjectWithRequiredFieldError", content=error + ) diff --git a/seed/fastapi/exhaustive/pydantic-v1/resources/types/resources/object/types/double_optional.py b/seed/fastapi/exhaustive/pydantic-v1/resources/types/resources/object/types/double_optional.py index 496516e1c7e..055935ee32e 100644 --- a/seed/fastapi/exhaustive/pydantic-v1/resources/types/resources/object/types/double_optional.py +++ b/seed/fastapi/exhaustive/pydantic-v1/resources/types/resources/object/types/double_optional.py @@ -1,18 +1,21 @@ # This file was auto-generated by Fern from our API Definition. +from ......core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .optional_alias import OptionalAlias +import pydantic +from ......core.pydantic_utilities import IS_PYDANTIC_V2 class DoubleOptional(UniversalBaseModel): - optional_alias: typing.Optional[OptionalAlias] = pydantic.Field(alias="optionalAlias", default=None) + optional_alias: typing.Optional[OptionalAlias] = pydantic.Field( + alias="optionalAlias", default=None + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/exhaustive/pydantic-v1/resources/types/resources/object/types/nested_object_with_optional_field.py b/seed/fastapi/exhaustive/pydantic-v1/resources/types/resources/object/types/nested_object_with_optional_field.py index ed1a24559d4..15fff182ee9 100644 --- a/seed/fastapi/exhaustive/pydantic-v1/resources/types/resources/object/types/nested_object_with_optional_field.py +++ b/seed/fastapi/exhaustive/pydantic-v1/resources/types/resources/object/types/nested_object_with_optional_field.py @@ -1,19 +1,22 @@ # This file was auto-generated by Fern from our API Definition. +from ......core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .object_with_optional_field import ObjectWithOptionalField +import pydantic +from ......core.pydantic_utilities import IS_PYDANTIC_V2 class NestedObjectWithOptionalField(UniversalBaseModel): string: typing.Optional[str] = None - nested_object: typing.Optional[ObjectWithOptionalField] = pydantic.Field(alias="NestedObject", default=None) + nested_object: typing.Optional[ObjectWithOptionalField] = pydantic.Field( + alias="NestedObject", default=None + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/exhaustive/pydantic-v1/resources/types/resources/object/types/nested_object_with_required_field.py b/seed/fastapi/exhaustive/pydantic-v1/resources/types/resources/object/types/nested_object_with_required_field.py index 9f1da7f2b69..c152f7caf34 100644 --- a/seed/fastapi/exhaustive/pydantic-v1/resources/types/resources/object/types/nested_object_with_required_field.py +++ b/seed/fastapi/exhaustive/pydantic-v1/resources/types/resources/object/types/nested_object_with_required_field.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ......core.pydantic_utilities import UniversalBaseModel from .object_with_optional_field import ObjectWithOptionalField +import pydantic +from ......core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class NestedObjectWithRequiredField(UniversalBaseModel): @@ -13,7 +12,9 @@ class NestedObjectWithRequiredField(UniversalBaseModel): nested_object: ObjectWithOptionalField = pydantic.Field(alias="NestedObject") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/exhaustive/pydantic-v1/resources/types/resources/object/types/object_with_map_of_map.py b/seed/fastapi/exhaustive/pydantic-v1/resources/types/resources/object/types/object_with_map_of_map.py index aba295a1e88..259d15f900b 100644 --- a/seed/fastapi/exhaustive/pydantic-v1/resources/types/resources/object/types/object_with_map_of_map.py +++ b/seed/fastapi/exhaustive/pydantic-v1/resources/types/resources/object/types/object_with_map_of_map.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ......core.pydantic_utilities import UniversalBaseModel import typing - import pydantic - -from ......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ......core.pydantic_utilities import IS_PYDANTIC_V2 class ObjectWithMapOfMap(UniversalBaseModel): map_: typing.Dict[str, typing.Dict[str, str]] = pydantic.Field(alias="map") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/exhaustive/pydantic-v1/resources/types/resources/object/types/object_with_optional_field.py b/seed/fastapi/exhaustive/pydantic-v1/resources/types/resources/object/types/object_with_optional_field.py index eb3565c51a2..b8d37eb85ef 100644 --- a/seed/fastapi/exhaustive/pydantic-v1/resources/types/resources/object/types/object_with_optional_field.py +++ b/seed/fastapi/exhaustive/pydantic-v1/resources/types/resources/object/types/object_with_optional_field.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. -import datetime as dt +from ......core.pydantic_utilities import UniversalBaseModel import typing -import uuid - import pydantic - -from ......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +import datetime as dt +import uuid +from ......core.pydantic_utilities import IS_PYDANTIC_V2 class ObjectWithOptionalField(UniversalBaseModel): @@ -23,13 +22,19 @@ class ObjectWithOptionalField(UniversalBaseModel): date: typing.Optional[dt.date] = None uuid_: typing.Optional[uuid.UUID] = pydantic.Field(alias="uuid", default=None) base_64: typing.Optional[str] = pydantic.Field(alias="base64", default=None) - list_: typing.Optional[typing.List[str]] = pydantic.Field(alias="list", default=None) + list_: typing.Optional[typing.List[str]] = pydantic.Field( + alias="list", default=None + ) set_: typing.Optional[typing.Set[str]] = pydantic.Field(alias="set", default=None) - map_: typing.Optional[typing.Dict[int, str]] = pydantic.Field(alias="map", default=None) + map_: typing.Optional[typing.Dict[int, str]] = pydantic.Field( + alias="map", default=None + ) bigint: typing.Optional[str] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/exhaustive/pydantic-v1/resources/types/resources/object/types/object_with_required_field.py b/seed/fastapi/exhaustive/pydantic-v1/resources/types/resources/object/types/object_with_required_field.py index 20aee4fa01f..460dec359be 100644 --- a/seed/fastapi/exhaustive/pydantic-v1/resources/types/resources/object/types/object_with_required_field.py +++ b/seed/fastapi/exhaustive/pydantic-v1/resources/types/resources/object/types/object_with_required_field.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ......core.pydantic_utilities import UniversalBaseModel +from ......core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class ObjectWithRequiredField(UniversalBaseModel): string: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/exhaustive/pydantic-v1/resources/types/resources/union/types/animal.py b/seed/fastapi/exhaustive/pydantic-v1/resources/types/resources/union/types/animal.py index 74285020765..a8ee74c09ed 100644 --- a/seed/fastapi/exhaustive/pydantic-v1/resources/types/resources/union/types/animal.py +++ b/seed/fastapi/exhaustive/pydantic-v1/resources/types/resources/union/types/animal.py @@ -1,15 +1,14 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from .dog import Dog as resources_types_resources_union_types_dog_Dog +from ......core.pydantic_utilities import IS_PYDANTIC_V2 +from .cat import Cat as resources_types_resources_union_types_cat_Cat +from ......core.pydantic_utilities import UniversalRootModel import typing - -import pydantic import typing_extensions - -from ......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalRootModel, update_forward_refs -from .cat import Cat as resources_types_resources_union_types_cat_Cat -from .dog import Dog as resources_types_resources_union_types_dog_Dog +import pydantic +from ......core.pydantic_utilities import update_forward_refs T_Result = typing.TypeVar("T_Result") @@ -17,15 +16,23 @@ class _Factory: def dog(self, value: resources_types_resources_union_types_dog_Dog) -> Animal: if IS_PYDANTIC_V2: - return Animal(root=_Animal.Dog(**value.dict(exclude_unset=True), animal="dog")) + return Animal( + root=_Animal.Dog(**value.dict(exclude_unset=True), animal="dog") + ) else: - return Animal(__root__=_Animal.Dog(**value.dict(exclude_unset=True), animal="dog")) + return Animal( + __root__=_Animal.Dog(**value.dict(exclude_unset=True), animal="dog") + ) def cat(self, value: resources_types_resources_union_types_cat_Cat) -> Animal: if IS_PYDANTIC_V2: - return Animal(root=_Animal.Cat(**value.dict(exclude_unset=True), animal="cat")) + return Animal( + root=_Animal.Cat(**value.dict(exclude_unset=True), animal="cat") + ) else: - return Animal(__root__=_Animal.Cat(**value.dict(exclude_unset=True), animal="cat")) + return Animal( + __root__=_Animal.Cat(**value.dict(exclude_unset=True), animal="cat") + ) class Animal(UniversalRootModel): @@ -33,15 +40,16 @@ class Animal(UniversalRootModel): if IS_PYDANTIC_V2: root: typing_extensions.Annotated[ - typing.Union[_Animal.Dog, _Animal.Cat], pydantic.Field(discriminator="animal") + typing.Union[_Animal.Dog, _Animal.Cat], + pydantic.Field(discriminator="animal"), ] def get_as_union(self) -> typing.Union[_Animal.Dog, _Animal.Cat]: return self.root - else: __root__: typing_extensions.Annotated[ - typing.Union[_Animal.Dog, _Animal.Cat], pydantic.Field(discriminator="animal") + typing.Union[_Animal.Dog, _Animal.Cat], + pydantic.Field(discriminator="animal"), ] def get_as_union(self) -> typing.Union[_Animal.Dog, _Animal.Cat]: diff --git a/seed/fastapi/exhaustive/pydantic-v1/resources/types/resources/union/types/cat.py b/seed/fastapi/exhaustive/pydantic-v1/resources/types/resources/union/types/cat.py index 2436a0fd384..cdcfe7a1d25 100644 --- a/seed/fastapi/exhaustive/pydantic-v1/resources/types/resources/union/types/cat.py +++ b/seed/fastapi/exhaustive/pydantic-v1/resources/types/resources/union/types/cat.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ......core.pydantic_utilities import UniversalBaseModel import pydantic - -from ......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ......core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class Cat(UniversalBaseModel): @@ -12,7 +11,9 @@ class Cat(UniversalBaseModel): likes_to_meow: bool = pydantic.Field(alias="likesToMeow") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/exhaustive/pydantic-v1/resources/types/resources/union/types/dog.py b/seed/fastapi/exhaustive/pydantic-v1/resources/types/resources/union/types/dog.py index 3afc51b5137..b5feda1e61c 100644 --- a/seed/fastapi/exhaustive/pydantic-v1/resources/types/resources/union/types/dog.py +++ b/seed/fastapi/exhaustive/pydantic-v1/resources/types/resources/union/types/dog.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ......core.pydantic_utilities import UniversalBaseModel import pydantic - -from ......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ......core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class Dog(UniversalBaseModel): @@ -12,7 +11,9 @@ class Dog(UniversalBaseModel): likes_to_woof: bool = pydantic.Field(alias="likesToWoof") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/exhaustive/pydantic-v1/security.py b/seed/fastapi/exhaustive/pydantic-v1/security.py index bab014441e1..4ccabc21106 100644 --- a/seed/fastapi/exhaustive/pydantic-v1/security.py +++ b/seed/fastapi/exhaustive/pydantic-v1/security.py @@ -1,8 +1,8 @@ # This file was auto-generated by Fern from our API Definition. +from .core.security.bearer import BearerToken import fastapi - -from .core.security.bearer import BearerToken, HTTPBearer +from .core.security.bearer import HTTPBearer ApiAuth = BearerToken diff --git a/seed/fastapi/exhaustive/pydantic-v2/__init__.py b/seed/fastapi/exhaustive/pydantic-v2/__init__.py index 2679cde4830..6eda4b194c2 100644 --- a/seed/fastapi/exhaustive/pydantic-v2/__init__.py +++ b/seed/fastapi/exhaustive/pydantic-v2/__init__.py @@ -1,6 +1,13 @@ # This file was auto-generated by Fern from our API Definition. -from .resources import BadObjectRequestInfo, BadRequestBody, PostWithObjectBody, general_errors, inlined_requests, types +from .resources import ( + BadObjectRequestInfo, + BadRequestBody, + PostWithObjectBody, + general_errors, + inlined_requests, + types, +) from .security import ApiAuth __all__ = [ diff --git a/seed/fastapi/exhaustive/pydantic-v2/core/abstract_fern_service.py b/seed/fastapi/exhaustive/pydantic-v2/core/abstract_fern_service.py index da7c8dc49c4..9966b4876da 100644 --- a/seed/fastapi/exhaustive/pydantic-v2/core/abstract_fern_service.py +++ b/seed/fastapi/exhaustive/pydantic-v2/core/abstract_fern_service.py @@ -7,5 +7,4 @@ class AbstractFernService(abc.ABC): @classmethod - def _init_fern(cls, router: fastapi.APIRouter) -> None: - ... + def _init_fern(cls, router: fastapi.APIRouter) -> None: ... diff --git a/seed/fastapi/exhaustive/pydantic-v2/core/datetime_utils.py b/seed/fastapi/exhaustive/pydantic-v2/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/fastapi/exhaustive/pydantic-v2/core/datetime_utils.py +++ b/seed/fastapi/exhaustive/pydantic-v2/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/fastapi/exhaustive/pydantic-v2/core/exceptions/__init__.py b/seed/fastapi/exhaustive/pydantic-v2/core/exceptions/__init__.py index 297d6e06f5f..dae4b8980c1 100644 --- a/seed/fastapi/exhaustive/pydantic-v2/core/exceptions/__init__.py +++ b/seed/fastapi/exhaustive/pydantic-v2/core/exceptions/__init__.py @@ -1,7 +1,11 @@ # This file was auto-generated by Fern from our API Definition. from .fern_http_exception import FernHTTPException -from .handlers import default_exception_handler, fern_http_exception_handler, http_exception_handler +from .handlers import ( + default_exception_handler, + fern_http_exception_handler, + http_exception_handler, +) from .unauthorized import UnauthorizedException __all__ = [ diff --git a/seed/fastapi/exhaustive/pydantic-v2/core/exceptions/fern_http_exception.py b/seed/fastapi/exhaustive/pydantic-v2/core/exceptions/fern_http_exception.py index bdf03862487..81610359a7f 100644 --- a/seed/fastapi/exhaustive/pydantic-v2/core/exceptions/fern_http_exception.py +++ b/seed/fastapi/exhaustive/pydantic-v2/core/exceptions/fern_http_exception.py @@ -1,14 +1,16 @@ # This file was auto-generated by Fern from our API Definition. import abc -import typing - import fastapi +import typing class FernHTTPException(abc.ABC, fastapi.HTTPException): def __init__( - self, status_code: int, name: typing.Optional[str] = None, content: typing.Optional[typing.Any] = None + self, + status_code: int, + name: typing.Optional[str] = None, + content: typing.Optional[typing.Any] = None, ): super().__init__(status_code=status_code) self.name = name @@ -17,4 +19,6 @@ def __init__( def to_json_response(self) -> fastapi.responses.JSONResponse: content = fastapi.encoders.jsonable_encoder(self.content, exclude_none=True) - return fastapi.responses.JSONResponse(content=content, status_code=self.status_code) + return fastapi.responses.JSONResponse( + content=content, status_code=self.status_code + ) diff --git a/seed/fastapi/exhaustive/pydantic-v2/core/exceptions/handlers.py b/seed/fastapi/exhaustive/pydantic-v2/core/exceptions/handlers.py index 6d8c4155c5a..ae1c2741f06 100644 --- a/seed/fastapi/exhaustive/pydantic-v2/core/exceptions/handlers.py +++ b/seed/fastapi/exhaustive/pydantic-v2/core/exceptions/handlers.py @@ -2,32 +2,49 @@ import logging -import fastapi import starlette import starlette.exceptions +import fastapi + from .fern_http_exception import FernHTTPException def fern_http_exception_handler( - request: fastapi.requests.Request, exc: FernHTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: FernHTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) return exc.to_json_response() def http_exception_handler( - request: fastapi.requests.Request, exc: starlette.exceptions.HTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: starlette.exceptions.HTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=exc.status_code, content=exc.detail).to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=exc.status_code, content=exc.detail + ).to_json_response() def default_exception_handler( - request: fastapi.requests.Request, exc: Exception, skip_log: bool = False + request: fastapi.requests.Request, + exc: Exception, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=500, content="Internal Server Error").to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=500, content="Internal Server Error" + ).to_json_response() diff --git a/seed/fastapi/exhaustive/pydantic-v2/core/pydantic_utilities.py b/seed/fastapi/exhaustive/pydantic-v2/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/fastapi/exhaustive/pydantic-v2/core/pydantic_utilities.py +++ b/seed/fastapi/exhaustive/pydantic-v2/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/fastapi/exhaustive/pydantic-v2/core/route_args.py b/seed/fastapi/exhaustive/pydantic-v2/core/route_args.py index 4228e2fe05d..bd940bf4ddd 100644 --- a/seed/fastapi/exhaustive/pydantic-v2/core/route_args.py +++ b/seed/fastapi/exhaustive/pydantic-v2/core/route_args.py @@ -20,9 +20,15 @@ class RouteArgs(typing_extensions.TypedDict): DEFAULT_ROUTE_ARGS = RouteArgs(openapi_extra=None, tags=None, include_in_schema=True) -def get_route_args(endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str) -> RouteArgs: - unwrapped = inspect.unwrap(endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY))) - route_args = typing.cast(RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS)) +def get_route_args( + endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str +) -> RouteArgs: + unwrapped = inspect.unwrap( + endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY)) + ) + route_args = typing.cast( + RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS) + ) if route_args["tags"] is None: return RouteArgs( openapi_extra=route_args["openapi_extra"], @@ -56,7 +62,11 @@ def decorator(endpoint_function: T) -> T: setattr( endpoint_function, FERN_CONFIG_KEY, - RouteArgs(openapi_extra=openapi_extra, tags=tags, include_in_schema=include_in_schema), + RouteArgs( + openapi_extra=openapi_extra, + tags=tags, + include_in_schema=include_in_schema, + ), ) return endpoint_function diff --git a/seed/fastapi/exhaustive/pydantic-v2/register.py b/seed/fastapi/exhaustive/pydantic-v2/register.py index be0c42bf3f9..1f804567f73 100644 --- a/seed/fastapi/exhaustive/pydantic-v2/register.py +++ b/seed/fastapi/exhaustive/pydantic-v2/register.py @@ -1,29 +1,43 @@ # This file was auto-generated by Fern from our API Definition. -import glob -import importlib -import os -import types -import typing - import fastapi -import starlette.exceptions -from fastapi import params - -from .core.abstract_fern_service import AbstractFernService -from .core.exceptions import default_exception_handler, fern_http_exception_handler, http_exception_handler -from .core.exceptions.fern_http_exception import FernHTTPException -from .resources.endpoints.resources.container.service.service import AbstractEndpointsContainerService -from .resources.endpoints.resources.enum.service.service import AbstractEndpointsEnumService -from .resources.endpoints.resources.http_methods.service.service import AbstractEndpointsHttpMethodsService -from .resources.endpoints.resources.object.service.service import AbstractEndpointsObjectService -from .resources.endpoints.resources.params.service.service import AbstractEndpointsParamsService -from .resources.endpoints.resources.primitive.service.service import AbstractEndpointsPrimitiveService -from .resources.endpoints.resources.union.service.service import AbstractEndpointsUnionService +from .resources.endpoints.resources.container.service.service import ( + AbstractEndpointsContainerService, +) +from .resources.endpoints.resources.enum.service.service import ( + AbstractEndpointsEnumService, +) +from .resources.endpoints.resources.http_methods.service.service import ( + AbstractEndpointsHttpMethodsService, +) +from .resources.endpoints.resources.object.service.service import ( + AbstractEndpointsObjectService, +) +from .resources.endpoints.resources.params.service.service import ( + AbstractEndpointsParamsService, +) +from .resources.endpoints.resources.primitive.service.service import ( + AbstractEndpointsPrimitiveService, +) +from .resources.endpoints.resources.union.service.service import ( + AbstractEndpointsUnionService, +) from .resources.inlined_requests.service.service import AbstractInlinedRequestsService from .resources.no_auth.service.service import AbstractNoAuthService from .resources.no_req_body.service.service import AbstractNoReqBodyService from .resources.req_with_headers.service.service import AbstractReqWithHeadersService +import typing +from fastapi import params +from .core.exceptions.fern_http_exception import FernHTTPException +from .core.exceptions import fern_http_exception_handler +import starlette.exceptions +from .core.exceptions import http_exception_handler +from .core.exceptions import default_exception_handler +from .core.abstract_fern_service import AbstractFernService +import types +import os +import glob +import importlib def register( @@ -40,14 +54,20 @@ def register( no_auth: AbstractNoAuthService, no_req_body: AbstractNoReqBodyService, req_with_headers: AbstractReqWithHeadersService, - dependencies: typing.Optional[typing.Sequence[params.Depends]] = None + dependencies: typing.Optional[typing.Sequence[params.Depends]] = None, ) -> None: - _app.include_router(__register_service(endpoints_container), dependencies=dependencies) + _app.include_router( + __register_service(endpoints_container), dependencies=dependencies + ) _app.include_router(__register_service(endpoints_enum), dependencies=dependencies) - _app.include_router(__register_service(endpoints_http_methods), dependencies=dependencies) + _app.include_router( + __register_service(endpoints_http_methods), dependencies=dependencies + ) _app.include_router(__register_service(endpoints_object), dependencies=dependencies) _app.include_router(__register_service(endpoints_params), dependencies=dependencies) - _app.include_router(__register_service(endpoints_primitive), dependencies=dependencies) + _app.include_router( + __register_service(endpoints_primitive), dependencies=dependencies + ) _app.include_router(__register_service(endpoints_union), dependencies=dependencies) _app.include_router(__register_service(inlined_requests), dependencies=dependencies) _app.include_router(__register_service(no_auth), dependencies=dependencies) @@ -55,7 +75,9 @@ def register( _app.include_router(__register_service(req_with_headers), dependencies=dependencies) _app.add_exception_handler(FernHTTPException, fern_http_exception_handler) # type: ignore - _app.add_exception_handler(starlette.exceptions.HTTPException, http_exception_handler) # type: ignore + _app.add_exception_handler( + starlette.exceptions.HTTPException, http_exception_handler + ) # type: ignore _app.add_exception_handler(Exception, default_exception_handler) # type: ignore @@ -67,7 +89,9 @@ def __register_service(service: AbstractFernService) -> fastapi.APIRouter: def register_validators(module: types.ModuleType) -> None: validators_directory: str = os.path.dirname(module.__file__) # type: ignore - for path in glob.glob(os.path.join(validators_directory, "**/*.py"), recursive=True): + for path in glob.glob( + os.path.join(validators_directory, "**/*.py"), recursive=True + ): if os.path.isfile(path): relative_path = os.path.relpath(path, start=validators_directory) module_path = ".".join([module.__name__] + relative_path[:-3].split("/")) diff --git a/seed/fastapi/exhaustive/pydantic-v2/resources/endpoints/resources/container/service/service.py b/seed/fastapi/exhaustive/pydantic-v2/resources/endpoints/resources/container/service/service.py index af2cbf4be28..79da48ea0cc 100644 --- a/seed/fastapi/exhaustive/pydantic-v2/resources/endpoints/resources/container/service/service.py +++ b/seed/fastapi/exhaustive/pydantic-v2/resources/endpoints/resources/container/service/service.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. -import abc -import functools -import inspect -import logging +from ......core.abstract_fern_service import AbstractFernService import typing - +from ......security import ApiAuth +import abc +from .....types.resources.object.types.object_with_required_field import ( + ObjectWithRequiredField, +) import fastapi - -from ......core.abstract_fern_service import AbstractFernService +import inspect +from ......security import FernAuth from ......core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools from ......core.route_args import get_route_args -from ......security import ApiAuth, FernAuth -from .....types.resources.object.types.object_with_required_field import ObjectWithRequiredField class AbstractEndpointsContainerService(AbstractFernService): @@ -25,40 +26,39 @@ class AbstractEndpointsContainerService(AbstractFernService): """ @abc.abstractmethod - def get_and_return_list_of_primitives(self, *, body: typing.List[str], auth: ApiAuth) -> typing.Sequence[str]: - ... + def get_and_return_list_of_primitives( + self, *, body: typing.List[str], auth: ApiAuth + ) -> typing.Sequence[str]: ... @abc.abstractmethod def get_and_return_list_of_objects( self, *, body: typing.List[ObjectWithRequiredField], auth: ApiAuth - ) -> typing.Sequence[ObjectWithRequiredField]: - ... + ) -> typing.Sequence[ObjectWithRequiredField]: ... @abc.abstractmethod - def get_and_return_set_of_primitives(self, *, body: typing.Set[str], auth: ApiAuth) -> typing.Set[str]: - ... + def get_and_return_set_of_primitives( + self, *, body: typing.Set[str], auth: ApiAuth + ) -> typing.Set[str]: ... @abc.abstractmethod def get_and_return_set_of_objects( self, *, body: typing.List[ObjectWithRequiredField], auth: ApiAuth - ) -> typing.Sequence[ObjectWithRequiredField]: - ... + ) -> typing.Sequence[ObjectWithRequiredField]: ... @abc.abstractmethod - def get_and_return_map_prim_to_prim(self, *, body: typing.Dict[str, str], auth: ApiAuth) -> typing.Dict[str, str]: - ... + def get_and_return_map_prim_to_prim( + self, *, body: typing.Dict[str, str], auth: ApiAuth + ) -> typing.Dict[str, str]: ... @abc.abstractmethod def get_and_return_map_of_prim_to_object( self, *, body: typing.Dict[str, ObjectWithRequiredField], auth: ApiAuth - ) -> typing.Dict[str, ObjectWithRequiredField]: - ... + ) -> typing.Dict[str, ObjectWithRequiredField]: ... @abc.abstractmethod def get_and_return_optional( self, *, body: typing.Optional[ObjectWithRequiredField] = None, auth: ApiAuth - ) -> typing.Optional[ObjectWithRequiredField]: - ... + ) -> typing.Optional[ObjectWithRequiredField]: ... """ Below are internal methods used by Fern to register your implementation. @@ -76,20 +76,28 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: cls.__init_get_and_return_optional(router=router) @classmethod - def __init_get_and_return_list_of_primitives(cls, router: fastapi.APIRouter) -> None: + def __init_get_and_return_list_of_primitives( + cls, router: fastapi.APIRouter + ) -> None: endpoint_function = inspect.signature(cls.get_and_return_list_of_primitives) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) setattr( - cls.get_and_return_list_of_primitives, "__signature__", endpoint_function.replace(parameters=new_parameters) + cls.get_and_return_list_of_primitives, + "__signature__", + endpoint_function.replace(parameters=new_parameters), ) @functools.wraps(cls.get_and_return_list_of_primitives) @@ -112,28 +120,38 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> typing.Sequence[str]: path="/container/list-of-primitives", response_model=typing.Sequence[str], description=AbstractEndpointsContainerService.get_and_return_list_of_primitives.__doc__, - **get_route_args(cls.get_and_return_list_of_primitives, default_tag="endpoints.container"), + **get_route_args( + cls.get_and_return_list_of_primitives, default_tag="endpoints.container" + ), )(wrapper) @classmethod def __init_get_and_return_list_of_objects(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_and_return_list_of_objects) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) setattr( - cls.get_and_return_list_of_objects, "__signature__", endpoint_function.replace(parameters=new_parameters) + cls.get_and_return_list_of_objects, + "__signature__", + endpoint_function.replace(parameters=new_parameters), ) @functools.wraps(cls.get_and_return_list_of_objects) - def wrapper(*args: typing.Any, **kwargs: typing.Any) -> typing.Sequence[ObjectWithRequiredField]: + def wrapper( + *args: typing.Any, **kwargs: typing.Any + ) -> typing.Sequence[ObjectWithRequiredField]: try: return cls.get_and_return_list_of_objects(*args, **kwargs) except FernHTTPException as e: @@ -152,24 +170,32 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> typing.Sequence[ObjectWi path="/container/list-of-objects", response_model=typing.Sequence[ObjectWithRequiredField], description=AbstractEndpointsContainerService.get_and_return_list_of_objects.__doc__, - **get_route_args(cls.get_and_return_list_of_objects, default_tag="endpoints.container"), + **get_route_args( + cls.get_and_return_list_of_objects, default_tag="endpoints.container" + ), )(wrapper) @classmethod def __init_get_and_return_set_of_primitives(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_and_return_set_of_primitives) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) setattr( - cls.get_and_return_set_of_primitives, "__signature__", endpoint_function.replace(parameters=new_parameters) + cls.get_and_return_set_of_primitives, + "__signature__", + endpoint_function.replace(parameters=new_parameters), ) @functools.wraps(cls.get_and_return_set_of_primitives) @@ -192,28 +218,38 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> typing.Set[str]: path="/container/set-of-primitives", response_model=typing.Set[str], description=AbstractEndpointsContainerService.get_and_return_set_of_primitives.__doc__, - **get_route_args(cls.get_and_return_set_of_primitives, default_tag="endpoints.container"), + **get_route_args( + cls.get_and_return_set_of_primitives, default_tag="endpoints.container" + ), )(wrapper) @classmethod def __init_get_and_return_set_of_objects(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_and_return_set_of_objects) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) setattr( - cls.get_and_return_set_of_objects, "__signature__", endpoint_function.replace(parameters=new_parameters) + cls.get_and_return_set_of_objects, + "__signature__", + endpoint_function.replace(parameters=new_parameters), ) @functools.wraps(cls.get_and_return_set_of_objects) - def wrapper(*args: typing.Any, **kwargs: typing.Any) -> typing.Sequence[ObjectWithRequiredField]: + def wrapper( + *args: typing.Any, **kwargs: typing.Any + ) -> typing.Sequence[ObjectWithRequiredField]: try: return cls.get_and_return_set_of_objects(*args, **kwargs) except FernHTTPException as e: @@ -232,24 +268,32 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> typing.Sequence[ObjectWi path="/container/set-of-objects", response_model=typing.Sequence[ObjectWithRequiredField], description=AbstractEndpointsContainerService.get_and_return_set_of_objects.__doc__, - **get_route_args(cls.get_and_return_set_of_objects, default_tag="endpoints.container"), + **get_route_args( + cls.get_and_return_set_of_objects, default_tag="endpoints.container" + ), )(wrapper) @classmethod def __init_get_and_return_map_prim_to_prim(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_and_return_map_prim_to_prim) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) setattr( - cls.get_and_return_map_prim_to_prim, "__signature__", endpoint_function.replace(parameters=new_parameters) + cls.get_and_return_map_prim_to_prim, + "__signature__", + endpoint_function.replace(parameters=new_parameters), ) @functools.wraps(cls.get_and_return_map_prim_to_prim) @@ -272,20 +316,28 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> typing.Dict[str, str]: path="/container/map-prim-to-prim", response_model=typing.Dict[str, str], description=AbstractEndpointsContainerService.get_and_return_map_prim_to_prim.__doc__, - **get_route_args(cls.get_and_return_map_prim_to_prim, default_tag="endpoints.container"), + **get_route_args( + cls.get_and_return_map_prim_to_prim, default_tag="endpoints.container" + ), )(wrapper) @classmethod - def __init_get_and_return_map_of_prim_to_object(cls, router: fastapi.APIRouter) -> None: + def __init_get_and_return_map_of_prim_to_object( + cls, router: fastapi.APIRouter + ) -> None: endpoint_function = inspect.signature(cls.get_and_return_map_of_prim_to_object) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) setattr( @@ -295,7 +347,9 @@ def __init_get_and_return_map_of_prim_to_object(cls, router: fastapi.APIRouter) ) @functools.wraps(cls.get_and_return_map_of_prim_to_object) - def wrapper(*args: typing.Any, **kwargs: typing.Any) -> typing.Dict[str, ObjectWithRequiredField]: + def wrapper( + *args: typing.Any, **kwargs: typing.Any + ) -> typing.Dict[str, ObjectWithRequiredField]: try: return cls.get_and_return_map_of_prim_to_object(*args, **kwargs) except FernHTTPException as e: @@ -314,26 +368,39 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> typing.Dict[str, ObjectW path="/container/map-prim-to-object", response_model=typing.Dict[str, ObjectWithRequiredField], description=AbstractEndpointsContainerService.get_and_return_map_of_prim_to_object.__doc__, - **get_route_args(cls.get_and_return_map_of_prim_to_object, default_tag="endpoints.container"), + **get_route_args( + cls.get_and_return_map_of_prim_to_object, + default_tag="endpoints.container", + ), )(wrapper) @classmethod def __init_get_and_return_optional(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_and_return_optional) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_and_return_optional, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_and_return_optional, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_and_return_optional) - def wrapper(*args: typing.Any, **kwargs: typing.Any) -> typing.Optional[ObjectWithRequiredField]: + def wrapper( + *args: typing.Any, **kwargs: typing.Any + ) -> typing.Optional[ObjectWithRequiredField]: try: return cls.get_and_return_optional(*args, **kwargs) except FernHTTPException as e: @@ -352,5 +419,7 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> typing.Optional[ObjectWi path="/container/opt-objects", response_model=typing.Optional[ObjectWithRequiredField], description=AbstractEndpointsContainerService.get_and_return_optional.__doc__, - **get_route_args(cls.get_and_return_optional, default_tag="endpoints.container"), + **get_route_args( + cls.get_and_return_optional, default_tag="endpoints.container" + ), )(wrapper) diff --git a/seed/fastapi/exhaustive/pydantic-v2/resources/endpoints/resources/enum/service/service.py b/seed/fastapi/exhaustive/pydantic-v2/resources/endpoints/resources/enum/service/service.py index a279991058b..4c665920e0b 100644 --- a/seed/fastapi/exhaustive/pydantic-v2/resources/endpoints/resources/enum/service/service.py +++ b/seed/fastapi/exhaustive/pydantic-v2/resources/endpoints/resources/enum/service/service.py @@ -1,18 +1,17 @@ # This file was auto-generated by Fern from our API Definition. +from ......core.abstract_fern_service import AbstractFernService +from .....types.resources.enum.types.weather_report import WeatherReport +from ......security import ApiAuth import abc -import functools +import fastapi import inspect -import logging import typing - -import fastapi - -from ......core.abstract_fern_service import AbstractFernService +from ......security import FernAuth from ......core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools from ......core.route_args import get_route_args -from ......security import ApiAuth, FernAuth -from .....types.resources.enum.types.weather_report import WeatherReport class AbstractEndpointsEnumService(AbstractFernService): @@ -25,8 +24,9 @@ class AbstractEndpointsEnumService(AbstractFernService): """ @abc.abstractmethod - def get_and_return_enum(self, *, body: WeatherReport, auth: ApiAuth) -> WeatherReport: - ... + def get_and_return_enum( + self, *, body: WeatherReport, auth: ApiAuth + ) -> WeatherReport: ... """ Below are internal methods used by Fern to register your implementation. @@ -41,16 +41,24 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_get_and_return_enum(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_and_return_enum) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_and_return_enum, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_and_return_enum, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_and_return_enum) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> WeatherReport: diff --git a/seed/fastapi/exhaustive/pydantic-v2/resources/endpoints/resources/http_methods/service/service.py b/seed/fastapi/exhaustive/pydantic-v2/resources/endpoints/resources/http_methods/service/service.py index 4ec18085f84..73b65270c55 100644 --- a/seed/fastapi/exhaustive/pydantic-v2/resources/endpoints/resources/http_methods/service/service.py +++ b/seed/fastapi/exhaustive/pydantic-v2/resources/endpoints/resources/http_methods/service/service.py @@ -1,19 +1,22 @@ # This file was auto-generated by Fern from our API Definition. +from ......core.abstract_fern_service import AbstractFernService +from ......security import ApiAuth import abc -import functools +from .....types.resources.object.types.object_with_required_field import ( + ObjectWithRequiredField, +) +from .....types.resources.object.types.object_with_optional_field import ( + ObjectWithOptionalField, +) +import fastapi import inspect -import logging import typing - -import fastapi - -from ......core.abstract_fern_service import AbstractFernService +from ......security import FernAuth from ......core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools from ......core.route_args import get_route_args -from ......security import ApiAuth, FernAuth -from .....types.resources.object.types.object_with_optional_field import ObjectWithOptionalField -from .....types.resources.object.types.object_with_required_field import ObjectWithRequiredField class AbstractEndpointsHttpMethodsService(AbstractFernService): @@ -26,24 +29,25 @@ class AbstractEndpointsHttpMethodsService(AbstractFernService): """ @abc.abstractmethod - def test_get(self, *, id: str, auth: ApiAuth) -> str: - ... + def test_get(self, *, id: str, auth: ApiAuth) -> str: ... @abc.abstractmethod - def test_post(self, *, body: ObjectWithRequiredField, auth: ApiAuth) -> ObjectWithOptionalField: - ... + def test_post( + self, *, body: ObjectWithRequiredField, auth: ApiAuth + ) -> ObjectWithOptionalField: ... @abc.abstractmethod - def test_put(self, *, body: ObjectWithRequiredField, id: str, auth: ApiAuth) -> ObjectWithOptionalField: - ... + def test_put( + self, *, body: ObjectWithRequiredField, id: str, auth: ApiAuth + ) -> ObjectWithOptionalField: ... @abc.abstractmethod - def test_patch(self, *, body: ObjectWithOptionalField, id: str, auth: ApiAuth) -> ObjectWithOptionalField: - ... + def test_patch( + self, *, body: ObjectWithOptionalField, id: str, auth: ApiAuth + ) -> ObjectWithOptionalField: ... @abc.abstractmethod - def test_delete(self, *, id: str, auth: ApiAuth) -> bool: - ... + def test_delete(self, *, id: str, auth: ApiAuth) -> bool: ... """ Below are internal methods used by Fern to register your implementation. @@ -62,16 +66,24 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_test_get(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.test_get) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "id": new_parameters.append(parameter.replace(default=fastapi.Path(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.test_get, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.test_get, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.test_get) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> str: @@ -100,16 +112,24 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> str: def __init_test_post(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.test_post) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.test_post, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.test_post, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.test_post) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> ObjectWithOptionalField: @@ -138,7 +158,9 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> ObjectWithOptionalField: def __init_test_put(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.test_put) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": @@ -146,10 +168,16 @@ def __init_test_put(cls, router: fastapi.APIRouter) -> None: elif parameter_name == "id": new_parameters.append(parameter.replace(default=fastapi.Path(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.test_put, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.test_put, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.test_put) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> ObjectWithOptionalField: @@ -178,7 +206,9 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> ObjectWithOptionalField: def __init_test_patch(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.test_patch) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": @@ -186,10 +216,16 @@ def __init_test_patch(cls, router: fastapi.APIRouter) -> None: elif parameter_name == "id": new_parameters.append(parameter.replace(default=fastapi.Path(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.test_patch, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.test_patch, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.test_patch) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> ObjectWithOptionalField: @@ -218,16 +254,24 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> ObjectWithOptionalField: def __init_test_delete(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.test_delete) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "id": new_parameters.append(parameter.replace(default=fastapi.Path(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.test_delete, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.test_delete, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.test_delete) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> bool: diff --git a/seed/fastapi/exhaustive/pydantic-v2/resources/endpoints/resources/object/service/service.py b/seed/fastapi/exhaustive/pydantic-v2/resources/endpoints/resources/object/service/service.py index b3f2bc65b51..8b73109a788 100644 --- a/seed/fastapi/exhaustive/pydantic-v2/resources/endpoints/resources/object/service/service.py +++ b/seed/fastapi/exhaustive/pydantic-v2/resources/endpoints/resources/object/service/service.py @@ -1,22 +1,29 @@ # This file was auto-generated by Fern from our API Definition. +from ......core.abstract_fern_service import AbstractFernService +from .....types.resources.object.types.object_with_optional_field import ( + ObjectWithOptionalField, +) +from ......security import ApiAuth import abc -import functools -import inspect -import logging +from .....types.resources.object.types.object_with_required_field import ( + ObjectWithRequiredField, +) +from .....types.resources.object.types.object_with_map_of_map import ObjectWithMapOfMap +from .....types.resources.object.types.nested_object_with_optional_field import ( + NestedObjectWithOptionalField, +) +from .....types.resources.object.types.nested_object_with_required_field import ( + NestedObjectWithRequiredField, +) import typing - import fastapi - -from ......core.abstract_fern_service import AbstractFernService +import inspect +from ......security import FernAuth from ......core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools from ......core.route_args import get_route_args -from ......security import ApiAuth, FernAuth -from .....types.resources.object.types.nested_object_with_optional_field import NestedObjectWithOptionalField -from .....types.resources.object.types.nested_object_with_required_field import NestedObjectWithRequiredField -from .....types.resources.object.types.object_with_map_of_map import ObjectWithMapOfMap -from .....types.resources.object.types.object_with_optional_field import ObjectWithOptionalField -from .....types.resources.object.types.object_with_required_field import ObjectWithRequiredField class AbstractEndpointsObjectService(AbstractFernService): @@ -31,36 +38,32 @@ class AbstractEndpointsObjectService(AbstractFernService): @abc.abstractmethod def get_and_return_with_optional_field( self, *, body: ObjectWithOptionalField, auth: ApiAuth - ) -> ObjectWithOptionalField: - ... + ) -> ObjectWithOptionalField: ... @abc.abstractmethod def get_and_return_with_required_field( self, *, body: ObjectWithRequiredField, auth: ApiAuth - ) -> ObjectWithRequiredField: - ... + ) -> ObjectWithRequiredField: ... @abc.abstractmethod - def get_and_return_with_map_of_map(self, *, body: ObjectWithMapOfMap, auth: ApiAuth) -> ObjectWithMapOfMap: - ... + def get_and_return_with_map_of_map( + self, *, body: ObjectWithMapOfMap, auth: ApiAuth + ) -> ObjectWithMapOfMap: ... @abc.abstractmethod def get_and_return_nested_with_optional_field( self, *, body: NestedObjectWithOptionalField, auth: ApiAuth - ) -> NestedObjectWithOptionalField: - ... + ) -> NestedObjectWithOptionalField: ... @abc.abstractmethod def get_and_return_nested_with_required_field( self, *, body: NestedObjectWithRequiredField, string: str, auth: ApiAuth - ) -> NestedObjectWithRequiredField: - ... + ) -> NestedObjectWithRequiredField: ... @abc.abstractmethod def get_and_return_nested_with_required_field_as_list( self, *, body: typing.List[NestedObjectWithRequiredField], auth: ApiAuth - ) -> NestedObjectWithRequiredField: - ... + ) -> NestedObjectWithRequiredField: ... """ Below are internal methods used by Fern to register your implementation. @@ -77,16 +80,22 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: cls.__init_get_and_return_nested_with_required_field_as_list(router=router) @classmethod - def __init_get_and_return_with_optional_field(cls, router: fastapi.APIRouter) -> None: + def __init_get_and_return_with_optional_field( + cls, router: fastapi.APIRouter + ) -> None: endpoint_function = inspect.signature(cls.get_and_return_with_optional_field) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) setattr( @@ -115,20 +124,28 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> ObjectWithOptionalField: path="/object/get-and-return-with-optional-field", response_model=ObjectWithOptionalField, description=AbstractEndpointsObjectService.get_and_return_with_optional_field.__doc__, - **get_route_args(cls.get_and_return_with_optional_field, default_tag="endpoints.object"), + **get_route_args( + cls.get_and_return_with_optional_field, default_tag="endpoints.object" + ), )(wrapper) @classmethod - def __init_get_and_return_with_required_field(cls, router: fastapi.APIRouter) -> None: + def __init_get_and_return_with_required_field( + cls, router: fastapi.APIRouter + ) -> None: endpoint_function = inspect.signature(cls.get_and_return_with_required_field) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) setattr( @@ -157,24 +174,32 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> ObjectWithRequiredField: path="/object/get-and-return-with-required-field", response_model=ObjectWithRequiredField, description=AbstractEndpointsObjectService.get_and_return_with_required_field.__doc__, - **get_route_args(cls.get_and_return_with_required_field, default_tag="endpoints.object"), + **get_route_args( + cls.get_and_return_with_required_field, default_tag="endpoints.object" + ), )(wrapper) @classmethod def __init_get_and_return_with_map_of_map(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_and_return_with_map_of_map) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) setattr( - cls.get_and_return_with_map_of_map, "__signature__", endpoint_function.replace(parameters=new_parameters) + cls.get_and_return_with_map_of_map, + "__signature__", + endpoint_function.replace(parameters=new_parameters), ) @functools.wraps(cls.get_and_return_with_map_of_map) @@ -197,20 +222,30 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> ObjectWithMapOfMap: path="/object/get-and-return-with-map-of-map", response_model=ObjectWithMapOfMap, description=AbstractEndpointsObjectService.get_and_return_with_map_of_map.__doc__, - **get_route_args(cls.get_and_return_with_map_of_map, default_tag="endpoints.object"), + **get_route_args( + cls.get_and_return_with_map_of_map, default_tag="endpoints.object" + ), )(wrapper) @classmethod - def __init_get_and_return_nested_with_optional_field(cls, router: fastapi.APIRouter) -> None: - endpoint_function = inspect.signature(cls.get_and_return_nested_with_optional_field) + def __init_get_and_return_nested_with_optional_field( + cls, router: fastapi.APIRouter + ) -> None: + endpoint_function = inspect.signature( + cls.get_and_return_nested_with_optional_field + ) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) setattr( @@ -220,7 +255,9 @@ def __init_get_and_return_nested_with_optional_field(cls, router: fastapi.APIRou ) @functools.wraps(cls.get_and_return_nested_with_optional_field) - def wrapper(*args: typing.Any, **kwargs: typing.Any) -> NestedObjectWithOptionalField: + def wrapper( + *args: typing.Any, **kwargs: typing.Any + ) -> NestedObjectWithOptionalField: try: return cls.get_and_return_nested_with_optional_field(*args, **kwargs) except FernHTTPException as e: @@ -233,20 +270,31 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> NestedObjectWithOptional # this is necessary for FastAPI to find forward-ref'ed type hints. # https://github.com/tiangolo/fastapi/pull/5077 - wrapper.__globals__.update(cls.get_and_return_nested_with_optional_field.__globals__) + wrapper.__globals__.update( + cls.get_and_return_nested_with_optional_field.__globals__ + ) router.post( path="/object/get-and-return-nested-with-optional-field", response_model=NestedObjectWithOptionalField, description=AbstractEndpointsObjectService.get_and_return_nested_with_optional_field.__doc__, - **get_route_args(cls.get_and_return_nested_with_optional_field, default_tag="endpoints.object"), + **get_route_args( + cls.get_and_return_nested_with_optional_field, + default_tag="endpoints.object", + ), )(wrapper) @classmethod - def __init_get_and_return_nested_with_required_field(cls, router: fastapi.APIRouter) -> None: - endpoint_function = inspect.signature(cls.get_and_return_nested_with_required_field) + def __init_get_and_return_nested_with_required_field( + cls, router: fastapi.APIRouter + ) -> None: + endpoint_function = inspect.signature( + cls.get_and_return_nested_with_required_field + ) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": @@ -254,7 +302,9 @@ def __init_get_and_return_nested_with_required_field(cls, router: fastapi.APIRou elif parameter_name == "string": new_parameters.append(parameter.replace(default=fastapi.Path(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) setattr( @@ -264,7 +314,9 @@ def __init_get_and_return_nested_with_required_field(cls, router: fastapi.APIRou ) @functools.wraps(cls.get_and_return_nested_with_required_field) - def wrapper(*args: typing.Any, **kwargs: typing.Any) -> NestedObjectWithRequiredField: + def wrapper( + *args: typing.Any, **kwargs: typing.Any + ) -> NestedObjectWithRequiredField: try: return cls.get_and_return_nested_with_required_field(*args, **kwargs) except FernHTTPException as e: @@ -277,26 +329,39 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> NestedObjectWithRequired # this is necessary for FastAPI to find forward-ref'ed type hints. # https://github.com/tiangolo/fastapi/pull/5077 - wrapper.__globals__.update(cls.get_and_return_nested_with_required_field.__globals__) + wrapper.__globals__.update( + cls.get_and_return_nested_with_required_field.__globals__ + ) router.post( path="/object/get-and-return-nested-with-required-field/{string}", response_model=NestedObjectWithRequiredField, description=AbstractEndpointsObjectService.get_and_return_nested_with_required_field.__doc__, - **get_route_args(cls.get_and_return_nested_with_required_field, default_tag="endpoints.object"), + **get_route_args( + cls.get_and_return_nested_with_required_field, + default_tag="endpoints.object", + ), )(wrapper) @classmethod - def __init_get_and_return_nested_with_required_field_as_list(cls, router: fastapi.APIRouter) -> None: - endpoint_function = inspect.signature(cls.get_and_return_nested_with_required_field_as_list) + def __init_get_and_return_nested_with_required_field_as_list( + cls, router: fastapi.APIRouter + ) -> None: + endpoint_function = inspect.signature( + cls.get_and_return_nested_with_required_field_as_list + ) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) setattr( @@ -306,9 +371,13 @@ def __init_get_and_return_nested_with_required_field_as_list(cls, router: fastap ) @functools.wraps(cls.get_and_return_nested_with_required_field_as_list) - def wrapper(*args: typing.Any, **kwargs: typing.Any) -> NestedObjectWithRequiredField: + def wrapper( + *args: typing.Any, **kwargs: typing.Any + ) -> NestedObjectWithRequiredField: try: - return cls.get_and_return_nested_with_required_field_as_list(*args, **kwargs) + return cls.get_and_return_nested_with_required_field_as_list( + *args, **kwargs + ) except FernHTTPException as e: logging.getLogger(f"{cls.__module__}.{cls.__name__}").warn( f"Endpoint 'get_and_return_nested_with_required_field_as_list' unexpectedly threw {e.__class__.__name__}. " @@ -319,11 +388,16 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> NestedObjectWithRequired # this is necessary for FastAPI to find forward-ref'ed type hints. # https://github.com/tiangolo/fastapi/pull/5077 - wrapper.__globals__.update(cls.get_and_return_nested_with_required_field_as_list.__globals__) + wrapper.__globals__.update( + cls.get_and_return_nested_with_required_field_as_list.__globals__ + ) router.post( path="/object/get-and-return-nested-with-required-field-list", response_model=NestedObjectWithRequiredField, description=AbstractEndpointsObjectService.get_and_return_nested_with_required_field_as_list.__doc__, - **get_route_args(cls.get_and_return_nested_with_required_field_as_list, default_tag="endpoints.object"), + **get_route_args( + cls.get_and_return_nested_with_required_field_as_list, + default_tag="endpoints.object", + ), )(wrapper) diff --git a/seed/fastapi/exhaustive/pydantic-v2/resources/endpoints/resources/params/service/service.py b/seed/fastapi/exhaustive/pydantic-v2/resources/endpoints/resources/params/service/service.py index a7ae7b277b2..93c809bd4e7 100644 --- a/seed/fastapi/exhaustive/pydantic-v2/resources/endpoints/resources/params/service/service.py +++ b/seed/fastapi/exhaustive/pydantic-v2/resources/endpoints/resources/params/service/service.py @@ -1,18 +1,17 @@ # This file was auto-generated by Fern from our API Definition. +from ......core.abstract_fern_service import AbstractFernService +from ......security import ApiAuth import abc -import functools -import inspect -import logging import typing - import fastapi -import starlette - -from ......core.abstract_fern_service import AbstractFernService +import inspect +from ......security import FernAuth from ......core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools from ......core.route_args import get_route_args -from ......security import ApiAuth, FernAuth +import starlette class AbstractEndpointsParamsService(AbstractFernService): @@ -39,7 +38,9 @@ def get_with_query(self, *, query: str, number: int, auth: ApiAuth) -> None: ... @abc.abstractmethod - def get_with_allow_multiple_query(self, *, query: typing.List[str], numer: typing.List[int], auth: ApiAuth) -> None: + def get_with_allow_multiple_query( + self, *, query: typing.List[str], numer: typing.List[int], auth: ApiAuth + ) -> None: """ GET with multiple of same query param """ @@ -76,16 +77,24 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_get_with_path(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_with_path) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "param": new_parameters.append(parameter.replace(default=fastapi.Path(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_with_path, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_with_path, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_with_path) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> str: @@ -114,18 +123,30 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> str: def __init_get_with_query(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_with_query) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "query": - new_parameters.append(parameter.replace(default=fastapi.Query(default=...))) + new_parameters.append( + parameter.replace(default=fastapi.Query(default=...)) + ) elif parameter_name == "number": - new_parameters.append(parameter.replace(default=fastapi.Query(default=...))) + new_parameters.append( + parameter.replace(default=fastapi.Query(default=...)) + ) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_with_query, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_with_query, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_with_query) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> None: @@ -155,19 +176,29 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> None: def __init_get_with_allow_multiple_query(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_with_allow_multiple_query) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "query": - new_parameters.append(parameter.replace(default=fastapi.Query(default=[]))) + new_parameters.append( + parameter.replace(default=fastapi.Query(default=[])) + ) elif parameter_name == "numer": - new_parameters.append(parameter.replace(default=fastapi.Query(default=[]))) + new_parameters.append( + parameter.replace(default=fastapi.Query(default=[])) + ) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) setattr( - cls.get_with_allow_multiple_query, "__signature__", endpoint_function.replace(parameters=new_parameters) + cls.get_with_allow_multiple_query, + "__signature__", + endpoint_function.replace(parameters=new_parameters), ) @functools.wraps(cls.get_with_allow_multiple_query) @@ -191,25 +222,37 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> None: response_model=None, status_code=starlette.status.HTTP_204_NO_CONTENT, description=AbstractEndpointsParamsService.get_with_allow_multiple_query.__doc__, - **get_route_args(cls.get_with_allow_multiple_query, default_tag="endpoints.params"), + **get_route_args( + cls.get_with_allow_multiple_query, default_tag="endpoints.params" + ), )(wrapper) @classmethod def __init_get_with_path_and_query(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_with_path_and_query) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "param": new_parameters.append(parameter.replace(default=fastapi.Path(...))) elif parameter_name == "query": - new_parameters.append(parameter.replace(default=fastapi.Query(default=...))) + new_parameters.append( + parameter.replace(default=fastapi.Query(default=...)) + ) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_with_path_and_query, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_with_path_and_query, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_with_path_and_query) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> None: @@ -232,14 +275,18 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> None: response_model=None, status_code=starlette.status.HTTP_204_NO_CONTENT, description=AbstractEndpointsParamsService.get_with_path_and_query.__doc__, - **get_route_args(cls.get_with_path_and_query, default_tag="endpoints.params"), + **get_route_args( + cls.get_with_path_and_query, default_tag="endpoints.params" + ), )(wrapper) @classmethod def __init_modify_with_path(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.modify_with_path) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": @@ -247,10 +294,16 @@ def __init_modify_with_path(cls, router: fastapi.APIRouter) -> None: elif parameter_name == "param": new_parameters.append(parameter.replace(default=fastapi.Path(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.modify_with_path, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.modify_with_path, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.modify_with_path) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> str: diff --git a/seed/fastapi/exhaustive/pydantic-v2/resources/endpoints/resources/primitive/service/service.py b/seed/fastapi/exhaustive/pydantic-v2/resources/endpoints/resources/primitive/service/service.py index db7ef44676c..78b3526b630 100644 --- a/seed/fastapi/exhaustive/pydantic-v2/resources/endpoints/resources/primitive/service/service.py +++ b/seed/fastapi/exhaustive/pydantic-v2/resources/endpoints/resources/primitive/service/service.py @@ -1,19 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ......core.abstract_fern_service import AbstractFernService +from ......security import ApiAuth import abc import datetime as dt -import functools -import inspect -import logging -import typing import uuid - import fastapi - -from ......core.abstract_fern_service import AbstractFernService +import inspect +import typing +from ......security import FernAuth from ......core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools from ......core.route_args import get_route_args -from ......security import ApiAuth, FernAuth class AbstractEndpointsPrimitiveService(AbstractFernService): @@ -26,40 +25,33 @@ class AbstractEndpointsPrimitiveService(AbstractFernService): """ @abc.abstractmethod - def get_and_return_string(self, *, body: str, auth: ApiAuth) -> str: - ... + def get_and_return_string(self, *, body: str, auth: ApiAuth) -> str: ... @abc.abstractmethod - def get_and_return_int(self, *, body: int, auth: ApiAuth) -> int: - ... + def get_and_return_int(self, *, body: int, auth: ApiAuth) -> int: ... @abc.abstractmethod - def get_and_return_long(self, *, body: int, auth: ApiAuth) -> int: - ... + def get_and_return_long(self, *, body: int, auth: ApiAuth) -> int: ... @abc.abstractmethod - def get_and_return_double(self, *, body: float, auth: ApiAuth) -> float: - ... + def get_and_return_double(self, *, body: float, auth: ApiAuth) -> float: ... @abc.abstractmethod - def get_and_return_bool(self, *, body: bool, auth: ApiAuth) -> bool: - ... + def get_and_return_bool(self, *, body: bool, auth: ApiAuth) -> bool: ... @abc.abstractmethod - def get_and_return_datetime(self, *, body: dt.datetime, auth: ApiAuth) -> dt.datetime: - ... + def get_and_return_datetime( + self, *, body: dt.datetime, auth: ApiAuth + ) -> dt.datetime: ... @abc.abstractmethod - def get_and_return_date(self, *, body: dt.date, auth: ApiAuth) -> dt.date: - ... + def get_and_return_date(self, *, body: dt.date, auth: ApiAuth) -> dt.date: ... @abc.abstractmethod - def get_and_return_uuid(self, *, body: uuid.UUID, auth: ApiAuth) -> uuid.UUID: - ... + def get_and_return_uuid(self, *, body: uuid.UUID, auth: ApiAuth) -> uuid.UUID: ... @abc.abstractmethod - def get_and_return_base_64(self, *, body: str, auth: ApiAuth) -> str: - ... + def get_and_return_base_64(self, *, body: str, auth: ApiAuth) -> str: ... """ Below are internal methods used by Fern to register your implementation. @@ -82,16 +74,24 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_get_and_return_string(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_and_return_string) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_and_return_string, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_and_return_string, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_and_return_string) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> str: @@ -113,23 +113,33 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> str: path="/primitive/string", response_model=str, description=AbstractEndpointsPrimitiveService.get_and_return_string.__doc__, - **get_route_args(cls.get_and_return_string, default_tag="endpoints.primitive"), + **get_route_args( + cls.get_and_return_string, default_tag="endpoints.primitive" + ), )(wrapper) @classmethod def __init_get_and_return_int(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_and_return_int) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_and_return_int, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_and_return_int, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_and_return_int) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> int: @@ -158,16 +168,24 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> int: def __init_get_and_return_long(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_and_return_long) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_and_return_long, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_and_return_long, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_and_return_long) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> int: @@ -189,23 +207,33 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> int: path="/primitive/long", response_model=int, description=AbstractEndpointsPrimitiveService.get_and_return_long.__doc__, - **get_route_args(cls.get_and_return_long, default_tag="endpoints.primitive"), + **get_route_args( + cls.get_and_return_long, default_tag="endpoints.primitive" + ), )(wrapper) @classmethod def __init_get_and_return_double(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_and_return_double) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_and_return_double, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_and_return_double, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_and_return_double) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> float: @@ -227,23 +255,33 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> float: path="/primitive/double", response_model=float, description=AbstractEndpointsPrimitiveService.get_and_return_double.__doc__, - **get_route_args(cls.get_and_return_double, default_tag="endpoints.primitive"), + **get_route_args( + cls.get_and_return_double, default_tag="endpoints.primitive" + ), )(wrapper) @classmethod def __init_get_and_return_bool(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_and_return_bool) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_and_return_bool, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_and_return_bool, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_and_return_bool) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> bool: @@ -265,23 +303,33 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> bool: path="/primitive/boolean", response_model=bool, description=AbstractEndpointsPrimitiveService.get_and_return_bool.__doc__, - **get_route_args(cls.get_and_return_bool, default_tag="endpoints.primitive"), + **get_route_args( + cls.get_and_return_bool, default_tag="endpoints.primitive" + ), )(wrapper) @classmethod def __init_get_and_return_datetime(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_and_return_datetime) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_and_return_datetime, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_and_return_datetime, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_and_return_datetime) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> dt.datetime: @@ -303,23 +351,33 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> dt.datetime: path="/primitive/datetime", response_model=dt.datetime, description=AbstractEndpointsPrimitiveService.get_and_return_datetime.__doc__, - **get_route_args(cls.get_and_return_datetime, default_tag="endpoints.primitive"), + **get_route_args( + cls.get_and_return_datetime, default_tag="endpoints.primitive" + ), )(wrapper) @classmethod def __init_get_and_return_date(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_and_return_date) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_and_return_date, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_and_return_date, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_and_return_date) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> dt.date: @@ -341,23 +399,33 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> dt.date: path="/primitive/date", response_model=dt.date, description=AbstractEndpointsPrimitiveService.get_and_return_date.__doc__, - **get_route_args(cls.get_and_return_date, default_tag="endpoints.primitive"), + **get_route_args( + cls.get_and_return_date, default_tag="endpoints.primitive" + ), )(wrapper) @classmethod def __init_get_and_return_uuid(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_and_return_uuid) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_and_return_uuid, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_and_return_uuid, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_and_return_uuid) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> uuid.UUID: @@ -379,23 +447,33 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> uuid.UUID: path="/primitive/uuid", response_model=uuid.UUID, description=AbstractEndpointsPrimitiveService.get_and_return_uuid.__doc__, - **get_route_args(cls.get_and_return_uuid, default_tag="endpoints.primitive"), + **get_route_args( + cls.get_and_return_uuid, default_tag="endpoints.primitive" + ), )(wrapper) @classmethod def __init_get_and_return_base_64(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_and_return_base_64) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_and_return_base_64, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_and_return_base_64, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_and_return_base_64) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> str: @@ -417,5 +495,7 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> str: path="/primitive/base64", response_model=str, description=AbstractEndpointsPrimitiveService.get_and_return_base_64.__doc__, - **get_route_args(cls.get_and_return_base_64, default_tag="endpoints.primitive"), + **get_route_args( + cls.get_and_return_base_64, default_tag="endpoints.primitive" + ), )(wrapper) diff --git a/seed/fastapi/exhaustive/pydantic-v2/resources/endpoints/resources/union/service/service.py b/seed/fastapi/exhaustive/pydantic-v2/resources/endpoints/resources/union/service/service.py index 5c026188aca..cc962963db9 100644 --- a/seed/fastapi/exhaustive/pydantic-v2/resources/endpoints/resources/union/service/service.py +++ b/seed/fastapi/exhaustive/pydantic-v2/resources/endpoints/resources/union/service/service.py @@ -1,18 +1,17 @@ # This file was auto-generated by Fern from our API Definition. +from ......core.abstract_fern_service import AbstractFernService +from .....types.resources.union.types.animal import Animal +from ......security import ApiAuth import abc -import functools +import fastapi import inspect -import logging import typing - -import fastapi - -from ......core.abstract_fern_service import AbstractFernService +from ......security import FernAuth from ......core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools from ......core.route_args import get_route_args -from ......security import ApiAuth, FernAuth -from .....types.resources.union.types.animal import Animal class AbstractEndpointsUnionService(AbstractFernService): @@ -25,8 +24,7 @@ class AbstractEndpointsUnionService(AbstractFernService): """ @abc.abstractmethod - def get_and_return_union(self, *, body: Animal, auth: ApiAuth) -> Animal: - ... + def get_and_return_union(self, *, body: Animal, auth: ApiAuth) -> Animal: ... """ Below are internal methods used by Fern to register your implementation. @@ -41,16 +39,24 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_get_and_return_union(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_and_return_union) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_and_return_union, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_and_return_union, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_and_return_union) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> Animal: diff --git a/seed/fastapi/exhaustive/pydantic-v2/resources/general_errors/types/bad_object_request_info.py b/seed/fastapi/exhaustive/pydantic-v2/resources/general_errors/types/bad_object_request_info.py index 08402f7e618..3b4b5d03362 100644 --- a/seed/fastapi/exhaustive/pydantic-v2/resources/general_errors/types/bad_object_request_info.py +++ b/seed/fastapi/exhaustive/pydantic-v2/resources/general_errors/types/bad_object_request_info.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class BadObjectRequestInfo(UniversalBaseModel): message: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/exhaustive/pydantic-v2/resources/inlined_requests/service/post_with_object_body.py b/seed/fastapi/exhaustive/pydantic-v2/resources/inlined_requests/service/post_with_object_body.py index b62587f8d32..647905603ee 100644 --- a/seed/fastapi/exhaustive/pydantic-v2/resources/inlined_requests/service/post_with_object_body.py +++ b/seed/fastapi/exhaustive/pydantic-v2/resources/inlined_requests/service/post_with_object_body.py @@ -1,11 +1,12 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ....core.pydantic_utilities import UniversalBaseModel +from ...types.resources.object.types.object_with_optional_field import ( + ObjectWithOptionalField, +) import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from ...types.resources.object.types.object_with_optional_field import ObjectWithOptionalField +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class PostWithObjectBody(UniversalBaseModel): @@ -14,7 +15,9 @@ class PostWithObjectBody(UniversalBaseModel): nested_object: ObjectWithOptionalField = pydantic.Field(alias="NestedObject") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/exhaustive/pydantic-v2/resources/inlined_requests/service/service.py b/seed/fastapi/exhaustive/pydantic-v2/resources/inlined_requests/service/service.py index 24b6ac5ff85..9894c433149 100644 --- a/seed/fastapi/exhaustive/pydantic-v2/resources/inlined_requests/service/service.py +++ b/seed/fastapi/exhaustive/pydantic-v2/resources/inlined_requests/service/service.py @@ -1,19 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.abstract_fern_service import AbstractFernService +from .post_with_object_body import PostWithObjectBody +from ...types.resources.object.types.object_with_optional_field import ( + ObjectWithOptionalField, +) import abc -import functools +import fastapi import inspect -import logging import typing - -import fastapi - -from ....core.abstract_fern_service import AbstractFernService +from ...general_errors.errors.bad_request_body import BadRequestBody from ....core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools from ....core.route_args import get_route_args -from ...general_errors.errors.bad_request_body import BadRequestBody -from ...types.resources.object.types.object_with_optional_field import ObjectWithOptionalField -from .post_with_object_body import PostWithObjectBody class AbstractInlinedRequestsService(AbstractFernService): @@ -26,7 +26,9 @@ class AbstractInlinedRequestsService(AbstractFernService): """ @abc.abstractmethod - def post_with_object_bodyand_response(self, *, body: PostWithObjectBody) -> ObjectWithOptionalField: + def post_with_object_bodyand_response( + self, *, body: PostWithObjectBody + ) -> ObjectWithOptionalField: """ POST with custom object in request body, response is an object """ @@ -42,10 +44,14 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: cls.__init_post_with_object_bodyand_response(router=router) @classmethod - def __init_post_with_object_bodyand_response(cls, router: fastapi.APIRouter) -> None: + def __init_post_with_object_bodyand_response( + cls, router: fastapi.APIRouter + ) -> None: endpoint_function = inspect.signature(cls.post_with_object_bodyand_response) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": @@ -53,7 +59,9 @@ def __init_post_with_object_bodyand_response(cls, router: fastapi.APIRouter) -> else: new_parameters.append(parameter) setattr( - cls.post_with_object_bodyand_response, "__signature__", endpoint_function.replace(parameters=new_parameters) + cls.post_with_object_bodyand_response, + "__signature__", + endpoint_function.replace(parameters=new_parameters), ) @functools.wraps(cls.post_with_object_bodyand_response) @@ -78,5 +86,7 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> ObjectWithOptionalField: path="/req-bodies/object", response_model=ObjectWithOptionalField, description=AbstractInlinedRequestsService.post_with_object_bodyand_response.__doc__, - **get_route_args(cls.post_with_object_bodyand_response, default_tag="inlined_requests"), + **get_route_args( + cls.post_with_object_bodyand_response, default_tag="inlined_requests" + ), )(wrapper) diff --git a/seed/fastapi/exhaustive/pydantic-v2/resources/no_auth/service/service.py b/seed/fastapi/exhaustive/pydantic-v2/resources/no_auth/service/service.py index 952a7322d89..b0984ae6360 100644 --- a/seed/fastapi/exhaustive/pydantic-v2/resources/no_auth/service/service.py +++ b/seed/fastapi/exhaustive/pydantic-v2/resources/no_auth/service/service.py @@ -1,17 +1,15 @@ # This file was auto-generated by Fern from our API Definition. -import abc -import functools -import inspect -import logging +from ....core.abstract_fern_service import AbstractFernService import typing - +import abc import fastapi - -from ....core.abstract_fern_service import AbstractFernService +import inspect +from ...general_errors.errors.bad_request_body import BadRequestBody from ....core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools from ....core.route_args import get_route_args -from ...general_errors.errors.bad_request_body import BadRequestBody class AbstractNoAuthService(AbstractFernService): @@ -43,14 +41,20 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_post_with_no_auth(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.post_with_no_auth) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) else: new_parameters.append(parameter) - setattr(cls.post_with_no_auth, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.post_with_no_auth, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.post_with_no_auth) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> bool: diff --git a/seed/fastapi/exhaustive/pydantic-v2/resources/no_req_body/service/service.py b/seed/fastapi/exhaustive/pydantic-v2/resources/no_req_body/service/service.py index 09c805cc1c7..40b96353e2d 100644 --- a/seed/fastapi/exhaustive/pydantic-v2/resources/no_req_body/service/service.py +++ b/seed/fastapi/exhaustive/pydantic-v2/resources/no_req_body/service/service.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.abstract_fern_service import AbstractFernService +from ....security import ApiAuth +from ...types.resources.object.types.object_with_optional_field import ( + ObjectWithOptionalField, +) import abc -import functools +import fastapi import inspect -import logging import typing - -import fastapi - -from ....core.abstract_fern_service import AbstractFernService +from ....security import FernAuth from ....core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools from ....core.route_args import get_route_args -from ....security import ApiAuth, FernAuth -from ...types.resources.object.types.object_with_optional_field import ObjectWithOptionalField class AbstractNoReqBodyService(AbstractFernService): @@ -25,12 +26,10 @@ class AbstractNoReqBodyService(AbstractFernService): """ @abc.abstractmethod - def get_with_no_request_body(self, *, auth: ApiAuth) -> ObjectWithOptionalField: - ... + def get_with_no_request_body(self, *, auth: ApiAuth) -> ObjectWithOptionalField: ... @abc.abstractmethod - def post_with_no_request_body(self, *, auth: ApiAuth) -> str: - ... + def post_with_no_request_body(self, *, auth: ApiAuth) -> str: ... """ Below are internal methods used by Fern to register your implementation. @@ -46,14 +45,22 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_get_with_no_request_body(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_with_no_request_body) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_with_no_request_body, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_with_no_request_body, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_with_no_request_body) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> ObjectWithOptionalField: @@ -82,14 +89,22 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> ObjectWithOptionalField: def __init_post_with_no_request_body(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.post_with_no_request_body) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.post_with_no_request_body, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.post_with_no_request_body, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.post_with_no_request_body) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> str: diff --git a/seed/fastapi/exhaustive/pydantic-v2/resources/req_with_headers/service/service.py b/seed/fastapi/exhaustive/pydantic-v2/resources/req_with_headers/service/service.py index 7b31e8311b8..0bb5ea5b04c 100644 --- a/seed/fastapi/exhaustive/pydantic-v2/resources/req_with_headers/service/service.py +++ b/seed/fastapi/exhaustive/pydantic-v2/resources/req_with_headers/service/service.py @@ -1,18 +1,17 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.abstract_fern_service import AbstractFernService +from ....security import ApiAuth import abc -import functools +import fastapi import inspect -import logging import typing - -import fastapi -import starlette - -from ....core.abstract_fern_service import AbstractFernService +from ....security import FernAuth from ....core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools +import starlette from ....core.route_args import get_route_args -from ....security import ApiAuth, FernAuth class AbstractReqWithHeadersService(AbstractFernService): @@ -25,8 +24,9 @@ class AbstractReqWithHeadersService(AbstractFernService): """ @abc.abstractmethod - def get_with_custom_header(self, *, body: str, x_test_endpoint_header: str, auth: ApiAuth) -> None: - ... + def get_with_custom_header( + self, *, body: str, x_test_endpoint_header: str, auth: ApiAuth + ) -> None: ... """ Below are internal methods used by Fern to register your implementation. @@ -41,18 +41,30 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_get_with_custom_header(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_with_custom_header) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "x_test_endpoint_header": - new_parameters.append(parameter.replace(default=fastapi.Header(alias="X-TEST-ENDPOINT-HEADER"))) + new_parameters.append( + parameter.replace( + default=fastapi.Header(alias="X-TEST-ENDPOINT-HEADER") + ) + ) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_with_custom_header, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_with_custom_header, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_with_custom_header) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> None: @@ -75,5 +87,7 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> None: response_model=None, status_code=starlette.status.HTTP_204_NO_CONTENT, description=AbstractReqWithHeadersService.get_with_custom_header.__doc__, - **get_route_args(cls.get_with_custom_header, default_tag="req_with_headers"), + **get_route_args( + cls.get_with_custom_header, default_tag="req_with_headers" + ), )(wrapper) diff --git a/seed/fastapi/exhaustive/pydantic-v2/resources/types/resources/object/errors/nested_object_with_optional_field_error.py b/seed/fastapi/exhaustive/pydantic-v2/resources/types/resources/object/errors/nested_object_with_optional_field_error.py index 3ba440b272a..8ccad4823e1 100644 --- a/seed/fastapi/exhaustive/pydantic-v2/resources/types/resources/object/errors/nested_object_with_optional_field_error.py +++ b/seed/fastapi/exhaustive/pydantic-v2/resources/types/resources/object/errors/nested_object_with_optional_field_error.py @@ -6,4 +6,6 @@ class NestedObjectWithOptionalFieldError(FernHTTPException): def __init__(self, error: NestedObjectWithOptionalField): - super().__init__(status_code=400, name="NestedObjectWithOptionalFieldError", content=error) + super().__init__( + status_code=400, name="NestedObjectWithOptionalFieldError", content=error + ) diff --git a/seed/fastapi/exhaustive/pydantic-v2/resources/types/resources/object/errors/nested_object_with_required_field_error.py b/seed/fastapi/exhaustive/pydantic-v2/resources/types/resources/object/errors/nested_object_with_required_field_error.py index 10b5e850066..d328ecaf35e 100644 --- a/seed/fastapi/exhaustive/pydantic-v2/resources/types/resources/object/errors/nested_object_with_required_field_error.py +++ b/seed/fastapi/exhaustive/pydantic-v2/resources/types/resources/object/errors/nested_object_with_required_field_error.py @@ -6,4 +6,6 @@ class NestedObjectWithRequiredFieldError(FernHTTPException): def __init__(self, error: NestedObjectWithRequiredField): - super().__init__(status_code=400, name="NestedObjectWithRequiredFieldError", content=error) + super().__init__( + status_code=400, name="NestedObjectWithRequiredFieldError", content=error + ) diff --git a/seed/fastapi/exhaustive/pydantic-v2/resources/types/resources/object/errors/object_with_optional_field_error.py b/seed/fastapi/exhaustive/pydantic-v2/resources/types/resources/object/errors/object_with_optional_field_error.py index 09a92f4c466..1205d252c69 100644 --- a/seed/fastapi/exhaustive/pydantic-v2/resources/types/resources/object/errors/object_with_optional_field_error.py +++ b/seed/fastapi/exhaustive/pydantic-v2/resources/types/resources/object/errors/object_with_optional_field_error.py @@ -6,4 +6,6 @@ class ObjectWithOptionalFieldError(FernHTTPException): def __init__(self, error: ObjectWithOptionalField): - super().__init__(status_code=400, name="ObjectWithOptionalFieldError", content=error) + super().__init__( + status_code=400, name="ObjectWithOptionalFieldError", content=error + ) diff --git a/seed/fastapi/exhaustive/pydantic-v2/resources/types/resources/object/errors/object_with_required_field_error.py b/seed/fastapi/exhaustive/pydantic-v2/resources/types/resources/object/errors/object_with_required_field_error.py index c0c5cc11812..53045a6279e 100644 --- a/seed/fastapi/exhaustive/pydantic-v2/resources/types/resources/object/errors/object_with_required_field_error.py +++ b/seed/fastapi/exhaustive/pydantic-v2/resources/types/resources/object/errors/object_with_required_field_error.py @@ -6,4 +6,6 @@ class ObjectWithRequiredFieldError(FernHTTPException): def __init__(self, error: ObjectWithRequiredField): - super().__init__(status_code=400, name="ObjectWithRequiredFieldError", content=error) + super().__init__( + status_code=400, name="ObjectWithRequiredFieldError", content=error + ) diff --git a/seed/fastapi/exhaustive/pydantic-v2/resources/types/resources/object/types/double_optional.py b/seed/fastapi/exhaustive/pydantic-v2/resources/types/resources/object/types/double_optional.py index 496516e1c7e..055935ee32e 100644 --- a/seed/fastapi/exhaustive/pydantic-v2/resources/types/resources/object/types/double_optional.py +++ b/seed/fastapi/exhaustive/pydantic-v2/resources/types/resources/object/types/double_optional.py @@ -1,18 +1,21 @@ # This file was auto-generated by Fern from our API Definition. +from ......core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .optional_alias import OptionalAlias +import pydantic +from ......core.pydantic_utilities import IS_PYDANTIC_V2 class DoubleOptional(UniversalBaseModel): - optional_alias: typing.Optional[OptionalAlias] = pydantic.Field(alias="optionalAlias", default=None) + optional_alias: typing.Optional[OptionalAlias] = pydantic.Field( + alias="optionalAlias", default=None + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/exhaustive/pydantic-v2/resources/types/resources/object/types/nested_object_with_optional_field.py b/seed/fastapi/exhaustive/pydantic-v2/resources/types/resources/object/types/nested_object_with_optional_field.py index ed1a24559d4..15fff182ee9 100644 --- a/seed/fastapi/exhaustive/pydantic-v2/resources/types/resources/object/types/nested_object_with_optional_field.py +++ b/seed/fastapi/exhaustive/pydantic-v2/resources/types/resources/object/types/nested_object_with_optional_field.py @@ -1,19 +1,22 @@ # This file was auto-generated by Fern from our API Definition. +from ......core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .object_with_optional_field import ObjectWithOptionalField +import pydantic +from ......core.pydantic_utilities import IS_PYDANTIC_V2 class NestedObjectWithOptionalField(UniversalBaseModel): string: typing.Optional[str] = None - nested_object: typing.Optional[ObjectWithOptionalField] = pydantic.Field(alias="NestedObject", default=None) + nested_object: typing.Optional[ObjectWithOptionalField] = pydantic.Field( + alias="NestedObject", default=None + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/exhaustive/pydantic-v2/resources/types/resources/object/types/nested_object_with_required_field.py b/seed/fastapi/exhaustive/pydantic-v2/resources/types/resources/object/types/nested_object_with_required_field.py index 9f1da7f2b69..c152f7caf34 100644 --- a/seed/fastapi/exhaustive/pydantic-v2/resources/types/resources/object/types/nested_object_with_required_field.py +++ b/seed/fastapi/exhaustive/pydantic-v2/resources/types/resources/object/types/nested_object_with_required_field.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ......core.pydantic_utilities import UniversalBaseModel from .object_with_optional_field import ObjectWithOptionalField +import pydantic +from ......core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class NestedObjectWithRequiredField(UniversalBaseModel): @@ -13,7 +12,9 @@ class NestedObjectWithRequiredField(UniversalBaseModel): nested_object: ObjectWithOptionalField = pydantic.Field(alias="NestedObject") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/exhaustive/pydantic-v2/resources/types/resources/object/types/object_with_map_of_map.py b/seed/fastapi/exhaustive/pydantic-v2/resources/types/resources/object/types/object_with_map_of_map.py index aba295a1e88..259d15f900b 100644 --- a/seed/fastapi/exhaustive/pydantic-v2/resources/types/resources/object/types/object_with_map_of_map.py +++ b/seed/fastapi/exhaustive/pydantic-v2/resources/types/resources/object/types/object_with_map_of_map.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ......core.pydantic_utilities import UniversalBaseModel import typing - import pydantic - -from ......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ......core.pydantic_utilities import IS_PYDANTIC_V2 class ObjectWithMapOfMap(UniversalBaseModel): map_: typing.Dict[str, typing.Dict[str, str]] = pydantic.Field(alias="map") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/exhaustive/pydantic-v2/resources/types/resources/object/types/object_with_optional_field.py b/seed/fastapi/exhaustive/pydantic-v2/resources/types/resources/object/types/object_with_optional_field.py index eb3565c51a2..b8d37eb85ef 100644 --- a/seed/fastapi/exhaustive/pydantic-v2/resources/types/resources/object/types/object_with_optional_field.py +++ b/seed/fastapi/exhaustive/pydantic-v2/resources/types/resources/object/types/object_with_optional_field.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. -import datetime as dt +from ......core.pydantic_utilities import UniversalBaseModel import typing -import uuid - import pydantic - -from ......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +import datetime as dt +import uuid +from ......core.pydantic_utilities import IS_PYDANTIC_V2 class ObjectWithOptionalField(UniversalBaseModel): @@ -23,13 +22,19 @@ class ObjectWithOptionalField(UniversalBaseModel): date: typing.Optional[dt.date] = None uuid_: typing.Optional[uuid.UUID] = pydantic.Field(alias="uuid", default=None) base_64: typing.Optional[str] = pydantic.Field(alias="base64", default=None) - list_: typing.Optional[typing.List[str]] = pydantic.Field(alias="list", default=None) + list_: typing.Optional[typing.List[str]] = pydantic.Field( + alias="list", default=None + ) set_: typing.Optional[typing.Set[str]] = pydantic.Field(alias="set", default=None) - map_: typing.Optional[typing.Dict[int, str]] = pydantic.Field(alias="map", default=None) + map_: typing.Optional[typing.Dict[int, str]] = pydantic.Field( + alias="map", default=None + ) bigint: typing.Optional[str] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/exhaustive/pydantic-v2/resources/types/resources/object/types/object_with_required_field.py b/seed/fastapi/exhaustive/pydantic-v2/resources/types/resources/object/types/object_with_required_field.py index 20aee4fa01f..460dec359be 100644 --- a/seed/fastapi/exhaustive/pydantic-v2/resources/types/resources/object/types/object_with_required_field.py +++ b/seed/fastapi/exhaustive/pydantic-v2/resources/types/resources/object/types/object_with_required_field.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ......core.pydantic_utilities import UniversalBaseModel +from ......core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class ObjectWithRequiredField(UniversalBaseModel): string: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/exhaustive/pydantic-v2/resources/types/resources/union/types/animal.py b/seed/fastapi/exhaustive/pydantic-v2/resources/types/resources/union/types/animal.py index 74285020765..a8ee74c09ed 100644 --- a/seed/fastapi/exhaustive/pydantic-v2/resources/types/resources/union/types/animal.py +++ b/seed/fastapi/exhaustive/pydantic-v2/resources/types/resources/union/types/animal.py @@ -1,15 +1,14 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from .dog import Dog as resources_types_resources_union_types_dog_Dog +from ......core.pydantic_utilities import IS_PYDANTIC_V2 +from .cat import Cat as resources_types_resources_union_types_cat_Cat +from ......core.pydantic_utilities import UniversalRootModel import typing - -import pydantic import typing_extensions - -from ......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalRootModel, update_forward_refs -from .cat import Cat as resources_types_resources_union_types_cat_Cat -from .dog import Dog as resources_types_resources_union_types_dog_Dog +import pydantic +from ......core.pydantic_utilities import update_forward_refs T_Result = typing.TypeVar("T_Result") @@ -17,15 +16,23 @@ class _Factory: def dog(self, value: resources_types_resources_union_types_dog_Dog) -> Animal: if IS_PYDANTIC_V2: - return Animal(root=_Animal.Dog(**value.dict(exclude_unset=True), animal="dog")) + return Animal( + root=_Animal.Dog(**value.dict(exclude_unset=True), animal="dog") + ) else: - return Animal(__root__=_Animal.Dog(**value.dict(exclude_unset=True), animal="dog")) + return Animal( + __root__=_Animal.Dog(**value.dict(exclude_unset=True), animal="dog") + ) def cat(self, value: resources_types_resources_union_types_cat_Cat) -> Animal: if IS_PYDANTIC_V2: - return Animal(root=_Animal.Cat(**value.dict(exclude_unset=True), animal="cat")) + return Animal( + root=_Animal.Cat(**value.dict(exclude_unset=True), animal="cat") + ) else: - return Animal(__root__=_Animal.Cat(**value.dict(exclude_unset=True), animal="cat")) + return Animal( + __root__=_Animal.Cat(**value.dict(exclude_unset=True), animal="cat") + ) class Animal(UniversalRootModel): @@ -33,15 +40,16 @@ class Animal(UniversalRootModel): if IS_PYDANTIC_V2: root: typing_extensions.Annotated[ - typing.Union[_Animal.Dog, _Animal.Cat], pydantic.Field(discriminator="animal") + typing.Union[_Animal.Dog, _Animal.Cat], + pydantic.Field(discriminator="animal"), ] def get_as_union(self) -> typing.Union[_Animal.Dog, _Animal.Cat]: return self.root - else: __root__: typing_extensions.Annotated[ - typing.Union[_Animal.Dog, _Animal.Cat], pydantic.Field(discriminator="animal") + typing.Union[_Animal.Dog, _Animal.Cat], + pydantic.Field(discriminator="animal"), ] def get_as_union(self) -> typing.Union[_Animal.Dog, _Animal.Cat]: diff --git a/seed/fastapi/exhaustive/pydantic-v2/resources/types/resources/union/types/cat.py b/seed/fastapi/exhaustive/pydantic-v2/resources/types/resources/union/types/cat.py index 2436a0fd384..cdcfe7a1d25 100644 --- a/seed/fastapi/exhaustive/pydantic-v2/resources/types/resources/union/types/cat.py +++ b/seed/fastapi/exhaustive/pydantic-v2/resources/types/resources/union/types/cat.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ......core.pydantic_utilities import UniversalBaseModel import pydantic - -from ......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ......core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class Cat(UniversalBaseModel): @@ -12,7 +11,9 @@ class Cat(UniversalBaseModel): likes_to_meow: bool = pydantic.Field(alias="likesToMeow") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/exhaustive/pydantic-v2/resources/types/resources/union/types/dog.py b/seed/fastapi/exhaustive/pydantic-v2/resources/types/resources/union/types/dog.py index 3afc51b5137..b5feda1e61c 100644 --- a/seed/fastapi/exhaustive/pydantic-v2/resources/types/resources/union/types/dog.py +++ b/seed/fastapi/exhaustive/pydantic-v2/resources/types/resources/union/types/dog.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ......core.pydantic_utilities import UniversalBaseModel import pydantic - -from ......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ......core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class Dog(UniversalBaseModel): @@ -12,7 +11,9 @@ class Dog(UniversalBaseModel): likes_to_woof: bool = pydantic.Field(alias="likesToWoof") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/exhaustive/pydantic-v2/security.py b/seed/fastapi/exhaustive/pydantic-v2/security.py index bab014441e1..4ccabc21106 100644 --- a/seed/fastapi/exhaustive/pydantic-v2/security.py +++ b/seed/fastapi/exhaustive/pydantic-v2/security.py @@ -1,8 +1,8 @@ # This file was auto-generated by Fern from our API Definition. +from .core.security.bearer import BearerToken import fastapi - -from .core.security.bearer import BearerToken, HTTPBearer +from .core.security.bearer import HTTPBearer ApiAuth = BearerToken diff --git a/seed/fastapi/exhaustive/skip-formatting/__init__.py b/seed/fastapi/exhaustive/skip-formatting/__init__.py index 6c6c35bc0c2..6eda4b194c2 100644 --- a/seed/fastapi/exhaustive/skip-formatting/__init__.py +++ b/seed/fastapi/exhaustive/skip-formatting/__init__.py @@ -1,5 +1,21 @@ # This file was auto-generated by Fern from our API Definition. -from .resources import BadObjectRequestInfo, BadRequestBody, PostWithObjectBody, general_errors, inlined_requests, types +from .resources import ( + BadObjectRequestInfo, + BadRequestBody, + PostWithObjectBody, + general_errors, + inlined_requests, + types, +) from .security import ApiAuth -__all__ = ["ApiAuth", "BadObjectRequestInfo", "BadRequestBody", "PostWithObjectBody", "general_errors", "inlined_requests", "types"] + +__all__ = [ + "ApiAuth", + "BadObjectRequestInfo", + "BadRequestBody", + "PostWithObjectBody", + "general_errors", + "inlined_requests", + "types", +] diff --git a/seed/fastapi/exhaustive/skip-formatting/core/__init__.py b/seed/fastapi/exhaustive/skip-formatting/core/__init__.py index 227c81bd4f9..f375cd27ae8 100644 --- a/seed/fastapi/exhaustive/skip-formatting/core/__init__.py +++ b/seed/fastapi/exhaustive/skip-formatting/core/__init__.py @@ -1,8 +1,41 @@ # This file was auto-generated by Fern from our API Definition. from .datetime_utils import serialize_datetime -from .exceptions import FernHTTPException, UnauthorizedException, default_exception_handler, fern_http_exception_handler, http_exception_handler -from .pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel, UniversalRootModel, deep_union_pydantic_dicts, parse_obj_as, universal_field_validator, universal_root_validator, update_forward_refs +from .exceptions import ( + FernHTTPException, + UnauthorizedException, + default_exception_handler, + fern_http_exception_handler, + http_exception_handler, +) +from .pydantic_utilities import ( + IS_PYDANTIC_V2, + UniversalBaseModel, + UniversalRootModel, + deep_union_pydantic_dicts, + parse_obj_as, + universal_field_validator, + universal_root_validator, + update_forward_refs, +) from .route_args import route_args from .security import BearerToken -__all__ = ["BearerToken", "FernHTTPException", "IS_PYDANTIC_V2", "UnauthorizedException", "UniversalBaseModel", "UniversalRootModel", "deep_union_pydantic_dicts", "default_exception_handler", "fern_http_exception_handler", "http_exception_handler", "parse_obj_as", "route_args", "serialize_datetime", "universal_field_validator", "universal_root_validator", "update_forward_refs"] + +__all__ = [ + "BearerToken", + "FernHTTPException", + "IS_PYDANTIC_V2", + "UnauthorizedException", + "UniversalBaseModel", + "UniversalRootModel", + "deep_union_pydantic_dicts", + "default_exception_handler", + "fern_http_exception_handler", + "http_exception_handler", + "parse_obj_as", + "route_args", + "serialize_datetime", + "universal_field_validator", + "universal_root_validator", + "update_forward_refs", +] diff --git a/seed/fastapi/exhaustive/skip-formatting/core/abstract_fern_service.py b/seed/fastapi/exhaustive/skip-formatting/core/abstract_fern_service.py index da7c8dc49c4..9966b4876da 100644 --- a/seed/fastapi/exhaustive/skip-formatting/core/abstract_fern_service.py +++ b/seed/fastapi/exhaustive/skip-formatting/core/abstract_fern_service.py @@ -7,5 +7,4 @@ class AbstractFernService(abc.ABC): @classmethod - def _init_fern(cls, router: fastapi.APIRouter) -> None: - ... + def _init_fern(cls, router: fastapi.APIRouter) -> None: ... diff --git a/seed/fastapi/exhaustive/skip-formatting/core/datetime_utils.py b/seed/fastapi/exhaustive/skip-formatting/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/fastapi/exhaustive/skip-formatting/core/datetime_utils.py +++ b/seed/fastapi/exhaustive/skip-formatting/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/fastapi/exhaustive/skip-formatting/core/exceptions/__init__.py b/seed/fastapi/exhaustive/skip-formatting/core/exceptions/__init__.py index c5d9bfdf9aa..dae4b8980c1 100644 --- a/seed/fastapi/exhaustive/skip-formatting/core/exceptions/__init__.py +++ b/seed/fastapi/exhaustive/skip-formatting/core/exceptions/__init__.py @@ -1,6 +1,17 @@ # This file was auto-generated by Fern from our API Definition. from .fern_http_exception import FernHTTPException -from .handlers import default_exception_handler, fern_http_exception_handler, http_exception_handler +from .handlers import ( + default_exception_handler, + fern_http_exception_handler, + http_exception_handler, +) from .unauthorized import UnauthorizedException -__all__ = ["FernHTTPException", "UnauthorizedException", "default_exception_handler", "fern_http_exception_handler", "http_exception_handler"] + +__all__ = [ + "FernHTTPException", + "UnauthorizedException", + "default_exception_handler", + "fern_http_exception_handler", + "http_exception_handler", +] diff --git a/seed/fastapi/exhaustive/skip-formatting/core/exceptions/fern_http_exception.py b/seed/fastapi/exhaustive/skip-formatting/core/exceptions/fern_http_exception.py index c33bebae141..81610359a7f 100644 --- a/seed/fastapi/exhaustive/skip-formatting/core/exceptions/fern_http_exception.py +++ b/seed/fastapi/exhaustive/skip-formatting/core/exceptions/fern_http_exception.py @@ -3,13 +3,22 @@ import abc import fastapi import typing + + class FernHTTPException(abc.ABC, fastapi.HTTPException): - def __init__(self, status_code: int, name: typing.Optional[str] = None, content: typing.Optional[typing.Any] = None): + def __init__( + self, + status_code: int, + name: typing.Optional[str] = None, + content: typing.Optional[typing.Any] = None, + ): super().__init__(status_code=status_code) self.name = name self.status_code = status_code self.content = content - + def to_json_response(self) -> fastapi.responses.JSONResponse: content = fastapi.encoders.jsonable_encoder(self.content, exclude_none=True) - return fastapi.responses.JSONResponse(content=content, status_code=self.status_code) + return fastapi.responses.JSONResponse( + content=content, status_code=self.status_code + ) diff --git a/seed/fastapi/exhaustive/skip-formatting/core/exceptions/handlers.py b/seed/fastapi/exhaustive/skip-formatting/core/exceptions/handlers.py index b40c00fcbb8..ae1c2741f06 100644 --- a/seed/fastapi/exhaustive/skip-formatting/core/exceptions/handlers.py +++ b/seed/fastapi/exhaustive/skip-formatting/core/exceptions/handlers.py @@ -16,7 +16,9 @@ def fern_http_exception_handler( skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) return exc.to_json_response() @@ -26,8 +28,12 @@ def http_exception_handler( skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=exc.status_code, content=exc.detail).to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=exc.status_code, content=exc.detail + ).to_json_response() def default_exception_handler( @@ -36,5 +42,9 @@ def default_exception_handler( skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=500, content="Internal Server Error").to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=500, content="Internal Server Error" + ).to_json_response() diff --git a/seed/fastapi/exhaustive/skip-formatting/core/pydantic_utilities.py b/seed/fastapi/exhaustive/skip-formatting/core/pydantic_utilities.py index e2901360572..a93b06c3fca 100644 --- a/seed/fastapi/exhaustive/skip-formatting/core/pydantic_utilities.py +++ b/seed/fastapi/exhaustive/skip-formatting/core/pydantic_utilities.py @@ -94,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -111,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -151,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -167,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/fastapi/exhaustive/skip-formatting/core/route_args.py b/seed/fastapi/exhaustive/skip-formatting/core/route_args.py index 4228e2fe05d..bd940bf4ddd 100644 --- a/seed/fastapi/exhaustive/skip-formatting/core/route_args.py +++ b/seed/fastapi/exhaustive/skip-formatting/core/route_args.py @@ -20,9 +20,15 @@ class RouteArgs(typing_extensions.TypedDict): DEFAULT_ROUTE_ARGS = RouteArgs(openapi_extra=None, tags=None, include_in_schema=True) -def get_route_args(endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str) -> RouteArgs: - unwrapped = inspect.unwrap(endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY))) - route_args = typing.cast(RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS)) +def get_route_args( + endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str +) -> RouteArgs: + unwrapped = inspect.unwrap( + endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY)) + ) + route_args = typing.cast( + RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS) + ) if route_args["tags"] is None: return RouteArgs( openapi_extra=route_args["openapi_extra"], @@ -56,7 +62,11 @@ def decorator(endpoint_function: T) -> T: setattr( endpoint_function, FERN_CONFIG_KEY, - RouteArgs(openapi_extra=openapi_extra, tags=tags, include_in_schema=include_in_schema), + RouteArgs( + openapi_extra=openapi_extra, + tags=tags, + include_in_schema=include_in_schema, + ), ) return endpoint_function diff --git a/seed/fastapi/exhaustive/skip-formatting/core/security/__init__.py b/seed/fastapi/exhaustive/skip-formatting/core/security/__init__.py index b44bad47182..e69ee6d9c5a 100644 --- a/seed/fastapi/exhaustive/skip-formatting/core/security/__init__.py +++ b/seed/fastapi/exhaustive/skip-formatting/core/security/__init__.py @@ -1,4 +1,5 @@ # This file was auto-generated by Fern from our API Definition. from .bearer import BearerToken + __all__ = ["BearerToken"] diff --git a/seed/fastapi/exhaustive/skip-formatting/register.py b/seed/fastapi/exhaustive/skip-formatting/register.py index 0a63ad31d5c..1f804567f73 100644 --- a/seed/fastapi/exhaustive/skip-formatting/register.py +++ b/seed/fastapi/exhaustive/skip-formatting/register.py @@ -1,13 +1,27 @@ # This file was auto-generated by Fern from our API Definition. import fastapi -from .resources.endpoints.resources.container.service.service import AbstractEndpointsContainerService -from .resources.endpoints.resources.enum.service.service import AbstractEndpointsEnumService -from .resources.endpoints.resources.http_methods.service.service import AbstractEndpointsHttpMethodsService -from .resources.endpoints.resources.object.service.service import AbstractEndpointsObjectService -from .resources.endpoints.resources.params.service.service import AbstractEndpointsParamsService -from .resources.endpoints.resources.primitive.service.service import AbstractEndpointsPrimitiveService -from .resources.endpoints.resources.union.service.service import AbstractEndpointsUnionService +from .resources.endpoints.resources.container.service.service import ( + AbstractEndpointsContainerService, +) +from .resources.endpoints.resources.enum.service.service import ( + AbstractEndpointsEnumService, +) +from .resources.endpoints.resources.http_methods.service.service import ( + AbstractEndpointsHttpMethodsService, +) +from .resources.endpoints.resources.object.service.service import ( + AbstractEndpointsObjectService, +) +from .resources.endpoints.resources.params.service.service import ( + AbstractEndpointsParamsService, +) +from .resources.endpoints.resources.primitive.service.service import ( + AbstractEndpointsPrimitiveService, +) +from .resources.endpoints.resources.union.service.service import ( + AbstractEndpointsUnionService, +) from .resources.inlined_requests.service.service import AbstractInlinedRequestsService from .resources.no_auth.service.service import AbstractNoAuthService from .resources.no_req_body.service.service import AbstractNoReqBodyService @@ -24,29 +38,60 @@ import os import glob import importlib -def register(_app: fastapi.FastAPI, *, endpoints_container: AbstractEndpointsContainerService, endpoints_enum: AbstractEndpointsEnumService, endpoints_http_methods: AbstractEndpointsHttpMethodsService, endpoints_object: AbstractEndpointsObjectService, endpoints_params: AbstractEndpointsParamsService, endpoints_primitive: AbstractEndpointsPrimitiveService, endpoints_union: AbstractEndpointsUnionService, inlined_requests: AbstractInlinedRequestsService, no_auth: AbstractNoAuthService, no_req_body: AbstractNoReqBodyService, req_with_headers: AbstractReqWithHeadersService, dependencies: typing.Optional[typing.Sequence[params.Depends]] = None) -> None: - _app.include_router(__register_service(endpoints_container), dependencies=dependencies) + + +def register( + _app: fastapi.FastAPI, + *, + endpoints_container: AbstractEndpointsContainerService, + endpoints_enum: AbstractEndpointsEnumService, + endpoints_http_methods: AbstractEndpointsHttpMethodsService, + endpoints_object: AbstractEndpointsObjectService, + endpoints_params: AbstractEndpointsParamsService, + endpoints_primitive: AbstractEndpointsPrimitiveService, + endpoints_union: AbstractEndpointsUnionService, + inlined_requests: AbstractInlinedRequestsService, + no_auth: AbstractNoAuthService, + no_req_body: AbstractNoReqBodyService, + req_with_headers: AbstractReqWithHeadersService, + dependencies: typing.Optional[typing.Sequence[params.Depends]] = None, +) -> None: + _app.include_router( + __register_service(endpoints_container), dependencies=dependencies + ) _app.include_router(__register_service(endpoints_enum), dependencies=dependencies) - _app.include_router(__register_service(endpoints_http_methods), dependencies=dependencies) + _app.include_router( + __register_service(endpoints_http_methods), dependencies=dependencies + ) _app.include_router(__register_service(endpoints_object), dependencies=dependencies) _app.include_router(__register_service(endpoints_params), dependencies=dependencies) - _app.include_router(__register_service(endpoints_primitive), dependencies=dependencies) + _app.include_router( + __register_service(endpoints_primitive), dependencies=dependencies + ) _app.include_router(__register_service(endpoints_union), dependencies=dependencies) _app.include_router(__register_service(inlined_requests), dependencies=dependencies) _app.include_router(__register_service(no_auth), dependencies=dependencies) _app.include_router(__register_service(no_req_body), dependencies=dependencies) _app.include_router(__register_service(req_with_headers), dependencies=dependencies) - + _app.add_exception_handler(FernHTTPException, fern_http_exception_handler) # type: ignore - _app.add_exception_handler(starlette.exceptions.HTTPException, http_exception_handler) # type: ignore + _app.add_exception_handler( + starlette.exceptions.HTTPException, http_exception_handler + ) # type: ignore _app.add_exception_handler(Exception, default_exception_handler) # type: ignore + + def __register_service(service: AbstractFernService) -> fastapi.APIRouter: router = fastapi.APIRouter() type(service)._init_fern(router) return router + + def register_validators(module: types.ModuleType) -> None: validators_directory: str = os.path.dirname(module.__file__) # type: ignore - for path in glob.glob(os.path.join(validators_directory, "**/*.py"), recursive=True): + for path in glob.glob( + os.path.join(validators_directory, "**/*.py"), recursive=True + ): if os.path.isfile(path): relative_path = os.path.relpath(path, start=validators_directory) module_path = ".".join([module.__name__] + relative_path[:-3].split("/")) diff --git a/seed/fastapi/exhaustive/skip-formatting/resources/__init__.py b/seed/fastapi/exhaustive/skip-formatting/resources/__init__.py index fa8a36785ec..29cd2856565 100644 --- a/seed/fastapi/exhaustive/skip-formatting/resources/__init__.py +++ b/seed/fastapi/exhaustive/skip-formatting/resources/__init__.py @@ -3,4 +3,12 @@ from . import general_errors, inlined_requests, types from .general_errors import BadObjectRequestInfo, BadRequestBody from .inlined_requests import PostWithObjectBody -__all__ = ["BadObjectRequestInfo", "BadRequestBody", "PostWithObjectBody", "general_errors", "inlined_requests", "types"] + +__all__ = [ + "BadObjectRequestInfo", + "BadRequestBody", + "PostWithObjectBody", + "general_errors", + "inlined_requests", + "types", +] diff --git a/seed/fastapi/exhaustive/skip-formatting/resources/endpoints/resources/container/service/__init__.py b/seed/fastapi/exhaustive/skip-formatting/resources/endpoints/resources/container/service/__init__.py index 71fd7bc50fe..21bb0c47d17 100644 --- a/seed/fastapi/exhaustive/skip-formatting/resources/endpoints/resources/container/service/__init__.py +++ b/seed/fastapi/exhaustive/skip-formatting/resources/endpoints/resources/container/service/__init__.py @@ -1,4 +1,5 @@ # This file was auto-generated by Fern from our API Definition. from .service import AbstractEndpointsContainerService + __all__ = ["AbstractEndpointsContainerService"] diff --git a/seed/fastapi/exhaustive/skip-formatting/resources/endpoints/resources/container/service/service.py b/seed/fastapi/exhaustive/skip-formatting/resources/endpoints/resources/container/service/service.py index cb1dbe4f96d..79da48ea0cc 100644 --- a/seed/fastapi/exhaustive/skip-formatting/resources/endpoints/resources/container/service/service.py +++ b/seed/fastapi/exhaustive/skip-formatting/resources/endpoints/resources/container/service/service.py @@ -4,7 +4,9 @@ import typing from ......security import ApiAuth import abc -from .....types.resources.object.types.object_with_required_field import ObjectWithRequiredField +from .....types.resources.object.types.object_with_required_field import ( + ObjectWithRequiredField, +) import fastapi import inspect from ......security import FernAuth @@ -12,48 +14,57 @@ import logging import functools from ......core.route_args import get_route_args + + class AbstractEndpointsContainerService(AbstractFernService): """ AbstractEndpointsContainerService is an abstract class containing the methods that you should implement. - + Each method is associated with an API route, which will be registered with FastAPI when you register your implementation using Fern's register() function. """ - + @abc.abstractmethod - def get_and_return_list_of_primitives(self, *, body: typing.List[str], auth: ApiAuth) -> typing.Sequence[str]: - ... - + def get_and_return_list_of_primitives( + self, *, body: typing.List[str], auth: ApiAuth + ) -> typing.Sequence[str]: ... + @abc.abstractmethod - def get_and_return_list_of_objects(self, *, body: typing.List[ObjectWithRequiredField], auth: ApiAuth) -> typing.Sequence[ObjectWithRequiredField]: - ... - + def get_and_return_list_of_objects( + self, *, body: typing.List[ObjectWithRequiredField], auth: ApiAuth + ) -> typing.Sequence[ObjectWithRequiredField]: ... + @abc.abstractmethod - def get_and_return_set_of_primitives(self, *, body: typing.Set[str], auth: ApiAuth) -> typing.Set[str]: - ... - + def get_and_return_set_of_primitives( + self, *, body: typing.Set[str], auth: ApiAuth + ) -> typing.Set[str]: ... + @abc.abstractmethod - def get_and_return_set_of_objects(self, *, body: typing.List[ObjectWithRequiredField], auth: ApiAuth) -> typing.Sequence[ObjectWithRequiredField]: - ... - + def get_and_return_set_of_objects( + self, *, body: typing.List[ObjectWithRequiredField], auth: ApiAuth + ) -> typing.Sequence[ObjectWithRequiredField]: ... + @abc.abstractmethod - def get_and_return_map_prim_to_prim(self, *, body: typing.Dict[str, str], auth: ApiAuth) -> typing.Dict[str, str]: - ... - + def get_and_return_map_prim_to_prim( + self, *, body: typing.Dict[str, str], auth: ApiAuth + ) -> typing.Dict[str, str]: ... + @abc.abstractmethod - def get_and_return_map_of_prim_to_object(self, *, body: typing.Dict[str, ObjectWithRequiredField], auth: ApiAuth) -> typing.Dict[str, ObjectWithRequiredField]: - ... - + def get_and_return_map_of_prim_to_object( + self, *, body: typing.Dict[str, ObjectWithRequiredField], auth: ApiAuth + ) -> typing.Dict[str, ObjectWithRequiredField]: ... + @abc.abstractmethod - def get_and_return_optional(self, *, body: typing.Optional[ObjectWithRequiredField] = None, auth: ApiAuth) -> typing.Optional[ObjectWithRequiredField]: - ... - + def get_and_return_optional( + self, *, body: typing.Optional[ObjectWithRequiredField] = None, auth: ApiAuth + ) -> typing.Optional[ObjectWithRequiredField]: ... + """ Below are internal methods used by Fern to register your implementation. You can ignore them. """ - + @classmethod def _init_fern(cls, router: fastapi.APIRouter) -> None: cls.__init_get_and_return_list_of_primitives(router=router) @@ -63,22 +74,32 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: cls.__init_get_and_return_map_prim_to_prim(router=router) cls.__init_get_and_return_map_of_prim_to_object(router=router) cls.__init_get_and_return_optional(router=router) - + @classmethod - def __init_get_and_return_list_of_primitives(cls, router: fastapi.APIRouter) -> None: + def __init_get_and_return_list_of_primitives( + cls, router: fastapi.APIRouter + ) -> None: endpoint_function = inspect.signature(cls.get_and_return_list_of_primitives) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_and_return_list_of_primitives, "__signature__", endpoint_function.replace(parameters=new_parameters)) - + setattr( + cls.get_and_return_list_of_primitives, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) + @functools.wraps(cls.get_and_return_list_of_primitives) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> typing.Sequence[str]: try: @@ -90,35 +111,47 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> typing.Sequence[str]: + "the endpoint's errors list in your Fern Definition." ) raise e - + # this is necessary for FastAPI to find forward-ref'ed type hints. # https://github.com/tiangolo/fastapi/pull/5077 wrapper.__globals__.update(cls.get_and_return_list_of_primitives.__globals__) - + router.post( path="/container/list-of-primitives", response_model=typing.Sequence[str], description=AbstractEndpointsContainerService.get_and_return_list_of_primitives.__doc__, - **get_route_args(cls.get_and_return_list_of_primitives, default_tag="endpoints.container"), + **get_route_args( + cls.get_and_return_list_of_primitives, default_tag="endpoints.container" + ), )(wrapper) - + @classmethod def __init_get_and_return_list_of_objects(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_and_return_list_of_objects) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_and_return_list_of_objects, "__signature__", endpoint_function.replace(parameters=new_parameters)) - + setattr( + cls.get_and_return_list_of_objects, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) + @functools.wraps(cls.get_and_return_list_of_objects) - def wrapper(*args: typing.Any, **kwargs: typing.Any) -> typing.Sequence[ObjectWithRequiredField]: + def wrapper( + *args: typing.Any, **kwargs: typing.Any + ) -> typing.Sequence[ObjectWithRequiredField]: try: return cls.get_and_return_list_of_objects(*args, **kwargs) except FernHTTPException as e: @@ -128,33 +161,43 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> typing.Sequence[ObjectWi + "the endpoint's errors list in your Fern Definition." ) raise e - + # this is necessary for FastAPI to find forward-ref'ed type hints. # https://github.com/tiangolo/fastapi/pull/5077 wrapper.__globals__.update(cls.get_and_return_list_of_objects.__globals__) - + router.post( path="/container/list-of-objects", response_model=typing.Sequence[ObjectWithRequiredField], description=AbstractEndpointsContainerService.get_and_return_list_of_objects.__doc__, - **get_route_args(cls.get_and_return_list_of_objects, default_tag="endpoints.container"), + **get_route_args( + cls.get_and_return_list_of_objects, default_tag="endpoints.container" + ), )(wrapper) - + @classmethod def __init_get_and_return_set_of_primitives(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_and_return_set_of_primitives) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_and_return_set_of_primitives, "__signature__", endpoint_function.replace(parameters=new_parameters)) - + setattr( + cls.get_and_return_set_of_primitives, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) + @functools.wraps(cls.get_and_return_set_of_primitives) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> typing.Set[str]: try: @@ -166,35 +209,47 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> typing.Set[str]: + "the endpoint's errors list in your Fern Definition." ) raise e - + # this is necessary for FastAPI to find forward-ref'ed type hints. # https://github.com/tiangolo/fastapi/pull/5077 wrapper.__globals__.update(cls.get_and_return_set_of_primitives.__globals__) - + router.post( path="/container/set-of-primitives", response_model=typing.Set[str], description=AbstractEndpointsContainerService.get_and_return_set_of_primitives.__doc__, - **get_route_args(cls.get_and_return_set_of_primitives, default_tag="endpoints.container"), + **get_route_args( + cls.get_and_return_set_of_primitives, default_tag="endpoints.container" + ), )(wrapper) - + @classmethod def __init_get_and_return_set_of_objects(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_and_return_set_of_objects) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_and_return_set_of_objects, "__signature__", endpoint_function.replace(parameters=new_parameters)) - + setattr( + cls.get_and_return_set_of_objects, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) + @functools.wraps(cls.get_and_return_set_of_objects) - def wrapper(*args: typing.Any, **kwargs: typing.Any) -> typing.Sequence[ObjectWithRequiredField]: + def wrapper( + *args: typing.Any, **kwargs: typing.Any + ) -> typing.Sequence[ObjectWithRequiredField]: try: return cls.get_and_return_set_of_objects(*args, **kwargs) except FernHTTPException as e: @@ -204,33 +259,43 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> typing.Sequence[ObjectWi + "the endpoint's errors list in your Fern Definition." ) raise e - + # this is necessary for FastAPI to find forward-ref'ed type hints. # https://github.com/tiangolo/fastapi/pull/5077 wrapper.__globals__.update(cls.get_and_return_set_of_objects.__globals__) - + router.post( path="/container/set-of-objects", response_model=typing.Sequence[ObjectWithRequiredField], description=AbstractEndpointsContainerService.get_and_return_set_of_objects.__doc__, - **get_route_args(cls.get_and_return_set_of_objects, default_tag="endpoints.container"), + **get_route_args( + cls.get_and_return_set_of_objects, default_tag="endpoints.container" + ), )(wrapper) - + @classmethod def __init_get_and_return_map_prim_to_prim(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_and_return_map_prim_to_prim) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_and_return_map_prim_to_prim, "__signature__", endpoint_function.replace(parameters=new_parameters)) - + setattr( + cls.get_and_return_map_prim_to_prim, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) + @functools.wraps(cls.get_and_return_map_prim_to_prim) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> typing.Dict[str, str]: try: @@ -242,35 +307,49 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> typing.Dict[str, str]: + "the endpoint's errors list in your Fern Definition." ) raise e - + # this is necessary for FastAPI to find forward-ref'ed type hints. # https://github.com/tiangolo/fastapi/pull/5077 wrapper.__globals__.update(cls.get_and_return_map_prim_to_prim.__globals__) - + router.post( path="/container/map-prim-to-prim", response_model=typing.Dict[str, str], description=AbstractEndpointsContainerService.get_and_return_map_prim_to_prim.__doc__, - **get_route_args(cls.get_and_return_map_prim_to_prim, default_tag="endpoints.container"), + **get_route_args( + cls.get_and_return_map_prim_to_prim, default_tag="endpoints.container" + ), )(wrapper) - + @classmethod - def __init_get_and_return_map_of_prim_to_object(cls, router: fastapi.APIRouter) -> None: + def __init_get_and_return_map_of_prim_to_object( + cls, router: fastapi.APIRouter + ) -> None: endpoint_function = inspect.signature(cls.get_and_return_map_of_prim_to_object) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_and_return_map_of_prim_to_object, "__signature__", endpoint_function.replace(parameters=new_parameters)) - + setattr( + cls.get_and_return_map_of_prim_to_object, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) + @functools.wraps(cls.get_and_return_map_of_prim_to_object) - def wrapper(*args: typing.Any, **kwargs: typing.Any) -> typing.Dict[str, ObjectWithRequiredField]: + def wrapper( + *args: typing.Any, **kwargs: typing.Any + ) -> typing.Dict[str, ObjectWithRequiredField]: try: return cls.get_and_return_map_of_prim_to_object(*args, **kwargs) except FernHTTPException as e: @@ -280,35 +359,48 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> typing.Dict[str, ObjectW + "the endpoint's errors list in your Fern Definition." ) raise e - + # this is necessary for FastAPI to find forward-ref'ed type hints. # https://github.com/tiangolo/fastapi/pull/5077 wrapper.__globals__.update(cls.get_and_return_map_of_prim_to_object.__globals__) - + router.post( path="/container/map-prim-to-object", response_model=typing.Dict[str, ObjectWithRequiredField], description=AbstractEndpointsContainerService.get_and_return_map_of_prim_to_object.__doc__, - **get_route_args(cls.get_and_return_map_of_prim_to_object, default_tag="endpoints.container"), + **get_route_args( + cls.get_and_return_map_of_prim_to_object, + default_tag="endpoints.container", + ), )(wrapper) - + @classmethod def __init_get_and_return_optional(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_and_return_optional) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_and_return_optional, "__signature__", endpoint_function.replace(parameters=new_parameters)) - + setattr( + cls.get_and_return_optional, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) + @functools.wraps(cls.get_and_return_optional) - def wrapper(*args: typing.Any, **kwargs: typing.Any) -> typing.Optional[ObjectWithRequiredField]: + def wrapper( + *args: typing.Any, **kwargs: typing.Any + ) -> typing.Optional[ObjectWithRequiredField]: try: return cls.get_and_return_optional(*args, **kwargs) except FernHTTPException as e: @@ -318,14 +410,16 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> typing.Optional[ObjectWi + "the endpoint's errors list in your Fern Definition." ) raise e - + # this is necessary for FastAPI to find forward-ref'ed type hints. # https://github.com/tiangolo/fastapi/pull/5077 wrapper.__globals__.update(cls.get_and_return_optional.__globals__) - + router.post( path="/container/opt-objects", response_model=typing.Optional[ObjectWithRequiredField], description=AbstractEndpointsContainerService.get_and_return_optional.__doc__, - **get_route_args(cls.get_and_return_optional, default_tag="endpoints.container"), + **get_route_args( + cls.get_and_return_optional, default_tag="endpoints.container" + ), )(wrapper) diff --git a/seed/fastapi/exhaustive/skip-formatting/resources/endpoints/resources/enum/service/__init__.py b/seed/fastapi/exhaustive/skip-formatting/resources/endpoints/resources/enum/service/__init__.py index 50e0c23e6f5..6415e959895 100644 --- a/seed/fastapi/exhaustive/skip-formatting/resources/endpoints/resources/enum/service/__init__.py +++ b/seed/fastapi/exhaustive/skip-formatting/resources/endpoints/resources/enum/service/__init__.py @@ -1,4 +1,5 @@ # This file was auto-generated by Fern from our API Definition. from .service import AbstractEndpointsEnumService + __all__ = ["AbstractEndpointsEnumService"] diff --git a/seed/fastapi/exhaustive/skip-formatting/resources/endpoints/resources/enum/service/service.py b/seed/fastapi/exhaustive/skip-formatting/resources/endpoints/resources/enum/service/service.py index a03bbc2ad44..4c665920e0b 100644 --- a/seed/fastapi/exhaustive/skip-formatting/resources/endpoints/resources/enum/service/service.py +++ b/seed/fastapi/exhaustive/skip-formatting/resources/endpoints/resources/enum/service/service.py @@ -12,43 +12,54 @@ import logging import functools from ......core.route_args import get_route_args + + class AbstractEndpointsEnumService(AbstractFernService): """ AbstractEndpointsEnumService is an abstract class containing the methods that you should implement. - + Each method is associated with an API route, which will be registered with FastAPI when you register your implementation using Fern's register() function. """ - + @abc.abstractmethod - def get_and_return_enum(self, *, body: WeatherReport, auth: ApiAuth) -> WeatherReport: - ... - + def get_and_return_enum( + self, *, body: WeatherReport, auth: ApiAuth + ) -> WeatherReport: ... + """ Below are internal methods used by Fern to register your implementation. You can ignore them. """ - + @classmethod def _init_fern(cls, router: fastapi.APIRouter) -> None: cls.__init_get_and_return_enum(router=router) - + @classmethod def __init_get_and_return_enum(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_and_return_enum) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_and_return_enum, "__signature__", endpoint_function.replace(parameters=new_parameters)) - + setattr( + cls.get_and_return_enum, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) + @functools.wraps(cls.get_and_return_enum) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> WeatherReport: try: @@ -60,11 +71,11 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> WeatherReport: + "the endpoint's errors list in your Fern Definition." ) raise e - + # this is necessary for FastAPI to find forward-ref'ed type hints. # https://github.com/tiangolo/fastapi/pull/5077 wrapper.__globals__.update(cls.get_and_return_enum.__globals__) - + router.post( path="/enum", response_model=WeatherReport, diff --git a/seed/fastapi/exhaustive/skip-formatting/resources/endpoints/resources/http_methods/service/__init__.py b/seed/fastapi/exhaustive/skip-formatting/resources/endpoints/resources/http_methods/service/__init__.py index eb8ecdff01b..22ea254d225 100644 --- a/seed/fastapi/exhaustive/skip-formatting/resources/endpoints/resources/http_methods/service/__init__.py +++ b/seed/fastapi/exhaustive/skip-formatting/resources/endpoints/resources/http_methods/service/__init__.py @@ -1,4 +1,5 @@ # This file was auto-generated by Fern from our API Definition. from .service import AbstractEndpointsHttpMethodsService + __all__ = ["AbstractEndpointsHttpMethodsService"] diff --git a/seed/fastapi/exhaustive/skip-formatting/resources/endpoints/resources/http_methods/service/service.py b/seed/fastapi/exhaustive/skip-formatting/resources/endpoints/resources/http_methods/service/service.py index a279de30890..73b65270c55 100644 --- a/seed/fastapi/exhaustive/skip-formatting/resources/endpoints/resources/http_methods/service/service.py +++ b/seed/fastapi/exhaustive/skip-formatting/resources/endpoints/resources/http_methods/service/service.py @@ -3,8 +3,12 @@ from ......core.abstract_fern_service import AbstractFernService from ......security import ApiAuth import abc -from .....types.resources.object.types.object_with_required_field import ObjectWithRequiredField -from .....types.resources.object.types.object_with_optional_field import ObjectWithOptionalField +from .....types.resources.object.types.object_with_required_field import ( + ObjectWithRequiredField, +) +from .....types.resources.object.types.object_with_optional_field import ( + ObjectWithOptionalField, +) import fastapi import inspect import typing @@ -13,40 +17,43 @@ import logging import functools from ......core.route_args import get_route_args + + class AbstractEndpointsHttpMethodsService(AbstractFernService): """ AbstractEndpointsHttpMethodsService is an abstract class containing the methods that you should implement. - + Each method is associated with an API route, which will be registered with FastAPI when you register your implementation using Fern's register() function. """ - + @abc.abstractmethod - def test_get(self, *, id: str, auth: ApiAuth) -> str: - ... - + def test_get(self, *, id: str, auth: ApiAuth) -> str: ... + @abc.abstractmethod - def test_post(self, *, body: ObjectWithRequiredField, auth: ApiAuth) -> ObjectWithOptionalField: - ... - + def test_post( + self, *, body: ObjectWithRequiredField, auth: ApiAuth + ) -> ObjectWithOptionalField: ... + @abc.abstractmethod - def test_put(self, *, body: ObjectWithRequiredField, id: str, auth: ApiAuth) -> ObjectWithOptionalField: - ... - + def test_put( + self, *, body: ObjectWithRequiredField, id: str, auth: ApiAuth + ) -> ObjectWithOptionalField: ... + @abc.abstractmethod - def test_patch(self, *, body: ObjectWithOptionalField, id: str, auth: ApiAuth) -> ObjectWithOptionalField: - ... - + def test_patch( + self, *, body: ObjectWithOptionalField, id: str, auth: ApiAuth + ) -> ObjectWithOptionalField: ... + @abc.abstractmethod - def test_delete(self, *, id: str, auth: ApiAuth) -> bool: - ... - + def test_delete(self, *, id: str, auth: ApiAuth) -> bool: ... + """ Below are internal methods used by Fern to register your implementation. You can ignore them. """ - + @classmethod def _init_fern(cls, router: fastapi.APIRouter) -> None: cls.__init_test_get(router=router) @@ -54,22 +61,30 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: cls.__init_test_put(router=router) cls.__init_test_patch(router=router) cls.__init_test_delete(router=router) - + @classmethod def __init_test_get(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.test_get) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "id": new_parameters.append(parameter.replace(default=fastapi.Path(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.test_get, "__signature__", endpoint_function.replace(parameters=new_parameters)) - + setattr( + cls.test_get, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) + @functools.wraps(cls.test_get) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> str: try: @@ -81,33 +96,41 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> str: + "the endpoint's errors list in your Fern Definition." ) raise e - + # this is necessary for FastAPI to find forward-ref'ed type hints. # https://github.com/tiangolo/fastapi/pull/5077 wrapper.__globals__.update(cls.test_get.__globals__) - + router.get( path="/http-methods/{id}", response_model=str, description=AbstractEndpointsHttpMethodsService.test_get.__doc__, **get_route_args(cls.test_get, default_tag="endpoints.http_methods"), )(wrapper) - + @classmethod def __init_test_post(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.test_post) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.test_post, "__signature__", endpoint_function.replace(parameters=new_parameters)) - + setattr( + cls.test_post, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) + @functools.wraps(cls.test_post) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> ObjectWithOptionalField: try: @@ -119,23 +142,25 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> ObjectWithOptionalField: + "the endpoint's errors list in your Fern Definition." ) raise e - + # this is necessary for FastAPI to find forward-ref'ed type hints. # https://github.com/tiangolo/fastapi/pull/5077 wrapper.__globals__.update(cls.test_post.__globals__) - + router.post( path="/http-methods", response_model=ObjectWithOptionalField, description=AbstractEndpointsHttpMethodsService.test_post.__doc__, **get_route_args(cls.test_post, default_tag="endpoints.http_methods"), )(wrapper) - + @classmethod def __init_test_put(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.test_put) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": @@ -143,11 +168,17 @@ def __init_test_put(cls, router: fastapi.APIRouter) -> None: elif parameter_name == "id": new_parameters.append(parameter.replace(default=fastapi.Path(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.test_put, "__signature__", endpoint_function.replace(parameters=new_parameters)) - + setattr( + cls.test_put, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) + @functools.wraps(cls.test_put) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> ObjectWithOptionalField: try: @@ -159,23 +190,25 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> ObjectWithOptionalField: + "the endpoint's errors list in your Fern Definition." ) raise e - + # this is necessary for FastAPI to find forward-ref'ed type hints. # https://github.com/tiangolo/fastapi/pull/5077 wrapper.__globals__.update(cls.test_put.__globals__) - + router.put( path="/http-methods/{id}", response_model=ObjectWithOptionalField, description=AbstractEndpointsHttpMethodsService.test_put.__doc__, **get_route_args(cls.test_put, default_tag="endpoints.http_methods"), )(wrapper) - + @classmethod def __init_test_patch(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.test_patch) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": @@ -183,11 +216,17 @@ def __init_test_patch(cls, router: fastapi.APIRouter) -> None: elif parameter_name == "id": new_parameters.append(parameter.replace(default=fastapi.Path(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.test_patch, "__signature__", endpoint_function.replace(parameters=new_parameters)) - + setattr( + cls.test_patch, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) + @functools.wraps(cls.test_patch) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> ObjectWithOptionalField: try: @@ -199,33 +238,41 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> ObjectWithOptionalField: + "the endpoint's errors list in your Fern Definition." ) raise e - + # this is necessary for FastAPI to find forward-ref'ed type hints. # https://github.com/tiangolo/fastapi/pull/5077 wrapper.__globals__.update(cls.test_patch.__globals__) - + router.patch( path="/http-methods/{id}", response_model=ObjectWithOptionalField, description=AbstractEndpointsHttpMethodsService.test_patch.__doc__, **get_route_args(cls.test_patch, default_tag="endpoints.http_methods"), )(wrapper) - + @classmethod def __init_test_delete(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.test_delete) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "id": new_parameters.append(parameter.replace(default=fastapi.Path(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.test_delete, "__signature__", endpoint_function.replace(parameters=new_parameters)) - + setattr( + cls.test_delete, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) + @functools.wraps(cls.test_delete) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> bool: try: @@ -237,11 +284,11 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> bool: + "the endpoint's errors list in your Fern Definition." ) raise e - + # this is necessary for FastAPI to find forward-ref'ed type hints. # https://github.com/tiangolo/fastapi/pull/5077 wrapper.__globals__.update(cls.test_delete.__globals__) - + router.delete( path="/http-methods/{id}", response_model=bool, diff --git a/seed/fastapi/exhaustive/skip-formatting/resources/endpoints/resources/object/service/__init__.py b/seed/fastapi/exhaustive/skip-formatting/resources/endpoints/resources/object/service/__init__.py index 3de86f5a993..9b7c53dfae2 100644 --- a/seed/fastapi/exhaustive/skip-formatting/resources/endpoints/resources/object/service/__init__.py +++ b/seed/fastapi/exhaustive/skip-formatting/resources/endpoints/resources/object/service/__init__.py @@ -1,4 +1,5 @@ # This file was auto-generated by Fern from our API Definition. from .service import AbstractEndpointsObjectService + __all__ = ["AbstractEndpointsObjectService"] diff --git a/seed/fastapi/exhaustive/skip-formatting/resources/endpoints/resources/object/service/service.py b/seed/fastapi/exhaustive/skip-formatting/resources/endpoints/resources/object/service/service.py index bd1c7ee98c8..8b73109a788 100644 --- a/seed/fastapi/exhaustive/skip-formatting/resources/endpoints/resources/object/service/service.py +++ b/seed/fastapi/exhaustive/skip-formatting/resources/endpoints/resources/object/service/service.py @@ -1,13 +1,21 @@ # This file was auto-generated by Fern from our API Definition. from ......core.abstract_fern_service import AbstractFernService -from .....types.resources.object.types.object_with_optional_field import ObjectWithOptionalField +from .....types.resources.object.types.object_with_optional_field import ( + ObjectWithOptionalField, +) from ......security import ApiAuth import abc -from .....types.resources.object.types.object_with_required_field import ObjectWithRequiredField +from .....types.resources.object.types.object_with_required_field import ( + ObjectWithRequiredField, +) from .....types.resources.object.types.object_with_map_of_map import ObjectWithMapOfMap -from .....types.resources.object.types.nested_object_with_optional_field import NestedObjectWithOptionalField -from .....types.resources.object.types.nested_object_with_required_field import NestedObjectWithRequiredField +from .....types.resources.object.types.nested_object_with_optional_field import ( + NestedObjectWithOptionalField, +) +from .....types.resources.object.types.nested_object_with_required_field import ( + NestedObjectWithRequiredField, +) import typing import fastapi import inspect @@ -16,44 +24,52 @@ import logging import functools from ......core.route_args import get_route_args + + class AbstractEndpointsObjectService(AbstractFernService): """ AbstractEndpointsObjectService is an abstract class containing the methods that you should implement. - + Each method is associated with an API route, which will be registered with FastAPI when you register your implementation using Fern's register() function. """ - + @abc.abstractmethod - def get_and_return_with_optional_field(self, *, body: ObjectWithOptionalField, auth: ApiAuth) -> ObjectWithOptionalField: - ... - + def get_and_return_with_optional_field( + self, *, body: ObjectWithOptionalField, auth: ApiAuth + ) -> ObjectWithOptionalField: ... + @abc.abstractmethod - def get_and_return_with_required_field(self, *, body: ObjectWithRequiredField, auth: ApiAuth) -> ObjectWithRequiredField: - ... - + def get_and_return_with_required_field( + self, *, body: ObjectWithRequiredField, auth: ApiAuth + ) -> ObjectWithRequiredField: ... + @abc.abstractmethod - def get_and_return_with_map_of_map(self, *, body: ObjectWithMapOfMap, auth: ApiAuth) -> ObjectWithMapOfMap: - ... - + def get_and_return_with_map_of_map( + self, *, body: ObjectWithMapOfMap, auth: ApiAuth + ) -> ObjectWithMapOfMap: ... + @abc.abstractmethod - def get_and_return_nested_with_optional_field(self, *, body: NestedObjectWithOptionalField, auth: ApiAuth) -> NestedObjectWithOptionalField: - ... - + def get_and_return_nested_with_optional_field( + self, *, body: NestedObjectWithOptionalField, auth: ApiAuth + ) -> NestedObjectWithOptionalField: ... + @abc.abstractmethod - def get_and_return_nested_with_required_field(self, *, body: NestedObjectWithRequiredField, string: str, auth: ApiAuth) -> NestedObjectWithRequiredField: - ... - + def get_and_return_nested_with_required_field( + self, *, body: NestedObjectWithRequiredField, string: str, auth: ApiAuth + ) -> NestedObjectWithRequiredField: ... + @abc.abstractmethod - def get_and_return_nested_with_required_field_as_list(self, *, body: typing.List[NestedObjectWithRequiredField], auth: ApiAuth) -> NestedObjectWithRequiredField: - ... - + def get_and_return_nested_with_required_field_as_list( + self, *, body: typing.List[NestedObjectWithRequiredField], auth: ApiAuth + ) -> NestedObjectWithRequiredField: ... + """ Below are internal methods used by Fern to register your implementation. You can ignore them. """ - + @classmethod def _init_fern(cls, router: fastapi.APIRouter) -> None: cls.__init_get_and_return_with_optional_field(router=router) @@ -62,22 +78,32 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: cls.__init_get_and_return_nested_with_optional_field(router=router) cls.__init_get_and_return_nested_with_required_field(router=router) cls.__init_get_and_return_nested_with_required_field_as_list(router=router) - + @classmethod - def __init_get_and_return_with_optional_field(cls, router: fastapi.APIRouter) -> None: + def __init_get_and_return_with_optional_field( + cls, router: fastapi.APIRouter + ) -> None: endpoint_function = inspect.signature(cls.get_and_return_with_optional_field) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_and_return_with_optional_field, "__signature__", endpoint_function.replace(parameters=new_parameters)) - + setattr( + cls.get_and_return_with_optional_field, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) + @functools.wraps(cls.get_and_return_with_optional_field) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> ObjectWithOptionalField: try: @@ -89,33 +115,45 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> ObjectWithOptionalField: + "the endpoint's errors list in your Fern Definition." ) raise e - + # this is necessary for FastAPI to find forward-ref'ed type hints. # https://github.com/tiangolo/fastapi/pull/5077 wrapper.__globals__.update(cls.get_and_return_with_optional_field.__globals__) - + router.post( path="/object/get-and-return-with-optional-field", response_model=ObjectWithOptionalField, description=AbstractEndpointsObjectService.get_and_return_with_optional_field.__doc__, - **get_route_args(cls.get_and_return_with_optional_field, default_tag="endpoints.object"), + **get_route_args( + cls.get_and_return_with_optional_field, default_tag="endpoints.object" + ), )(wrapper) - + @classmethod - def __init_get_and_return_with_required_field(cls, router: fastapi.APIRouter) -> None: + def __init_get_and_return_with_required_field( + cls, router: fastapi.APIRouter + ) -> None: endpoint_function = inspect.signature(cls.get_and_return_with_required_field) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_and_return_with_required_field, "__signature__", endpoint_function.replace(parameters=new_parameters)) - + setattr( + cls.get_and_return_with_required_field, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) + @functools.wraps(cls.get_and_return_with_required_field) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> ObjectWithRequiredField: try: @@ -127,33 +165,43 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> ObjectWithRequiredField: + "the endpoint's errors list in your Fern Definition." ) raise e - + # this is necessary for FastAPI to find forward-ref'ed type hints. # https://github.com/tiangolo/fastapi/pull/5077 wrapper.__globals__.update(cls.get_and_return_with_required_field.__globals__) - + router.post( path="/object/get-and-return-with-required-field", response_model=ObjectWithRequiredField, description=AbstractEndpointsObjectService.get_and_return_with_required_field.__doc__, - **get_route_args(cls.get_and_return_with_required_field, default_tag="endpoints.object"), + **get_route_args( + cls.get_and_return_with_required_field, default_tag="endpoints.object" + ), )(wrapper) - + @classmethod def __init_get_and_return_with_map_of_map(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_and_return_with_map_of_map) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_and_return_with_map_of_map, "__signature__", endpoint_function.replace(parameters=new_parameters)) - + setattr( + cls.get_and_return_with_map_of_map, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) + @functools.wraps(cls.get_and_return_with_map_of_map) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> ObjectWithMapOfMap: try: @@ -165,35 +213,51 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> ObjectWithMapOfMap: + "the endpoint's errors list in your Fern Definition." ) raise e - + # this is necessary for FastAPI to find forward-ref'ed type hints. # https://github.com/tiangolo/fastapi/pull/5077 wrapper.__globals__.update(cls.get_and_return_with_map_of_map.__globals__) - + router.post( path="/object/get-and-return-with-map-of-map", response_model=ObjectWithMapOfMap, description=AbstractEndpointsObjectService.get_and_return_with_map_of_map.__doc__, - **get_route_args(cls.get_and_return_with_map_of_map, default_tag="endpoints.object"), + **get_route_args( + cls.get_and_return_with_map_of_map, default_tag="endpoints.object" + ), )(wrapper) - + @classmethod - def __init_get_and_return_nested_with_optional_field(cls, router: fastapi.APIRouter) -> None: - endpoint_function = inspect.signature(cls.get_and_return_nested_with_optional_field) + def __init_get_and_return_nested_with_optional_field( + cls, router: fastapi.APIRouter + ) -> None: + endpoint_function = inspect.signature( + cls.get_and_return_nested_with_optional_field + ) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_and_return_nested_with_optional_field, "__signature__", endpoint_function.replace(parameters=new_parameters)) - + setattr( + cls.get_and_return_nested_with_optional_field, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) + @functools.wraps(cls.get_and_return_nested_with_optional_field) - def wrapper(*args: typing.Any, **kwargs: typing.Any) -> NestedObjectWithOptionalField: + def wrapper( + *args: typing.Any, **kwargs: typing.Any + ) -> NestedObjectWithOptionalField: try: return cls.get_and_return_nested_with_optional_field(*args, **kwargs) except FernHTTPException as e: @@ -203,23 +267,34 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> NestedObjectWithOptional + "the endpoint's errors list in your Fern Definition." ) raise e - + # this is necessary for FastAPI to find forward-ref'ed type hints. # https://github.com/tiangolo/fastapi/pull/5077 - wrapper.__globals__.update(cls.get_and_return_nested_with_optional_field.__globals__) - + wrapper.__globals__.update( + cls.get_and_return_nested_with_optional_field.__globals__ + ) + router.post( path="/object/get-and-return-nested-with-optional-field", response_model=NestedObjectWithOptionalField, description=AbstractEndpointsObjectService.get_and_return_nested_with_optional_field.__doc__, - **get_route_args(cls.get_and_return_nested_with_optional_field, default_tag="endpoints.object"), + **get_route_args( + cls.get_and_return_nested_with_optional_field, + default_tag="endpoints.object", + ), )(wrapper) - + @classmethod - def __init_get_and_return_nested_with_required_field(cls, router: fastapi.APIRouter) -> None: - endpoint_function = inspect.signature(cls.get_and_return_nested_with_required_field) + def __init_get_and_return_nested_with_required_field( + cls, router: fastapi.APIRouter + ) -> None: + endpoint_function = inspect.signature( + cls.get_and_return_nested_with_required_field + ) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": @@ -227,13 +302,21 @@ def __init_get_and_return_nested_with_required_field(cls, router: fastapi.APIRou elif parameter_name == "string": new_parameters.append(parameter.replace(default=fastapi.Path(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_and_return_nested_with_required_field, "__signature__", endpoint_function.replace(parameters=new_parameters)) - + setattr( + cls.get_and_return_nested_with_required_field, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) + @functools.wraps(cls.get_and_return_nested_with_required_field) - def wrapper(*args: typing.Any, **kwargs: typing.Any) -> NestedObjectWithRequiredField: + def wrapper( + *args: typing.Any, **kwargs: typing.Any + ) -> NestedObjectWithRequiredField: try: return cls.get_and_return_nested_with_required_field(*args, **kwargs) except FernHTTPException as e: @@ -243,37 +326,58 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> NestedObjectWithRequired + "the endpoint's errors list in your Fern Definition." ) raise e - + # this is necessary for FastAPI to find forward-ref'ed type hints. # https://github.com/tiangolo/fastapi/pull/5077 - wrapper.__globals__.update(cls.get_and_return_nested_with_required_field.__globals__) - + wrapper.__globals__.update( + cls.get_and_return_nested_with_required_field.__globals__ + ) + router.post( path="/object/get-and-return-nested-with-required-field/{string}", response_model=NestedObjectWithRequiredField, description=AbstractEndpointsObjectService.get_and_return_nested_with_required_field.__doc__, - **get_route_args(cls.get_and_return_nested_with_required_field, default_tag="endpoints.object"), + **get_route_args( + cls.get_and_return_nested_with_required_field, + default_tag="endpoints.object", + ), )(wrapper) - + @classmethod - def __init_get_and_return_nested_with_required_field_as_list(cls, router: fastapi.APIRouter) -> None: - endpoint_function = inspect.signature(cls.get_and_return_nested_with_required_field_as_list) + def __init_get_and_return_nested_with_required_field_as_list( + cls, router: fastapi.APIRouter + ) -> None: + endpoint_function = inspect.signature( + cls.get_and_return_nested_with_required_field_as_list + ) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_and_return_nested_with_required_field_as_list, "__signature__", endpoint_function.replace(parameters=new_parameters)) - + setattr( + cls.get_and_return_nested_with_required_field_as_list, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) + @functools.wraps(cls.get_and_return_nested_with_required_field_as_list) - def wrapper(*args: typing.Any, **kwargs: typing.Any) -> NestedObjectWithRequiredField: + def wrapper( + *args: typing.Any, **kwargs: typing.Any + ) -> NestedObjectWithRequiredField: try: - return cls.get_and_return_nested_with_required_field_as_list(*args, **kwargs) + return cls.get_and_return_nested_with_required_field_as_list( + *args, **kwargs + ) except FernHTTPException as e: logging.getLogger(f"{cls.__module__}.{cls.__name__}").warn( f"Endpoint 'get_and_return_nested_with_required_field_as_list' unexpectedly threw {e.__class__.__name__}. " @@ -281,14 +385,19 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> NestedObjectWithRequired + "the endpoint's errors list in your Fern Definition." ) raise e - + # this is necessary for FastAPI to find forward-ref'ed type hints. # https://github.com/tiangolo/fastapi/pull/5077 - wrapper.__globals__.update(cls.get_and_return_nested_with_required_field_as_list.__globals__) - + wrapper.__globals__.update( + cls.get_and_return_nested_with_required_field_as_list.__globals__ + ) + router.post( path="/object/get-and-return-nested-with-required-field-list", response_model=NestedObjectWithRequiredField, description=AbstractEndpointsObjectService.get_and_return_nested_with_required_field_as_list.__doc__, - **get_route_args(cls.get_and_return_nested_with_required_field_as_list, default_tag="endpoints.object"), + **get_route_args( + cls.get_and_return_nested_with_required_field_as_list, + default_tag="endpoints.object", + ), )(wrapper) diff --git a/seed/fastapi/exhaustive/skip-formatting/resources/endpoints/resources/params/service/__init__.py b/seed/fastapi/exhaustive/skip-formatting/resources/endpoints/resources/params/service/__init__.py index ec5599c4168..f7278fe82be 100644 --- a/seed/fastapi/exhaustive/skip-formatting/resources/endpoints/resources/params/service/__init__.py +++ b/seed/fastapi/exhaustive/skip-formatting/resources/endpoints/resources/params/service/__init__.py @@ -1,4 +1,5 @@ # This file was auto-generated by Fern from our API Definition. from .service import AbstractEndpointsParamsService + __all__ = ["AbstractEndpointsParamsService"] diff --git a/seed/fastapi/exhaustive/skip-formatting/resources/endpoints/resources/params/service/service.py b/seed/fastapi/exhaustive/skip-formatting/resources/endpoints/resources/params/service/service.py index 0228c3590dc..93c809bd4e7 100644 --- a/seed/fastapi/exhaustive/skip-formatting/resources/endpoints/resources/params/service/service.py +++ b/seed/fastapi/exhaustive/skip-formatting/resources/endpoints/resources/params/service/service.py @@ -12,55 +12,59 @@ import functools from ......core.route_args import get_route_args import starlette + + class AbstractEndpointsParamsService(AbstractFernService): """ AbstractEndpointsParamsService is an abstract class containing the methods that you should implement. - + Each method is associated with an API route, which will be registered with FastAPI when you register your implementation using Fern's register() function. """ - + @abc.abstractmethod def get_with_path(self, *, param: str, auth: ApiAuth) -> str: """ GET with path param """ ... - + @abc.abstractmethod def get_with_query(self, *, query: str, number: int, auth: ApiAuth) -> None: """ GET with query param """ ... - + @abc.abstractmethod - def get_with_allow_multiple_query(self, *, query: typing.List[str], numer: typing.List[int], auth: ApiAuth) -> None: + def get_with_allow_multiple_query( + self, *, query: typing.List[str], numer: typing.List[int], auth: ApiAuth + ) -> None: """ GET with multiple of same query param """ ... - + @abc.abstractmethod def get_with_path_and_query(self, *, param: str, query: str, auth: ApiAuth) -> None: """ GET with path and query params """ ... - + @abc.abstractmethod def modify_with_path(self, *, body: str, param: str, auth: ApiAuth) -> str: """ PUT to update with path param """ ... - + """ Below are internal methods used by Fern to register your implementation. You can ignore them. """ - + @classmethod def _init_fern(cls, router: fastapi.APIRouter) -> None: cls.__init_get_with_path(router=router) @@ -68,22 +72,30 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: cls.__init_get_with_allow_multiple_query(router=router) cls.__init_get_with_path_and_query(router=router) cls.__init_modify_with_path(router=router) - + @classmethod def __init_get_with_path(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_with_path) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "param": new_parameters.append(parameter.replace(default=fastapi.Path(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_with_path, "__signature__", endpoint_function.replace(parameters=new_parameters)) - + setattr( + cls.get_with_path, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) + @functools.wraps(cls.get_with_path) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> str: try: @@ -95,35 +107,47 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> str: + "the endpoint's errors list in your Fern Definition." ) raise e - + # this is necessary for FastAPI to find forward-ref'ed type hints. # https://github.com/tiangolo/fastapi/pull/5077 wrapper.__globals__.update(cls.get_with_path.__globals__) - + router.get( path="/params/path/{param}", response_model=str, description=AbstractEndpointsParamsService.get_with_path.__doc__, **get_route_args(cls.get_with_path, default_tag="endpoints.params"), )(wrapper) - + @classmethod def __init_get_with_query(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_with_query) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "query": - new_parameters.append(parameter.replace(default=fastapi.Query(default=...))) + new_parameters.append( + parameter.replace(default=fastapi.Query(default=...)) + ) elif parameter_name == "number": - new_parameters.append(parameter.replace(default=fastapi.Query(default=...))) + new_parameters.append( + parameter.replace(default=fastapi.Query(default=...)) + ) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_with_query, "__signature__", endpoint_function.replace(parameters=new_parameters)) - + setattr( + cls.get_with_query, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) + @functools.wraps(cls.get_with_query) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> None: try: @@ -135,11 +159,11 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> None: + "the endpoint's errors list in your Fern Definition." ) raise e - + # this is necessary for FastAPI to find forward-ref'ed type hints. # https://github.com/tiangolo/fastapi/pull/5077 wrapper.__globals__.update(cls.get_with_query.__globals__) - + router.get( path="/params", response_model=None, @@ -147,24 +171,36 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> None: description=AbstractEndpointsParamsService.get_with_query.__doc__, **get_route_args(cls.get_with_query, default_tag="endpoints.params"), )(wrapper) - + @classmethod def __init_get_with_allow_multiple_query(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_with_allow_multiple_query) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "query": - new_parameters.append(parameter.replace(default=fastapi.Query(default=[]))) + new_parameters.append( + parameter.replace(default=fastapi.Query(default=[])) + ) elif parameter_name == "numer": - new_parameters.append(parameter.replace(default=fastapi.Query(default=[]))) + new_parameters.append( + parameter.replace(default=fastapi.Query(default=[])) + ) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_with_allow_multiple_query, "__signature__", endpoint_function.replace(parameters=new_parameters)) - + setattr( + cls.get_with_allow_multiple_query, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) + @functools.wraps(cls.get_with_allow_multiple_query) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> None: try: @@ -176,36 +212,48 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> None: + "the endpoint's errors list in your Fern Definition." ) raise e - + # this is necessary for FastAPI to find forward-ref'ed type hints. # https://github.com/tiangolo/fastapi/pull/5077 wrapper.__globals__.update(cls.get_with_allow_multiple_query.__globals__) - + router.get( path="/params", response_model=None, status_code=starlette.status.HTTP_204_NO_CONTENT, description=AbstractEndpointsParamsService.get_with_allow_multiple_query.__doc__, - **get_route_args(cls.get_with_allow_multiple_query, default_tag="endpoints.params"), + **get_route_args( + cls.get_with_allow_multiple_query, default_tag="endpoints.params" + ), )(wrapper) - + @classmethod def __init_get_with_path_and_query(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_with_path_and_query) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "param": new_parameters.append(parameter.replace(default=fastapi.Path(...))) elif parameter_name == "query": - new_parameters.append(parameter.replace(default=fastapi.Query(default=...))) + new_parameters.append( + parameter.replace(default=fastapi.Query(default=...)) + ) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_with_path_and_query, "__signature__", endpoint_function.replace(parameters=new_parameters)) - + setattr( + cls.get_with_path_and_query, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) + @functools.wraps(cls.get_with_path_and_query) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> None: try: @@ -217,24 +265,28 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> None: + "the endpoint's errors list in your Fern Definition." ) raise e - + # this is necessary for FastAPI to find forward-ref'ed type hints. # https://github.com/tiangolo/fastapi/pull/5077 wrapper.__globals__.update(cls.get_with_path_and_query.__globals__) - + router.get( path="/params/path-query/{param}", response_model=None, status_code=starlette.status.HTTP_204_NO_CONTENT, description=AbstractEndpointsParamsService.get_with_path_and_query.__doc__, - **get_route_args(cls.get_with_path_and_query, default_tag="endpoints.params"), + **get_route_args( + cls.get_with_path_and_query, default_tag="endpoints.params" + ), )(wrapper) - + @classmethod def __init_modify_with_path(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.modify_with_path) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": @@ -242,11 +294,17 @@ def __init_modify_with_path(cls, router: fastapi.APIRouter) -> None: elif parameter_name == "param": new_parameters.append(parameter.replace(default=fastapi.Path(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.modify_with_path, "__signature__", endpoint_function.replace(parameters=new_parameters)) - + setattr( + cls.modify_with_path, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) + @functools.wraps(cls.modify_with_path) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> str: try: @@ -258,11 +316,11 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> str: + "the endpoint's errors list in your Fern Definition." ) raise e - + # this is necessary for FastAPI to find forward-ref'ed type hints. # https://github.com/tiangolo/fastapi/pull/5077 wrapper.__globals__.update(cls.modify_with_path.__globals__) - + router.put( path="/params/path/{param}", response_model=str, diff --git a/seed/fastapi/exhaustive/skip-formatting/resources/endpoints/resources/primitive/service/__init__.py b/seed/fastapi/exhaustive/skip-formatting/resources/endpoints/resources/primitive/service/__init__.py index e852579b983..cbdabe15630 100644 --- a/seed/fastapi/exhaustive/skip-formatting/resources/endpoints/resources/primitive/service/__init__.py +++ b/seed/fastapi/exhaustive/skip-formatting/resources/endpoints/resources/primitive/service/__init__.py @@ -1,4 +1,5 @@ # This file was auto-generated by Fern from our API Definition. from .service import AbstractEndpointsPrimitiveService + __all__ = ["AbstractEndpointsPrimitiveService"] diff --git a/seed/fastapi/exhaustive/skip-formatting/resources/endpoints/resources/primitive/service/service.py b/seed/fastapi/exhaustive/skip-formatting/resources/endpoints/resources/primitive/service/service.py index c8664096bd6..78b3526b630 100644 --- a/seed/fastapi/exhaustive/skip-formatting/resources/endpoints/resources/primitive/service/service.py +++ b/seed/fastapi/exhaustive/skip-formatting/resources/endpoints/resources/primitive/service/service.py @@ -13,56 +13,51 @@ import logging import functools from ......core.route_args import get_route_args + + class AbstractEndpointsPrimitiveService(AbstractFernService): """ AbstractEndpointsPrimitiveService is an abstract class containing the methods that you should implement. - + Each method is associated with an API route, which will be registered with FastAPI when you register your implementation using Fern's register() function. """ - + @abc.abstractmethod - def get_and_return_string(self, *, body: str, auth: ApiAuth) -> str: - ... - + def get_and_return_string(self, *, body: str, auth: ApiAuth) -> str: ... + @abc.abstractmethod - def get_and_return_int(self, *, body: int, auth: ApiAuth) -> int: - ... - + def get_and_return_int(self, *, body: int, auth: ApiAuth) -> int: ... + @abc.abstractmethod - def get_and_return_long(self, *, body: int, auth: ApiAuth) -> int: - ... - + def get_and_return_long(self, *, body: int, auth: ApiAuth) -> int: ... + @abc.abstractmethod - def get_and_return_double(self, *, body: float, auth: ApiAuth) -> float: - ... - + def get_and_return_double(self, *, body: float, auth: ApiAuth) -> float: ... + @abc.abstractmethod - def get_and_return_bool(self, *, body: bool, auth: ApiAuth) -> bool: - ... - + def get_and_return_bool(self, *, body: bool, auth: ApiAuth) -> bool: ... + @abc.abstractmethod - def get_and_return_datetime(self, *, body: dt.datetime, auth: ApiAuth) -> dt.datetime: - ... - + def get_and_return_datetime( + self, *, body: dt.datetime, auth: ApiAuth + ) -> dt.datetime: ... + @abc.abstractmethod - def get_and_return_date(self, *, body: dt.date, auth: ApiAuth) -> dt.date: - ... - + def get_and_return_date(self, *, body: dt.date, auth: ApiAuth) -> dt.date: ... + @abc.abstractmethod - def get_and_return_uuid(self, *, body: uuid.UUID, auth: ApiAuth) -> uuid.UUID: - ... - + def get_and_return_uuid(self, *, body: uuid.UUID, auth: ApiAuth) -> uuid.UUID: ... + @abc.abstractmethod - def get_and_return_base_64(self, *, body: str, auth: ApiAuth) -> str: - ... - + def get_and_return_base_64(self, *, body: str, auth: ApiAuth) -> str: ... + """ Below are internal methods used by Fern to register your implementation. You can ignore them. """ - + @classmethod def _init_fern(cls, router: fastapi.APIRouter) -> None: cls.__init_get_and_return_string(router=router) @@ -74,22 +69,30 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: cls.__init_get_and_return_date(router=router) cls.__init_get_and_return_uuid(router=router) cls.__init_get_and_return_base_64(router=router) - + @classmethod def __init_get_and_return_string(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_and_return_string) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_and_return_string, "__signature__", endpoint_function.replace(parameters=new_parameters)) - + setattr( + cls.get_and_return_string, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) + @functools.wraps(cls.get_and_return_string) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> str: try: @@ -101,33 +104,43 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> str: + "the endpoint's errors list in your Fern Definition." ) raise e - + # this is necessary for FastAPI to find forward-ref'ed type hints. # https://github.com/tiangolo/fastapi/pull/5077 wrapper.__globals__.update(cls.get_and_return_string.__globals__) - + router.post( path="/primitive/string", response_model=str, description=AbstractEndpointsPrimitiveService.get_and_return_string.__doc__, - **get_route_args(cls.get_and_return_string, default_tag="endpoints.primitive"), + **get_route_args( + cls.get_and_return_string, default_tag="endpoints.primitive" + ), )(wrapper) - + @classmethod def __init_get_and_return_int(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_and_return_int) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_and_return_int, "__signature__", endpoint_function.replace(parameters=new_parameters)) - + setattr( + cls.get_and_return_int, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) + @functools.wraps(cls.get_and_return_int) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> int: try: @@ -139,33 +152,41 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> int: + "the endpoint's errors list in your Fern Definition." ) raise e - + # this is necessary for FastAPI to find forward-ref'ed type hints. # https://github.com/tiangolo/fastapi/pull/5077 wrapper.__globals__.update(cls.get_and_return_int.__globals__) - + router.post( path="/primitive/integer", response_model=int, description=AbstractEndpointsPrimitiveService.get_and_return_int.__doc__, **get_route_args(cls.get_and_return_int, default_tag="endpoints.primitive"), )(wrapper) - + @classmethod def __init_get_and_return_long(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_and_return_long) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_and_return_long, "__signature__", endpoint_function.replace(parameters=new_parameters)) - + setattr( + cls.get_and_return_long, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) + @functools.wraps(cls.get_and_return_long) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> int: try: @@ -177,33 +198,43 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> int: + "the endpoint's errors list in your Fern Definition." ) raise e - + # this is necessary for FastAPI to find forward-ref'ed type hints. # https://github.com/tiangolo/fastapi/pull/5077 wrapper.__globals__.update(cls.get_and_return_long.__globals__) - + router.post( path="/primitive/long", response_model=int, description=AbstractEndpointsPrimitiveService.get_and_return_long.__doc__, - **get_route_args(cls.get_and_return_long, default_tag="endpoints.primitive"), + **get_route_args( + cls.get_and_return_long, default_tag="endpoints.primitive" + ), )(wrapper) - + @classmethod def __init_get_and_return_double(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_and_return_double) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_and_return_double, "__signature__", endpoint_function.replace(parameters=new_parameters)) - + setattr( + cls.get_and_return_double, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) + @functools.wraps(cls.get_and_return_double) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> float: try: @@ -215,33 +246,43 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> float: + "the endpoint's errors list in your Fern Definition." ) raise e - + # this is necessary for FastAPI to find forward-ref'ed type hints. # https://github.com/tiangolo/fastapi/pull/5077 wrapper.__globals__.update(cls.get_and_return_double.__globals__) - + router.post( path="/primitive/double", response_model=float, description=AbstractEndpointsPrimitiveService.get_and_return_double.__doc__, - **get_route_args(cls.get_and_return_double, default_tag="endpoints.primitive"), + **get_route_args( + cls.get_and_return_double, default_tag="endpoints.primitive" + ), )(wrapper) - + @classmethod def __init_get_and_return_bool(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_and_return_bool) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_and_return_bool, "__signature__", endpoint_function.replace(parameters=new_parameters)) - + setattr( + cls.get_and_return_bool, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) + @functools.wraps(cls.get_and_return_bool) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> bool: try: @@ -253,33 +294,43 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> bool: + "the endpoint's errors list in your Fern Definition." ) raise e - + # this is necessary for FastAPI to find forward-ref'ed type hints. # https://github.com/tiangolo/fastapi/pull/5077 wrapper.__globals__.update(cls.get_and_return_bool.__globals__) - + router.post( path="/primitive/boolean", response_model=bool, description=AbstractEndpointsPrimitiveService.get_and_return_bool.__doc__, - **get_route_args(cls.get_and_return_bool, default_tag="endpoints.primitive"), + **get_route_args( + cls.get_and_return_bool, default_tag="endpoints.primitive" + ), )(wrapper) - + @classmethod def __init_get_and_return_datetime(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_and_return_datetime) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_and_return_datetime, "__signature__", endpoint_function.replace(parameters=new_parameters)) - + setattr( + cls.get_and_return_datetime, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) + @functools.wraps(cls.get_and_return_datetime) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> dt.datetime: try: @@ -291,33 +342,43 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> dt.datetime: + "the endpoint's errors list in your Fern Definition." ) raise e - + # this is necessary for FastAPI to find forward-ref'ed type hints. # https://github.com/tiangolo/fastapi/pull/5077 wrapper.__globals__.update(cls.get_and_return_datetime.__globals__) - + router.post( path="/primitive/datetime", response_model=dt.datetime, description=AbstractEndpointsPrimitiveService.get_and_return_datetime.__doc__, - **get_route_args(cls.get_and_return_datetime, default_tag="endpoints.primitive"), + **get_route_args( + cls.get_and_return_datetime, default_tag="endpoints.primitive" + ), )(wrapper) - + @classmethod def __init_get_and_return_date(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_and_return_date) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_and_return_date, "__signature__", endpoint_function.replace(parameters=new_parameters)) - + setattr( + cls.get_and_return_date, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) + @functools.wraps(cls.get_and_return_date) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> dt.date: try: @@ -329,33 +390,43 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> dt.date: + "the endpoint's errors list in your Fern Definition." ) raise e - + # this is necessary for FastAPI to find forward-ref'ed type hints. # https://github.com/tiangolo/fastapi/pull/5077 wrapper.__globals__.update(cls.get_and_return_date.__globals__) - + router.post( path="/primitive/date", response_model=dt.date, description=AbstractEndpointsPrimitiveService.get_and_return_date.__doc__, - **get_route_args(cls.get_and_return_date, default_tag="endpoints.primitive"), + **get_route_args( + cls.get_and_return_date, default_tag="endpoints.primitive" + ), )(wrapper) - + @classmethod def __init_get_and_return_uuid(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_and_return_uuid) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_and_return_uuid, "__signature__", endpoint_function.replace(parameters=new_parameters)) - + setattr( + cls.get_and_return_uuid, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) + @functools.wraps(cls.get_and_return_uuid) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> uuid.UUID: try: @@ -367,33 +438,43 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> uuid.UUID: + "the endpoint's errors list in your Fern Definition." ) raise e - + # this is necessary for FastAPI to find forward-ref'ed type hints. # https://github.com/tiangolo/fastapi/pull/5077 wrapper.__globals__.update(cls.get_and_return_uuid.__globals__) - + router.post( path="/primitive/uuid", response_model=uuid.UUID, description=AbstractEndpointsPrimitiveService.get_and_return_uuid.__doc__, - **get_route_args(cls.get_and_return_uuid, default_tag="endpoints.primitive"), + **get_route_args( + cls.get_and_return_uuid, default_tag="endpoints.primitive" + ), )(wrapper) - + @classmethod def __init_get_and_return_base_64(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_and_return_base_64) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_and_return_base_64, "__signature__", endpoint_function.replace(parameters=new_parameters)) - + setattr( + cls.get_and_return_base_64, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) + @functools.wraps(cls.get_and_return_base_64) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> str: try: @@ -405,14 +486,16 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> str: + "the endpoint's errors list in your Fern Definition." ) raise e - + # this is necessary for FastAPI to find forward-ref'ed type hints. # https://github.com/tiangolo/fastapi/pull/5077 wrapper.__globals__.update(cls.get_and_return_base_64.__globals__) - + router.post( path="/primitive/base64", response_model=str, description=AbstractEndpointsPrimitiveService.get_and_return_base_64.__doc__, - **get_route_args(cls.get_and_return_base_64, default_tag="endpoints.primitive"), + **get_route_args( + cls.get_and_return_base_64, default_tag="endpoints.primitive" + ), )(wrapper) diff --git a/seed/fastapi/exhaustive/skip-formatting/resources/endpoints/resources/union/service/__init__.py b/seed/fastapi/exhaustive/skip-formatting/resources/endpoints/resources/union/service/__init__.py index bef96c9f278..37bb942b185 100644 --- a/seed/fastapi/exhaustive/skip-formatting/resources/endpoints/resources/union/service/__init__.py +++ b/seed/fastapi/exhaustive/skip-formatting/resources/endpoints/resources/union/service/__init__.py @@ -1,4 +1,5 @@ # This file was auto-generated by Fern from our API Definition. from .service import AbstractEndpointsUnionService + __all__ = ["AbstractEndpointsUnionService"] diff --git a/seed/fastapi/exhaustive/skip-formatting/resources/endpoints/resources/union/service/service.py b/seed/fastapi/exhaustive/skip-formatting/resources/endpoints/resources/union/service/service.py index f0877d562ae..cc962963db9 100644 --- a/seed/fastapi/exhaustive/skip-formatting/resources/endpoints/resources/union/service/service.py +++ b/seed/fastapi/exhaustive/skip-formatting/resources/endpoints/resources/union/service/service.py @@ -12,43 +12,52 @@ import logging import functools from ......core.route_args import get_route_args + + class AbstractEndpointsUnionService(AbstractFernService): """ AbstractEndpointsUnionService is an abstract class containing the methods that you should implement. - + Each method is associated with an API route, which will be registered with FastAPI when you register your implementation using Fern's register() function. """ - + @abc.abstractmethod - def get_and_return_union(self, *, body: Animal, auth: ApiAuth) -> Animal: - ... - + def get_and_return_union(self, *, body: Animal, auth: ApiAuth) -> Animal: ... + """ Below are internal methods used by Fern to register your implementation. You can ignore them. """ - + @classmethod def _init_fern(cls, router: fastapi.APIRouter) -> None: cls.__init_get_and_return_union(router=router) - + @classmethod def __init_get_and_return_union(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_and_return_union) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_and_return_union, "__signature__", endpoint_function.replace(parameters=new_parameters)) - + setattr( + cls.get_and_return_union, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) + @functools.wraps(cls.get_and_return_union) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> Animal: try: @@ -60,11 +69,11 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> Animal: + "the endpoint's errors list in your Fern Definition." ) raise e - + # this is necessary for FastAPI to find forward-ref'ed type hints. # https://github.com/tiangolo/fastapi/pull/5077 wrapper.__globals__.update(cls.get_and_return_union.__globals__) - + router.post( path="/union", response_model=Animal, diff --git a/seed/fastapi/exhaustive/skip-formatting/resources/general_errors/__init__.py b/seed/fastapi/exhaustive/skip-formatting/resources/general_errors/__init__.py index 0e09099cf00..115c26555f3 100644 --- a/seed/fastapi/exhaustive/skip-formatting/resources/general_errors/__init__.py +++ b/seed/fastapi/exhaustive/skip-formatting/resources/general_errors/__init__.py @@ -2,4 +2,5 @@ from .errors import BadRequestBody from .types import BadObjectRequestInfo + __all__ = ["BadObjectRequestInfo", "BadRequestBody"] diff --git a/seed/fastapi/exhaustive/skip-formatting/resources/general_errors/errors/__init__.py b/seed/fastapi/exhaustive/skip-formatting/resources/general_errors/errors/__init__.py index 38f7fed738c..04eaf8e383b 100644 --- a/seed/fastapi/exhaustive/skip-formatting/resources/general_errors/errors/__init__.py +++ b/seed/fastapi/exhaustive/skip-formatting/resources/general_errors/errors/__init__.py @@ -1,4 +1,5 @@ # This file was auto-generated by Fern from our API Definition. from .bad_request_body import BadRequestBody + __all__ = ["BadRequestBody"] diff --git a/seed/fastapi/exhaustive/skip-formatting/resources/general_errors/errors/bad_request_body.py b/seed/fastapi/exhaustive/skip-formatting/resources/general_errors/errors/bad_request_body.py index da074e29e6d..9c75b4bcf0c 100644 --- a/seed/fastapi/exhaustive/skip-formatting/resources/general_errors/errors/bad_request_body.py +++ b/seed/fastapi/exhaustive/skip-formatting/resources/general_errors/errors/bad_request_body.py @@ -2,6 +2,8 @@ from ....core.exceptions.fern_http_exception import FernHTTPException from ..types.bad_object_request_info import BadObjectRequestInfo + + class BadRequestBody(FernHTTPException): def __init__(self, error: BadObjectRequestInfo): super().__init__(status_code=400, name="BadRequestBody", content=error) diff --git a/seed/fastapi/exhaustive/skip-formatting/resources/general_errors/types/__init__.py b/seed/fastapi/exhaustive/skip-formatting/resources/general_errors/types/__init__.py index 12feabb154c..b6788a57056 100644 --- a/seed/fastapi/exhaustive/skip-formatting/resources/general_errors/types/__init__.py +++ b/seed/fastapi/exhaustive/skip-formatting/resources/general_errors/types/__init__.py @@ -1,4 +1,5 @@ # This file was auto-generated by Fern from our API Definition. from .bad_object_request_info import BadObjectRequestInfo + __all__ = ["BadObjectRequestInfo"] diff --git a/seed/fastapi/exhaustive/skip-formatting/resources/general_errors/types/bad_object_request_info.py b/seed/fastapi/exhaustive/skip-formatting/resources/general_errors/types/bad_object_request_info.py index 3644ee3e297..3b4b5d03362 100644 --- a/seed/fastapi/exhaustive/skip-formatting/resources/general_errors/types/bad_object_request_info.py +++ b/seed/fastapi/exhaustive/skip-formatting/resources/general_errors/types/bad_object_request_info.py @@ -4,11 +4,16 @@ from ....core.pydantic_utilities import IS_PYDANTIC_V2 import typing import pydantic + + class BadObjectRequestInfo(UniversalBaseModel): message: str - + if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: + class Config: extra = pydantic.Extra.forbid diff --git a/seed/fastapi/exhaustive/skip-formatting/resources/inlined_requests/__init__.py b/seed/fastapi/exhaustive/skip-formatting/resources/inlined_requests/__init__.py index 9b666f21e1f..e49491cc185 100644 --- a/seed/fastapi/exhaustive/skip-formatting/resources/inlined_requests/__init__.py +++ b/seed/fastapi/exhaustive/skip-formatting/resources/inlined_requests/__init__.py @@ -1,4 +1,5 @@ # This file was auto-generated by Fern from our API Definition. from .service import PostWithObjectBody + __all__ = ["PostWithObjectBody"] diff --git a/seed/fastapi/exhaustive/skip-formatting/resources/inlined_requests/service/__init__.py b/seed/fastapi/exhaustive/skip-formatting/resources/inlined_requests/service/__init__.py index 9f69b6551e4..c1d5bec72c8 100644 --- a/seed/fastapi/exhaustive/skip-formatting/resources/inlined_requests/service/__init__.py +++ b/seed/fastapi/exhaustive/skip-formatting/resources/inlined_requests/service/__init__.py @@ -2,4 +2,5 @@ from .post_with_object_body import PostWithObjectBody from .service import AbstractInlinedRequestsService + __all__ = ["AbstractInlinedRequestsService", "PostWithObjectBody"] diff --git a/seed/fastapi/exhaustive/skip-formatting/resources/inlined_requests/service/post_with_object_body.py b/seed/fastapi/exhaustive/skip-formatting/resources/inlined_requests/service/post_with_object_body.py index a64e20ce63a..647905603ee 100644 --- a/seed/fastapi/exhaustive/skip-formatting/resources/inlined_requests/service/post_with_object_body.py +++ b/seed/fastapi/exhaustive/skip-formatting/resources/inlined_requests/service/post_with_object_body.py @@ -1,17 +1,24 @@ # This file was auto-generated by Fern from our API Definition. from ....core.pydantic_utilities import UniversalBaseModel -from ...types.resources.object.types.object_with_optional_field import ObjectWithOptionalField +from ...types.resources.object.types.object_with_optional_field import ( + ObjectWithOptionalField, +) import pydantic from ....core.pydantic_utilities import IS_PYDANTIC_V2 import typing + + class PostWithObjectBody(UniversalBaseModel): string: str integer: int nested_object: ObjectWithOptionalField = pydantic.Field(alias="NestedObject") - + if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: + class Config: extra = pydantic.Extra.forbid diff --git a/seed/fastapi/exhaustive/skip-formatting/resources/inlined_requests/service/service.py b/seed/fastapi/exhaustive/skip-formatting/resources/inlined_requests/service/service.py index 91f7434b2b2..9894c433149 100644 --- a/seed/fastapi/exhaustive/skip-formatting/resources/inlined_requests/service/service.py +++ b/seed/fastapi/exhaustive/skip-formatting/resources/inlined_requests/service/service.py @@ -2,7 +2,9 @@ from ....core.abstract_fern_service import AbstractFernService from .post_with_object_body import PostWithObjectBody -from ...types.resources.object.types.object_with_optional_field import ObjectWithOptionalField +from ...types.resources.object.types.object_with_optional_field import ( + ObjectWithOptionalField, +) import abc import fastapi import inspect @@ -12,44 +14,56 @@ import logging import functools from ....core.route_args import get_route_args + + class AbstractInlinedRequestsService(AbstractFernService): """ AbstractInlinedRequestsService is an abstract class containing the methods that you should implement. - + Each method is associated with an API route, which will be registered with FastAPI when you register your implementation using Fern's register() function. """ - + @abc.abstractmethod - def post_with_object_bodyand_response(self, *, body: PostWithObjectBody) -> ObjectWithOptionalField: + def post_with_object_bodyand_response( + self, *, body: PostWithObjectBody + ) -> ObjectWithOptionalField: """ POST with custom object in request body, response is an object """ ... - + """ Below are internal methods used by Fern to register your implementation. You can ignore them. """ - + @classmethod def _init_fern(cls, router: fastapi.APIRouter) -> None: cls.__init_post_with_object_bodyand_response(router=router) - + @classmethod - def __init_post_with_object_bodyand_response(cls, router: fastapi.APIRouter) -> None: + def __init_post_with_object_bodyand_response( + cls, router: fastapi.APIRouter + ) -> None: endpoint_function = inspect.signature(cls.post_with_object_bodyand_response) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) else: new_parameters.append(parameter) - setattr(cls.post_with_object_bodyand_response, "__signature__", endpoint_function.replace(parameters=new_parameters)) - + setattr( + cls.post_with_object_bodyand_response, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) + @functools.wraps(cls.post_with_object_bodyand_response) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> ObjectWithOptionalField: try: @@ -63,14 +77,16 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> ObjectWithOptionalField: + "the endpoint's errors list in your Fern Definition." ) raise e - + # this is necessary for FastAPI to find forward-ref'ed type hints. # https://github.com/tiangolo/fastapi/pull/5077 wrapper.__globals__.update(cls.post_with_object_bodyand_response.__globals__) - + router.post( path="/req-bodies/object", response_model=ObjectWithOptionalField, description=AbstractInlinedRequestsService.post_with_object_bodyand_response.__doc__, - **get_route_args(cls.post_with_object_bodyand_response, default_tag="inlined_requests"), + **get_route_args( + cls.post_with_object_bodyand_response, default_tag="inlined_requests" + ), )(wrapper) diff --git a/seed/fastapi/exhaustive/skip-formatting/resources/no_auth/service/__init__.py b/seed/fastapi/exhaustive/skip-formatting/resources/no_auth/service/__init__.py index c74d19ffc7b..1c29f9f2a06 100644 --- a/seed/fastapi/exhaustive/skip-formatting/resources/no_auth/service/__init__.py +++ b/seed/fastapi/exhaustive/skip-formatting/resources/no_auth/service/__init__.py @@ -1,4 +1,5 @@ # This file was auto-generated by Fern from our API Definition. from .service import AbstractNoAuthService + __all__ = ["AbstractNoAuthService"] diff --git a/seed/fastapi/exhaustive/skip-formatting/resources/no_auth/service/service.py b/seed/fastapi/exhaustive/skip-formatting/resources/no_auth/service/service.py index 0e8f153e5db..b0984ae6360 100644 --- a/seed/fastapi/exhaustive/skip-formatting/resources/no_auth/service/service.py +++ b/seed/fastapi/exhaustive/skip-formatting/resources/no_auth/service/service.py @@ -10,44 +10,52 @@ import logging import functools from ....core.route_args import get_route_args + + class AbstractNoAuthService(AbstractFernService): """ AbstractNoAuthService is an abstract class containing the methods that you should implement. - + Each method is associated with an API route, which will be registered with FastAPI when you register your implementation using Fern's register() function. """ - + @abc.abstractmethod def post_with_no_auth(self, *, body: typing.Any) -> bool: """ POST request with no auth """ ... - + """ Below are internal methods used by Fern to register your implementation. You can ignore them. """ - + @classmethod def _init_fern(cls, router: fastapi.APIRouter) -> None: cls.__init_post_with_no_auth(router=router) - + @classmethod def __init_post_with_no_auth(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.post_with_no_auth) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) else: new_parameters.append(parameter) - setattr(cls.post_with_no_auth, "__signature__", endpoint_function.replace(parameters=new_parameters)) - + setattr( + cls.post_with_no_auth, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) + @functools.wraps(cls.post_with_no_auth) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> bool: try: @@ -61,11 +69,11 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> bool: + "the endpoint's errors list in your Fern Definition." ) raise e - + # this is necessary for FastAPI to find forward-ref'ed type hints. # https://github.com/tiangolo/fastapi/pull/5077 wrapper.__globals__.update(cls.post_with_no_auth.__globals__) - + router.post( path="/no-auth", response_model=bool, diff --git a/seed/fastapi/exhaustive/skip-formatting/resources/no_req_body/service/__init__.py b/seed/fastapi/exhaustive/skip-formatting/resources/no_req_body/service/__init__.py index c8ff926aa1b..a0ad1b0152f 100644 --- a/seed/fastapi/exhaustive/skip-formatting/resources/no_req_body/service/__init__.py +++ b/seed/fastapi/exhaustive/skip-formatting/resources/no_req_body/service/__init__.py @@ -1,4 +1,5 @@ # This file was auto-generated by Fern from our API Definition. from .service import AbstractNoReqBodyService + __all__ = ["AbstractNoReqBodyService"] diff --git a/seed/fastapi/exhaustive/skip-formatting/resources/no_req_body/service/service.py b/seed/fastapi/exhaustive/skip-formatting/resources/no_req_body/service/service.py index c7416176da5..40b96353e2d 100644 --- a/seed/fastapi/exhaustive/skip-formatting/resources/no_req_body/service/service.py +++ b/seed/fastapi/exhaustive/skip-formatting/resources/no_req_body/service/service.py @@ -2,7 +2,9 @@ from ....core.abstract_fern_service import AbstractFernService from ....security import ApiAuth -from ...types.resources.object.types.object_with_optional_field import ObjectWithOptionalField +from ...types.resources.object.types.object_with_optional_field import ( + ObjectWithOptionalField, +) import abc import fastapi import inspect @@ -12,46 +14,54 @@ import logging import functools from ....core.route_args import get_route_args + + class AbstractNoReqBodyService(AbstractFernService): """ AbstractNoReqBodyService is an abstract class containing the methods that you should implement. - + Each method is associated with an API route, which will be registered with FastAPI when you register your implementation using Fern's register() function. """ - + @abc.abstractmethod - def get_with_no_request_body(self, *, auth: ApiAuth) -> ObjectWithOptionalField: - ... - + def get_with_no_request_body(self, *, auth: ApiAuth) -> ObjectWithOptionalField: ... + @abc.abstractmethod - def post_with_no_request_body(self, *, auth: ApiAuth) -> str: - ... - + def post_with_no_request_body(self, *, auth: ApiAuth) -> str: ... + """ Below are internal methods used by Fern to register your implementation. You can ignore them. """ - + @classmethod def _init_fern(cls, router: fastapi.APIRouter) -> None: cls.__init_get_with_no_request_body(router=router) cls.__init_post_with_no_request_body(router=router) - + @classmethod def __init_get_with_no_request_body(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_with_no_request_body) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_with_no_request_body, "__signature__", endpoint_function.replace(parameters=new_parameters)) - + setattr( + cls.get_with_no_request_body, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) + @functools.wraps(cls.get_with_no_request_body) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> ObjectWithOptionalField: try: @@ -63,31 +73,39 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> ObjectWithOptionalField: + "the endpoint's errors list in your Fern Definition." ) raise e - + # this is necessary for FastAPI to find forward-ref'ed type hints. # https://github.com/tiangolo/fastapi/pull/5077 wrapper.__globals__.update(cls.get_with_no_request_body.__globals__) - + router.get( path="/no-req-body", response_model=ObjectWithOptionalField, description=AbstractNoReqBodyService.get_with_no_request_body.__doc__, **get_route_args(cls.get_with_no_request_body, default_tag="no_req_body"), )(wrapper) - + @classmethod def __init_post_with_no_request_body(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.post_with_no_request_body) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.post_with_no_request_body, "__signature__", endpoint_function.replace(parameters=new_parameters)) - + setattr( + cls.post_with_no_request_body, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) + @functools.wraps(cls.post_with_no_request_body) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> str: try: @@ -99,11 +117,11 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> str: + "the endpoint's errors list in your Fern Definition." ) raise e - + # this is necessary for FastAPI to find forward-ref'ed type hints. # https://github.com/tiangolo/fastapi/pull/5077 wrapper.__globals__.update(cls.post_with_no_request_body.__globals__) - + router.post( path="/no-req-body", response_model=str, diff --git a/seed/fastapi/exhaustive/skip-formatting/resources/req_with_headers/service/__init__.py b/seed/fastapi/exhaustive/skip-formatting/resources/req_with_headers/service/__init__.py index ae66848a1be..c5f17c39b40 100644 --- a/seed/fastapi/exhaustive/skip-formatting/resources/req_with_headers/service/__init__.py +++ b/seed/fastapi/exhaustive/skip-formatting/resources/req_with_headers/service/__init__.py @@ -1,4 +1,5 @@ # This file was auto-generated by Fern from our API Definition. from .service import AbstractReqWithHeadersService + __all__ = ["AbstractReqWithHeadersService"] diff --git a/seed/fastapi/exhaustive/skip-formatting/resources/req_with_headers/service/service.py b/seed/fastapi/exhaustive/skip-formatting/resources/req_with_headers/service/service.py index 52c4fbdd06c..0bb5ea5b04c 100644 --- a/seed/fastapi/exhaustive/skip-formatting/resources/req_with_headers/service/service.py +++ b/seed/fastapi/exhaustive/skip-formatting/resources/req_with_headers/service/service.py @@ -12,45 +12,60 @@ import functools import starlette from ....core.route_args import get_route_args + + class AbstractReqWithHeadersService(AbstractFernService): """ AbstractReqWithHeadersService is an abstract class containing the methods that you should implement. - + Each method is associated with an API route, which will be registered with FastAPI when you register your implementation using Fern's register() function. """ - + @abc.abstractmethod - def get_with_custom_header(self, *, body: str, x_test_endpoint_header: str, auth: ApiAuth) -> None: - ... - + def get_with_custom_header( + self, *, body: str, x_test_endpoint_header: str, auth: ApiAuth + ) -> None: ... + """ Below are internal methods used by Fern to register your implementation. You can ignore them. """ - + @classmethod def _init_fern(cls, router: fastapi.APIRouter) -> None: cls.__init_get_with_custom_header(router=router) - + @classmethod def __init_get_with_custom_header(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_with_custom_header) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "x_test_endpoint_header": - new_parameters.append(parameter.replace(default=fastapi.Header(alias="X-TEST-ENDPOINT-HEADER"))) + new_parameters.append( + parameter.replace( + default=fastapi.Header(alias="X-TEST-ENDPOINT-HEADER") + ) + ) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_with_custom_header, "__signature__", endpoint_function.replace(parameters=new_parameters)) - + setattr( + cls.get_with_custom_header, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) + @functools.wraps(cls.get_with_custom_header) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> None: try: @@ -62,15 +77,17 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> None: + "the endpoint's errors list in your Fern Definition." ) raise e - + # this is necessary for FastAPI to find forward-ref'ed type hints. # https://github.com/tiangolo/fastapi/pull/5077 wrapper.__globals__.update(cls.get_with_custom_header.__globals__) - + router.post( path="/test-headers/custom-header", response_model=None, status_code=starlette.status.HTTP_204_NO_CONTENT, description=AbstractReqWithHeadersService.get_with_custom_header.__doc__, - **get_route_args(cls.get_with_custom_header, default_tag="req_with_headers"), + **get_route_args( + cls.get_with_custom_header, default_tag="req_with_headers" + ), )(wrapper) diff --git a/seed/fastapi/exhaustive/skip-formatting/resources/types/__init__.py b/seed/fastapi/exhaustive/skip-formatting/resources/types/__init__.py index 7760969b3cc..a3867a6ebb1 100644 --- a/seed/fastapi/exhaustive/skip-formatting/resources/types/__init__.py +++ b/seed/fastapi/exhaustive/skip-formatting/resources/types/__init__.py @@ -1,4 +1,47 @@ # This file was auto-generated by Fern from our API Definition. -from .resources import Animal, Cat, Dog, DoubleOptional, ErrorWithEnumBody, ErrorWithUnionBody, NestedObjectWithOptionalField, NestedObjectWithOptionalFieldError, NestedObjectWithRequiredField, NestedObjectWithRequiredFieldError, ObjectWithMapOfMap, ObjectWithOptionalField, ObjectWithOptionalFieldError, ObjectWithRequiredField, ObjectWithRequiredFieldError, OptionalAlias, WeatherReport, enum, object, union -__all__ = ["Animal", "Cat", "Dog", "DoubleOptional", "ErrorWithEnumBody", "ErrorWithUnionBody", "NestedObjectWithOptionalField", "NestedObjectWithOptionalFieldError", "NestedObjectWithRequiredField", "NestedObjectWithRequiredFieldError", "ObjectWithMapOfMap", "ObjectWithOptionalField", "ObjectWithOptionalFieldError", "ObjectWithRequiredField", "ObjectWithRequiredFieldError", "OptionalAlias", "WeatherReport", "enum", "object", "union"] +from .resources import ( + Animal, + Cat, + Dog, + DoubleOptional, + ErrorWithEnumBody, + ErrorWithUnionBody, + NestedObjectWithOptionalField, + NestedObjectWithOptionalFieldError, + NestedObjectWithRequiredField, + NestedObjectWithRequiredFieldError, + ObjectWithMapOfMap, + ObjectWithOptionalField, + ObjectWithOptionalFieldError, + ObjectWithRequiredField, + ObjectWithRequiredFieldError, + OptionalAlias, + WeatherReport, + enum, + object, + union, +) + +__all__ = [ + "Animal", + "Cat", + "Dog", + "DoubleOptional", + "ErrorWithEnumBody", + "ErrorWithUnionBody", + "NestedObjectWithOptionalField", + "NestedObjectWithOptionalFieldError", + "NestedObjectWithRequiredField", + "NestedObjectWithRequiredFieldError", + "ObjectWithMapOfMap", + "ObjectWithOptionalField", + "ObjectWithOptionalFieldError", + "ObjectWithRequiredField", + "ObjectWithRequiredFieldError", + "OptionalAlias", + "WeatherReport", + "enum", + "object", + "union", +] diff --git a/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/__init__.py b/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/__init__.py index f2a66b569bd..8d48c2cf24e 100644 --- a/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/__init__.py +++ b/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/__init__.py @@ -2,6 +2,40 @@ from . import enum, object, union from .enum import ErrorWithEnumBody, WeatherReport -from .object import DoubleOptional, NestedObjectWithOptionalField, NestedObjectWithOptionalFieldError, NestedObjectWithRequiredField, NestedObjectWithRequiredFieldError, ObjectWithMapOfMap, ObjectWithOptionalField, ObjectWithOptionalFieldError, ObjectWithRequiredField, ObjectWithRequiredFieldError, OptionalAlias +from .object import ( + DoubleOptional, + NestedObjectWithOptionalField, + NestedObjectWithOptionalFieldError, + NestedObjectWithRequiredField, + NestedObjectWithRequiredFieldError, + ObjectWithMapOfMap, + ObjectWithOptionalField, + ObjectWithOptionalFieldError, + ObjectWithRequiredField, + ObjectWithRequiredFieldError, + OptionalAlias, +) from .union import Animal, Cat, Dog, ErrorWithUnionBody -__all__ = ["Animal", "Cat", "Dog", "DoubleOptional", "ErrorWithEnumBody", "ErrorWithUnionBody", "NestedObjectWithOptionalField", "NestedObjectWithOptionalFieldError", "NestedObjectWithRequiredField", "NestedObjectWithRequiredFieldError", "ObjectWithMapOfMap", "ObjectWithOptionalField", "ObjectWithOptionalFieldError", "ObjectWithRequiredField", "ObjectWithRequiredFieldError", "OptionalAlias", "WeatherReport", "enum", "object", "union"] + +__all__ = [ + "Animal", + "Cat", + "Dog", + "DoubleOptional", + "ErrorWithEnumBody", + "ErrorWithUnionBody", + "NestedObjectWithOptionalField", + "NestedObjectWithOptionalFieldError", + "NestedObjectWithRequiredField", + "NestedObjectWithRequiredFieldError", + "ObjectWithMapOfMap", + "ObjectWithOptionalField", + "ObjectWithOptionalFieldError", + "ObjectWithRequiredField", + "ObjectWithRequiredFieldError", + "OptionalAlias", + "WeatherReport", + "enum", + "object", + "union", +] diff --git a/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/enum/__init__.py b/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/enum/__init__.py index 56922faa185..3983fd06a84 100644 --- a/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/enum/__init__.py +++ b/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/enum/__init__.py @@ -2,4 +2,5 @@ from .errors import ErrorWithEnumBody from .types import WeatherReport + __all__ = ["ErrorWithEnumBody", "WeatherReport"] diff --git a/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/enum/errors/__init__.py b/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/enum/errors/__init__.py index 117cabc9f78..f5945e36d9d 100644 --- a/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/enum/errors/__init__.py +++ b/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/enum/errors/__init__.py @@ -1,4 +1,5 @@ # This file was auto-generated by Fern from our API Definition. from .error_with_enum_body import ErrorWithEnumBody + __all__ = ["ErrorWithEnumBody"] diff --git a/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/enum/errors/error_with_enum_body.py b/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/enum/errors/error_with_enum_body.py index 6309713beea..8b8a0d981c3 100644 --- a/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/enum/errors/error_with_enum_body.py +++ b/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/enum/errors/error_with_enum_body.py @@ -2,6 +2,8 @@ from ......core.exceptions.fern_http_exception import FernHTTPException from ..types.weather_report import WeatherReport + + class ErrorWithEnumBody(FernHTTPException): def __init__(self, error: WeatherReport): super().__init__(status_code=400, name="ErrorWithEnumBody", content=error) diff --git a/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/enum/types/__init__.py b/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/enum/types/__init__.py index e0972e22619..7a47d1fefc6 100644 --- a/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/enum/types/__init__.py +++ b/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/enum/types/__init__.py @@ -1,4 +1,5 @@ # This file was auto-generated by Fern from our API Definition. from .weather_report import WeatherReport + __all__ = ["WeatherReport"] diff --git a/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/enum/types/weather_report.py b/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/enum/types/weather_report.py index c6b56110956..0f2fc3aee2a 100644 --- a/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/enum/types/weather_report.py +++ b/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/enum/types/weather_report.py @@ -2,23 +2,28 @@ import enum import typing + T_Result = typing.TypeVar("T_Result") + + class WeatherReport(str, enum.Enum): SUNNY = "SUNNY" CLOUDY = "CLOUDY" RAINING = "RAINING" SNOWING = "SNOWING" - - def visit(self, sunny: typing.Callable[[], T_Result], cloudy: typing.Callable[[], T_Result], raining: typing.Callable[[], T_Result], snowing: typing.Callable[[], T_Result]) -> T_Result: + + def visit( + self, + sunny: typing.Callable[[], T_Result], + cloudy: typing.Callable[[], T_Result], + raining: typing.Callable[[], T_Result], + snowing: typing.Callable[[], T_Result], + ) -> T_Result: if self is WeatherReport.SUNNY: - return sunny( - ) + return sunny() if self is WeatherReport.CLOUDY: - return cloudy( - ) + return cloudy() if self is WeatherReport.RAINING: - return raining( - ) + return raining() if self is WeatherReport.SNOWING: - return snowing( - ) + return snowing() diff --git a/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/object/__init__.py b/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/object/__init__.py index 8a6b7de0ce9..6be602ca8ef 100644 --- a/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/object/__init__.py +++ b/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/object/__init__.py @@ -1,5 +1,31 @@ # This file was auto-generated by Fern from our API Definition. -from .errors import NestedObjectWithOptionalFieldError, NestedObjectWithRequiredFieldError, ObjectWithOptionalFieldError, ObjectWithRequiredFieldError -from .types import DoubleOptional, NestedObjectWithOptionalField, NestedObjectWithRequiredField, ObjectWithMapOfMap, ObjectWithOptionalField, ObjectWithRequiredField, OptionalAlias -__all__ = ["DoubleOptional", "NestedObjectWithOptionalField", "NestedObjectWithOptionalFieldError", "NestedObjectWithRequiredField", "NestedObjectWithRequiredFieldError", "ObjectWithMapOfMap", "ObjectWithOptionalField", "ObjectWithOptionalFieldError", "ObjectWithRequiredField", "ObjectWithRequiredFieldError", "OptionalAlias"] +from .errors import ( + NestedObjectWithOptionalFieldError, + NestedObjectWithRequiredFieldError, + ObjectWithOptionalFieldError, + ObjectWithRequiredFieldError, +) +from .types import ( + DoubleOptional, + NestedObjectWithOptionalField, + NestedObjectWithRequiredField, + ObjectWithMapOfMap, + ObjectWithOptionalField, + ObjectWithRequiredField, + OptionalAlias, +) + +__all__ = [ + "DoubleOptional", + "NestedObjectWithOptionalField", + "NestedObjectWithOptionalFieldError", + "NestedObjectWithRequiredField", + "NestedObjectWithRequiredFieldError", + "ObjectWithMapOfMap", + "ObjectWithOptionalField", + "ObjectWithOptionalFieldError", + "ObjectWithRequiredField", + "ObjectWithRequiredFieldError", + "OptionalAlias", +] diff --git a/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/object/errors/__init__.py b/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/object/errors/__init__.py index f9e70d7e1a9..7e7e4c63aa8 100644 --- a/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/object/errors/__init__.py +++ b/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/object/errors/__init__.py @@ -4,4 +4,10 @@ from .nested_object_with_required_field_error import NestedObjectWithRequiredFieldError from .object_with_optional_field_error import ObjectWithOptionalFieldError from .object_with_required_field_error import ObjectWithRequiredFieldError -__all__ = ["NestedObjectWithOptionalFieldError", "NestedObjectWithRequiredFieldError", "ObjectWithOptionalFieldError", "ObjectWithRequiredFieldError"] + +__all__ = [ + "NestedObjectWithOptionalFieldError", + "NestedObjectWithRequiredFieldError", + "ObjectWithOptionalFieldError", + "ObjectWithRequiredFieldError", +] diff --git a/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/object/errors/nested_object_with_optional_field_error.py b/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/object/errors/nested_object_with_optional_field_error.py index 40182079f5c..8ccad4823e1 100644 --- a/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/object/errors/nested_object_with_optional_field_error.py +++ b/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/object/errors/nested_object_with_optional_field_error.py @@ -2,6 +2,10 @@ from ......core.exceptions.fern_http_exception import FernHTTPException from ..types.nested_object_with_optional_field import NestedObjectWithOptionalField + + class NestedObjectWithOptionalFieldError(FernHTTPException): def __init__(self, error: NestedObjectWithOptionalField): - super().__init__(status_code=400, name="NestedObjectWithOptionalFieldError", content=error) + super().__init__( + status_code=400, name="NestedObjectWithOptionalFieldError", content=error + ) diff --git a/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/object/errors/nested_object_with_required_field_error.py b/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/object/errors/nested_object_with_required_field_error.py index 8e7e5becaa0..d328ecaf35e 100644 --- a/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/object/errors/nested_object_with_required_field_error.py +++ b/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/object/errors/nested_object_with_required_field_error.py @@ -2,6 +2,10 @@ from ......core.exceptions.fern_http_exception import FernHTTPException from ..types.nested_object_with_required_field import NestedObjectWithRequiredField + + class NestedObjectWithRequiredFieldError(FernHTTPException): def __init__(self, error: NestedObjectWithRequiredField): - super().__init__(status_code=400, name="NestedObjectWithRequiredFieldError", content=error) + super().__init__( + status_code=400, name="NestedObjectWithRequiredFieldError", content=error + ) diff --git a/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/object/errors/object_with_optional_field_error.py b/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/object/errors/object_with_optional_field_error.py index a1d15b64619..1205d252c69 100644 --- a/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/object/errors/object_with_optional_field_error.py +++ b/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/object/errors/object_with_optional_field_error.py @@ -2,6 +2,10 @@ from ......core.exceptions.fern_http_exception import FernHTTPException from ..types.object_with_optional_field import ObjectWithOptionalField + + class ObjectWithOptionalFieldError(FernHTTPException): def __init__(self, error: ObjectWithOptionalField): - super().__init__(status_code=400, name="ObjectWithOptionalFieldError", content=error) + super().__init__( + status_code=400, name="ObjectWithOptionalFieldError", content=error + ) diff --git a/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/object/errors/object_with_required_field_error.py b/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/object/errors/object_with_required_field_error.py index d727e2da0a5..53045a6279e 100644 --- a/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/object/errors/object_with_required_field_error.py +++ b/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/object/errors/object_with_required_field_error.py @@ -2,6 +2,10 @@ from ......core.exceptions.fern_http_exception import FernHTTPException from ..types.object_with_required_field import ObjectWithRequiredField + + class ObjectWithRequiredFieldError(FernHTTPException): def __init__(self, error: ObjectWithRequiredField): - super().__init__(status_code=400, name="ObjectWithRequiredFieldError", content=error) + super().__init__( + status_code=400, name="ObjectWithRequiredFieldError", content=error + ) diff --git a/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/object/types/__init__.py b/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/object/types/__init__.py index 0a29c3d3718..2620e6eea12 100644 --- a/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/object/types/__init__.py +++ b/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/object/types/__init__.py @@ -7,4 +7,13 @@ from .object_with_optional_field import ObjectWithOptionalField from .object_with_required_field import ObjectWithRequiredField from .optional_alias import OptionalAlias -__all__ = ["DoubleOptional", "NestedObjectWithOptionalField", "NestedObjectWithRequiredField", "ObjectWithMapOfMap", "ObjectWithOptionalField", "ObjectWithRequiredField", "OptionalAlias"] + +__all__ = [ + "DoubleOptional", + "NestedObjectWithOptionalField", + "NestedObjectWithRequiredField", + "ObjectWithMapOfMap", + "ObjectWithOptionalField", + "ObjectWithRequiredField", + "OptionalAlias", +] diff --git a/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/object/types/double_optional.py b/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/object/types/double_optional.py index 628b36555b5..055935ee32e 100644 --- a/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/object/types/double_optional.py +++ b/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/object/types/double_optional.py @@ -5,11 +5,18 @@ from .optional_alias import OptionalAlias import pydantic from ......core.pydantic_utilities import IS_PYDANTIC_V2 + + class DoubleOptional(UniversalBaseModel): - optional_alias: typing.Optional[OptionalAlias] = pydantic.Field(alias="optionalAlias", default=None) - + optional_alias: typing.Optional[OptionalAlias] = pydantic.Field( + alias="optionalAlias", default=None + ) + if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: + class Config: extra = pydantic.Extra.forbid diff --git a/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/object/types/nested_object_with_optional_field.py b/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/object/types/nested_object_with_optional_field.py index 27c24f8bd93..15fff182ee9 100644 --- a/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/object/types/nested_object_with_optional_field.py +++ b/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/object/types/nested_object_with_optional_field.py @@ -5,12 +5,19 @@ from .object_with_optional_field import ObjectWithOptionalField import pydantic from ......core.pydantic_utilities import IS_PYDANTIC_V2 + + class NestedObjectWithOptionalField(UniversalBaseModel): string: typing.Optional[str] = None - nested_object: typing.Optional[ObjectWithOptionalField] = pydantic.Field(alias="NestedObject", default=None) - + nested_object: typing.Optional[ObjectWithOptionalField] = pydantic.Field( + alias="NestedObject", default=None + ) + if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: + class Config: extra = pydantic.Extra.forbid diff --git a/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/object/types/nested_object_with_required_field.py b/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/object/types/nested_object_with_required_field.py index 1fd063b76dc..c152f7caf34 100644 --- a/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/object/types/nested_object_with_required_field.py +++ b/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/object/types/nested_object_with_required_field.py @@ -5,12 +5,17 @@ import pydantic from ......core.pydantic_utilities import IS_PYDANTIC_V2 import typing + + class NestedObjectWithRequiredField(UniversalBaseModel): string: str nested_object: ObjectWithOptionalField = pydantic.Field(alias="NestedObject") - + if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: + class Config: extra = pydantic.Extra.forbid diff --git a/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/object/types/object_with_map_of_map.py b/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/object/types/object_with_map_of_map.py index 1ee6e92fdd7..259d15f900b 100644 --- a/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/object/types/object_with_map_of_map.py +++ b/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/object/types/object_with_map_of_map.py @@ -4,11 +4,16 @@ import typing import pydantic from ......core.pydantic_utilities import IS_PYDANTIC_V2 + + class ObjectWithMapOfMap(UniversalBaseModel): map_: typing.Dict[str, typing.Dict[str, str]] = pydantic.Field(alias="map") - + if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: + class Config: extra = pydantic.Extra.forbid diff --git a/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/object/types/object_with_optional_field.py b/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/object/types/object_with_optional_field.py index 11930809291..b8d37eb85ef 100644 --- a/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/object/types/object_with_optional_field.py +++ b/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/object/types/object_with_optional_field.py @@ -6,12 +6,14 @@ import datetime as dt import uuid from ......core.pydantic_utilities import IS_PYDANTIC_V2 + + class ObjectWithOptionalField(UniversalBaseModel): string: typing.Optional[str] = pydantic.Field(default=None) """ This is a rather long descriptor of this single field in a more complex type. If you ask me I think this is a pretty good description for this field all things considered. """ - + integer: typing.Optional[int] = None long_: typing.Optional[int] = pydantic.Field(alias="long", default=None) double: typing.Optional[float] = None @@ -20,13 +22,20 @@ class ObjectWithOptionalField(UniversalBaseModel): date: typing.Optional[dt.date] = None uuid_: typing.Optional[uuid.UUID] = pydantic.Field(alias="uuid", default=None) base_64: typing.Optional[str] = pydantic.Field(alias="base64", default=None) - list_: typing.Optional[typing.List[str]] = pydantic.Field(alias="list", default=None) + list_: typing.Optional[typing.List[str]] = pydantic.Field( + alias="list", default=None + ) set_: typing.Optional[typing.Set[str]] = pydantic.Field(alias="set", default=None) - map_: typing.Optional[typing.Dict[int, str]] = pydantic.Field(alias="map", default=None) + map_: typing.Optional[typing.Dict[int, str]] = pydantic.Field( + alias="map", default=None + ) bigint: typing.Optional[str] = None - + if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: + class Config: extra = pydantic.Extra.forbid diff --git a/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/object/types/object_with_required_field.py b/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/object/types/object_with_required_field.py index 92b8193a5e8..460dec359be 100644 --- a/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/object/types/object_with_required_field.py +++ b/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/object/types/object_with_required_field.py @@ -4,11 +4,16 @@ from ......core.pydantic_utilities import IS_PYDANTIC_V2 import typing import pydantic + + class ObjectWithRequiredField(UniversalBaseModel): string: str - + if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: + class Config: extra = pydantic.Extra.forbid diff --git a/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/object/types/optional_alias.py b/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/object/types/optional_alias.py index 33af2c89e68..fa09e3be001 100644 --- a/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/object/types/optional_alias.py +++ b/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/object/types/optional_alias.py @@ -1,4 +1,5 @@ # This file was auto-generated by Fern from our API Definition. import typing + OptionalAlias = typing.Optional[str] diff --git a/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/union/__init__.py b/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/union/__init__.py index cc51d4d12c4..8033ac545f0 100644 --- a/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/union/__init__.py +++ b/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/union/__init__.py @@ -2,4 +2,5 @@ from .errors import ErrorWithUnionBody from .types import Animal, Cat, Dog + __all__ = ["Animal", "Cat", "Dog", "ErrorWithUnionBody"] diff --git a/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/union/errors/__init__.py b/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/union/errors/__init__.py index e2a27e537b2..568a71fa3c4 100644 --- a/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/union/errors/__init__.py +++ b/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/union/errors/__init__.py @@ -1,4 +1,5 @@ # This file was auto-generated by Fern from our API Definition. from .error_with_union_body import ErrorWithUnionBody + __all__ = ["ErrorWithUnionBody"] diff --git a/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/union/errors/error_with_union_body.py b/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/union/errors/error_with_union_body.py index ccfa23b835f..d4343a0aea5 100644 --- a/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/union/errors/error_with_union_body.py +++ b/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/union/errors/error_with_union_body.py @@ -2,6 +2,8 @@ from ......core.exceptions.fern_http_exception import FernHTTPException from ..types.animal import Animal + + class ErrorWithUnionBody(FernHTTPException): def __init__(self, error: Animal): super().__init__(status_code=400, name="ErrorWithUnionBody", content=error) diff --git a/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/union/types/__init__.py b/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/union/types/__init__.py index 633816807a5..e8c68486eda 100644 --- a/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/union/types/__init__.py +++ b/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/union/types/__init__.py @@ -3,4 +3,5 @@ from .animal import Animal from .cat import Cat from .dog import Dog + __all__ = ["Animal", "Cat", "Dog"] diff --git a/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/union/types/animal.py b/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/union/types/animal.py index 1f7ba829989..a8ee74c09ed 100644 --- a/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/union/types/animal.py +++ b/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/union/types/animal.py @@ -9,47 +9,78 @@ import typing_extensions import pydantic from ......core.pydantic_utilities import update_forward_refs + T_Result = typing.TypeVar("T_Result") + + class _Factory: - def dog(self, value: resources_types_resources_union_types_dog_Dog) -> Animal: if IS_PYDANTIC_V2: - return Animal(root=_Animal.Dog(**value.dict(exclude_unset=True), animal="dog")) + return Animal( + root=_Animal.Dog(**value.dict(exclude_unset=True), animal="dog") + ) else: - return Animal(__root__=_Animal.Dog(**value.dict(exclude_unset=True), animal="dog")) - + return Animal( + __root__=_Animal.Dog(**value.dict(exclude_unset=True), animal="dog") + ) + def cat(self, value: resources_types_resources_union_types_cat_Cat) -> Animal: if IS_PYDANTIC_V2: - return Animal(root=_Animal.Cat(**value.dict(exclude_unset=True), animal="cat")) + return Animal( + root=_Animal.Cat(**value.dict(exclude_unset=True), animal="cat") + ) else: - return Animal(__root__=_Animal.Cat(**value.dict(exclude_unset=True), animal="cat")) + return Animal( + __root__=_Animal.Cat(**value.dict(exclude_unset=True), animal="cat") + ) + + class Animal(UniversalRootModel): factory: typing.ClassVar[_Factory] = _Factory() - + if IS_PYDANTIC_V2: - root: typing_extensions.Annotated[typing.Union[_Animal.Dog, _Animal.Cat], pydantic.Field(discriminator="animal")] + root: typing_extensions.Annotated[ + typing.Union[_Animal.Dog, _Animal.Cat], + pydantic.Field(discriminator="animal"), + ] + def get_as_union(self) -> typing.Union[_Animal.Dog, _Animal.Cat]: return self.root else: - __root__: typing_extensions.Annotated[typing.Union[_Animal.Dog, _Animal.Cat], pydantic.Field(discriminator="animal")] + __root__: typing_extensions.Annotated[ + typing.Union[_Animal.Dog, _Animal.Cat], + pydantic.Field(discriminator="animal"), + ] + def get_as_union(self) -> typing.Union[_Animal.Dog, _Animal.Cat]: return self.__root__ - - def visit(self, dog: typing.Callable[[resources_types_resources_union_types_dog_Dog], T_Result], cat: typing.Callable[[resources_types_resources_union_types_cat_Cat], T_Result]) -> T_Result: + + def visit( + self, + dog: typing.Callable[[resources_types_resources_union_types_dog_Dog], T_Result], + cat: typing.Callable[[resources_types_resources_union_types_cat_Cat], T_Result], + ) -> T_Result: unioned_value = self.get_as_union() if unioned_value.animal == "dog": return dog( - resources_types_resources_union_types_dog_Dog(**unioned_value.dict(exclude_unset=True, exclude={"animal"}))) + resources_types_resources_union_types_dog_Dog( + **unioned_value.dict(exclude_unset=True, exclude={"animal"}) + ) + ) if unioned_value.animal == "cat": return cat( - resources_types_resources_union_types_cat_Cat(**unioned_value.dict(exclude_unset=True, exclude={"animal"}))) + resources_types_resources_union_types_cat_Cat( + **unioned_value.dict(exclude_unset=True, exclude={"animal"}) + ) + ) + + class _Animal: - class Dog(resources_types_resources_union_types_dog_Dog): animal: typing.Literal["dog"] = "dog" - - + class Cat(resources_types_resources_union_types_cat_Cat): animal: typing.Literal["cat"] = "cat" - + + update_forward_refs(Animal) diff --git a/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/union/types/cat.py b/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/union/types/cat.py index 8b717ba3c9f..cdcfe7a1d25 100644 --- a/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/union/types/cat.py +++ b/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/union/types/cat.py @@ -4,12 +4,17 @@ import pydantic from ......core.pydantic_utilities import IS_PYDANTIC_V2 import typing + + class Cat(UniversalBaseModel): name: str likes_to_meow: bool = pydantic.Field(alias="likesToMeow") - + if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: + class Config: extra = pydantic.Extra.forbid diff --git a/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/union/types/dog.py b/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/union/types/dog.py index 88356e42c91..b5feda1e61c 100644 --- a/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/union/types/dog.py +++ b/seed/fastapi/exhaustive/skip-formatting/resources/types/resources/union/types/dog.py @@ -4,12 +4,17 @@ import pydantic from ......core.pydantic_utilities import IS_PYDANTIC_V2 import typing + + class Dog(UniversalBaseModel): name: str likes_to_woof: bool = pydantic.Field(alias="likesToWoof") - + if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: + class Config: extra = pydantic.Extra.forbid diff --git a/seed/fastapi/exhaustive/skip-formatting/security.py b/seed/fastapi/exhaustive/skip-formatting/security.py index 47809667976..4ccabc21106 100644 --- a/seed/fastapi/exhaustive/skip-formatting/security.py +++ b/seed/fastapi/exhaustive/skip-formatting/security.py @@ -3,6 +3,9 @@ from .core.security.bearer import BearerToken import fastapi from .core.security.bearer import HTTPBearer + ApiAuth = BearerToken + + def FernAuth(auth: BearerToken = fastapi.Depends(HTTPBearer)) -> BearerToken: return auth diff --git a/seed/fastapi/extends/core/abstract_fern_service.py b/seed/fastapi/extends/core/abstract_fern_service.py index da7c8dc49c4..9966b4876da 100644 --- a/seed/fastapi/extends/core/abstract_fern_service.py +++ b/seed/fastapi/extends/core/abstract_fern_service.py @@ -7,5 +7,4 @@ class AbstractFernService(abc.ABC): @classmethod - def _init_fern(cls, router: fastapi.APIRouter) -> None: - ... + def _init_fern(cls, router: fastapi.APIRouter) -> None: ... diff --git a/seed/fastapi/extends/core/datetime_utils.py b/seed/fastapi/extends/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/fastapi/extends/core/datetime_utils.py +++ b/seed/fastapi/extends/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/fastapi/extends/core/exceptions/__init__.py b/seed/fastapi/extends/core/exceptions/__init__.py index 297d6e06f5f..dae4b8980c1 100644 --- a/seed/fastapi/extends/core/exceptions/__init__.py +++ b/seed/fastapi/extends/core/exceptions/__init__.py @@ -1,7 +1,11 @@ # This file was auto-generated by Fern from our API Definition. from .fern_http_exception import FernHTTPException -from .handlers import default_exception_handler, fern_http_exception_handler, http_exception_handler +from .handlers import ( + default_exception_handler, + fern_http_exception_handler, + http_exception_handler, +) from .unauthorized import UnauthorizedException __all__ = [ diff --git a/seed/fastapi/extends/core/exceptions/fern_http_exception.py b/seed/fastapi/extends/core/exceptions/fern_http_exception.py index bdf03862487..81610359a7f 100644 --- a/seed/fastapi/extends/core/exceptions/fern_http_exception.py +++ b/seed/fastapi/extends/core/exceptions/fern_http_exception.py @@ -1,14 +1,16 @@ # This file was auto-generated by Fern from our API Definition. import abc -import typing - import fastapi +import typing class FernHTTPException(abc.ABC, fastapi.HTTPException): def __init__( - self, status_code: int, name: typing.Optional[str] = None, content: typing.Optional[typing.Any] = None + self, + status_code: int, + name: typing.Optional[str] = None, + content: typing.Optional[typing.Any] = None, ): super().__init__(status_code=status_code) self.name = name @@ -17,4 +19,6 @@ def __init__( def to_json_response(self) -> fastapi.responses.JSONResponse: content = fastapi.encoders.jsonable_encoder(self.content, exclude_none=True) - return fastapi.responses.JSONResponse(content=content, status_code=self.status_code) + return fastapi.responses.JSONResponse( + content=content, status_code=self.status_code + ) diff --git a/seed/fastapi/extends/core/exceptions/handlers.py b/seed/fastapi/extends/core/exceptions/handlers.py index 6d8c4155c5a..ae1c2741f06 100644 --- a/seed/fastapi/extends/core/exceptions/handlers.py +++ b/seed/fastapi/extends/core/exceptions/handlers.py @@ -2,32 +2,49 @@ import logging -import fastapi import starlette import starlette.exceptions +import fastapi + from .fern_http_exception import FernHTTPException def fern_http_exception_handler( - request: fastapi.requests.Request, exc: FernHTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: FernHTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) return exc.to_json_response() def http_exception_handler( - request: fastapi.requests.Request, exc: starlette.exceptions.HTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: starlette.exceptions.HTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=exc.status_code, content=exc.detail).to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=exc.status_code, content=exc.detail + ).to_json_response() def default_exception_handler( - request: fastapi.requests.Request, exc: Exception, skip_log: bool = False + request: fastapi.requests.Request, + exc: Exception, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=500, content="Internal Server Error").to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=500, content="Internal Server Error" + ).to_json_response() diff --git a/seed/fastapi/extends/core/pydantic_utilities.py b/seed/fastapi/extends/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/fastapi/extends/core/pydantic_utilities.py +++ b/seed/fastapi/extends/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/fastapi/extends/core/route_args.py b/seed/fastapi/extends/core/route_args.py index 4228e2fe05d..bd940bf4ddd 100644 --- a/seed/fastapi/extends/core/route_args.py +++ b/seed/fastapi/extends/core/route_args.py @@ -20,9 +20,15 @@ class RouteArgs(typing_extensions.TypedDict): DEFAULT_ROUTE_ARGS = RouteArgs(openapi_extra=None, tags=None, include_in_schema=True) -def get_route_args(endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str) -> RouteArgs: - unwrapped = inspect.unwrap(endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY))) - route_args = typing.cast(RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS)) +def get_route_args( + endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str +) -> RouteArgs: + unwrapped = inspect.unwrap( + endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY)) + ) + route_args = typing.cast( + RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS) + ) if route_args["tags"] is None: return RouteArgs( openapi_extra=route_args["openapi_extra"], @@ -56,7 +62,11 @@ def decorator(endpoint_function: T) -> T: setattr( endpoint_function, FERN_CONFIG_KEY, - RouteArgs(openapi_extra=openapi_extra, tags=tags, include_in_schema=include_in_schema), + RouteArgs( + openapi_extra=openapi_extra, + tags=tags, + include_in_schema=include_in_schema, + ), ) return endpoint_function diff --git a/seed/fastapi/extends/register.py b/seed/fastapi/extends/register.py index 3b90d0c034f..ce9f38fa412 100644 --- a/seed/fastapi/extends/register.py +++ b/seed/fastapi/extends/register.py @@ -1,31 +1,33 @@ # This file was auto-generated by Fern from our API Definition. -import glob -import importlib -import os -import types -import typing - import fastapi -import starlette.exceptions +from .service.service import AbstractRootService +import typing from fastapi import params - -from .core.abstract_fern_service import AbstractFernService -from .core.exceptions import default_exception_handler, fern_http_exception_handler, http_exception_handler from .core.exceptions.fern_http_exception import FernHTTPException -from .service.service import AbstractRootService +from .core.exceptions import fern_http_exception_handler +import starlette.exceptions +from .core.exceptions import http_exception_handler +from .core.exceptions import default_exception_handler +from .core.abstract_fern_service import AbstractFernService +import types +import os +import glob +import importlib def register( _app: fastapi.FastAPI, *, root: AbstractRootService, - dependencies: typing.Optional[typing.Sequence[params.Depends]] = None + dependencies: typing.Optional[typing.Sequence[params.Depends]] = None, ) -> None: _app.include_router(__register_service(root), dependencies=dependencies) _app.add_exception_handler(FernHTTPException, fern_http_exception_handler) # type: ignore - _app.add_exception_handler(starlette.exceptions.HTTPException, http_exception_handler) # type: ignore + _app.add_exception_handler( + starlette.exceptions.HTTPException, http_exception_handler + ) # type: ignore _app.add_exception_handler(Exception, default_exception_handler) # type: ignore @@ -37,7 +39,9 @@ def __register_service(service: AbstractFernService) -> fastapi.APIRouter: def register_validators(module: types.ModuleType) -> None: validators_directory: str = os.path.dirname(module.__file__) # type: ignore - for path in glob.glob(os.path.join(validators_directory, "**/*.py"), recursive=True): + for path in glob.glob( + os.path.join(validators_directory, "**/*.py"), recursive=True + ): if os.path.isfile(path): relative_path = os.path.relpath(path, start=validators_directory) module_path = ".".join([module.__name__] + relative_path[:-3].split("/")) diff --git a/seed/fastapi/extends/service/inlined.py b/seed/fastapi/extends/service/inlined.py index f5c6fcfdd76..5df20709bac 100644 --- a/seed/fastapi/extends/service/inlined.py +++ b/seed/fastapi/extends/service/inlined.py @@ -1,18 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ..types.example_type import ExampleType +from ..core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ..core.pydantic_utilities import IS_PYDANTIC_V2 -from ..types.example_type import ExampleType - class Inlined(ExampleType): unique: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/extends/service/service.py b/seed/fastapi/extends/service/service.py index 0ca17c74f6c..2b177f0cdb5 100644 --- a/seed/fastapi/extends/service/service.py +++ b/seed/fastapi/extends/service/service.py @@ -1,18 +1,16 @@ # This file was auto-generated by Fern from our API Definition. +from ..core.abstract_fern_service import AbstractFernService +from .inlined import Inlined import abc -import functools +import fastapi import inspect -import logging import typing - -import fastapi -import starlette - -from ..core.abstract_fern_service import AbstractFernService from ..core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools +import starlette from ..core.route_args import get_route_args -from .inlined import Inlined class AbstractRootService(AbstractFernService): @@ -25,8 +23,7 @@ class AbstractRootService(AbstractFernService): """ @abc.abstractmethod - def extended_inline_request_body(self, *, body: Inlined) -> None: - ... + def extended_inline_request_body(self, *, body: Inlined) -> None: ... """ Below are internal methods used by Fern to register your implementation. @@ -41,14 +38,20 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_extended_inline_request_body(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.extended_inline_request_body) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) else: new_parameters.append(parameter) - setattr(cls.extended_inline_request_body, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.extended_inline_request_body, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.extended_inline_request_body) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> None: diff --git a/seed/fastapi/extends/types/docs.py b/seed/fastapi/extends/types/docs.py index b71b959d795..d7c5edc9bc5 100644 --- a/seed/fastapi/extends/types/docs.py +++ b/seed/fastapi/extends/types/docs.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from ..core.pydantic_utilities import UniversalBaseModel +from ..core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class Docs(UniversalBaseModel): """ @@ -21,7 +20,9 @@ class Docs(UniversalBaseModel): docs: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/extends/types/example_type.py b/seed/fastapi/extends/types/example_type.py index 252dcc92b27..5728537231b 100644 --- a/seed/fastapi/extends/types/example_type.py +++ b/seed/fastapi/extends/types/example_type.py @@ -1,12 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from .docs import Docs +from ..core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ..core.pydantic_utilities import IS_PYDANTIC_V2 -from .docs import Docs - class ExampleType(Docs): """ @@ -23,7 +21,9 @@ class ExampleType(Docs): name: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/extends/types/json.py b/seed/fastapi/extends/types/json.py index f82dc71ed10..1f4b5858db9 100644 --- a/seed/fastapi/extends/types/json.py +++ b/seed/fastapi/extends/types/json.py @@ -1,12 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from .docs import Docs +from ..core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ..core.pydantic_utilities import IS_PYDANTIC_V2 -from .docs import Docs - class Json(Docs): """ @@ -23,7 +21,9 @@ class Json(Docs): raw: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/extends/types/nested_type.py b/seed/fastapi/extends/types/nested_type.py index 4ad7ecb1724..bd6374d83d5 100644 --- a/seed/fastapi/extends/types/nested_type.py +++ b/seed/fastapi/extends/types/nested_type.py @@ -1,12 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from .json import Json +from ..core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ..core.pydantic_utilities import IS_PYDANTIC_V2 -from .json import Json - class NestedType(Json): """ @@ -24,7 +22,9 @@ class NestedType(Json): name: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/extra-properties/core/abstract_fern_service.py b/seed/fastapi/extra-properties/core/abstract_fern_service.py index da7c8dc49c4..9966b4876da 100644 --- a/seed/fastapi/extra-properties/core/abstract_fern_service.py +++ b/seed/fastapi/extra-properties/core/abstract_fern_service.py @@ -7,5 +7,4 @@ class AbstractFernService(abc.ABC): @classmethod - def _init_fern(cls, router: fastapi.APIRouter) -> None: - ... + def _init_fern(cls, router: fastapi.APIRouter) -> None: ... diff --git a/seed/fastapi/extra-properties/core/datetime_utils.py b/seed/fastapi/extra-properties/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/fastapi/extra-properties/core/datetime_utils.py +++ b/seed/fastapi/extra-properties/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/fastapi/extra-properties/core/exceptions/__init__.py b/seed/fastapi/extra-properties/core/exceptions/__init__.py index 297d6e06f5f..dae4b8980c1 100644 --- a/seed/fastapi/extra-properties/core/exceptions/__init__.py +++ b/seed/fastapi/extra-properties/core/exceptions/__init__.py @@ -1,7 +1,11 @@ # This file was auto-generated by Fern from our API Definition. from .fern_http_exception import FernHTTPException -from .handlers import default_exception_handler, fern_http_exception_handler, http_exception_handler +from .handlers import ( + default_exception_handler, + fern_http_exception_handler, + http_exception_handler, +) from .unauthorized import UnauthorizedException __all__ = [ diff --git a/seed/fastapi/extra-properties/core/exceptions/fern_http_exception.py b/seed/fastapi/extra-properties/core/exceptions/fern_http_exception.py index bdf03862487..81610359a7f 100644 --- a/seed/fastapi/extra-properties/core/exceptions/fern_http_exception.py +++ b/seed/fastapi/extra-properties/core/exceptions/fern_http_exception.py @@ -1,14 +1,16 @@ # This file was auto-generated by Fern from our API Definition. import abc -import typing - import fastapi +import typing class FernHTTPException(abc.ABC, fastapi.HTTPException): def __init__( - self, status_code: int, name: typing.Optional[str] = None, content: typing.Optional[typing.Any] = None + self, + status_code: int, + name: typing.Optional[str] = None, + content: typing.Optional[typing.Any] = None, ): super().__init__(status_code=status_code) self.name = name @@ -17,4 +19,6 @@ def __init__( def to_json_response(self) -> fastapi.responses.JSONResponse: content = fastapi.encoders.jsonable_encoder(self.content, exclude_none=True) - return fastapi.responses.JSONResponse(content=content, status_code=self.status_code) + return fastapi.responses.JSONResponse( + content=content, status_code=self.status_code + ) diff --git a/seed/fastapi/extra-properties/core/exceptions/handlers.py b/seed/fastapi/extra-properties/core/exceptions/handlers.py index 6d8c4155c5a..ae1c2741f06 100644 --- a/seed/fastapi/extra-properties/core/exceptions/handlers.py +++ b/seed/fastapi/extra-properties/core/exceptions/handlers.py @@ -2,32 +2,49 @@ import logging -import fastapi import starlette import starlette.exceptions +import fastapi + from .fern_http_exception import FernHTTPException def fern_http_exception_handler( - request: fastapi.requests.Request, exc: FernHTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: FernHTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) return exc.to_json_response() def http_exception_handler( - request: fastapi.requests.Request, exc: starlette.exceptions.HTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: starlette.exceptions.HTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=exc.status_code, content=exc.detail).to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=exc.status_code, content=exc.detail + ).to_json_response() def default_exception_handler( - request: fastapi.requests.Request, exc: Exception, skip_log: bool = False + request: fastapi.requests.Request, + exc: Exception, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=500, content="Internal Server Error").to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=500, content="Internal Server Error" + ).to_json_response() diff --git a/seed/fastapi/extra-properties/core/pydantic_utilities.py b/seed/fastapi/extra-properties/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/fastapi/extra-properties/core/pydantic_utilities.py +++ b/seed/fastapi/extra-properties/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/fastapi/extra-properties/core/route_args.py b/seed/fastapi/extra-properties/core/route_args.py index 4228e2fe05d..bd940bf4ddd 100644 --- a/seed/fastapi/extra-properties/core/route_args.py +++ b/seed/fastapi/extra-properties/core/route_args.py @@ -20,9 +20,15 @@ class RouteArgs(typing_extensions.TypedDict): DEFAULT_ROUTE_ARGS = RouteArgs(openapi_extra=None, tags=None, include_in_schema=True) -def get_route_args(endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str) -> RouteArgs: - unwrapped = inspect.unwrap(endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY))) - route_args = typing.cast(RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS)) +def get_route_args( + endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str +) -> RouteArgs: + unwrapped = inspect.unwrap( + endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY)) + ) + route_args = typing.cast( + RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS) + ) if route_args["tags"] is None: return RouteArgs( openapi_extra=route_args["openapi_extra"], @@ -56,7 +62,11 @@ def decorator(endpoint_function: T) -> T: setattr( endpoint_function, FERN_CONFIG_KEY, - RouteArgs(openapi_extra=openapi_extra, tags=tags, include_in_schema=include_in_schema), + RouteArgs( + openapi_extra=openapi_extra, + tags=tags, + include_in_schema=include_in_schema, + ), ) return endpoint_function diff --git a/seed/fastapi/extra-properties/register.py b/seed/fastapi/extra-properties/register.py index cad83228e21..f0b801ec079 100644 --- a/seed/fastapi/extra-properties/register.py +++ b/seed/fastapi/extra-properties/register.py @@ -1,31 +1,33 @@ # This file was auto-generated by Fern from our API Definition. -import glob -import importlib -import os -import types -import typing - import fastapi -import starlette.exceptions +from .resources.user.service.service import AbstractUserService +import typing from fastapi import params - -from .core.abstract_fern_service import AbstractFernService -from .core.exceptions import default_exception_handler, fern_http_exception_handler, http_exception_handler from .core.exceptions.fern_http_exception import FernHTTPException -from .resources.user.service.service import AbstractUserService +from .core.exceptions import fern_http_exception_handler +import starlette.exceptions +from .core.exceptions import http_exception_handler +from .core.exceptions import default_exception_handler +from .core.abstract_fern_service import AbstractFernService +import types +import os +import glob +import importlib def register( _app: fastapi.FastAPI, *, user: AbstractUserService, - dependencies: typing.Optional[typing.Sequence[params.Depends]] = None + dependencies: typing.Optional[typing.Sequence[params.Depends]] = None, ) -> None: _app.include_router(__register_service(user), dependencies=dependencies) _app.add_exception_handler(FernHTTPException, fern_http_exception_handler) # type: ignore - _app.add_exception_handler(starlette.exceptions.HTTPException, http_exception_handler) # type: ignore + _app.add_exception_handler( + starlette.exceptions.HTTPException, http_exception_handler + ) # type: ignore _app.add_exception_handler(Exception, default_exception_handler) # type: ignore @@ -37,7 +39,9 @@ def __register_service(service: AbstractFernService) -> fastapi.APIRouter: def register_validators(module: types.ModuleType) -> None: validators_directory: str = os.path.dirname(module.__file__) # type: ignore - for path in glob.glob(os.path.join(validators_directory, "**/*.py"), recursive=True): + for path in glob.glob( + os.path.join(validators_directory, "**/*.py"), recursive=True + ): if os.path.isfile(path): relative_path = os.path.relpath(path, start=validators_directory) module_path = ".".join([module.__name__] + relative_path[:-3].split("/")) diff --git a/seed/fastapi/extra-properties/resources/user/service/create_user_request.py b/seed/fastapi/extra-properties/resources/user/service/create_user_request.py index 6fd82e3e1ba..177fa2811cb 100644 --- a/seed/fastapi/extra-properties/resources/user/service/create_user_request.py +++ b/seed/fastapi/extra-properties/resources/user/service/create_user_request.py @@ -1,19 +1,22 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class CreateUserRequest(UniversalBaseModel): - type: typing.Literal["CreateUserRequest"] = pydantic.Field(alias="_type", default="CreateUserRequest") + type: typing.Literal["CreateUserRequest"] = pydantic.Field( + alias="_type", default="CreateUserRequest" + ) version: typing.Literal["v1"] = pydantic.Field(alias="_version", default="v1") name: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/extra-properties/resources/user/service/service.py b/seed/fastapi/extra-properties/resources/user/service/service.py index a71320a216c..361ca9d2317 100644 --- a/seed/fastapi/extra-properties/resources/user/service/service.py +++ b/seed/fastapi/extra-properties/resources/user/service/service.py @@ -1,18 +1,16 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.abstract_fern_service import AbstractFernService +from .create_user_request import CreateUserRequest +from ..types.user import User import abc -import functools +import fastapi import inspect -import logging import typing - -import fastapi - -from ....core.abstract_fern_service import AbstractFernService from ....core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools from ....core.route_args import get_route_args -from ..types.user import User -from .create_user_request import CreateUserRequest class AbstractUserService(AbstractFernService): @@ -25,8 +23,7 @@ class AbstractUserService(AbstractFernService): """ @abc.abstractmethod - def create_user(self, *, body: CreateUserRequest) -> User: - ... + def create_user(self, *, body: CreateUserRequest) -> User: ... """ Below are internal methods used by Fern to register your implementation. @@ -41,14 +38,20 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_create_user(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.create_user) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) else: new_parameters.append(parameter) - setattr(cls.create_user, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.create_user, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.create_user) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> User: diff --git a/seed/fastapi/extra-properties/resources/user/types/user.py b/seed/fastapi/extra-properties/resources/user/types/user.py index 872bbd26df8..07e0eddf391 100644 --- a/seed/fastapi/extra-properties/resources/user/types/user.py +++ b/seed/fastapi/extra-properties/resources/user/types/user.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class User(UniversalBaseModel): name: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/extra-properties/types/failure.py b/seed/fastapi/extra-properties/types/failure.py index c926658290a..eafa6c21add 100644 --- a/seed/fastapi/extra-properties/types/failure.py +++ b/seed/fastapi/extra-properties/types/failure.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ..core.pydantic_utilities import UniversalBaseModel import typing - +from ..core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class Failure(UniversalBaseModel): status: typing.Literal["failure"] = "failure" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/folders/core/abstract_fern_service.py b/seed/fastapi/folders/core/abstract_fern_service.py index da7c8dc49c4..9966b4876da 100644 --- a/seed/fastapi/folders/core/abstract_fern_service.py +++ b/seed/fastapi/folders/core/abstract_fern_service.py @@ -7,5 +7,4 @@ class AbstractFernService(abc.ABC): @classmethod - def _init_fern(cls, router: fastapi.APIRouter) -> None: - ... + def _init_fern(cls, router: fastapi.APIRouter) -> None: ... diff --git a/seed/fastapi/folders/core/datetime_utils.py b/seed/fastapi/folders/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/fastapi/folders/core/datetime_utils.py +++ b/seed/fastapi/folders/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/fastapi/folders/core/exceptions/__init__.py b/seed/fastapi/folders/core/exceptions/__init__.py index 297d6e06f5f..dae4b8980c1 100644 --- a/seed/fastapi/folders/core/exceptions/__init__.py +++ b/seed/fastapi/folders/core/exceptions/__init__.py @@ -1,7 +1,11 @@ # This file was auto-generated by Fern from our API Definition. from .fern_http_exception import FernHTTPException -from .handlers import default_exception_handler, fern_http_exception_handler, http_exception_handler +from .handlers import ( + default_exception_handler, + fern_http_exception_handler, + http_exception_handler, +) from .unauthorized import UnauthorizedException __all__ = [ diff --git a/seed/fastapi/folders/core/exceptions/fern_http_exception.py b/seed/fastapi/folders/core/exceptions/fern_http_exception.py index bdf03862487..81610359a7f 100644 --- a/seed/fastapi/folders/core/exceptions/fern_http_exception.py +++ b/seed/fastapi/folders/core/exceptions/fern_http_exception.py @@ -1,14 +1,16 @@ # This file was auto-generated by Fern from our API Definition. import abc -import typing - import fastapi +import typing class FernHTTPException(abc.ABC, fastapi.HTTPException): def __init__( - self, status_code: int, name: typing.Optional[str] = None, content: typing.Optional[typing.Any] = None + self, + status_code: int, + name: typing.Optional[str] = None, + content: typing.Optional[typing.Any] = None, ): super().__init__(status_code=status_code) self.name = name @@ -17,4 +19,6 @@ def __init__( def to_json_response(self) -> fastapi.responses.JSONResponse: content = fastapi.encoders.jsonable_encoder(self.content, exclude_none=True) - return fastapi.responses.JSONResponse(content=content, status_code=self.status_code) + return fastapi.responses.JSONResponse( + content=content, status_code=self.status_code + ) diff --git a/seed/fastapi/folders/core/exceptions/handlers.py b/seed/fastapi/folders/core/exceptions/handlers.py index 6d8c4155c5a..ae1c2741f06 100644 --- a/seed/fastapi/folders/core/exceptions/handlers.py +++ b/seed/fastapi/folders/core/exceptions/handlers.py @@ -2,32 +2,49 @@ import logging -import fastapi import starlette import starlette.exceptions +import fastapi + from .fern_http_exception import FernHTTPException def fern_http_exception_handler( - request: fastapi.requests.Request, exc: FernHTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: FernHTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) return exc.to_json_response() def http_exception_handler( - request: fastapi.requests.Request, exc: starlette.exceptions.HTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: starlette.exceptions.HTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=exc.status_code, content=exc.detail).to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=exc.status_code, content=exc.detail + ).to_json_response() def default_exception_handler( - request: fastapi.requests.Request, exc: Exception, skip_log: bool = False + request: fastapi.requests.Request, + exc: Exception, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=500, content="Internal Server Error").to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=500, content="Internal Server Error" + ).to_json_response() diff --git a/seed/fastapi/folders/core/pydantic_utilities.py b/seed/fastapi/folders/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/fastapi/folders/core/pydantic_utilities.py +++ b/seed/fastapi/folders/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/fastapi/folders/core/route_args.py b/seed/fastapi/folders/core/route_args.py index 4228e2fe05d..bd940bf4ddd 100644 --- a/seed/fastapi/folders/core/route_args.py +++ b/seed/fastapi/folders/core/route_args.py @@ -20,9 +20,15 @@ class RouteArgs(typing_extensions.TypedDict): DEFAULT_ROUTE_ARGS = RouteArgs(openapi_extra=None, tags=None, include_in_schema=True) -def get_route_args(endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str) -> RouteArgs: - unwrapped = inspect.unwrap(endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY))) - route_args = typing.cast(RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS)) +def get_route_args( + endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str +) -> RouteArgs: + unwrapped = inspect.unwrap( + endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY)) + ) + route_args = typing.cast( + RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS) + ) if route_args["tags"] is None: return RouteArgs( openapi_extra=route_args["openapi_extra"], @@ -56,7 +62,11 @@ def decorator(endpoint_function: T) -> T: setattr( endpoint_function, FERN_CONFIG_KEY, - RouteArgs(openapi_extra=openapi_extra, tags=tags, include_in_schema=include_in_schema), + RouteArgs( + openapi_extra=openapi_extra, + tags=tags, + include_in_schema=include_in_schema, + ), ) return endpoint_function diff --git a/seed/fastapi/folders/register.py b/seed/fastapi/folders/register.py index 7aa57f057ac..496f740f8b3 100644 --- a/seed/fastapi/folders/register.py +++ b/seed/fastapi/folders/register.py @@ -1,23 +1,25 @@ # This file was auto-generated by Fern from our API Definition. -import glob -import importlib -import os -import types -import typing - import fastapi -import starlette.exceptions -from fastapi import params - -from .core.abstract_fern_service import AbstractFernService -from .core.exceptions import default_exception_handler, fern_http_exception_handler, http_exception_handler -from .core.exceptions.fern_http_exception import FernHTTPException +from .service.service import AbstractRootService from .resources.a.resources.b.service.service import AbstractABService from .resources.a.resources.c.service.service import AbstractACService -from .resources.folder.resources.service.service.service import AbstractFolderServiceService from .resources.folder.service.service import AbstractFolderService -from .service.service import AbstractRootService +from .resources.folder.resources.service.service.service import ( + AbstractFolderServiceService, +) +import typing +from fastapi import params +from .core.exceptions.fern_http_exception import FernHTTPException +from .core.exceptions import fern_http_exception_handler +import starlette.exceptions +from .core.exceptions import http_exception_handler +from .core.exceptions import default_exception_handler +from .core.abstract_fern_service import AbstractFernService +import types +import os +import glob +import importlib def register( @@ -28,7 +30,7 @@ def register( a_c: AbstractACService, folder: AbstractFolderService, folder_service: AbstractFolderServiceService, - dependencies: typing.Optional[typing.Sequence[params.Depends]] = None + dependencies: typing.Optional[typing.Sequence[params.Depends]] = None, ) -> None: _app.include_router(__register_service(root), dependencies=dependencies) _app.include_router(__register_service(a_b), dependencies=dependencies) @@ -37,7 +39,9 @@ def register( _app.include_router(__register_service(folder_service), dependencies=dependencies) _app.add_exception_handler(FernHTTPException, fern_http_exception_handler) # type: ignore - _app.add_exception_handler(starlette.exceptions.HTTPException, http_exception_handler) # type: ignore + _app.add_exception_handler( + starlette.exceptions.HTTPException, http_exception_handler + ) # type: ignore _app.add_exception_handler(Exception, default_exception_handler) # type: ignore @@ -49,7 +53,9 @@ def __register_service(service: AbstractFernService) -> fastapi.APIRouter: def register_validators(module: types.ModuleType) -> None: validators_directory: str = os.path.dirname(module.__file__) # type: ignore - for path in glob.glob(os.path.join(validators_directory, "**/*.py"), recursive=True): + for path in glob.glob( + os.path.join(validators_directory, "**/*.py"), recursive=True + ): if os.path.isfile(path): relative_path = os.path.relpath(path, start=validators_directory) module_path = ".".join([module.__name__] + relative_path[:-3].split("/")) diff --git a/seed/fastapi/folders/resources/a/resources/b/service/service.py b/seed/fastapi/folders/resources/a/resources/b/service/service.py index 9c66d66ea74..ade81707f46 100644 --- a/seed/fastapi/folders/resources/a/resources/b/service/service.py +++ b/seed/fastapi/folders/resources/a/resources/b/service/service.py @@ -1,16 +1,14 @@ # This file was auto-generated by Fern from our API Definition. +from ......core.abstract_fern_service import AbstractFernService import abc -import functools +import fastapi import inspect -import logging import typing - -import fastapi -import starlette - -from ......core.abstract_fern_service import AbstractFernService from ......core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools +import starlette from ......core.route_args import get_route_args @@ -24,8 +22,7 @@ class AbstractABService(AbstractFernService): """ @abc.abstractmethod - def foo(self) -> None: - ... + def foo(self) -> None: ... """ Below are internal methods used by Fern to register your implementation. @@ -40,12 +37,18 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_foo(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.foo) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) else: new_parameters.append(parameter) - setattr(cls.foo, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.foo, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.foo) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> None: diff --git a/seed/fastapi/folders/resources/a/resources/c/service/service.py b/seed/fastapi/folders/resources/a/resources/c/service/service.py index 4aa46bd507a..e41b5552b12 100644 --- a/seed/fastapi/folders/resources/a/resources/c/service/service.py +++ b/seed/fastapi/folders/resources/a/resources/c/service/service.py @@ -1,16 +1,14 @@ # This file was auto-generated by Fern from our API Definition. +from ......core.abstract_fern_service import AbstractFernService import abc -import functools +import fastapi import inspect -import logging import typing - -import fastapi -import starlette - -from ......core.abstract_fern_service import AbstractFernService from ......core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools +import starlette from ......core.route_args import get_route_args @@ -24,8 +22,7 @@ class AbstractACService(AbstractFernService): """ @abc.abstractmethod - def foo(self) -> None: - ... + def foo(self) -> None: ... """ Below are internal methods used by Fern to register your implementation. @@ -40,12 +37,18 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_foo(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.foo) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) else: new_parameters.append(parameter) - setattr(cls.foo, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.foo, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.foo) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> None: diff --git a/seed/fastapi/folders/resources/folder/resources/service/service/service.py b/seed/fastapi/folders/resources/folder/resources/service/service/service.py index a8a6bfc075f..ef0c517a933 100644 --- a/seed/fastapi/folders/resources/folder/resources/service/service/service.py +++ b/seed/fastapi/folders/resources/folder/resources/service/service/service.py @@ -1,16 +1,14 @@ # This file was auto-generated by Fern from our API Definition. +from ......core.abstract_fern_service import AbstractFernService import abc -import functools -import inspect -import logging import typing - import fastapi -import starlette - -from ......core.abstract_fern_service import AbstractFernService +import inspect from ......core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools +import starlette from ......core.route_args import get_route_args from ..errors.not_found_error import NotFoundError @@ -25,12 +23,10 @@ class AbstractFolderServiceService(AbstractFernService): """ @abc.abstractmethod - def endpoint(self) -> None: - ... + def endpoint(self) -> None: ... @abc.abstractmethod - def unknown_request(self, *, body: typing.Any) -> None: - ... + def unknown_request(self, *, body: typing.Any) -> None: ... """ Below are internal methods used by Fern to register your implementation. @@ -46,12 +42,18 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_endpoint(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.endpoint) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) else: new_parameters.append(parameter) - setattr(cls.endpoint, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.endpoint, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.endpoint) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> None: @@ -81,14 +83,20 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> None: def __init_unknown_request(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.unknown_request) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) else: new_parameters.append(parameter) - setattr(cls.unknown_request, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.unknown_request, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.unknown_request) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> None: diff --git a/seed/fastapi/folders/resources/folder/service/service.py b/seed/fastapi/folders/resources/folder/service/service.py index 3f812ecb1b3..59b3dd47aa3 100644 --- a/seed/fastapi/folders/resources/folder/service/service.py +++ b/seed/fastapi/folders/resources/folder/service/service.py @@ -1,16 +1,14 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.abstract_fern_service import AbstractFernService import abc -import functools +import fastapi import inspect -import logging import typing - -import fastapi -import starlette - -from ....core.abstract_fern_service import AbstractFernService from ....core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools +import starlette from ....core.route_args import get_route_args @@ -24,8 +22,7 @@ class AbstractFolderService(AbstractFernService): """ @abc.abstractmethod - def foo(self) -> None: - ... + def foo(self) -> None: ... """ Below are internal methods used by Fern to register your implementation. @@ -40,12 +37,18 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_foo(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.foo) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) else: new_parameters.append(parameter) - setattr(cls.foo, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.foo, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.foo) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> None: diff --git a/seed/fastapi/folders/service/service.py b/seed/fastapi/folders/service/service.py index 149cb7eb37b..3701f303c0b 100644 --- a/seed/fastapi/folders/service/service.py +++ b/seed/fastapi/folders/service/service.py @@ -1,16 +1,14 @@ # This file was auto-generated by Fern from our API Definition. +from ..core.abstract_fern_service import AbstractFernService import abc -import functools +import fastapi import inspect -import logging import typing - -import fastapi -import starlette - -from ..core.abstract_fern_service import AbstractFernService from ..core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools +import starlette from ..core.route_args import get_route_args @@ -24,8 +22,7 @@ class AbstractRootService(AbstractFernService): """ @abc.abstractmethod - def foo(self) -> None: - ... + def foo(self) -> None: ... """ Below are internal methods used by Fern to register your implementation. @@ -40,12 +37,18 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_foo(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.foo) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) else: new_parameters.append(parameter) - setattr(cls.foo, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.foo, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.foo) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> None: diff --git a/seed/fastapi/idempotency-headers/core/abstract_fern_service.py b/seed/fastapi/idempotency-headers/core/abstract_fern_service.py index da7c8dc49c4..9966b4876da 100644 --- a/seed/fastapi/idempotency-headers/core/abstract_fern_service.py +++ b/seed/fastapi/idempotency-headers/core/abstract_fern_service.py @@ -7,5 +7,4 @@ class AbstractFernService(abc.ABC): @classmethod - def _init_fern(cls, router: fastapi.APIRouter) -> None: - ... + def _init_fern(cls, router: fastapi.APIRouter) -> None: ... diff --git a/seed/fastapi/idempotency-headers/core/datetime_utils.py b/seed/fastapi/idempotency-headers/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/fastapi/idempotency-headers/core/datetime_utils.py +++ b/seed/fastapi/idempotency-headers/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/fastapi/idempotency-headers/core/exceptions/__init__.py b/seed/fastapi/idempotency-headers/core/exceptions/__init__.py index 297d6e06f5f..dae4b8980c1 100644 --- a/seed/fastapi/idempotency-headers/core/exceptions/__init__.py +++ b/seed/fastapi/idempotency-headers/core/exceptions/__init__.py @@ -1,7 +1,11 @@ # This file was auto-generated by Fern from our API Definition. from .fern_http_exception import FernHTTPException -from .handlers import default_exception_handler, fern_http_exception_handler, http_exception_handler +from .handlers import ( + default_exception_handler, + fern_http_exception_handler, + http_exception_handler, +) from .unauthorized import UnauthorizedException __all__ = [ diff --git a/seed/fastapi/idempotency-headers/core/exceptions/fern_http_exception.py b/seed/fastapi/idempotency-headers/core/exceptions/fern_http_exception.py index bdf03862487..81610359a7f 100644 --- a/seed/fastapi/idempotency-headers/core/exceptions/fern_http_exception.py +++ b/seed/fastapi/idempotency-headers/core/exceptions/fern_http_exception.py @@ -1,14 +1,16 @@ # This file was auto-generated by Fern from our API Definition. import abc -import typing - import fastapi +import typing class FernHTTPException(abc.ABC, fastapi.HTTPException): def __init__( - self, status_code: int, name: typing.Optional[str] = None, content: typing.Optional[typing.Any] = None + self, + status_code: int, + name: typing.Optional[str] = None, + content: typing.Optional[typing.Any] = None, ): super().__init__(status_code=status_code) self.name = name @@ -17,4 +19,6 @@ def __init__( def to_json_response(self) -> fastapi.responses.JSONResponse: content = fastapi.encoders.jsonable_encoder(self.content, exclude_none=True) - return fastapi.responses.JSONResponse(content=content, status_code=self.status_code) + return fastapi.responses.JSONResponse( + content=content, status_code=self.status_code + ) diff --git a/seed/fastapi/idempotency-headers/core/exceptions/handlers.py b/seed/fastapi/idempotency-headers/core/exceptions/handlers.py index 6d8c4155c5a..ae1c2741f06 100644 --- a/seed/fastapi/idempotency-headers/core/exceptions/handlers.py +++ b/seed/fastapi/idempotency-headers/core/exceptions/handlers.py @@ -2,32 +2,49 @@ import logging -import fastapi import starlette import starlette.exceptions +import fastapi + from .fern_http_exception import FernHTTPException def fern_http_exception_handler( - request: fastapi.requests.Request, exc: FernHTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: FernHTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) return exc.to_json_response() def http_exception_handler( - request: fastapi.requests.Request, exc: starlette.exceptions.HTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: starlette.exceptions.HTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=exc.status_code, content=exc.detail).to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=exc.status_code, content=exc.detail + ).to_json_response() def default_exception_handler( - request: fastapi.requests.Request, exc: Exception, skip_log: bool = False + request: fastapi.requests.Request, + exc: Exception, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=500, content="Internal Server Error").to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=500, content="Internal Server Error" + ).to_json_response() diff --git a/seed/fastapi/idempotency-headers/core/pydantic_utilities.py b/seed/fastapi/idempotency-headers/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/fastapi/idempotency-headers/core/pydantic_utilities.py +++ b/seed/fastapi/idempotency-headers/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/fastapi/idempotency-headers/core/route_args.py b/seed/fastapi/idempotency-headers/core/route_args.py index 4228e2fe05d..bd940bf4ddd 100644 --- a/seed/fastapi/idempotency-headers/core/route_args.py +++ b/seed/fastapi/idempotency-headers/core/route_args.py @@ -20,9 +20,15 @@ class RouteArgs(typing_extensions.TypedDict): DEFAULT_ROUTE_ARGS = RouteArgs(openapi_extra=None, tags=None, include_in_schema=True) -def get_route_args(endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str) -> RouteArgs: - unwrapped = inspect.unwrap(endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY))) - route_args = typing.cast(RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS)) +def get_route_args( + endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str +) -> RouteArgs: + unwrapped = inspect.unwrap( + endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY)) + ) + route_args = typing.cast( + RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS) + ) if route_args["tags"] is None: return RouteArgs( openapi_extra=route_args["openapi_extra"], @@ -56,7 +62,11 @@ def decorator(endpoint_function: T) -> T: setattr( endpoint_function, FERN_CONFIG_KEY, - RouteArgs(openapi_extra=openapi_extra, tags=tags, include_in_schema=include_in_schema), + RouteArgs( + openapi_extra=openapi_extra, + tags=tags, + include_in_schema=include_in_schema, + ), ) return endpoint_function diff --git a/seed/fastapi/idempotency-headers/register.py b/seed/fastapi/idempotency-headers/register.py index 1f56b4c93f8..aac3eb884b1 100644 --- a/seed/fastapi/idempotency-headers/register.py +++ b/seed/fastapi/idempotency-headers/register.py @@ -1,31 +1,33 @@ # This file was auto-generated by Fern from our API Definition. -import glob -import importlib -import os -import types -import typing - import fastapi -import starlette.exceptions +from .resources.payment.service.service import AbstractPaymentService +import typing from fastapi import params - -from .core.abstract_fern_service import AbstractFernService -from .core.exceptions import default_exception_handler, fern_http_exception_handler, http_exception_handler from .core.exceptions.fern_http_exception import FernHTTPException -from .resources.payment.service.service import AbstractPaymentService +from .core.exceptions import fern_http_exception_handler +import starlette.exceptions +from .core.exceptions import http_exception_handler +from .core.exceptions import default_exception_handler +from .core.abstract_fern_service import AbstractFernService +import types +import os +import glob +import importlib def register( _app: fastapi.FastAPI, *, payment: AbstractPaymentService, - dependencies: typing.Optional[typing.Sequence[params.Depends]] = None + dependencies: typing.Optional[typing.Sequence[params.Depends]] = None, ) -> None: _app.include_router(__register_service(payment), dependencies=dependencies) _app.add_exception_handler(FernHTTPException, fern_http_exception_handler) # type: ignore - _app.add_exception_handler(starlette.exceptions.HTTPException, http_exception_handler) # type: ignore + _app.add_exception_handler( + starlette.exceptions.HTTPException, http_exception_handler + ) # type: ignore _app.add_exception_handler(Exception, default_exception_handler) # type: ignore @@ -37,7 +39,9 @@ def __register_service(service: AbstractFernService) -> fastapi.APIRouter: def register_validators(module: types.ModuleType) -> None: validators_directory: str = os.path.dirname(module.__file__) # type: ignore - for path in glob.glob(os.path.join(validators_directory, "**/*.py"), recursive=True): + for path in glob.glob( + os.path.join(validators_directory, "**/*.py"), recursive=True + ): if os.path.isfile(path): relative_path = os.path.relpath(path, start=validators_directory) module_path = ".".join([module.__name__] + relative_path[:-3].split("/")) diff --git a/seed/fastapi/idempotency-headers/resources/payment/service/create_payment_request.py b/seed/fastapi/idempotency-headers/resources/payment/service/create_payment_request.py index ce20c150af0..567183e8b71 100644 --- a/seed/fastapi/idempotency-headers/resources/payment/service/create_payment_request.py +++ b/seed/fastapi/idempotency-headers/resources/payment/service/create_payment_request.py @@ -1,19 +1,20 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel +from ..types.currency import Currency +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from ..types.currency import Currency - class CreatePaymentRequest(UniversalBaseModel): amount: int currency: Currency if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/idempotency-headers/resources/payment/service/service.py b/seed/fastapi/idempotency-headers/resources/payment/service/service.py index 3dba556eb56..ea2571aa446 100644 --- a/seed/fastapi/idempotency-headers/resources/payment/service/service.py +++ b/seed/fastapi/idempotency-headers/resources/payment/service/service.py @@ -1,20 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.abstract_fern_service import AbstractFernService +from .create_payment_request import CreatePaymentRequest +from ....security import ApiAuth +import uuid import abc -import functools +import fastapi import inspect -import logging import typing -import uuid - -import fastapi -import starlette - -from ....core.abstract_fern_service import AbstractFernService +from ....security import FernAuth from ....core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools from ....core.route_args import get_route_args -from ....security import ApiAuth, FernAuth -from .create_payment_request import CreatePaymentRequest +import starlette class AbstractPaymentService(AbstractFernService): @@ -27,12 +26,10 @@ class AbstractPaymentService(AbstractFernService): """ @abc.abstractmethod - def create(self, *, body: CreatePaymentRequest, auth: ApiAuth) -> uuid.UUID: - ... + def create(self, *, body: CreatePaymentRequest, auth: ApiAuth) -> uuid.UUID: ... @abc.abstractmethod - def delete(self, *, payment_id: str, auth: ApiAuth) -> None: - ... + def delete(self, *, payment_id: str, auth: ApiAuth) -> None: ... """ Below are internal methods used by Fern to register your implementation. @@ -48,16 +45,24 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_create(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.create) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.create, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.create, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.create) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> uuid.UUID: @@ -86,16 +91,24 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> uuid.UUID: def __init_delete(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.delete) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "payment_id": new_parameters.append(parameter.replace(default=fastapi.Path(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.delete, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.delete, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.delete) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> None: diff --git a/seed/fastapi/idempotency-headers/resources/payment/types/currency.py b/seed/fastapi/idempotency-headers/resources/payment/types/currency.py index 0ba6306d1fe..a21abbe0819 100644 --- a/seed/fastapi/idempotency-headers/resources/payment/types/currency.py +++ b/seed/fastapi/idempotency-headers/resources/payment/types/currency.py @@ -10,7 +10,9 @@ class Currency(str, enum.Enum): USD = "USD" YEN = "YEN" - def visit(self, usd: typing.Callable[[], T_Result], yen: typing.Callable[[], T_Result]) -> T_Result: + def visit( + self, usd: typing.Callable[[], T_Result], yen: typing.Callable[[], T_Result] + ) -> T_Result: if self is Currency.USD: return usd() if self is Currency.YEN: diff --git a/seed/fastapi/idempotency-headers/security.py b/seed/fastapi/idempotency-headers/security.py index bab014441e1..4ccabc21106 100644 --- a/seed/fastapi/idempotency-headers/security.py +++ b/seed/fastapi/idempotency-headers/security.py @@ -1,8 +1,8 @@ # This file was auto-generated by Fern from our API Definition. +from .core.security.bearer import BearerToken import fastapi - -from .core.security.bearer import BearerToken, HTTPBearer +from .core.security.bearer import HTTPBearer ApiAuth = BearerToken diff --git a/seed/fastapi/imdb/__init__.py b/seed/fastapi/imdb/__init__.py index dad4d86772a..d78850eb26f 100644 --- a/seed/fastapi/imdb/__init__.py +++ b/seed/fastapi/imdb/__init__.py @@ -3,4 +3,11 @@ from .resources import CreateMovieRequest, Movie, MovieDoesNotExistError, MovieId, imdb from .security import ApiAuth -__all__ = ["ApiAuth", "CreateMovieRequest", "Movie", "MovieDoesNotExistError", "MovieId", "imdb"] +__all__ = [ + "ApiAuth", + "CreateMovieRequest", + "Movie", + "MovieDoesNotExistError", + "MovieId", + "imdb", +] diff --git a/seed/fastapi/imdb/async-handlers/__init__.py b/seed/fastapi/imdb/async-handlers/__init__.py index dad4d86772a..d78850eb26f 100644 --- a/seed/fastapi/imdb/async-handlers/__init__.py +++ b/seed/fastapi/imdb/async-handlers/__init__.py @@ -3,4 +3,11 @@ from .resources import CreateMovieRequest, Movie, MovieDoesNotExistError, MovieId, imdb from .security import ApiAuth -__all__ = ["ApiAuth", "CreateMovieRequest", "Movie", "MovieDoesNotExistError", "MovieId", "imdb"] +__all__ = [ + "ApiAuth", + "CreateMovieRequest", + "Movie", + "MovieDoesNotExistError", + "MovieId", + "imdb", +] diff --git a/seed/fastapi/imdb/async-handlers/core/abstract_fern_service.py b/seed/fastapi/imdb/async-handlers/core/abstract_fern_service.py index da7c8dc49c4..9966b4876da 100644 --- a/seed/fastapi/imdb/async-handlers/core/abstract_fern_service.py +++ b/seed/fastapi/imdb/async-handlers/core/abstract_fern_service.py @@ -7,5 +7,4 @@ class AbstractFernService(abc.ABC): @classmethod - def _init_fern(cls, router: fastapi.APIRouter) -> None: - ... + def _init_fern(cls, router: fastapi.APIRouter) -> None: ... diff --git a/seed/fastapi/imdb/async-handlers/core/datetime_utils.py b/seed/fastapi/imdb/async-handlers/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/fastapi/imdb/async-handlers/core/datetime_utils.py +++ b/seed/fastapi/imdb/async-handlers/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/fastapi/imdb/async-handlers/core/exceptions/__init__.py b/seed/fastapi/imdb/async-handlers/core/exceptions/__init__.py index 297d6e06f5f..dae4b8980c1 100644 --- a/seed/fastapi/imdb/async-handlers/core/exceptions/__init__.py +++ b/seed/fastapi/imdb/async-handlers/core/exceptions/__init__.py @@ -1,7 +1,11 @@ # This file was auto-generated by Fern from our API Definition. from .fern_http_exception import FernHTTPException -from .handlers import default_exception_handler, fern_http_exception_handler, http_exception_handler +from .handlers import ( + default_exception_handler, + fern_http_exception_handler, + http_exception_handler, +) from .unauthorized import UnauthorizedException __all__ = [ diff --git a/seed/fastapi/imdb/async-handlers/core/exceptions/fern_http_exception.py b/seed/fastapi/imdb/async-handlers/core/exceptions/fern_http_exception.py index bdf03862487..81610359a7f 100644 --- a/seed/fastapi/imdb/async-handlers/core/exceptions/fern_http_exception.py +++ b/seed/fastapi/imdb/async-handlers/core/exceptions/fern_http_exception.py @@ -1,14 +1,16 @@ # This file was auto-generated by Fern from our API Definition. import abc -import typing - import fastapi +import typing class FernHTTPException(abc.ABC, fastapi.HTTPException): def __init__( - self, status_code: int, name: typing.Optional[str] = None, content: typing.Optional[typing.Any] = None + self, + status_code: int, + name: typing.Optional[str] = None, + content: typing.Optional[typing.Any] = None, ): super().__init__(status_code=status_code) self.name = name @@ -17,4 +19,6 @@ def __init__( def to_json_response(self) -> fastapi.responses.JSONResponse: content = fastapi.encoders.jsonable_encoder(self.content, exclude_none=True) - return fastapi.responses.JSONResponse(content=content, status_code=self.status_code) + return fastapi.responses.JSONResponse( + content=content, status_code=self.status_code + ) diff --git a/seed/fastapi/imdb/async-handlers/core/exceptions/handlers.py b/seed/fastapi/imdb/async-handlers/core/exceptions/handlers.py index 6d8c4155c5a..ae1c2741f06 100644 --- a/seed/fastapi/imdb/async-handlers/core/exceptions/handlers.py +++ b/seed/fastapi/imdb/async-handlers/core/exceptions/handlers.py @@ -2,32 +2,49 @@ import logging -import fastapi import starlette import starlette.exceptions +import fastapi + from .fern_http_exception import FernHTTPException def fern_http_exception_handler( - request: fastapi.requests.Request, exc: FernHTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: FernHTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) return exc.to_json_response() def http_exception_handler( - request: fastapi.requests.Request, exc: starlette.exceptions.HTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: starlette.exceptions.HTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=exc.status_code, content=exc.detail).to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=exc.status_code, content=exc.detail + ).to_json_response() def default_exception_handler( - request: fastapi.requests.Request, exc: Exception, skip_log: bool = False + request: fastapi.requests.Request, + exc: Exception, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=500, content="Internal Server Error").to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=500, content="Internal Server Error" + ).to_json_response() diff --git a/seed/fastapi/imdb/async-handlers/core/pydantic_utilities.py b/seed/fastapi/imdb/async-handlers/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/fastapi/imdb/async-handlers/core/pydantic_utilities.py +++ b/seed/fastapi/imdb/async-handlers/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/fastapi/imdb/async-handlers/core/route_args.py b/seed/fastapi/imdb/async-handlers/core/route_args.py index 4228e2fe05d..bd940bf4ddd 100644 --- a/seed/fastapi/imdb/async-handlers/core/route_args.py +++ b/seed/fastapi/imdb/async-handlers/core/route_args.py @@ -20,9 +20,15 @@ class RouteArgs(typing_extensions.TypedDict): DEFAULT_ROUTE_ARGS = RouteArgs(openapi_extra=None, tags=None, include_in_schema=True) -def get_route_args(endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str) -> RouteArgs: - unwrapped = inspect.unwrap(endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY))) - route_args = typing.cast(RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS)) +def get_route_args( + endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str +) -> RouteArgs: + unwrapped = inspect.unwrap( + endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY)) + ) + route_args = typing.cast( + RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS) + ) if route_args["tags"] is None: return RouteArgs( openapi_extra=route_args["openapi_extra"], @@ -56,7 +62,11 @@ def decorator(endpoint_function: T) -> T: setattr( endpoint_function, FERN_CONFIG_KEY, - RouteArgs(openapi_extra=openapi_extra, tags=tags, include_in_schema=include_in_schema), + RouteArgs( + openapi_extra=openapi_extra, + tags=tags, + include_in_schema=include_in_schema, + ), ) return endpoint_function diff --git a/seed/fastapi/imdb/async-handlers/register.py b/seed/fastapi/imdb/async-handlers/register.py index b7d729ef371..8118c947793 100644 --- a/seed/fastapi/imdb/async-handlers/register.py +++ b/seed/fastapi/imdb/async-handlers/register.py @@ -1,31 +1,33 @@ # This file was auto-generated by Fern from our API Definition. -import glob -import importlib -import os -import types -import typing - import fastapi -import starlette.exceptions +from .resources.imdb.service.service import AbstractImdbService +import typing from fastapi import params - -from .core.abstract_fern_service import AbstractFernService -from .core.exceptions import default_exception_handler, fern_http_exception_handler, http_exception_handler from .core.exceptions.fern_http_exception import FernHTTPException -from .resources.imdb.service.service import AbstractImdbService +from .core.exceptions import fern_http_exception_handler +import starlette.exceptions +from .core.exceptions import http_exception_handler +from .core.exceptions import default_exception_handler +from .core.abstract_fern_service import AbstractFernService +import types +import os +import glob +import importlib def register( _app: fastapi.FastAPI, *, imdb: AbstractImdbService, - dependencies: typing.Optional[typing.Sequence[params.Depends]] = None + dependencies: typing.Optional[typing.Sequence[params.Depends]] = None, ) -> None: _app.include_router(__register_service(imdb), dependencies=dependencies) _app.add_exception_handler(FernHTTPException, fern_http_exception_handler) # type: ignore - _app.add_exception_handler(starlette.exceptions.HTTPException, http_exception_handler) # type: ignore + _app.add_exception_handler( + starlette.exceptions.HTTPException, http_exception_handler + ) # type: ignore _app.add_exception_handler(Exception, default_exception_handler) # type: ignore @@ -37,7 +39,9 @@ def __register_service(service: AbstractFernService) -> fastapi.APIRouter: def register_validators(module: types.ModuleType) -> None: validators_directory: str = os.path.dirname(module.__file__) # type: ignore - for path in glob.glob(os.path.join(validators_directory, "**/*.py"), recursive=True): + for path in glob.glob( + os.path.join(validators_directory, "**/*.py"), recursive=True + ): if os.path.isfile(path): relative_path = os.path.relpath(path, start=validators_directory) module_path = ".".join([module.__name__] + relative_path[:-3].split("/")) diff --git a/seed/fastapi/imdb/async-handlers/resources/imdb/service/service.py b/seed/fastapi/imdb/async-handlers/resources/imdb/service/service.py index 67a771ce1a8..3ac7065965d 100644 --- a/seed/fastapi/imdb/async-handlers/resources/imdb/service/service.py +++ b/seed/fastapi/imdb/async-handlers/resources/imdb/service/service.py @@ -1,20 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.abstract_fern_service import AbstractFernService +from ..types.create_movie_request import CreateMovieRequest +from ..types.movie_id import MovieId import abc -import functools +from ..types.movie import Movie +import fastapi import inspect -import logging import typing - -import fastapi - -from ....core.abstract_fern_service import AbstractFernService from ....core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools from ....core.route_args import get_route_args from ..errors.movie_does_not_exist_error import MovieDoesNotExistError -from ..types.create_movie_request import CreateMovieRequest -from ..types.movie import Movie -from ..types.movie_id import MovieId class AbstractImdbService(AbstractFernService): @@ -34,8 +32,7 @@ async def create_movie(self, *, body: CreateMovieRequest) -> MovieId: ... @abc.abstractmethod - def get_movie(self, *, movie_id: str) -> Movie: - ... + def get_movie(self, *, movie_id: str) -> Movie: ... """ Below are internal methods used by Fern to register your implementation. @@ -51,14 +48,20 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_create_movie(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.create_movie) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) else: new_parameters.append(parameter) - setattr(cls.create_movie, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.create_movie, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.create_movie) async def wrapper(*args: typing.Any, **kwargs: typing.Any) -> MovieId: @@ -87,14 +90,20 @@ async def wrapper(*args: typing.Any, **kwargs: typing.Any) -> MovieId: def __init_get_movie(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_movie) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "movie_id": new_parameters.append(parameter.replace(default=fastapi.Path(...))) else: new_parameters.append(parameter) - setattr(cls.get_movie, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_movie, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_movie) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> Movie: diff --git a/seed/fastapi/imdb/async-handlers/resources/imdb/types/create_movie_request.py b/seed/fastapi/imdb/async-handlers/resources/imdb/types/create_movie_request.py index d9a37cc4db8..4642ba54a78 100644 --- a/seed/fastapi/imdb/async-handlers/resources/imdb/types/create_movie_request.py +++ b/seed/fastapi/imdb/async-handlers/resources/imdb/types/create_movie_request.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class CreateMovieRequest(UniversalBaseModel): title: str rating: float if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/imdb/async-handlers/resources/imdb/types/movie.py b/seed/fastapi/imdb/async-handlers/resources/imdb/types/movie.py index b3d0889f76c..f3e5ea5b18a 100644 --- a/seed/fastapi/imdb/async-handlers/resources/imdb/types/movie.py +++ b/seed/fastapi/imdb/async-handlers/resources/imdb/types/movie.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import UniversalBaseModel from .movie_id import MovieId +import pydantic +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class Movie(UniversalBaseModel): @@ -17,7 +16,9 @@ class Movie(UniversalBaseModel): """ if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/imdb/async-handlers/security.py b/seed/fastapi/imdb/async-handlers/security.py index bab014441e1..4ccabc21106 100644 --- a/seed/fastapi/imdb/async-handlers/security.py +++ b/seed/fastapi/imdb/async-handlers/security.py @@ -1,8 +1,8 @@ # This file was auto-generated by Fern from our API Definition. +from .core.security.bearer import BearerToken import fastapi - -from .core.security.bearer import BearerToken, HTTPBearer +from .core.security.bearer import HTTPBearer ApiAuth = BearerToken diff --git a/seed/fastapi/imdb/core/abstract_fern_service.py b/seed/fastapi/imdb/core/abstract_fern_service.py index da7c8dc49c4..9966b4876da 100644 --- a/seed/fastapi/imdb/core/abstract_fern_service.py +++ b/seed/fastapi/imdb/core/abstract_fern_service.py @@ -7,5 +7,4 @@ class AbstractFernService(abc.ABC): @classmethod - def _init_fern(cls, router: fastapi.APIRouter) -> None: - ... + def _init_fern(cls, router: fastapi.APIRouter) -> None: ... diff --git a/seed/fastapi/imdb/core/datetime_utils.py b/seed/fastapi/imdb/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/fastapi/imdb/core/datetime_utils.py +++ b/seed/fastapi/imdb/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/fastapi/imdb/core/exceptions/__init__.py b/seed/fastapi/imdb/core/exceptions/__init__.py index 297d6e06f5f..dae4b8980c1 100644 --- a/seed/fastapi/imdb/core/exceptions/__init__.py +++ b/seed/fastapi/imdb/core/exceptions/__init__.py @@ -1,7 +1,11 @@ # This file was auto-generated by Fern from our API Definition. from .fern_http_exception import FernHTTPException -from .handlers import default_exception_handler, fern_http_exception_handler, http_exception_handler +from .handlers import ( + default_exception_handler, + fern_http_exception_handler, + http_exception_handler, +) from .unauthorized import UnauthorizedException __all__ = [ diff --git a/seed/fastapi/imdb/core/exceptions/fern_http_exception.py b/seed/fastapi/imdb/core/exceptions/fern_http_exception.py index bdf03862487..a5925c21510 100644 --- a/seed/fastapi/imdb/core/exceptions/fern_http_exception.py +++ b/seed/fastapi/imdb/core/exceptions/fern_http_exception.py @@ -8,7 +8,10 @@ class FernHTTPException(abc.ABC, fastapi.HTTPException): def __init__( - self, status_code: int, name: typing.Optional[str] = None, content: typing.Optional[typing.Any] = None + self, + status_code: int, + name: typing.Optional[str] = None, + content: typing.Optional[typing.Any] = None, ): super().__init__(status_code=status_code) self.name = name @@ -17,4 +20,6 @@ def __init__( def to_json_response(self) -> fastapi.responses.JSONResponse: content = fastapi.encoders.jsonable_encoder(self.content, exclude_none=True) - return fastapi.responses.JSONResponse(content=content, status_code=self.status_code) + return fastapi.responses.JSONResponse( + content=content, status_code=self.status_code + ) diff --git a/seed/fastapi/imdb/core/exceptions/handlers.py b/seed/fastapi/imdb/core/exceptions/handlers.py index fe5ac5419c7..6e7a82773f6 100644 --- a/seed/fastapi/imdb/core/exceptions/handlers.py +++ b/seed/fastapi/imdb/core/exceptions/handlers.py @@ -12,21 +12,33 @@ def fern_http_exception_handler( request: fastapi.requests.Request, exc: FernHTTPException, skip_log: bool = False ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) return exc.to_json_response() def http_exception_handler( - request: fastapi.requests.Request, exc: starlette.exceptions.HTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: starlette.exceptions.HTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=exc.status_code, content=exc.detail).to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=exc.status_code, content=exc.detail + ).to_json_response() def default_exception_handler( request: fastapi.requests.Request, exc: Exception, skip_log: bool = False ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=500, content="Internal Server Error").to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=500, content="Internal Server Error" + ).to_json_response() diff --git a/seed/fastapi/imdb/core/route_args.py b/seed/fastapi/imdb/core/route_args.py index 4228e2fe05d..bd940bf4ddd 100644 --- a/seed/fastapi/imdb/core/route_args.py +++ b/seed/fastapi/imdb/core/route_args.py @@ -20,9 +20,15 @@ class RouteArgs(typing_extensions.TypedDict): DEFAULT_ROUTE_ARGS = RouteArgs(openapi_extra=None, tags=None, include_in_schema=True) -def get_route_args(endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str) -> RouteArgs: - unwrapped = inspect.unwrap(endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY))) - route_args = typing.cast(RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS)) +def get_route_args( + endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str +) -> RouteArgs: + unwrapped = inspect.unwrap( + endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY)) + ) + route_args = typing.cast( + RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS) + ) if route_args["tags"] is None: return RouteArgs( openapi_extra=route_args["openapi_extra"], @@ -56,7 +62,11 @@ def decorator(endpoint_function: T) -> T: setattr( endpoint_function, FERN_CONFIG_KEY, - RouteArgs(openapi_extra=openapi_extra, tags=tags, include_in_schema=include_in_schema), + RouteArgs( + openapi_extra=openapi_extra, + tags=tags, + include_in_schema=include_in_schema, + ), ) return endpoint_function diff --git a/seed/fastapi/imdb/includes-extra-fields/__init__.py b/seed/fastapi/imdb/includes-extra-fields/__init__.py index dad4d86772a..d78850eb26f 100644 --- a/seed/fastapi/imdb/includes-extra-fields/__init__.py +++ b/seed/fastapi/imdb/includes-extra-fields/__init__.py @@ -3,4 +3,11 @@ from .resources import CreateMovieRequest, Movie, MovieDoesNotExistError, MovieId, imdb from .security import ApiAuth -__all__ = ["ApiAuth", "CreateMovieRequest", "Movie", "MovieDoesNotExistError", "MovieId", "imdb"] +__all__ = [ + "ApiAuth", + "CreateMovieRequest", + "Movie", + "MovieDoesNotExistError", + "MovieId", + "imdb", +] diff --git a/seed/fastapi/imdb/includes-extra-fields/core/abstract_fern_service.py b/seed/fastapi/imdb/includes-extra-fields/core/abstract_fern_service.py index da7c8dc49c4..9966b4876da 100644 --- a/seed/fastapi/imdb/includes-extra-fields/core/abstract_fern_service.py +++ b/seed/fastapi/imdb/includes-extra-fields/core/abstract_fern_service.py @@ -7,5 +7,4 @@ class AbstractFernService(abc.ABC): @classmethod - def _init_fern(cls, router: fastapi.APIRouter) -> None: - ... + def _init_fern(cls, router: fastapi.APIRouter) -> None: ... diff --git a/seed/fastapi/imdb/includes-extra-fields/core/datetime_utils.py b/seed/fastapi/imdb/includes-extra-fields/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/fastapi/imdb/includes-extra-fields/core/datetime_utils.py +++ b/seed/fastapi/imdb/includes-extra-fields/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/fastapi/imdb/includes-extra-fields/core/exceptions/__init__.py b/seed/fastapi/imdb/includes-extra-fields/core/exceptions/__init__.py index 297d6e06f5f..dae4b8980c1 100644 --- a/seed/fastapi/imdb/includes-extra-fields/core/exceptions/__init__.py +++ b/seed/fastapi/imdb/includes-extra-fields/core/exceptions/__init__.py @@ -1,7 +1,11 @@ # This file was auto-generated by Fern from our API Definition. from .fern_http_exception import FernHTTPException -from .handlers import default_exception_handler, fern_http_exception_handler, http_exception_handler +from .handlers import ( + default_exception_handler, + fern_http_exception_handler, + http_exception_handler, +) from .unauthorized import UnauthorizedException __all__ = [ diff --git a/seed/fastapi/imdb/includes-extra-fields/core/exceptions/fern_http_exception.py b/seed/fastapi/imdb/includes-extra-fields/core/exceptions/fern_http_exception.py index bdf03862487..81610359a7f 100644 --- a/seed/fastapi/imdb/includes-extra-fields/core/exceptions/fern_http_exception.py +++ b/seed/fastapi/imdb/includes-extra-fields/core/exceptions/fern_http_exception.py @@ -1,14 +1,16 @@ # This file was auto-generated by Fern from our API Definition. import abc -import typing - import fastapi +import typing class FernHTTPException(abc.ABC, fastapi.HTTPException): def __init__( - self, status_code: int, name: typing.Optional[str] = None, content: typing.Optional[typing.Any] = None + self, + status_code: int, + name: typing.Optional[str] = None, + content: typing.Optional[typing.Any] = None, ): super().__init__(status_code=status_code) self.name = name @@ -17,4 +19,6 @@ def __init__( def to_json_response(self) -> fastapi.responses.JSONResponse: content = fastapi.encoders.jsonable_encoder(self.content, exclude_none=True) - return fastapi.responses.JSONResponse(content=content, status_code=self.status_code) + return fastapi.responses.JSONResponse( + content=content, status_code=self.status_code + ) diff --git a/seed/fastapi/imdb/includes-extra-fields/core/exceptions/handlers.py b/seed/fastapi/imdb/includes-extra-fields/core/exceptions/handlers.py index 6d8c4155c5a..ae1c2741f06 100644 --- a/seed/fastapi/imdb/includes-extra-fields/core/exceptions/handlers.py +++ b/seed/fastapi/imdb/includes-extra-fields/core/exceptions/handlers.py @@ -2,32 +2,49 @@ import logging -import fastapi import starlette import starlette.exceptions +import fastapi + from .fern_http_exception import FernHTTPException def fern_http_exception_handler( - request: fastapi.requests.Request, exc: FernHTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: FernHTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) return exc.to_json_response() def http_exception_handler( - request: fastapi.requests.Request, exc: starlette.exceptions.HTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: starlette.exceptions.HTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=exc.status_code, content=exc.detail).to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=exc.status_code, content=exc.detail + ).to_json_response() def default_exception_handler( - request: fastapi.requests.Request, exc: Exception, skip_log: bool = False + request: fastapi.requests.Request, + exc: Exception, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=500, content="Internal Server Error").to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=500, content="Internal Server Error" + ).to_json_response() diff --git a/seed/fastapi/imdb/includes-extra-fields/core/pydantic_utilities.py b/seed/fastapi/imdb/includes-extra-fields/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/fastapi/imdb/includes-extra-fields/core/pydantic_utilities.py +++ b/seed/fastapi/imdb/includes-extra-fields/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/fastapi/imdb/includes-extra-fields/core/route_args.py b/seed/fastapi/imdb/includes-extra-fields/core/route_args.py index 4228e2fe05d..bd940bf4ddd 100644 --- a/seed/fastapi/imdb/includes-extra-fields/core/route_args.py +++ b/seed/fastapi/imdb/includes-extra-fields/core/route_args.py @@ -20,9 +20,15 @@ class RouteArgs(typing_extensions.TypedDict): DEFAULT_ROUTE_ARGS = RouteArgs(openapi_extra=None, tags=None, include_in_schema=True) -def get_route_args(endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str) -> RouteArgs: - unwrapped = inspect.unwrap(endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY))) - route_args = typing.cast(RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS)) +def get_route_args( + endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str +) -> RouteArgs: + unwrapped = inspect.unwrap( + endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY)) + ) + route_args = typing.cast( + RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS) + ) if route_args["tags"] is None: return RouteArgs( openapi_extra=route_args["openapi_extra"], @@ -56,7 +62,11 @@ def decorator(endpoint_function: T) -> T: setattr( endpoint_function, FERN_CONFIG_KEY, - RouteArgs(openapi_extra=openapi_extra, tags=tags, include_in_schema=include_in_schema), + RouteArgs( + openapi_extra=openapi_extra, + tags=tags, + include_in_schema=include_in_schema, + ), ) return endpoint_function diff --git a/seed/fastapi/imdb/includes-extra-fields/register.py b/seed/fastapi/imdb/includes-extra-fields/register.py index b7d729ef371..8118c947793 100644 --- a/seed/fastapi/imdb/includes-extra-fields/register.py +++ b/seed/fastapi/imdb/includes-extra-fields/register.py @@ -1,31 +1,33 @@ # This file was auto-generated by Fern from our API Definition. -import glob -import importlib -import os -import types -import typing - import fastapi -import starlette.exceptions +from .resources.imdb.service.service import AbstractImdbService +import typing from fastapi import params - -from .core.abstract_fern_service import AbstractFernService -from .core.exceptions import default_exception_handler, fern_http_exception_handler, http_exception_handler from .core.exceptions.fern_http_exception import FernHTTPException -from .resources.imdb.service.service import AbstractImdbService +from .core.exceptions import fern_http_exception_handler +import starlette.exceptions +from .core.exceptions import http_exception_handler +from .core.exceptions import default_exception_handler +from .core.abstract_fern_service import AbstractFernService +import types +import os +import glob +import importlib def register( _app: fastapi.FastAPI, *, imdb: AbstractImdbService, - dependencies: typing.Optional[typing.Sequence[params.Depends]] = None + dependencies: typing.Optional[typing.Sequence[params.Depends]] = None, ) -> None: _app.include_router(__register_service(imdb), dependencies=dependencies) _app.add_exception_handler(FernHTTPException, fern_http_exception_handler) # type: ignore - _app.add_exception_handler(starlette.exceptions.HTTPException, http_exception_handler) # type: ignore + _app.add_exception_handler( + starlette.exceptions.HTTPException, http_exception_handler + ) # type: ignore _app.add_exception_handler(Exception, default_exception_handler) # type: ignore @@ -37,7 +39,9 @@ def __register_service(service: AbstractFernService) -> fastapi.APIRouter: def register_validators(module: types.ModuleType) -> None: validators_directory: str = os.path.dirname(module.__file__) # type: ignore - for path in glob.glob(os.path.join(validators_directory, "**/*.py"), recursive=True): + for path in glob.glob( + os.path.join(validators_directory, "**/*.py"), recursive=True + ): if os.path.isfile(path): relative_path = os.path.relpath(path, start=validators_directory) module_path = ".".join([module.__name__] + relative_path[:-3].split("/")) diff --git a/seed/fastapi/imdb/includes-extra-fields/resources/imdb/service/service.py b/seed/fastapi/imdb/includes-extra-fields/resources/imdb/service/service.py index efa55473639..828fc01cdac 100644 --- a/seed/fastapi/imdb/includes-extra-fields/resources/imdb/service/service.py +++ b/seed/fastapi/imdb/includes-extra-fields/resources/imdb/service/service.py @@ -1,20 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.abstract_fern_service import AbstractFernService +from ..types.create_movie_request import CreateMovieRequest +from ..types.movie_id import MovieId import abc -import functools +from ..types.movie import Movie +import fastapi import inspect -import logging import typing - -import fastapi - -from ....core.abstract_fern_service import AbstractFernService from ....core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools from ....core.route_args import get_route_args from ..errors.movie_does_not_exist_error import MovieDoesNotExistError -from ..types.create_movie_request import CreateMovieRequest -from ..types.movie import Movie -from ..types.movie_id import MovieId class AbstractImdbService(AbstractFernService): @@ -34,8 +32,7 @@ def create_movie(self, *, body: CreateMovieRequest) -> MovieId: ... @abc.abstractmethod - def get_movie(self, *, movie_id: str) -> Movie: - ... + def get_movie(self, *, movie_id: str) -> Movie: ... """ Below are internal methods used by Fern to register your implementation. @@ -51,14 +48,20 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_create_movie(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.create_movie) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) else: new_parameters.append(parameter) - setattr(cls.create_movie, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.create_movie, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.create_movie) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> MovieId: @@ -87,14 +90,20 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> MovieId: def __init_get_movie(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_movie) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "movie_id": new_parameters.append(parameter.replace(default=fastapi.Path(...))) else: new_parameters.append(parameter) - setattr(cls.get_movie, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_movie, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_movie) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> Movie: diff --git a/seed/fastapi/imdb/includes-extra-fields/resources/imdb/types/create_movie_request.py b/seed/fastapi/imdb/includes-extra-fields/resources/imdb/types/create_movie_request.py index 6ca11271d10..57556d30cc0 100644 --- a/seed/fastapi/imdb/includes-extra-fields/resources/imdb/types/create_movie_request.py +++ b/seed/fastapi/imdb/includes-extra-fields/resources/imdb/types/create_movie_request.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class CreateMovieRequest(UniversalBaseModel): title: str rating: float if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/imdb/includes-extra-fields/resources/imdb/types/movie.py b/seed/fastapi/imdb/includes-extra-fields/resources/imdb/types/movie.py index 0d3a15f2e5d..7a9056b647c 100644 --- a/seed/fastapi/imdb/includes-extra-fields/resources/imdb/types/movie.py +++ b/seed/fastapi/imdb/includes-extra-fields/resources/imdb/types/movie.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import UniversalBaseModel from .movie_id import MovieId +import pydantic +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class Movie(UniversalBaseModel): @@ -17,7 +16,9 @@ class Movie(UniversalBaseModel): """ if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/imdb/includes-extra-fields/security.py b/seed/fastapi/imdb/includes-extra-fields/security.py index bab014441e1..4ccabc21106 100644 --- a/seed/fastapi/imdb/includes-extra-fields/security.py +++ b/seed/fastapi/imdb/includes-extra-fields/security.py @@ -1,8 +1,8 @@ # This file was auto-generated by Fern from our API Definition. +from .core.security.bearer import BearerToken import fastapi - -from .core.security.bearer import BearerToken, HTTPBearer +from .core.security.bearer import HTTPBearer ApiAuth = BearerToken diff --git a/seed/fastapi/imdb/no-custom-config/__init__.py b/seed/fastapi/imdb/no-custom-config/__init__.py index dad4d86772a..d78850eb26f 100644 --- a/seed/fastapi/imdb/no-custom-config/__init__.py +++ b/seed/fastapi/imdb/no-custom-config/__init__.py @@ -3,4 +3,11 @@ from .resources import CreateMovieRequest, Movie, MovieDoesNotExistError, MovieId, imdb from .security import ApiAuth -__all__ = ["ApiAuth", "CreateMovieRequest", "Movie", "MovieDoesNotExistError", "MovieId", "imdb"] +__all__ = [ + "ApiAuth", + "CreateMovieRequest", + "Movie", + "MovieDoesNotExistError", + "MovieId", + "imdb", +] diff --git a/seed/fastapi/imdb/no-custom-config/core/abstract_fern_service.py b/seed/fastapi/imdb/no-custom-config/core/abstract_fern_service.py index da7c8dc49c4..9966b4876da 100644 --- a/seed/fastapi/imdb/no-custom-config/core/abstract_fern_service.py +++ b/seed/fastapi/imdb/no-custom-config/core/abstract_fern_service.py @@ -7,5 +7,4 @@ class AbstractFernService(abc.ABC): @classmethod - def _init_fern(cls, router: fastapi.APIRouter) -> None: - ... + def _init_fern(cls, router: fastapi.APIRouter) -> None: ... diff --git a/seed/fastapi/imdb/no-custom-config/core/datetime_utils.py b/seed/fastapi/imdb/no-custom-config/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/fastapi/imdb/no-custom-config/core/datetime_utils.py +++ b/seed/fastapi/imdb/no-custom-config/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/fastapi/imdb/no-custom-config/core/exceptions/__init__.py b/seed/fastapi/imdb/no-custom-config/core/exceptions/__init__.py index 297d6e06f5f..dae4b8980c1 100644 --- a/seed/fastapi/imdb/no-custom-config/core/exceptions/__init__.py +++ b/seed/fastapi/imdb/no-custom-config/core/exceptions/__init__.py @@ -1,7 +1,11 @@ # This file was auto-generated by Fern from our API Definition. from .fern_http_exception import FernHTTPException -from .handlers import default_exception_handler, fern_http_exception_handler, http_exception_handler +from .handlers import ( + default_exception_handler, + fern_http_exception_handler, + http_exception_handler, +) from .unauthorized import UnauthorizedException __all__ = [ diff --git a/seed/fastapi/imdb/no-custom-config/core/exceptions/fern_http_exception.py b/seed/fastapi/imdb/no-custom-config/core/exceptions/fern_http_exception.py index bdf03862487..81610359a7f 100644 --- a/seed/fastapi/imdb/no-custom-config/core/exceptions/fern_http_exception.py +++ b/seed/fastapi/imdb/no-custom-config/core/exceptions/fern_http_exception.py @@ -1,14 +1,16 @@ # This file was auto-generated by Fern from our API Definition. import abc -import typing - import fastapi +import typing class FernHTTPException(abc.ABC, fastapi.HTTPException): def __init__( - self, status_code: int, name: typing.Optional[str] = None, content: typing.Optional[typing.Any] = None + self, + status_code: int, + name: typing.Optional[str] = None, + content: typing.Optional[typing.Any] = None, ): super().__init__(status_code=status_code) self.name = name @@ -17,4 +19,6 @@ def __init__( def to_json_response(self) -> fastapi.responses.JSONResponse: content = fastapi.encoders.jsonable_encoder(self.content, exclude_none=True) - return fastapi.responses.JSONResponse(content=content, status_code=self.status_code) + return fastapi.responses.JSONResponse( + content=content, status_code=self.status_code + ) diff --git a/seed/fastapi/imdb/no-custom-config/core/exceptions/handlers.py b/seed/fastapi/imdb/no-custom-config/core/exceptions/handlers.py index 6d8c4155c5a..ae1c2741f06 100644 --- a/seed/fastapi/imdb/no-custom-config/core/exceptions/handlers.py +++ b/seed/fastapi/imdb/no-custom-config/core/exceptions/handlers.py @@ -2,32 +2,49 @@ import logging -import fastapi import starlette import starlette.exceptions +import fastapi + from .fern_http_exception import FernHTTPException def fern_http_exception_handler( - request: fastapi.requests.Request, exc: FernHTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: FernHTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) return exc.to_json_response() def http_exception_handler( - request: fastapi.requests.Request, exc: starlette.exceptions.HTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: starlette.exceptions.HTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=exc.status_code, content=exc.detail).to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=exc.status_code, content=exc.detail + ).to_json_response() def default_exception_handler( - request: fastapi.requests.Request, exc: Exception, skip_log: bool = False + request: fastapi.requests.Request, + exc: Exception, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=500, content="Internal Server Error").to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=500, content="Internal Server Error" + ).to_json_response() diff --git a/seed/fastapi/imdb/no-custom-config/core/pydantic_utilities.py b/seed/fastapi/imdb/no-custom-config/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/fastapi/imdb/no-custom-config/core/pydantic_utilities.py +++ b/seed/fastapi/imdb/no-custom-config/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/fastapi/imdb/no-custom-config/core/route_args.py b/seed/fastapi/imdb/no-custom-config/core/route_args.py index 4228e2fe05d..bd940bf4ddd 100644 --- a/seed/fastapi/imdb/no-custom-config/core/route_args.py +++ b/seed/fastapi/imdb/no-custom-config/core/route_args.py @@ -20,9 +20,15 @@ class RouteArgs(typing_extensions.TypedDict): DEFAULT_ROUTE_ARGS = RouteArgs(openapi_extra=None, tags=None, include_in_schema=True) -def get_route_args(endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str) -> RouteArgs: - unwrapped = inspect.unwrap(endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY))) - route_args = typing.cast(RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS)) +def get_route_args( + endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str +) -> RouteArgs: + unwrapped = inspect.unwrap( + endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY)) + ) + route_args = typing.cast( + RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS) + ) if route_args["tags"] is None: return RouteArgs( openapi_extra=route_args["openapi_extra"], @@ -56,7 +62,11 @@ def decorator(endpoint_function: T) -> T: setattr( endpoint_function, FERN_CONFIG_KEY, - RouteArgs(openapi_extra=openapi_extra, tags=tags, include_in_schema=include_in_schema), + RouteArgs( + openapi_extra=openapi_extra, + tags=tags, + include_in_schema=include_in_schema, + ), ) return endpoint_function diff --git a/seed/fastapi/imdb/no-custom-config/register.py b/seed/fastapi/imdb/no-custom-config/register.py index b7d729ef371..8118c947793 100644 --- a/seed/fastapi/imdb/no-custom-config/register.py +++ b/seed/fastapi/imdb/no-custom-config/register.py @@ -1,31 +1,33 @@ # This file was auto-generated by Fern from our API Definition. -import glob -import importlib -import os -import types -import typing - import fastapi -import starlette.exceptions +from .resources.imdb.service.service import AbstractImdbService +import typing from fastapi import params - -from .core.abstract_fern_service import AbstractFernService -from .core.exceptions import default_exception_handler, fern_http_exception_handler, http_exception_handler from .core.exceptions.fern_http_exception import FernHTTPException -from .resources.imdb.service.service import AbstractImdbService +from .core.exceptions import fern_http_exception_handler +import starlette.exceptions +from .core.exceptions import http_exception_handler +from .core.exceptions import default_exception_handler +from .core.abstract_fern_service import AbstractFernService +import types +import os +import glob +import importlib def register( _app: fastapi.FastAPI, *, imdb: AbstractImdbService, - dependencies: typing.Optional[typing.Sequence[params.Depends]] = None + dependencies: typing.Optional[typing.Sequence[params.Depends]] = None, ) -> None: _app.include_router(__register_service(imdb), dependencies=dependencies) _app.add_exception_handler(FernHTTPException, fern_http_exception_handler) # type: ignore - _app.add_exception_handler(starlette.exceptions.HTTPException, http_exception_handler) # type: ignore + _app.add_exception_handler( + starlette.exceptions.HTTPException, http_exception_handler + ) # type: ignore _app.add_exception_handler(Exception, default_exception_handler) # type: ignore @@ -37,7 +39,9 @@ def __register_service(service: AbstractFernService) -> fastapi.APIRouter: def register_validators(module: types.ModuleType) -> None: validators_directory: str = os.path.dirname(module.__file__) # type: ignore - for path in glob.glob(os.path.join(validators_directory, "**/*.py"), recursive=True): + for path in glob.glob( + os.path.join(validators_directory, "**/*.py"), recursive=True + ): if os.path.isfile(path): relative_path = os.path.relpath(path, start=validators_directory) module_path = ".".join([module.__name__] + relative_path[:-3].split("/")) diff --git a/seed/fastapi/imdb/no-custom-config/resources/imdb/service/service.py b/seed/fastapi/imdb/no-custom-config/resources/imdb/service/service.py index efa55473639..828fc01cdac 100644 --- a/seed/fastapi/imdb/no-custom-config/resources/imdb/service/service.py +++ b/seed/fastapi/imdb/no-custom-config/resources/imdb/service/service.py @@ -1,20 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.abstract_fern_service import AbstractFernService +from ..types.create_movie_request import CreateMovieRequest +from ..types.movie_id import MovieId import abc -import functools +from ..types.movie import Movie +import fastapi import inspect -import logging import typing - -import fastapi - -from ....core.abstract_fern_service import AbstractFernService from ....core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools from ....core.route_args import get_route_args from ..errors.movie_does_not_exist_error import MovieDoesNotExistError -from ..types.create_movie_request import CreateMovieRequest -from ..types.movie import Movie -from ..types.movie_id import MovieId class AbstractImdbService(AbstractFernService): @@ -34,8 +32,7 @@ def create_movie(self, *, body: CreateMovieRequest) -> MovieId: ... @abc.abstractmethod - def get_movie(self, *, movie_id: str) -> Movie: - ... + def get_movie(self, *, movie_id: str) -> Movie: ... """ Below are internal methods used by Fern to register your implementation. @@ -51,14 +48,20 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_create_movie(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.create_movie) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) else: new_parameters.append(parameter) - setattr(cls.create_movie, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.create_movie, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.create_movie) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> MovieId: @@ -87,14 +90,20 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> MovieId: def __init_get_movie(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_movie) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "movie_id": new_parameters.append(parameter.replace(default=fastapi.Path(...))) else: new_parameters.append(parameter) - setattr(cls.get_movie, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_movie, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_movie) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> Movie: diff --git a/seed/fastapi/imdb/no-custom-config/resources/imdb/types/create_movie_request.py b/seed/fastapi/imdb/no-custom-config/resources/imdb/types/create_movie_request.py index d9a37cc4db8..4642ba54a78 100644 --- a/seed/fastapi/imdb/no-custom-config/resources/imdb/types/create_movie_request.py +++ b/seed/fastapi/imdb/no-custom-config/resources/imdb/types/create_movie_request.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class CreateMovieRequest(UniversalBaseModel): title: str rating: float if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/imdb/no-custom-config/resources/imdb/types/movie.py b/seed/fastapi/imdb/no-custom-config/resources/imdb/types/movie.py index b3d0889f76c..f3e5ea5b18a 100644 --- a/seed/fastapi/imdb/no-custom-config/resources/imdb/types/movie.py +++ b/seed/fastapi/imdb/no-custom-config/resources/imdb/types/movie.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import UniversalBaseModel from .movie_id import MovieId +import pydantic +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class Movie(UniversalBaseModel): @@ -17,7 +16,9 @@ class Movie(UniversalBaseModel): """ if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/imdb/no-custom-config/security.py b/seed/fastapi/imdb/no-custom-config/security.py index bab014441e1..4ccabc21106 100644 --- a/seed/fastapi/imdb/no-custom-config/security.py +++ b/seed/fastapi/imdb/no-custom-config/security.py @@ -1,8 +1,8 @@ # This file was auto-generated by Fern from our API Definition. +from .core.security.bearer import BearerToken import fastapi - -from .core.security.bearer import BearerToken, HTTPBearer +from .core.security.bearer import HTTPBearer ApiAuth = BearerToken diff --git a/seed/fastapi/imdb/register.py b/seed/fastapi/imdb/register.py index 6ca6f0daf84..3c2d7deb3b9 100644 --- a/seed/fastapi/imdb/register.py +++ b/seed/fastapi/imdb/register.py @@ -11,7 +11,11 @@ from fastapi import params from .core.abstract_fern_service import AbstractFernService -from .core.exceptions import default_exception_handler, fern_http_exception_handler, http_exception_handler +from .core.exceptions import ( + default_exception_handler, + fern_http_exception_handler, + http_exception_handler, +) from .core.exceptions.fern_http_exception import FernHTTPException from .resources.imdb.service.service import AbstractImdbService @@ -20,12 +24,14 @@ def register( _app: fastapi.FastAPI, *, imdb: AbstractImdbService, - dependencies: typing.Optional[typing.Sequence[params.Depends]] = None + dependencies: typing.Optional[typing.Sequence[params.Depends]] = None, ) -> None: _app.include_router(__register_service(imdb), dependencies=dependencies) _app.add_exception_handler(FernHTTPException, fern_http_exception_handler) - _app.add_exception_handler(starlette.exceptions.HTTPException, http_exception_handler) + _app.add_exception_handler( + starlette.exceptions.HTTPException, http_exception_handler + ) _app.add_exception_handler(Exception, default_exception_handler) @@ -37,7 +43,9 @@ def __register_service(service: AbstractFernService) -> fastapi.APIRouter: def register_validators(module: types.ModuleType) -> None: validators_directory: str = os.path.dirname(module.__file__) # type: ignore - for path in glob.glob(os.path.join(validators_directory, "**/*.py"), recursive=True): + for path in glob.glob( + os.path.join(validators_directory, "**/*.py"), recursive=True + ): if os.path.isfile(path): relative_path = os.path.relpath(path, start=validators_directory) module_path = ".".join([module.__name__] + relative_path[:-3].split("/")) diff --git a/seed/fastapi/imdb/resources/imdb/service/service.py b/seed/fastapi/imdb/resources/imdb/service/service.py index efa55473639..e015994a336 100644 --- a/seed/fastapi/imdb/resources/imdb/service/service.py +++ b/seed/fastapi/imdb/resources/imdb/service/service.py @@ -34,8 +34,7 @@ def create_movie(self, *, body: CreateMovieRequest) -> MovieId: ... @abc.abstractmethod - def get_movie(self, *, movie_id: str) -> Movie: - ... + def get_movie(self, *, movie_id: str) -> Movie: ... """ Below are internal methods used by Fern to register your implementation. @@ -51,14 +50,20 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_create_movie(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.create_movie) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) else: new_parameters.append(parameter) - setattr(cls.create_movie, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.create_movie, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.create_movie) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> MovieId: @@ -87,14 +92,20 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> MovieId: def __init_get_movie(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_movie) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "movie_id": new_parameters.append(parameter.replace(default=fastapi.Path(...))) else: new_parameters.append(parameter) - setattr(cls.get_movie, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_movie, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_movie) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> Movie: diff --git a/seed/fastapi/imdb/resources/imdb/types/create_movie_request.py b/seed/fastapi/imdb/resources/imdb/types/create_movie_request.py index 8b875de168a..a4f6c455907 100644 --- a/seed/fastapi/imdb/resources/imdb/types/create_movie_request.py +++ b/seed/fastapi/imdb/resources/imdb/types/create_movie_request.py @@ -12,15 +12,28 @@ class CreateMovieRequest(pydantic_v1.BaseModel): rating: float def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) class Config: diff --git a/seed/fastapi/imdb/resources/imdb/types/movie.py b/seed/fastapi/imdb/resources/imdb/types/movie.py index 6506f545b38..c0492f35d61 100644 --- a/seed/fastapi/imdb/resources/imdb/types/movie.py +++ b/seed/fastapi/imdb/resources/imdb/types/movie.py @@ -17,15 +17,28 @@ class Movie(pydantic_v1.BaseModel): """ def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) class Config: diff --git a/seed/fastapi/imdb/resources/imdb/types/movie_id.py b/seed/fastapi/imdb/resources/imdb/types/movie_id.py index e30f6d6f495..2b746b6dece 100644 --- a/seed/fastapi/imdb/resources/imdb/types/movie_id.py +++ b/seed/fastapi/imdb/resources/imdb/types/movie_id.py @@ -20,15 +20,28 @@ def from_str(value: str) -> MovieId: return MovieId(__root__=value) def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) class Config: diff --git a/seed/fastapi/literal/core/abstract_fern_service.py b/seed/fastapi/literal/core/abstract_fern_service.py index da7c8dc49c4..9966b4876da 100644 --- a/seed/fastapi/literal/core/abstract_fern_service.py +++ b/seed/fastapi/literal/core/abstract_fern_service.py @@ -7,5 +7,4 @@ class AbstractFernService(abc.ABC): @classmethod - def _init_fern(cls, router: fastapi.APIRouter) -> None: - ... + def _init_fern(cls, router: fastapi.APIRouter) -> None: ... diff --git a/seed/fastapi/literal/core/datetime_utils.py b/seed/fastapi/literal/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/fastapi/literal/core/datetime_utils.py +++ b/seed/fastapi/literal/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/fastapi/literal/core/exceptions/__init__.py b/seed/fastapi/literal/core/exceptions/__init__.py index 297d6e06f5f..dae4b8980c1 100644 --- a/seed/fastapi/literal/core/exceptions/__init__.py +++ b/seed/fastapi/literal/core/exceptions/__init__.py @@ -1,7 +1,11 @@ # This file was auto-generated by Fern from our API Definition. from .fern_http_exception import FernHTTPException -from .handlers import default_exception_handler, fern_http_exception_handler, http_exception_handler +from .handlers import ( + default_exception_handler, + fern_http_exception_handler, + http_exception_handler, +) from .unauthorized import UnauthorizedException __all__ = [ diff --git a/seed/fastapi/literal/core/exceptions/fern_http_exception.py b/seed/fastapi/literal/core/exceptions/fern_http_exception.py index bdf03862487..a5925c21510 100644 --- a/seed/fastapi/literal/core/exceptions/fern_http_exception.py +++ b/seed/fastapi/literal/core/exceptions/fern_http_exception.py @@ -8,7 +8,10 @@ class FernHTTPException(abc.ABC, fastapi.HTTPException): def __init__( - self, status_code: int, name: typing.Optional[str] = None, content: typing.Optional[typing.Any] = None + self, + status_code: int, + name: typing.Optional[str] = None, + content: typing.Optional[typing.Any] = None, ): super().__init__(status_code=status_code) self.name = name @@ -17,4 +20,6 @@ def __init__( def to_json_response(self) -> fastapi.responses.JSONResponse: content = fastapi.encoders.jsonable_encoder(self.content, exclude_none=True) - return fastapi.responses.JSONResponse(content=content, status_code=self.status_code) + return fastapi.responses.JSONResponse( + content=content, status_code=self.status_code + ) diff --git a/seed/fastapi/literal/core/exceptions/handlers.py b/seed/fastapi/literal/core/exceptions/handlers.py index fe5ac5419c7..6e7a82773f6 100644 --- a/seed/fastapi/literal/core/exceptions/handlers.py +++ b/seed/fastapi/literal/core/exceptions/handlers.py @@ -12,21 +12,33 @@ def fern_http_exception_handler( request: fastapi.requests.Request, exc: FernHTTPException, skip_log: bool = False ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) return exc.to_json_response() def http_exception_handler( - request: fastapi.requests.Request, exc: starlette.exceptions.HTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: starlette.exceptions.HTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=exc.status_code, content=exc.detail).to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=exc.status_code, content=exc.detail + ).to_json_response() def default_exception_handler( request: fastapi.requests.Request, exc: Exception, skip_log: bool = False ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=500, content="Internal Server Error").to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=500, content="Internal Server Error" + ).to_json_response() diff --git a/seed/fastapi/literal/core/route_args.py b/seed/fastapi/literal/core/route_args.py index 4228e2fe05d..bd940bf4ddd 100644 --- a/seed/fastapi/literal/core/route_args.py +++ b/seed/fastapi/literal/core/route_args.py @@ -20,9 +20,15 @@ class RouteArgs(typing_extensions.TypedDict): DEFAULT_ROUTE_ARGS = RouteArgs(openapi_extra=None, tags=None, include_in_schema=True) -def get_route_args(endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str) -> RouteArgs: - unwrapped = inspect.unwrap(endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY))) - route_args = typing.cast(RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS)) +def get_route_args( + endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str +) -> RouteArgs: + unwrapped = inspect.unwrap( + endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY)) + ) + route_args = typing.cast( + RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS) + ) if route_args["tags"] is None: return RouteArgs( openapi_extra=route_args["openapi_extra"], @@ -56,7 +62,11 @@ def decorator(endpoint_function: T) -> T: setattr( endpoint_function, FERN_CONFIG_KEY, - RouteArgs(openapi_extra=openapi_extra, tags=tags, include_in_schema=include_in_schema), + RouteArgs( + openapi_extra=openapi_extra, + tags=tags, + include_in_schema=include_in_schema, + ), ) return endpoint_function diff --git a/seed/fastapi/literal/register.py b/seed/fastapi/literal/register.py index cc075c3bbfb..0bed88d0557 100644 --- a/seed/fastapi/literal/register.py +++ b/seed/fastapi/literal/register.py @@ -11,7 +11,11 @@ from fastapi import params from .core.abstract_fern_service import AbstractFernService -from .core.exceptions import default_exception_handler, fern_http_exception_handler, http_exception_handler +from .core.exceptions import ( + default_exception_handler, + fern_http_exception_handler, + http_exception_handler, +) from .core.exceptions.fern_http_exception import FernHTTPException from .resources.literal.service.service import AbstractLiteralService @@ -20,12 +24,14 @@ def register( _app: fastapi.FastAPI, *, literal: AbstractLiteralService, - dependencies: typing.Optional[typing.Sequence[params.Depends]] = None + dependencies: typing.Optional[typing.Sequence[params.Depends]] = None, ) -> None: _app.include_router(__register_service(literal), dependencies=dependencies) _app.add_exception_handler(FernHTTPException, fern_http_exception_handler) - _app.add_exception_handler(starlette.exceptions.HTTPException, http_exception_handler) + _app.add_exception_handler( + starlette.exceptions.HTTPException, http_exception_handler + ) _app.add_exception_handler(Exception, default_exception_handler) @@ -37,7 +43,9 @@ def __register_service(service: AbstractFernService) -> fastapi.APIRouter: def register_validators(module: types.ModuleType) -> None: validators_directory: str = os.path.dirname(module.__file__) # type: ignore - for path in glob.glob(os.path.join(validators_directory, "**/*.py"), recursive=True): + for path in glob.glob( + os.path.join(validators_directory, "**/*.py"), recursive=True + ): if os.path.isfile(path): relative_path = os.path.relpath(path, start=validators_directory) module_path = ".".join([module.__name__] + relative_path[:-3].split("/")) diff --git a/seed/fastapi/literal/resources/literal/__init__.py b/seed/fastapi/literal/resources/literal/__init__.py index f4d08cf98f9..466e4dbb101 100644 --- a/seed/fastapi/literal/resources/literal/__init__.py +++ b/seed/fastapi/literal/resources/literal/__init__.py @@ -1,6 +1,10 @@ # This file was auto-generated by Fern from our API Definition. -from .service import CreateOptionsRequest, GetOptionsRequest, GetUndiscriminatedOptionsRequest +from .service import ( + CreateOptionsRequest, + GetOptionsRequest, + GetUndiscriminatedOptionsRequest, +) from .types import CreateOptionsResponse, Options, UndiscriminatedOptions __all__ = [ diff --git a/seed/fastapi/literal/resources/literal/service/__init__.py b/seed/fastapi/literal/resources/literal/service/__init__.py index c427a03eb4d..8e008ae8f84 100644 --- a/seed/fastapi/literal/resources/literal/service/__init__.py +++ b/seed/fastapi/literal/resources/literal/service/__init__.py @@ -5,4 +5,9 @@ from .get_undiscriminated_options_request import GetUndiscriminatedOptionsRequest from .service import AbstractLiteralService -__all__ = ["AbstractLiteralService", "CreateOptionsRequest", "GetOptionsRequest", "GetUndiscriminatedOptionsRequest"] +__all__ = [ + "AbstractLiteralService", + "CreateOptionsRequest", + "GetOptionsRequest", + "GetUndiscriminatedOptionsRequest", +] diff --git a/seed/fastapi/literal/resources/literal/service/create_options_request.py b/seed/fastapi/literal/resources/literal/service/create_options_request.py index 0ba2f13d780..ce4e514ad14 100644 --- a/seed/fastapi/literal/resources/literal/service/create_options_request.py +++ b/seed/fastapi/literal/resources/literal/service/create_options_request.py @@ -15,11 +15,19 @@ class CreateOptionsRequest(pydantic.BaseModel): values: typing.Dict[str, str] def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/fastapi/literal/resources/literal/service/get_options_request.py b/seed/fastapi/literal/resources/literal/service/get_options_request.py index cdcd00d75d3..5a83efecef0 100644 --- a/seed/fastapi/literal/resources/literal/service/get_options_request.py +++ b/seed/fastapi/literal/resources/literal/service/get_options_request.py @@ -15,11 +15,19 @@ class GetOptionsRequest(pydantic.BaseModel): dry_run: typing.Literal[True] = pydantic.Field(alias="dryRun") def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/fastapi/literal/resources/literal/service/get_undiscriminated_options_request.py b/seed/fastapi/literal/resources/literal/service/get_undiscriminated_options_request.py index 88eebc44234..287d2388cea 100644 --- a/seed/fastapi/literal/resources/literal/service/get_undiscriminated_options_request.py +++ b/seed/fastapi/literal/resources/literal/service/get_undiscriminated_options_request.py @@ -15,11 +15,19 @@ class GetUndiscriminatedOptionsRequest(pydantic.BaseModel): dry_run: typing.Literal[True] = pydantic.Field(alias="dryRun") def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/fastapi/literal/resources/literal/service/service.py b/seed/fastapi/literal/resources/literal/service/service.py index aa1d99d1193..ac7da9d877f 100644 --- a/seed/fastapi/literal/resources/literal/service/service.py +++ b/seed/fastapi/literal/resources/literal/service/service.py @@ -29,16 +29,17 @@ class AbstractLiteralService(AbstractFernService): """ @abc.abstractmethod - def create_options(self, *, body: CreateOptionsRequest) -> CreateOptionsResponse: - ... + def create_options( + self, *, body: CreateOptionsRequest + ) -> CreateOptionsResponse: ... @abc.abstractmethod - def get_options(self, *, body: GetOptionsRequest) -> Options: - ... + def get_options(self, *, body: GetOptionsRequest) -> Options: ... @abc.abstractmethod - def get_undiscriminated_options(self, *, body: GetUndiscriminatedOptionsRequest) -> UndiscriminatedOptions: - ... + def get_undiscriminated_options( + self, *, body: GetUndiscriminatedOptionsRequest + ) -> UndiscriminatedOptions: ... """ Below are internal methods used by Fern to register your implementation. @@ -55,14 +56,20 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_create_options(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.create_options) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) else: new_parameters.append(parameter) - setattr(cls.create_options, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.create_options, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.create_options) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> CreateOptionsResponse: @@ -91,14 +98,20 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> CreateOptionsResponse: def __init_get_options(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_options) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) else: new_parameters.append(parameter) - setattr(cls.get_options, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_options, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_options) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> Options: @@ -127,14 +140,20 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> Options: def __init_get_undiscriminated_options(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_undiscriminated_options) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) else: new_parameters.append(parameter) - setattr(cls.get_undiscriminated_options, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_undiscriminated_options, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_undiscriminated_options) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> UndiscriminatedOptions: diff --git a/seed/fastapi/literal/resources/literal/types/create_options_response.py b/seed/fastapi/literal/resources/literal/types/create_options_response.py index c8974dfee84..f197ede89ed 100644 --- a/seed/fastapi/literal/resources/literal/types/create_options_response.py +++ b/seed/fastapi/literal/resources/literal/types/create_options_response.py @@ -18,18 +18,26 @@ class _Factory: def ok(self, value: typing.Literal[True]) -> CreateOptionsResponse: - return CreateOptionsResponse(__root__=_CreateOptionsResponse.Ok(type="ok", value=value)) + return CreateOptionsResponse( + __root__=_CreateOptionsResponse.Ok(type="ok", value=value) + ) - def options(self, value: resources_literal_types_options_Options) -> CreateOptionsResponse: + def options( + self, value: resources_literal_types_options_Options + ) -> CreateOptionsResponse: return CreateOptionsResponse( - __root__=_CreateOptionsResponse.Options(**value.dict(exclude_unset=True), type="options") + __root__=_CreateOptionsResponse.Options( + **value.dict(exclude_unset=True), type="options" + ) ) class CreateOptionsResponse(pydantic.BaseModel): factory: typing.ClassVar[_Factory] = _Factory() - def get_as_union(self) -> typing.Union[_CreateOptionsResponse.Ok, _CreateOptionsResponse.Options]: + def get_as_union( + self, + ) -> typing.Union[_CreateOptionsResponse.Ok, _CreateOptionsResponse.Options]: return self.__root__ def visit( @@ -41,19 +49,30 @@ def visit( return ok(self.__root__.value) if self.__root__.type == "options": return options( - resources_literal_types_options_Options(**self.__root__.dict(exclude_unset=True, exclude={"type"})) + resources_literal_types_options_Options( + **self.__root__.dict(exclude_unset=True, exclude={"type"}) + ) ) __root__: typing.Annotated[ - typing.Union[_CreateOptionsResponse.Ok, _CreateOptionsResponse.Options], pydantic.Field(discriminator="type") + typing.Union[_CreateOptionsResponse.Ok, _CreateOptionsResponse.Options], + pydantic.Field(discriminator="type"), ] def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/fastapi/literal/resources/literal/types/options.py b/seed/fastapi/literal/resources/literal/types/options.py index e8704d236d0..a9f08d81a63 100644 --- a/seed/fastapi/literal/resources/literal/types/options.py +++ b/seed/fastapi/literal/resources/literal/types/options.py @@ -17,11 +17,19 @@ class Options(pydantic.BaseModel): values: typing.Dict[str, str] def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/fastapi/literal/resources/literal/types/undiscriminated_options.py b/seed/fastapi/literal/resources/literal/types/undiscriminated_options.py index 312a4630012..af2bee11ace 100644 --- a/seed/fastapi/literal/resources/literal/types/undiscriminated_options.py +++ b/seed/fastapi/literal/resources/literal/types/undiscriminated_options.py @@ -2,4 +2,6 @@ import typing -UndiscriminatedOptions = typing.Union[typing.Literal["options"], typing.Literal[True], typing.Dict[str, str]] +UndiscriminatedOptions = typing.Union[ + typing.Literal["options"], typing.Literal[True], typing.Dict[str, str] +] diff --git a/seed/fastapi/mixed-case/__init__.py b/seed/fastapi/mixed-case/__init__.py index 91a1212f49b..9ab389143d9 100644 --- a/seed/fastapi/mixed-case/__init__.py +++ b/seed/fastapi/mixed-case/__init__.py @@ -2,4 +2,11 @@ from .resources import NestedUser, Organization, Resource, ResourceStatus, User, service -__all__ = ["NestedUser", "Organization", "Resource", "ResourceStatus", "User", "service"] +__all__ = [ + "NestedUser", + "Organization", + "Resource", + "ResourceStatus", + "User", + "service", +] diff --git a/seed/fastapi/mixed-case/core/abstract_fern_service.py b/seed/fastapi/mixed-case/core/abstract_fern_service.py index da7c8dc49c4..9966b4876da 100644 --- a/seed/fastapi/mixed-case/core/abstract_fern_service.py +++ b/seed/fastapi/mixed-case/core/abstract_fern_service.py @@ -7,5 +7,4 @@ class AbstractFernService(abc.ABC): @classmethod - def _init_fern(cls, router: fastapi.APIRouter) -> None: - ... + def _init_fern(cls, router: fastapi.APIRouter) -> None: ... diff --git a/seed/fastapi/mixed-case/core/datetime_utils.py b/seed/fastapi/mixed-case/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/fastapi/mixed-case/core/datetime_utils.py +++ b/seed/fastapi/mixed-case/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/fastapi/mixed-case/core/exceptions/__init__.py b/seed/fastapi/mixed-case/core/exceptions/__init__.py index 297d6e06f5f..dae4b8980c1 100644 --- a/seed/fastapi/mixed-case/core/exceptions/__init__.py +++ b/seed/fastapi/mixed-case/core/exceptions/__init__.py @@ -1,7 +1,11 @@ # This file was auto-generated by Fern from our API Definition. from .fern_http_exception import FernHTTPException -from .handlers import default_exception_handler, fern_http_exception_handler, http_exception_handler +from .handlers import ( + default_exception_handler, + fern_http_exception_handler, + http_exception_handler, +) from .unauthorized import UnauthorizedException __all__ = [ diff --git a/seed/fastapi/mixed-case/core/exceptions/fern_http_exception.py b/seed/fastapi/mixed-case/core/exceptions/fern_http_exception.py index bdf03862487..81610359a7f 100644 --- a/seed/fastapi/mixed-case/core/exceptions/fern_http_exception.py +++ b/seed/fastapi/mixed-case/core/exceptions/fern_http_exception.py @@ -1,14 +1,16 @@ # This file was auto-generated by Fern from our API Definition. import abc -import typing - import fastapi +import typing class FernHTTPException(abc.ABC, fastapi.HTTPException): def __init__( - self, status_code: int, name: typing.Optional[str] = None, content: typing.Optional[typing.Any] = None + self, + status_code: int, + name: typing.Optional[str] = None, + content: typing.Optional[typing.Any] = None, ): super().__init__(status_code=status_code) self.name = name @@ -17,4 +19,6 @@ def __init__( def to_json_response(self) -> fastapi.responses.JSONResponse: content = fastapi.encoders.jsonable_encoder(self.content, exclude_none=True) - return fastapi.responses.JSONResponse(content=content, status_code=self.status_code) + return fastapi.responses.JSONResponse( + content=content, status_code=self.status_code + ) diff --git a/seed/fastapi/mixed-case/core/exceptions/handlers.py b/seed/fastapi/mixed-case/core/exceptions/handlers.py index 6d8c4155c5a..ae1c2741f06 100644 --- a/seed/fastapi/mixed-case/core/exceptions/handlers.py +++ b/seed/fastapi/mixed-case/core/exceptions/handlers.py @@ -2,32 +2,49 @@ import logging -import fastapi import starlette import starlette.exceptions +import fastapi + from .fern_http_exception import FernHTTPException def fern_http_exception_handler( - request: fastapi.requests.Request, exc: FernHTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: FernHTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) return exc.to_json_response() def http_exception_handler( - request: fastapi.requests.Request, exc: starlette.exceptions.HTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: starlette.exceptions.HTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=exc.status_code, content=exc.detail).to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=exc.status_code, content=exc.detail + ).to_json_response() def default_exception_handler( - request: fastapi.requests.Request, exc: Exception, skip_log: bool = False + request: fastapi.requests.Request, + exc: Exception, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=500, content="Internal Server Error").to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=500, content="Internal Server Error" + ).to_json_response() diff --git a/seed/fastapi/mixed-case/core/pydantic_utilities.py b/seed/fastapi/mixed-case/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/fastapi/mixed-case/core/pydantic_utilities.py +++ b/seed/fastapi/mixed-case/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/fastapi/mixed-case/core/route_args.py b/seed/fastapi/mixed-case/core/route_args.py index 4228e2fe05d..bd940bf4ddd 100644 --- a/seed/fastapi/mixed-case/core/route_args.py +++ b/seed/fastapi/mixed-case/core/route_args.py @@ -20,9 +20,15 @@ class RouteArgs(typing_extensions.TypedDict): DEFAULT_ROUTE_ARGS = RouteArgs(openapi_extra=None, tags=None, include_in_schema=True) -def get_route_args(endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str) -> RouteArgs: - unwrapped = inspect.unwrap(endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY))) - route_args = typing.cast(RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS)) +def get_route_args( + endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str +) -> RouteArgs: + unwrapped = inspect.unwrap( + endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY)) + ) + route_args = typing.cast( + RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS) + ) if route_args["tags"] is None: return RouteArgs( openapi_extra=route_args["openapi_extra"], @@ -56,7 +62,11 @@ def decorator(endpoint_function: T) -> T: setattr( endpoint_function, FERN_CONFIG_KEY, - RouteArgs(openapi_extra=openapi_extra, tags=tags, include_in_schema=include_in_schema), + RouteArgs( + openapi_extra=openapi_extra, + tags=tags, + include_in_schema=include_in_schema, + ), ) return endpoint_function diff --git a/seed/fastapi/mixed-case/register.py b/seed/fastapi/mixed-case/register.py index ebdfdf9318d..1d60bbe4d5d 100644 --- a/seed/fastapi/mixed-case/register.py +++ b/seed/fastapi/mixed-case/register.py @@ -1,31 +1,33 @@ # This file was auto-generated by Fern from our API Definition. -import glob -import importlib -import os -import types -import typing - import fastapi -import starlette.exceptions +from .resources.service.service.service import AbstractServiceService +import typing from fastapi import params - -from .core.abstract_fern_service import AbstractFernService -from .core.exceptions import default_exception_handler, fern_http_exception_handler, http_exception_handler from .core.exceptions.fern_http_exception import FernHTTPException -from .resources.service.service.service import AbstractServiceService +from .core.exceptions import fern_http_exception_handler +import starlette.exceptions +from .core.exceptions import http_exception_handler +from .core.exceptions import default_exception_handler +from .core.abstract_fern_service import AbstractFernService +import types +import os +import glob +import importlib def register( _app: fastapi.FastAPI, *, service: AbstractServiceService, - dependencies: typing.Optional[typing.Sequence[params.Depends]] = None + dependencies: typing.Optional[typing.Sequence[params.Depends]] = None, ) -> None: _app.include_router(__register_service(service), dependencies=dependencies) _app.add_exception_handler(FernHTTPException, fern_http_exception_handler) # type: ignore - _app.add_exception_handler(starlette.exceptions.HTTPException, http_exception_handler) # type: ignore + _app.add_exception_handler( + starlette.exceptions.HTTPException, http_exception_handler + ) # type: ignore _app.add_exception_handler(Exception, default_exception_handler) # type: ignore @@ -37,7 +39,9 @@ def __register_service(service: AbstractFernService) -> fastapi.APIRouter: def register_validators(module: types.ModuleType) -> None: validators_directory: str = os.path.dirname(module.__file__) # type: ignore - for path in glob.glob(os.path.join(validators_directory, "**/*.py"), recursive=True): + for path in glob.glob( + os.path.join(validators_directory, "**/*.py"), recursive=True + ): if os.path.isfile(path): relative_path = os.path.relpath(path, start=validators_directory) module_path = ".".join([module.__name__] + relative_path[:-3].split("/")) diff --git a/seed/fastapi/mixed-case/resources/__init__.py b/seed/fastapi/mixed-case/resources/__init__.py index 4eca3433d73..03404083809 100644 --- a/seed/fastapi/mixed-case/resources/__init__.py +++ b/seed/fastapi/mixed-case/resources/__init__.py @@ -3,4 +3,11 @@ from . import service from .service import NestedUser, Organization, Resource, ResourceStatus, User -__all__ = ["NestedUser", "Organization", "Resource", "ResourceStatus", "User", "service"] +__all__ = [ + "NestedUser", + "Organization", + "Resource", + "ResourceStatus", + "User", + "service", +] diff --git a/seed/fastapi/mixed-case/resources/service/service/service.py b/seed/fastapi/mixed-case/resources/service/service/service.py index 4fc5ba1d17a..74c4cdf5279 100644 --- a/seed/fastapi/mixed-case/resources/service/service/service.py +++ b/seed/fastapi/mixed-case/resources/service/service/service.py @@ -1,18 +1,16 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.abstract_fern_service import AbstractFernService +from ..types.resource import Resource import abc import datetime as dt -import functools -import inspect -import logging import typing - import fastapi - -from ....core.abstract_fern_service import AbstractFernService +import inspect from ....core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools from ....core.route_args import get_route_args -from ..types.resource import Resource class AbstractServiceService(AbstractFernService): @@ -25,12 +23,12 @@ class AbstractServiceService(AbstractFernService): """ @abc.abstractmethod - def get_resource(self, *, resource_id: str) -> Resource: - ... + def get_resource(self, *, resource_id: str) -> Resource: ... @abc.abstractmethod - def list_resources(self, *, page_limit: int, before_date: dt.date) -> typing.Sequence[Resource]: - ... + def list_resources( + self, *, page_limit: int, before_date: dt.date + ) -> typing.Sequence[Resource]: ... """ Below are internal methods used by Fern to register your implementation. @@ -46,14 +44,20 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_get_resource(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_resource) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "resource_id": new_parameters.append(parameter.replace(default=fastapi.Path(...))) else: new_parameters.append(parameter) - setattr(cls.get_resource, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_resource, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_resource) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> Resource: @@ -82,19 +86,33 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> Resource: def __init_list_resources(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.list_resources) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "page_limit": - new_parameters.append(parameter.replace(default=fastapi.Query(default=...))) + new_parameters.append( + parameter.replace(default=fastapi.Query(default=...)) + ) elif parameter_name == "before_date": - new_parameters.append(parameter.replace(default=fastapi.Query(default=..., alias="beforeDate"))) + new_parameters.append( + parameter.replace( + default=fastapi.Query(default=..., alias="beforeDate") + ) + ) else: new_parameters.append(parameter) - setattr(cls.list_resources, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.list_resources, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.list_resources) - def wrapper(*args: typing.Any, **kwargs: typing.Any) -> typing.Sequence[Resource]: + def wrapper( + *args: typing.Any, **kwargs: typing.Any + ) -> typing.Sequence[Resource]: try: return cls.list_resources(*args, **kwargs) except FernHTTPException as e: diff --git a/seed/fastapi/mixed-case/resources/service/types/nested_user.py b/seed/fastapi/mixed-case/resources/service/types/nested_user.py index 52d0b89fee4..e8c1dbd442c 100644 --- a/seed/fastapi/mixed-case/resources/service/types/nested_user.py +++ b/seed/fastapi/mixed-case/resources/service/types/nested_user.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ....core.pydantic_utilities import UniversalBaseModel import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .user import User +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class NestedUser(UniversalBaseModel): @@ -28,7 +27,9 @@ class NestedUser(UniversalBaseModel): nested_user: User = pydantic.Field(alias="NestedUser") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/mixed-case/resources/service/types/organization.py b/seed/fastapi/mixed-case/resources/service/types/organization.py index 9dbe79d8e10..59ec25ee2b8 100644 --- a/seed/fastapi/mixed-case/resources/service/types/organization.py +++ b/seed/fastapi/mixed-case/resources/service/types/organization.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class Organization(UniversalBaseModel): """ @@ -21,7 +20,9 @@ class Organization(UniversalBaseModel): name: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/mixed-case/resources/service/types/resource.py b/seed/fastapi/mixed-case/resources/service/types/resource.py index 2a83025e87e..556c0752d53 100644 --- a/seed/fastapi/mixed-case/resources/service/types/resource.py +++ b/seed/fastapi/mixed-case/resources/service/types/resource.py @@ -1,15 +1,16 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from .user import User as resources_service_types_user_User +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +from .organization import ( + Organization as resources_service_types_organization_Organization, +) +from ....core.pydantic_utilities import UniversalRootModel import typing - -import pydantic import typing_extensions - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalRootModel, update_forward_refs -from .organization import Organization as resources_service_types_organization_Organization -from .user import User as resources_service_types_user_User +import pydantic +from ....core.pydantic_utilities import update_forward_refs T_Result = typing.TypeVar("T_Result") @@ -17,16 +18,32 @@ class _Factory: def user(self, value: resources_service_types_user_User) -> Resource: if IS_PYDANTIC_V2: - return Resource(root=_Resource.User(**value.dict(exclude_unset=True), resource_type="user")) + return Resource( + root=_Resource.User( + **value.dict(exclude_unset=True), resource_type="user" + ) + ) else: - return Resource(__root__=_Resource.User(**value.dict(exclude_unset=True), resource_type="user")) + return Resource( + __root__=_Resource.User( + **value.dict(exclude_unset=True), resource_type="user" + ) + ) - def organization(self, value: resources_service_types_organization_Organization) -> Resource: + def organization( + self, value: resources_service_types_organization_Organization + ) -> Resource: if IS_PYDANTIC_V2: - return Resource(root=_Resource.Organization(**value.dict(exclude_unset=True), resource_type="Organization")) + return Resource( + root=_Resource.Organization( + **value.dict(exclude_unset=True), resource_type="Organization" + ) + ) else: return Resource( - __root__=_Resource.Organization(**value.dict(exclude_unset=True), resource_type="Organization") + __root__=_Resource.Organization( + **value.dict(exclude_unset=True), resource_type="Organization" + ) ) @@ -47,15 +64,16 @@ class Resource(UniversalRootModel): if IS_PYDANTIC_V2: root: typing_extensions.Annotated[ - typing.Union[_Resource.User, _Resource.Organization], pydantic.Field(discriminator="resource_type") + typing.Union[_Resource.User, _Resource.Organization], + pydantic.Field(discriminator="resource_type"), ] def get_as_union(self) -> typing.Union[_Resource.User, _Resource.Organization]: return self.root - else: __root__: typing_extensions.Annotated[ - typing.Union[_Resource.User, _Resource.Organization], pydantic.Field(discriminator="resource_type") + typing.Union[_Resource.User, _Resource.Organization], + pydantic.Field(discriminator="resource_type"), ] def get_as_union(self) -> typing.Union[_Resource.User, _Resource.Organization]: @@ -64,12 +82,16 @@ def get_as_union(self) -> typing.Union[_Resource.User, _Resource.Organization]: def visit( self, user: typing.Callable[[resources_service_types_user_User], T_Result], - organization: typing.Callable[[resources_service_types_organization_Organization], T_Result], + organization: typing.Callable[ + [resources_service_types_organization_Organization], T_Result + ], ) -> T_Result: unioned_value = self.get_as_union() if unioned_value.resource_type == "user": return user( - resources_service_types_user_User(**unioned_value.dict(exclude_unset=True, exclude={"resource_type"})) + resources_service_types_user_User( + **unioned_value.dict(exclude_unset=True, exclude={"resource_type"}) + ) ) if unioned_value.resource_type == "Organization": return organization( diff --git a/seed/fastapi/mixed-case/resources/service/types/resource_status.py b/seed/fastapi/mixed-case/resources/service/types/resource_status.py index 21b0467fe29..af42d2b9f59 100644 --- a/seed/fastapi/mixed-case/resources/service/types/resource_status.py +++ b/seed/fastapi/mixed-case/resources/service/types/resource_status.py @@ -10,7 +10,11 @@ class ResourceStatus(str, enum.Enum): ACTIVE = "ACTIVE" INACTIVE = "INACTIVE" - def visit(self, active: typing.Callable[[], T_Result], inactive: typing.Callable[[], T_Result]) -> T_Result: + def visit( + self, + active: typing.Callable[[], T_Result], + inactive: typing.Callable[[], T_Result], + ) -> T_Result: if self is ResourceStatus.ACTIVE: return active() if self is ResourceStatus.INACTIVE: diff --git a/seed/fastapi/mixed-case/resources/service/types/user.py b/seed/fastapi/mixed-case/resources/service/types/user.py index effcaf38742..b70129c7cd4 100644 --- a/seed/fastapi/mixed-case/resources/service/types/user.py +++ b/seed/fastapi/mixed-case/resources/service/types/user.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ....core.pydantic_utilities import UniversalBaseModel import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +import typing +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class User(UniversalBaseModel): @@ -25,7 +24,9 @@ class User(UniversalBaseModel): extra_properties: typing.Dict[str, str] = pydantic.Field(alias="EXTRA_PROPERTIES") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/multi-line-docs/core/abstract_fern_service.py b/seed/fastapi/multi-line-docs/core/abstract_fern_service.py index da7c8dc49c4..9966b4876da 100644 --- a/seed/fastapi/multi-line-docs/core/abstract_fern_service.py +++ b/seed/fastapi/multi-line-docs/core/abstract_fern_service.py @@ -7,5 +7,4 @@ class AbstractFernService(abc.ABC): @classmethod - def _init_fern(cls, router: fastapi.APIRouter) -> None: - ... + def _init_fern(cls, router: fastapi.APIRouter) -> None: ... diff --git a/seed/fastapi/multi-line-docs/core/datetime_utils.py b/seed/fastapi/multi-line-docs/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/fastapi/multi-line-docs/core/datetime_utils.py +++ b/seed/fastapi/multi-line-docs/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/fastapi/multi-line-docs/core/exceptions/__init__.py b/seed/fastapi/multi-line-docs/core/exceptions/__init__.py index 297d6e06f5f..dae4b8980c1 100644 --- a/seed/fastapi/multi-line-docs/core/exceptions/__init__.py +++ b/seed/fastapi/multi-line-docs/core/exceptions/__init__.py @@ -1,7 +1,11 @@ # This file was auto-generated by Fern from our API Definition. from .fern_http_exception import FernHTTPException -from .handlers import default_exception_handler, fern_http_exception_handler, http_exception_handler +from .handlers import ( + default_exception_handler, + fern_http_exception_handler, + http_exception_handler, +) from .unauthorized import UnauthorizedException __all__ = [ diff --git a/seed/fastapi/multi-line-docs/core/exceptions/fern_http_exception.py b/seed/fastapi/multi-line-docs/core/exceptions/fern_http_exception.py index bdf03862487..81610359a7f 100644 --- a/seed/fastapi/multi-line-docs/core/exceptions/fern_http_exception.py +++ b/seed/fastapi/multi-line-docs/core/exceptions/fern_http_exception.py @@ -1,14 +1,16 @@ # This file was auto-generated by Fern from our API Definition. import abc -import typing - import fastapi +import typing class FernHTTPException(abc.ABC, fastapi.HTTPException): def __init__( - self, status_code: int, name: typing.Optional[str] = None, content: typing.Optional[typing.Any] = None + self, + status_code: int, + name: typing.Optional[str] = None, + content: typing.Optional[typing.Any] = None, ): super().__init__(status_code=status_code) self.name = name @@ -17,4 +19,6 @@ def __init__( def to_json_response(self) -> fastapi.responses.JSONResponse: content = fastapi.encoders.jsonable_encoder(self.content, exclude_none=True) - return fastapi.responses.JSONResponse(content=content, status_code=self.status_code) + return fastapi.responses.JSONResponse( + content=content, status_code=self.status_code + ) diff --git a/seed/fastapi/multi-line-docs/core/exceptions/handlers.py b/seed/fastapi/multi-line-docs/core/exceptions/handlers.py index 6d8c4155c5a..ae1c2741f06 100644 --- a/seed/fastapi/multi-line-docs/core/exceptions/handlers.py +++ b/seed/fastapi/multi-line-docs/core/exceptions/handlers.py @@ -2,32 +2,49 @@ import logging -import fastapi import starlette import starlette.exceptions +import fastapi + from .fern_http_exception import FernHTTPException def fern_http_exception_handler( - request: fastapi.requests.Request, exc: FernHTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: FernHTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) return exc.to_json_response() def http_exception_handler( - request: fastapi.requests.Request, exc: starlette.exceptions.HTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: starlette.exceptions.HTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=exc.status_code, content=exc.detail).to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=exc.status_code, content=exc.detail + ).to_json_response() def default_exception_handler( - request: fastapi.requests.Request, exc: Exception, skip_log: bool = False + request: fastapi.requests.Request, + exc: Exception, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=500, content="Internal Server Error").to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=500, content="Internal Server Error" + ).to_json_response() diff --git a/seed/fastapi/multi-line-docs/core/pydantic_utilities.py b/seed/fastapi/multi-line-docs/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/fastapi/multi-line-docs/core/pydantic_utilities.py +++ b/seed/fastapi/multi-line-docs/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/fastapi/multi-line-docs/core/route_args.py b/seed/fastapi/multi-line-docs/core/route_args.py index 4228e2fe05d..bd940bf4ddd 100644 --- a/seed/fastapi/multi-line-docs/core/route_args.py +++ b/seed/fastapi/multi-line-docs/core/route_args.py @@ -20,9 +20,15 @@ class RouteArgs(typing_extensions.TypedDict): DEFAULT_ROUTE_ARGS = RouteArgs(openapi_extra=None, tags=None, include_in_schema=True) -def get_route_args(endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str) -> RouteArgs: - unwrapped = inspect.unwrap(endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY))) - route_args = typing.cast(RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS)) +def get_route_args( + endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str +) -> RouteArgs: + unwrapped = inspect.unwrap( + endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY)) + ) + route_args = typing.cast( + RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS) + ) if route_args["tags"] is None: return RouteArgs( openapi_extra=route_args["openapi_extra"], @@ -56,7 +62,11 @@ def decorator(endpoint_function: T) -> T: setattr( endpoint_function, FERN_CONFIG_KEY, - RouteArgs(openapi_extra=openapi_extra, tags=tags, include_in_schema=include_in_schema), + RouteArgs( + openapi_extra=openapi_extra, + tags=tags, + include_in_schema=include_in_schema, + ), ) return endpoint_function diff --git a/seed/fastapi/multi-line-docs/register.py b/seed/fastapi/multi-line-docs/register.py index cad83228e21..f0b801ec079 100644 --- a/seed/fastapi/multi-line-docs/register.py +++ b/seed/fastapi/multi-line-docs/register.py @@ -1,31 +1,33 @@ # This file was auto-generated by Fern from our API Definition. -import glob -import importlib -import os -import types -import typing - import fastapi -import starlette.exceptions +from .resources.user.service.service import AbstractUserService +import typing from fastapi import params - -from .core.abstract_fern_service import AbstractFernService -from .core.exceptions import default_exception_handler, fern_http_exception_handler, http_exception_handler from .core.exceptions.fern_http_exception import FernHTTPException -from .resources.user.service.service import AbstractUserService +from .core.exceptions import fern_http_exception_handler +import starlette.exceptions +from .core.exceptions import http_exception_handler +from .core.exceptions import default_exception_handler +from .core.abstract_fern_service import AbstractFernService +import types +import os +import glob +import importlib def register( _app: fastapi.FastAPI, *, user: AbstractUserService, - dependencies: typing.Optional[typing.Sequence[params.Depends]] = None + dependencies: typing.Optional[typing.Sequence[params.Depends]] = None, ) -> None: _app.include_router(__register_service(user), dependencies=dependencies) _app.add_exception_handler(FernHTTPException, fern_http_exception_handler) # type: ignore - _app.add_exception_handler(starlette.exceptions.HTTPException, http_exception_handler) # type: ignore + _app.add_exception_handler( + starlette.exceptions.HTTPException, http_exception_handler + ) # type: ignore _app.add_exception_handler(Exception, default_exception_handler) # type: ignore @@ -37,7 +39,9 @@ def __register_service(service: AbstractFernService) -> fastapi.APIRouter: def register_validators(module: types.ModuleType) -> None: validators_directory: str = os.path.dirname(module.__file__) # type: ignore - for path in glob.glob(os.path.join(validators_directory, "**/*.py"), recursive=True): + for path in glob.glob( + os.path.join(validators_directory, "**/*.py"), recursive=True + ): if os.path.isfile(path): relative_path = os.path.relpath(path, start=validators_directory) module_path = ".".join([module.__name__] + relative_path[:-3].split("/")) diff --git a/seed/fastapi/multi-line-docs/resources/user/service/create_user_request.py b/seed/fastapi/multi-line-docs/resources/user/service/create_user_request.py index 37d9cfd4e52..c57488d818d 100644 --- a/seed/fastapi/multi-line-docs/resources/user/service/create_user_request.py +++ b/seed/fastapi/multi-line-docs/resources/user/service/create_user_request.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ....core.pydantic_utilities import UniversalBaseModel import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +import typing +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class CreateUserRequest(UniversalBaseModel): @@ -21,7 +20,9 @@ class CreateUserRequest(UniversalBaseModel): """ if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/multi-line-docs/resources/user/service/service.py b/seed/fastapi/multi-line-docs/resources/user/service/service.py index 356d670a7c6..7e3575eb46a 100644 --- a/seed/fastapi/multi-line-docs/resources/user/service/service.py +++ b/seed/fastapi/multi-line-docs/resources/user/service/service.py @@ -1,19 +1,17 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.abstract_fern_service import AbstractFernService import abc -import functools +from .create_user_request import CreateUserRequest +from ..types.user import User +import fastapi import inspect -import logging import typing - -import fastapi -import starlette - -from ....core.abstract_fern_service import AbstractFernService from ....core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools +import starlette from ....core.route_args import get_route_args -from ..types.user import User -from .create_user_request import CreateUserRequest class AbstractUserService(AbstractFernService): @@ -55,14 +53,20 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_get_user(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_user) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "user_id": new_parameters.append(parameter.replace(default=fastapi.Path(...))) else: new_parameters.append(parameter) - setattr(cls.get_user, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_user, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_user) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> None: @@ -92,14 +96,20 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> None: def __init_create_user(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.create_user) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) else: new_parameters.append(parameter) - setattr(cls.create_user, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.create_user, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.create_user) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> User: diff --git a/seed/fastapi/multi-line-docs/resources/user/types/user.py b/seed/fastapi/multi-line-docs/resources/user/types/user.py index 55e6350d3e8..8aecb3dd95e 100644 --- a/seed/fastapi/multi-line-docs/resources/user/types/user.py +++ b/seed/fastapi/multi-line-docs/resources/user/types/user.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ....core.pydantic_utilities import UniversalBaseModel import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +import typing +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class User(UniversalBaseModel): @@ -31,7 +30,9 @@ class User(UniversalBaseModel): """ if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/multi-url-environment-no-default/core/abstract_fern_service.py b/seed/fastapi/multi-url-environment-no-default/core/abstract_fern_service.py index da7c8dc49c4..9966b4876da 100644 --- a/seed/fastapi/multi-url-environment-no-default/core/abstract_fern_service.py +++ b/seed/fastapi/multi-url-environment-no-default/core/abstract_fern_service.py @@ -7,5 +7,4 @@ class AbstractFernService(abc.ABC): @classmethod - def _init_fern(cls, router: fastapi.APIRouter) -> None: - ... + def _init_fern(cls, router: fastapi.APIRouter) -> None: ... diff --git a/seed/fastapi/multi-url-environment-no-default/core/datetime_utils.py b/seed/fastapi/multi-url-environment-no-default/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/fastapi/multi-url-environment-no-default/core/datetime_utils.py +++ b/seed/fastapi/multi-url-environment-no-default/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/fastapi/multi-url-environment-no-default/core/exceptions/__init__.py b/seed/fastapi/multi-url-environment-no-default/core/exceptions/__init__.py index 297d6e06f5f..dae4b8980c1 100644 --- a/seed/fastapi/multi-url-environment-no-default/core/exceptions/__init__.py +++ b/seed/fastapi/multi-url-environment-no-default/core/exceptions/__init__.py @@ -1,7 +1,11 @@ # This file was auto-generated by Fern from our API Definition. from .fern_http_exception import FernHTTPException -from .handlers import default_exception_handler, fern_http_exception_handler, http_exception_handler +from .handlers import ( + default_exception_handler, + fern_http_exception_handler, + http_exception_handler, +) from .unauthorized import UnauthorizedException __all__ = [ diff --git a/seed/fastapi/multi-url-environment-no-default/core/exceptions/fern_http_exception.py b/seed/fastapi/multi-url-environment-no-default/core/exceptions/fern_http_exception.py index bdf03862487..81610359a7f 100644 --- a/seed/fastapi/multi-url-environment-no-default/core/exceptions/fern_http_exception.py +++ b/seed/fastapi/multi-url-environment-no-default/core/exceptions/fern_http_exception.py @@ -1,14 +1,16 @@ # This file was auto-generated by Fern from our API Definition. import abc -import typing - import fastapi +import typing class FernHTTPException(abc.ABC, fastapi.HTTPException): def __init__( - self, status_code: int, name: typing.Optional[str] = None, content: typing.Optional[typing.Any] = None + self, + status_code: int, + name: typing.Optional[str] = None, + content: typing.Optional[typing.Any] = None, ): super().__init__(status_code=status_code) self.name = name @@ -17,4 +19,6 @@ def __init__( def to_json_response(self) -> fastapi.responses.JSONResponse: content = fastapi.encoders.jsonable_encoder(self.content, exclude_none=True) - return fastapi.responses.JSONResponse(content=content, status_code=self.status_code) + return fastapi.responses.JSONResponse( + content=content, status_code=self.status_code + ) diff --git a/seed/fastapi/multi-url-environment-no-default/core/exceptions/handlers.py b/seed/fastapi/multi-url-environment-no-default/core/exceptions/handlers.py index 6d8c4155c5a..ae1c2741f06 100644 --- a/seed/fastapi/multi-url-environment-no-default/core/exceptions/handlers.py +++ b/seed/fastapi/multi-url-environment-no-default/core/exceptions/handlers.py @@ -2,32 +2,49 @@ import logging -import fastapi import starlette import starlette.exceptions +import fastapi + from .fern_http_exception import FernHTTPException def fern_http_exception_handler( - request: fastapi.requests.Request, exc: FernHTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: FernHTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) return exc.to_json_response() def http_exception_handler( - request: fastapi.requests.Request, exc: starlette.exceptions.HTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: starlette.exceptions.HTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=exc.status_code, content=exc.detail).to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=exc.status_code, content=exc.detail + ).to_json_response() def default_exception_handler( - request: fastapi.requests.Request, exc: Exception, skip_log: bool = False + request: fastapi.requests.Request, + exc: Exception, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=500, content="Internal Server Error").to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=500, content="Internal Server Error" + ).to_json_response() diff --git a/seed/fastapi/multi-url-environment-no-default/core/pydantic_utilities.py b/seed/fastapi/multi-url-environment-no-default/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/fastapi/multi-url-environment-no-default/core/pydantic_utilities.py +++ b/seed/fastapi/multi-url-environment-no-default/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/fastapi/multi-url-environment-no-default/core/route_args.py b/seed/fastapi/multi-url-environment-no-default/core/route_args.py index 4228e2fe05d..bd940bf4ddd 100644 --- a/seed/fastapi/multi-url-environment-no-default/core/route_args.py +++ b/seed/fastapi/multi-url-environment-no-default/core/route_args.py @@ -20,9 +20,15 @@ class RouteArgs(typing_extensions.TypedDict): DEFAULT_ROUTE_ARGS = RouteArgs(openapi_extra=None, tags=None, include_in_schema=True) -def get_route_args(endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str) -> RouteArgs: - unwrapped = inspect.unwrap(endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY))) - route_args = typing.cast(RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS)) +def get_route_args( + endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str +) -> RouteArgs: + unwrapped = inspect.unwrap( + endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY)) + ) + route_args = typing.cast( + RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS) + ) if route_args["tags"] is None: return RouteArgs( openapi_extra=route_args["openapi_extra"], @@ -56,7 +62,11 @@ def decorator(endpoint_function: T) -> T: setattr( endpoint_function, FERN_CONFIG_KEY, - RouteArgs(openapi_extra=openapi_extra, tags=tags, include_in_schema=include_in_schema), + RouteArgs( + openapi_extra=openapi_extra, + tags=tags, + include_in_schema=include_in_schema, + ), ) return endpoint_function diff --git a/seed/fastapi/multi-url-environment-no-default/register.py b/seed/fastapi/multi-url-environment-no-default/register.py index 5772974509f..36978c5669a 100644 --- a/seed/fastapi/multi-url-environment-no-default/register.py +++ b/seed/fastapi/multi-url-environment-no-default/register.py @@ -1,20 +1,20 @@ # This file was auto-generated by Fern from our API Definition. -import glob -import importlib -import os -import types -import typing - import fastapi -import starlette.exceptions -from fastapi import params - -from .core.abstract_fern_service import AbstractFernService -from .core.exceptions import default_exception_handler, fern_http_exception_handler, http_exception_handler -from .core.exceptions.fern_http_exception import FernHTTPException from .resources.ec_2.service.service import AbstractEc2Service from .resources.s_3.service.service import AbstractS3Service +import typing +from fastapi import params +from .core.exceptions.fern_http_exception import FernHTTPException +from .core.exceptions import fern_http_exception_handler +import starlette.exceptions +from .core.exceptions import http_exception_handler +from .core.exceptions import default_exception_handler +from .core.abstract_fern_service import AbstractFernService +import types +import os +import glob +import importlib def register( @@ -22,13 +22,15 @@ def register( *, ec_2: AbstractEc2Service, s_3: AbstractS3Service, - dependencies: typing.Optional[typing.Sequence[params.Depends]] = None + dependencies: typing.Optional[typing.Sequence[params.Depends]] = None, ) -> None: _app.include_router(__register_service(ec_2), dependencies=dependencies) _app.include_router(__register_service(s_3), dependencies=dependencies) _app.add_exception_handler(FernHTTPException, fern_http_exception_handler) # type: ignore - _app.add_exception_handler(starlette.exceptions.HTTPException, http_exception_handler) # type: ignore + _app.add_exception_handler( + starlette.exceptions.HTTPException, http_exception_handler + ) # type: ignore _app.add_exception_handler(Exception, default_exception_handler) # type: ignore @@ -40,7 +42,9 @@ def __register_service(service: AbstractFernService) -> fastapi.APIRouter: def register_validators(module: types.ModuleType) -> None: validators_directory: str = os.path.dirname(module.__file__) # type: ignore - for path in glob.glob(os.path.join(validators_directory, "**/*.py"), recursive=True): + for path in glob.glob( + os.path.join(validators_directory, "**/*.py"), recursive=True + ): if os.path.isfile(path): relative_path = os.path.relpath(path, start=validators_directory) module_path = ".".join([module.__name__] + relative_path[:-3].split("/")) diff --git a/seed/fastapi/multi-url-environment-no-default/resources/ec_2/service/boot_instance_request.py b/seed/fastapi/multi-url-environment-no-default/resources/ec_2/service/boot_instance_request.py index a79db22ba6b..3445164ad1c 100644 --- a/seed/fastapi/multi-url-environment-no-default/resources/ec_2/service/boot_instance_request.py +++ b/seed/fastapi/multi-url-environment-no-default/resources/ec_2/service/boot_instance_request.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class BootInstanceRequest(UniversalBaseModel): size: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/multi-url-environment-no-default/resources/ec_2/service/service.py b/seed/fastapi/multi-url-environment-no-default/resources/ec_2/service/service.py index 1582fba7163..9b171b4c89b 100644 --- a/seed/fastapi/multi-url-environment-no-default/resources/ec_2/service/service.py +++ b/seed/fastapi/multi-url-environment-no-default/resources/ec_2/service/service.py @@ -1,19 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.abstract_fern_service import AbstractFernService +from .boot_instance_request import BootInstanceRequest +from ....security import ApiAuth import abc -import functools +import fastapi import inspect -import logging import typing - -import fastapi -import starlette - -from ....core.abstract_fern_service import AbstractFernService +from ....security import FernAuth from ....core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools +import starlette from ....core.route_args import get_route_args -from ....security import ApiAuth, FernAuth -from .boot_instance_request import BootInstanceRequest class AbstractEc2Service(AbstractFernService): @@ -26,8 +25,7 @@ class AbstractEc2Service(AbstractFernService): """ @abc.abstractmethod - def boot_instance(self, *, body: BootInstanceRequest, auth: ApiAuth) -> None: - ... + def boot_instance(self, *, body: BootInstanceRequest, auth: ApiAuth) -> None: ... """ Below are internal methods used by Fern to register your implementation. @@ -42,16 +40,24 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_boot_instance(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.boot_instance) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.boot_instance, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.boot_instance, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.boot_instance) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> None: diff --git a/seed/fastapi/multi-url-environment-no-default/resources/s_3/service/get_presigned_url_request.py b/seed/fastapi/multi-url-environment-no-default/resources/s_3/service/get_presigned_url_request.py index 98032304dba..6170e8a4774 100644 --- a/seed/fastapi/multi-url-environment-no-default/resources/s_3/service/get_presigned_url_request.py +++ b/seed/fastapi/multi-url-environment-no-default/resources/s_3/service/get_presigned_url_request.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ....core.pydantic_utilities import UniversalBaseModel import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class GetPresignedUrlRequest(UniversalBaseModel): s_3_key: str = pydantic.Field(alias="s3Key") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/multi-url-environment-no-default/resources/s_3/service/service.py b/seed/fastapi/multi-url-environment-no-default/resources/s_3/service/service.py index 06399dcee56..3f379b76f5e 100644 --- a/seed/fastapi/multi-url-environment-no-default/resources/s_3/service/service.py +++ b/seed/fastapi/multi-url-environment-no-default/resources/s_3/service/service.py @@ -1,18 +1,17 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.abstract_fern_service import AbstractFernService +from .get_presigned_url_request import GetPresignedUrlRequest +from ....security import ApiAuth import abc -import functools +import fastapi import inspect -import logging import typing - -import fastapi - -from ....core.abstract_fern_service import AbstractFernService +from ....security import FernAuth from ....core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools from ....core.route_args import get_route_args -from ....security import ApiAuth, FernAuth -from .get_presigned_url_request import GetPresignedUrlRequest class AbstractS3Service(AbstractFernService): @@ -25,8 +24,9 @@ class AbstractS3Service(AbstractFernService): """ @abc.abstractmethod - def get_presigned_url(self, *, body: GetPresignedUrlRequest, auth: ApiAuth) -> str: - ... + def get_presigned_url( + self, *, body: GetPresignedUrlRequest, auth: ApiAuth + ) -> str: ... """ Below are internal methods used by Fern to register your implementation. @@ -41,16 +41,24 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_get_presigned_url(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_presigned_url) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_presigned_url, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_presigned_url, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_presigned_url) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> str: diff --git a/seed/fastapi/multi-url-environment-no-default/security.py b/seed/fastapi/multi-url-environment-no-default/security.py index bab014441e1..4ccabc21106 100644 --- a/seed/fastapi/multi-url-environment-no-default/security.py +++ b/seed/fastapi/multi-url-environment-no-default/security.py @@ -1,8 +1,8 @@ # This file was auto-generated by Fern from our API Definition. +from .core.security.bearer import BearerToken import fastapi - -from .core.security.bearer import BearerToken, HTTPBearer +from .core.security.bearer import HTTPBearer ApiAuth = BearerToken diff --git a/seed/fastapi/multi-url-environment/core/abstract_fern_service.py b/seed/fastapi/multi-url-environment/core/abstract_fern_service.py index da7c8dc49c4..9966b4876da 100644 --- a/seed/fastapi/multi-url-environment/core/abstract_fern_service.py +++ b/seed/fastapi/multi-url-environment/core/abstract_fern_service.py @@ -7,5 +7,4 @@ class AbstractFernService(abc.ABC): @classmethod - def _init_fern(cls, router: fastapi.APIRouter) -> None: - ... + def _init_fern(cls, router: fastapi.APIRouter) -> None: ... diff --git a/seed/fastapi/multi-url-environment/core/datetime_utils.py b/seed/fastapi/multi-url-environment/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/fastapi/multi-url-environment/core/datetime_utils.py +++ b/seed/fastapi/multi-url-environment/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/fastapi/multi-url-environment/core/exceptions/__init__.py b/seed/fastapi/multi-url-environment/core/exceptions/__init__.py index 297d6e06f5f..dae4b8980c1 100644 --- a/seed/fastapi/multi-url-environment/core/exceptions/__init__.py +++ b/seed/fastapi/multi-url-environment/core/exceptions/__init__.py @@ -1,7 +1,11 @@ # This file was auto-generated by Fern from our API Definition. from .fern_http_exception import FernHTTPException -from .handlers import default_exception_handler, fern_http_exception_handler, http_exception_handler +from .handlers import ( + default_exception_handler, + fern_http_exception_handler, + http_exception_handler, +) from .unauthorized import UnauthorizedException __all__ = [ diff --git a/seed/fastapi/multi-url-environment/core/exceptions/fern_http_exception.py b/seed/fastapi/multi-url-environment/core/exceptions/fern_http_exception.py index bdf03862487..81610359a7f 100644 --- a/seed/fastapi/multi-url-environment/core/exceptions/fern_http_exception.py +++ b/seed/fastapi/multi-url-environment/core/exceptions/fern_http_exception.py @@ -1,14 +1,16 @@ # This file was auto-generated by Fern from our API Definition. import abc -import typing - import fastapi +import typing class FernHTTPException(abc.ABC, fastapi.HTTPException): def __init__( - self, status_code: int, name: typing.Optional[str] = None, content: typing.Optional[typing.Any] = None + self, + status_code: int, + name: typing.Optional[str] = None, + content: typing.Optional[typing.Any] = None, ): super().__init__(status_code=status_code) self.name = name @@ -17,4 +19,6 @@ def __init__( def to_json_response(self) -> fastapi.responses.JSONResponse: content = fastapi.encoders.jsonable_encoder(self.content, exclude_none=True) - return fastapi.responses.JSONResponse(content=content, status_code=self.status_code) + return fastapi.responses.JSONResponse( + content=content, status_code=self.status_code + ) diff --git a/seed/fastapi/multi-url-environment/core/exceptions/handlers.py b/seed/fastapi/multi-url-environment/core/exceptions/handlers.py index 6d8c4155c5a..ae1c2741f06 100644 --- a/seed/fastapi/multi-url-environment/core/exceptions/handlers.py +++ b/seed/fastapi/multi-url-environment/core/exceptions/handlers.py @@ -2,32 +2,49 @@ import logging -import fastapi import starlette import starlette.exceptions +import fastapi + from .fern_http_exception import FernHTTPException def fern_http_exception_handler( - request: fastapi.requests.Request, exc: FernHTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: FernHTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) return exc.to_json_response() def http_exception_handler( - request: fastapi.requests.Request, exc: starlette.exceptions.HTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: starlette.exceptions.HTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=exc.status_code, content=exc.detail).to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=exc.status_code, content=exc.detail + ).to_json_response() def default_exception_handler( - request: fastapi.requests.Request, exc: Exception, skip_log: bool = False + request: fastapi.requests.Request, + exc: Exception, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=500, content="Internal Server Error").to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=500, content="Internal Server Error" + ).to_json_response() diff --git a/seed/fastapi/multi-url-environment/core/pydantic_utilities.py b/seed/fastapi/multi-url-environment/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/fastapi/multi-url-environment/core/pydantic_utilities.py +++ b/seed/fastapi/multi-url-environment/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/fastapi/multi-url-environment/core/route_args.py b/seed/fastapi/multi-url-environment/core/route_args.py index 4228e2fe05d..bd940bf4ddd 100644 --- a/seed/fastapi/multi-url-environment/core/route_args.py +++ b/seed/fastapi/multi-url-environment/core/route_args.py @@ -20,9 +20,15 @@ class RouteArgs(typing_extensions.TypedDict): DEFAULT_ROUTE_ARGS = RouteArgs(openapi_extra=None, tags=None, include_in_schema=True) -def get_route_args(endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str) -> RouteArgs: - unwrapped = inspect.unwrap(endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY))) - route_args = typing.cast(RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS)) +def get_route_args( + endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str +) -> RouteArgs: + unwrapped = inspect.unwrap( + endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY)) + ) + route_args = typing.cast( + RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS) + ) if route_args["tags"] is None: return RouteArgs( openapi_extra=route_args["openapi_extra"], @@ -56,7 +62,11 @@ def decorator(endpoint_function: T) -> T: setattr( endpoint_function, FERN_CONFIG_KEY, - RouteArgs(openapi_extra=openapi_extra, tags=tags, include_in_schema=include_in_schema), + RouteArgs( + openapi_extra=openapi_extra, + tags=tags, + include_in_schema=include_in_schema, + ), ) return endpoint_function diff --git a/seed/fastapi/multi-url-environment/register.py b/seed/fastapi/multi-url-environment/register.py index 5772974509f..36978c5669a 100644 --- a/seed/fastapi/multi-url-environment/register.py +++ b/seed/fastapi/multi-url-environment/register.py @@ -1,20 +1,20 @@ # This file was auto-generated by Fern from our API Definition. -import glob -import importlib -import os -import types -import typing - import fastapi -import starlette.exceptions -from fastapi import params - -from .core.abstract_fern_service import AbstractFernService -from .core.exceptions import default_exception_handler, fern_http_exception_handler, http_exception_handler -from .core.exceptions.fern_http_exception import FernHTTPException from .resources.ec_2.service.service import AbstractEc2Service from .resources.s_3.service.service import AbstractS3Service +import typing +from fastapi import params +from .core.exceptions.fern_http_exception import FernHTTPException +from .core.exceptions import fern_http_exception_handler +import starlette.exceptions +from .core.exceptions import http_exception_handler +from .core.exceptions import default_exception_handler +from .core.abstract_fern_service import AbstractFernService +import types +import os +import glob +import importlib def register( @@ -22,13 +22,15 @@ def register( *, ec_2: AbstractEc2Service, s_3: AbstractS3Service, - dependencies: typing.Optional[typing.Sequence[params.Depends]] = None + dependencies: typing.Optional[typing.Sequence[params.Depends]] = None, ) -> None: _app.include_router(__register_service(ec_2), dependencies=dependencies) _app.include_router(__register_service(s_3), dependencies=dependencies) _app.add_exception_handler(FernHTTPException, fern_http_exception_handler) # type: ignore - _app.add_exception_handler(starlette.exceptions.HTTPException, http_exception_handler) # type: ignore + _app.add_exception_handler( + starlette.exceptions.HTTPException, http_exception_handler + ) # type: ignore _app.add_exception_handler(Exception, default_exception_handler) # type: ignore @@ -40,7 +42,9 @@ def __register_service(service: AbstractFernService) -> fastapi.APIRouter: def register_validators(module: types.ModuleType) -> None: validators_directory: str = os.path.dirname(module.__file__) # type: ignore - for path in glob.glob(os.path.join(validators_directory, "**/*.py"), recursive=True): + for path in glob.glob( + os.path.join(validators_directory, "**/*.py"), recursive=True + ): if os.path.isfile(path): relative_path = os.path.relpath(path, start=validators_directory) module_path = ".".join([module.__name__] + relative_path[:-3].split("/")) diff --git a/seed/fastapi/multi-url-environment/resources/ec_2/service/boot_instance_request.py b/seed/fastapi/multi-url-environment/resources/ec_2/service/boot_instance_request.py index a79db22ba6b..3445164ad1c 100644 --- a/seed/fastapi/multi-url-environment/resources/ec_2/service/boot_instance_request.py +++ b/seed/fastapi/multi-url-environment/resources/ec_2/service/boot_instance_request.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class BootInstanceRequest(UniversalBaseModel): size: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/multi-url-environment/resources/ec_2/service/service.py b/seed/fastapi/multi-url-environment/resources/ec_2/service/service.py index 1582fba7163..9b171b4c89b 100644 --- a/seed/fastapi/multi-url-environment/resources/ec_2/service/service.py +++ b/seed/fastapi/multi-url-environment/resources/ec_2/service/service.py @@ -1,19 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.abstract_fern_service import AbstractFernService +from .boot_instance_request import BootInstanceRequest +from ....security import ApiAuth import abc -import functools +import fastapi import inspect -import logging import typing - -import fastapi -import starlette - -from ....core.abstract_fern_service import AbstractFernService +from ....security import FernAuth from ....core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools +import starlette from ....core.route_args import get_route_args -from ....security import ApiAuth, FernAuth -from .boot_instance_request import BootInstanceRequest class AbstractEc2Service(AbstractFernService): @@ -26,8 +25,7 @@ class AbstractEc2Service(AbstractFernService): """ @abc.abstractmethod - def boot_instance(self, *, body: BootInstanceRequest, auth: ApiAuth) -> None: - ... + def boot_instance(self, *, body: BootInstanceRequest, auth: ApiAuth) -> None: ... """ Below are internal methods used by Fern to register your implementation. @@ -42,16 +40,24 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_boot_instance(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.boot_instance) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.boot_instance, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.boot_instance, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.boot_instance) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> None: diff --git a/seed/fastapi/multi-url-environment/resources/s_3/service/get_presigned_url_request.py b/seed/fastapi/multi-url-environment/resources/s_3/service/get_presigned_url_request.py index 98032304dba..6170e8a4774 100644 --- a/seed/fastapi/multi-url-environment/resources/s_3/service/get_presigned_url_request.py +++ b/seed/fastapi/multi-url-environment/resources/s_3/service/get_presigned_url_request.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ....core.pydantic_utilities import UniversalBaseModel import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class GetPresignedUrlRequest(UniversalBaseModel): s_3_key: str = pydantic.Field(alias="s3Key") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/multi-url-environment/resources/s_3/service/service.py b/seed/fastapi/multi-url-environment/resources/s_3/service/service.py index 06399dcee56..3f379b76f5e 100644 --- a/seed/fastapi/multi-url-environment/resources/s_3/service/service.py +++ b/seed/fastapi/multi-url-environment/resources/s_3/service/service.py @@ -1,18 +1,17 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.abstract_fern_service import AbstractFernService +from .get_presigned_url_request import GetPresignedUrlRequest +from ....security import ApiAuth import abc -import functools +import fastapi import inspect -import logging import typing - -import fastapi - -from ....core.abstract_fern_service import AbstractFernService +from ....security import FernAuth from ....core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools from ....core.route_args import get_route_args -from ....security import ApiAuth, FernAuth -from .get_presigned_url_request import GetPresignedUrlRequest class AbstractS3Service(AbstractFernService): @@ -25,8 +24,9 @@ class AbstractS3Service(AbstractFernService): """ @abc.abstractmethod - def get_presigned_url(self, *, body: GetPresignedUrlRequest, auth: ApiAuth) -> str: - ... + def get_presigned_url( + self, *, body: GetPresignedUrlRequest, auth: ApiAuth + ) -> str: ... """ Below are internal methods used by Fern to register your implementation. @@ -41,16 +41,24 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_get_presigned_url(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_presigned_url) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_presigned_url, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_presigned_url, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_presigned_url) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> str: diff --git a/seed/fastapi/multi-url-environment/security.py b/seed/fastapi/multi-url-environment/security.py index bab014441e1..4ccabc21106 100644 --- a/seed/fastapi/multi-url-environment/security.py +++ b/seed/fastapi/multi-url-environment/security.py @@ -1,8 +1,8 @@ # This file was auto-generated by Fern from our API Definition. +from .core.security.bearer import BearerToken import fastapi - -from .core.security.bearer import BearerToken, HTTPBearer +from .core.security.bearer import HTTPBearer ApiAuth = BearerToken diff --git a/seed/fastapi/no-environment/core/abstract_fern_service.py b/seed/fastapi/no-environment/core/abstract_fern_service.py index da7c8dc49c4..9966b4876da 100644 --- a/seed/fastapi/no-environment/core/abstract_fern_service.py +++ b/seed/fastapi/no-environment/core/abstract_fern_service.py @@ -7,5 +7,4 @@ class AbstractFernService(abc.ABC): @classmethod - def _init_fern(cls, router: fastapi.APIRouter) -> None: - ... + def _init_fern(cls, router: fastapi.APIRouter) -> None: ... diff --git a/seed/fastapi/no-environment/core/datetime_utils.py b/seed/fastapi/no-environment/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/fastapi/no-environment/core/datetime_utils.py +++ b/seed/fastapi/no-environment/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/fastapi/no-environment/core/exceptions/__init__.py b/seed/fastapi/no-environment/core/exceptions/__init__.py index 297d6e06f5f..dae4b8980c1 100644 --- a/seed/fastapi/no-environment/core/exceptions/__init__.py +++ b/seed/fastapi/no-environment/core/exceptions/__init__.py @@ -1,7 +1,11 @@ # This file was auto-generated by Fern from our API Definition. from .fern_http_exception import FernHTTPException -from .handlers import default_exception_handler, fern_http_exception_handler, http_exception_handler +from .handlers import ( + default_exception_handler, + fern_http_exception_handler, + http_exception_handler, +) from .unauthorized import UnauthorizedException __all__ = [ diff --git a/seed/fastapi/no-environment/core/exceptions/fern_http_exception.py b/seed/fastapi/no-environment/core/exceptions/fern_http_exception.py index bdf03862487..81610359a7f 100644 --- a/seed/fastapi/no-environment/core/exceptions/fern_http_exception.py +++ b/seed/fastapi/no-environment/core/exceptions/fern_http_exception.py @@ -1,14 +1,16 @@ # This file was auto-generated by Fern from our API Definition. import abc -import typing - import fastapi +import typing class FernHTTPException(abc.ABC, fastapi.HTTPException): def __init__( - self, status_code: int, name: typing.Optional[str] = None, content: typing.Optional[typing.Any] = None + self, + status_code: int, + name: typing.Optional[str] = None, + content: typing.Optional[typing.Any] = None, ): super().__init__(status_code=status_code) self.name = name @@ -17,4 +19,6 @@ def __init__( def to_json_response(self) -> fastapi.responses.JSONResponse: content = fastapi.encoders.jsonable_encoder(self.content, exclude_none=True) - return fastapi.responses.JSONResponse(content=content, status_code=self.status_code) + return fastapi.responses.JSONResponse( + content=content, status_code=self.status_code + ) diff --git a/seed/fastapi/no-environment/core/exceptions/handlers.py b/seed/fastapi/no-environment/core/exceptions/handlers.py index 6d8c4155c5a..ae1c2741f06 100644 --- a/seed/fastapi/no-environment/core/exceptions/handlers.py +++ b/seed/fastapi/no-environment/core/exceptions/handlers.py @@ -2,32 +2,49 @@ import logging -import fastapi import starlette import starlette.exceptions +import fastapi + from .fern_http_exception import FernHTTPException def fern_http_exception_handler( - request: fastapi.requests.Request, exc: FernHTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: FernHTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) return exc.to_json_response() def http_exception_handler( - request: fastapi.requests.Request, exc: starlette.exceptions.HTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: starlette.exceptions.HTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=exc.status_code, content=exc.detail).to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=exc.status_code, content=exc.detail + ).to_json_response() def default_exception_handler( - request: fastapi.requests.Request, exc: Exception, skip_log: bool = False + request: fastapi.requests.Request, + exc: Exception, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=500, content="Internal Server Error").to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=500, content="Internal Server Error" + ).to_json_response() diff --git a/seed/fastapi/no-environment/core/pydantic_utilities.py b/seed/fastapi/no-environment/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/fastapi/no-environment/core/pydantic_utilities.py +++ b/seed/fastapi/no-environment/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/fastapi/no-environment/core/route_args.py b/seed/fastapi/no-environment/core/route_args.py index 4228e2fe05d..bd940bf4ddd 100644 --- a/seed/fastapi/no-environment/core/route_args.py +++ b/seed/fastapi/no-environment/core/route_args.py @@ -20,9 +20,15 @@ class RouteArgs(typing_extensions.TypedDict): DEFAULT_ROUTE_ARGS = RouteArgs(openapi_extra=None, tags=None, include_in_schema=True) -def get_route_args(endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str) -> RouteArgs: - unwrapped = inspect.unwrap(endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY))) - route_args = typing.cast(RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS)) +def get_route_args( + endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str +) -> RouteArgs: + unwrapped = inspect.unwrap( + endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY)) + ) + route_args = typing.cast( + RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS) + ) if route_args["tags"] is None: return RouteArgs( openapi_extra=route_args["openapi_extra"], @@ -56,7 +62,11 @@ def decorator(endpoint_function: T) -> T: setattr( endpoint_function, FERN_CONFIG_KEY, - RouteArgs(openapi_extra=openapi_extra, tags=tags, include_in_schema=include_in_schema), + RouteArgs( + openapi_extra=openapi_extra, + tags=tags, + include_in_schema=include_in_schema, + ), ) return endpoint_function diff --git a/seed/fastapi/no-environment/register.py b/seed/fastapi/no-environment/register.py index a8d6d7007ab..02e06d071ed 100644 --- a/seed/fastapi/no-environment/register.py +++ b/seed/fastapi/no-environment/register.py @@ -1,31 +1,33 @@ # This file was auto-generated by Fern from our API Definition. -import glob -import importlib -import os -import types -import typing - import fastapi -import starlette.exceptions +from .resources.dummy.service.service import AbstractDummyService +import typing from fastapi import params - -from .core.abstract_fern_service import AbstractFernService -from .core.exceptions import default_exception_handler, fern_http_exception_handler, http_exception_handler from .core.exceptions.fern_http_exception import FernHTTPException -from .resources.dummy.service.service import AbstractDummyService +from .core.exceptions import fern_http_exception_handler +import starlette.exceptions +from .core.exceptions import http_exception_handler +from .core.exceptions import default_exception_handler +from .core.abstract_fern_service import AbstractFernService +import types +import os +import glob +import importlib def register( _app: fastapi.FastAPI, *, dummy: AbstractDummyService, - dependencies: typing.Optional[typing.Sequence[params.Depends]] = None + dependencies: typing.Optional[typing.Sequence[params.Depends]] = None, ) -> None: _app.include_router(__register_service(dummy), dependencies=dependencies) _app.add_exception_handler(FernHTTPException, fern_http_exception_handler) # type: ignore - _app.add_exception_handler(starlette.exceptions.HTTPException, http_exception_handler) # type: ignore + _app.add_exception_handler( + starlette.exceptions.HTTPException, http_exception_handler + ) # type: ignore _app.add_exception_handler(Exception, default_exception_handler) # type: ignore @@ -37,7 +39,9 @@ def __register_service(service: AbstractFernService) -> fastapi.APIRouter: def register_validators(module: types.ModuleType) -> None: validators_directory: str = os.path.dirname(module.__file__) # type: ignore - for path in glob.glob(os.path.join(validators_directory, "**/*.py"), recursive=True): + for path in glob.glob( + os.path.join(validators_directory, "**/*.py"), recursive=True + ): if os.path.isfile(path): relative_path = os.path.relpath(path, start=validators_directory) module_path = ".".join([module.__name__] + relative_path[:-3].split("/")) diff --git a/seed/fastapi/no-environment/resources/dummy/service/service.py b/seed/fastapi/no-environment/resources/dummy/service/service.py index f7ebe94cb58..59d060eed53 100644 --- a/seed/fastapi/no-environment/resources/dummy/service/service.py +++ b/seed/fastapi/no-environment/resources/dummy/service/service.py @@ -1,17 +1,16 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.abstract_fern_service import AbstractFernService +from ....security import ApiAuth import abc -import functools +import fastapi import inspect -import logging import typing - -import fastapi - -from ....core.abstract_fern_service import AbstractFernService +from ....security import FernAuth from ....core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools from ....core.route_args import get_route_args -from ....security import ApiAuth, FernAuth class AbstractDummyService(AbstractFernService): @@ -24,8 +23,7 @@ class AbstractDummyService(AbstractFernService): """ @abc.abstractmethod - def get_dummy(self, *, auth: ApiAuth) -> str: - ... + def get_dummy(self, *, auth: ApiAuth) -> str: ... """ Below are internal methods used by Fern to register your implementation. @@ -40,14 +38,22 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_get_dummy(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_dummy) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_dummy, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_dummy, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_dummy) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> str: diff --git a/seed/fastapi/no-environment/security.py b/seed/fastapi/no-environment/security.py index bab014441e1..4ccabc21106 100644 --- a/seed/fastapi/no-environment/security.py +++ b/seed/fastapi/no-environment/security.py @@ -1,8 +1,8 @@ # This file was auto-generated by Fern from our API Definition. +from .core.security.bearer import BearerToken import fastapi - -from .core.security.bearer import BearerToken, HTTPBearer +from .core.security.bearer import HTTPBearer ApiAuth = BearerToken diff --git a/seed/fastapi/oauth-client-credentials-default/core/abstract_fern_service.py b/seed/fastapi/oauth-client-credentials-default/core/abstract_fern_service.py index da7c8dc49c4..9966b4876da 100644 --- a/seed/fastapi/oauth-client-credentials-default/core/abstract_fern_service.py +++ b/seed/fastapi/oauth-client-credentials-default/core/abstract_fern_service.py @@ -7,5 +7,4 @@ class AbstractFernService(abc.ABC): @classmethod - def _init_fern(cls, router: fastapi.APIRouter) -> None: - ... + def _init_fern(cls, router: fastapi.APIRouter) -> None: ... diff --git a/seed/fastapi/oauth-client-credentials-default/core/datetime_utils.py b/seed/fastapi/oauth-client-credentials-default/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/fastapi/oauth-client-credentials-default/core/datetime_utils.py +++ b/seed/fastapi/oauth-client-credentials-default/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/fastapi/oauth-client-credentials-default/core/exceptions/__init__.py b/seed/fastapi/oauth-client-credentials-default/core/exceptions/__init__.py index 297d6e06f5f..dae4b8980c1 100644 --- a/seed/fastapi/oauth-client-credentials-default/core/exceptions/__init__.py +++ b/seed/fastapi/oauth-client-credentials-default/core/exceptions/__init__.py @@ -1,7 +1,11 @@ # This file was auto-generated by Fern from our API Definition. from .fern_http_exception import FernHTTPException -from .handlers import default_exception_handler, fern_http_exception_handler, http_exception_handler +from .handlers import ( + default_exception_handler, + fern_http_exception_handler, + http_exception_handler, +) from .unauthorized import UnauthorizedException __all__ = [ diff --git a/seed/fastapi/oauth-client-credentials-default/core/exceptions/fern_http_exception.py b/seed/fastapi/oauth-client-credentials-default/core/exceptions/fern_http_exception.py index bdf03862487..81610359a7f 100644 --- a/seed/fastapi/oauth-client-credentials-default/core/exceptions/fern_http_exception.py +++ b/seed/fastapi/oauth-client-credentials-default/core/exceptions/fern_http_exception.py @@ -1,14 +1,16 @@ # This file was auto-generated by Fern from our API Definition. import abc -import typing - import fastapi +import typing class FernHTTPException(abc.ABC, fastapi.HTTPException): def __init__( - self, status_code: int, name: typing.Optional[str] = None, content: typing.Optional[typing.Any] = None + self, + status_code: int, + name: typing.Optional[str] = None, + content: typing.Optional[typing.Any] = None, ): super().__init__(status_code=status_code) self.name = name @@ -17,4 +19,6 @@ def __init__( def to_json_response(self) -> fastapi.responses.JSONResponse: content = fastapi.encoders.jsonable_encoder(self.content, exclude_none=True) - return fastapi.responses.JSONResponse(content=content, status_code=self.status_code) + return fastapi.responses.JSONResponse( + content=content, status_code=self.status_code + ) diff --git a/seed/fastapi/oauth-client-credentials-default/core/exceptions/handlers.py b/seed/fastapi/oauth-client-credentials-default/core/exceptions/handlers.py index 6d8c4155c5a..ae1c2741f06 100644 --- a/seed/fastapi/oauth-client-credentials-default/core/exceptions/handlers.py +++ b/seed/fastapi/oauth-client-credentials-default/core/exceptions/handlers.py @@ -2,32 +2,49 @@ import logging -import fastapi import starlette import starlette.exceptions +import fastapi + from .fern_http_exception import FernHTTPException def fern_http_exception_handler( - request: fastapi.requests.Request, exc: FernHTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: FernHTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) return exc.to_json_response() def http_exception_handler( - request: fastapi.requests.Request, exc: starlette.exceptions.HTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: starlette.exceptions.HTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=exc.status_code, content=exc.detail).to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=exc.status_code, content=exc.detail + ).to_json_response() def default_exception_handler( - request: fastapi.requests.Request, exc: Exception, skip_log: bool = False + request: fastapi.requests.Request, + exc: Exception, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=500, content="Internal Server Error").to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=500, content="Internal Server Error" + ).to_json_response() diff --git a/seed/fastapi/oauth-client-credentials-default/core/pydantic_utilities.py b/seed/fastapi/oauth-client-credentials-default/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/fastapi/oauth-client-credentials-default/core/pydantic_utilities.py +++ b/seed/fastapi/oauth-client-credentials-default/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/fastapi/oauth-client-credentials-default/core/route_args.py b/seed/fastapi/oauth-client-credentials-default/core/route_args.py index 4228e2fe05d..bd940bf4ddd 100644 --- a/seed/fastapi/oauth-client-credentials-default/core/route_args.py +++ b/seed/fastapi/oauth-client-credentials-default/core/route_args.py @@ -20,9 +20,15 @@ class RouteArgs(typing_extensions.TypedDict): DEFAULT_ROUTE_ARGS = RouteArgs(openapi_extra=None, tags=None, include_in_schema=True) -def get_route_args(endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str) -> RouteArgs: - unwrapped = inspect.unwrap(endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY))) - route_args = typing.cast(RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS)) +def get_route_args( + endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str +) -> RouteArgs: + unwrapped = inspect.unwrap( + endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY)) + ) + route_args = typing.cast( + RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS) + ) if route_args["tags"] is None: return RouteArgs( openapi_extra=route_args["openapi_extra"], @@ -56,7 +62,11 @@ def decorator(endpoint_function: T) -> T: setattr( endpoint_function, FERN_CONFIG_KEY, - RouteArgs(openapi_extra=openapi_extra, tags=tags, include_in_schema=include_in_schema), + RouteArgs( + openapi_extra=openapi_extra, + tags=tags, + include_in_schema=include_in_schema, + ), ) return endpoint_function diff --git a/seed/fastapi/oauth-client-credentials-default/register.py b/seed/fastapi/oauth-client-credentials-default/register.py index 1f622e78ae3..43cd5cf4660 100644 --- a/seed/fastapi/oauth-client-credentials-default/register.py +++ b/seed/fastapi/oauth-client-credentials-default/register.py @@ -1,31 +1,33 @@ # This file was auto-generated by Fern from our API Definition. -import glob -import importlib -import os -import types -import typing - import fastapi -import starlette.exceptions +from .resources.auth.service.service import AbstractAuthService +import typing from fastapi import params - -from .core.abstract_fern_service import AbstractFernService -from .core.exceptions import default_exception_handler, fern_http_exception_handler, http_exception_handler from .core.exceptions.fern_http_exception import FernHTTPException -from .resources.auth.service.service import AbstractAuthService +from .core.exceptions import fern_http_exception_handler +import starlette.exceptions +from .core.exceptions import http_exception_handler +from .core.exceptions import default_exception_handler +from .core.abstract_fern_service import AbstractFernService +import types +import os +import glob +import importlib def register( _app: fastapi.FastAPI, *, auth: AbstractAuthService, - dependencies: typing.Optional[typing.Sequence[params.Depends]] = None + dependencies: typing.Optional[typing.Sequence[params.Depends]] = None, ) -> None: _app.include_router(__register_service(auth), dependencies=dependencies) _app.add_exception_handler(FernHTTPException, fern_http_exception_handler) # type: ignore - _app.add_exception_handler(starlette.exceptions.HTTPException, http_exception_handler) # type: ignore + _app.add_exception_handler( + starlette.exceptions.HTTPException, http_exception_handler + ) # type: ignore _app.add_exception_handler(Exception, default_exception_handler) # type: ignore @@ -37,7 +39,9 @@ def __register_service(service: AbstractFernService) -> fastapi.APIRouter: def register_validators(module: types.ModuleType) -> None: validators_directory: str = os.path.dirname(module.__file__) # type: ignore - for path in glob.glob(os.path.join(validators_directory, "**/*.py"), recursive=True): + for path in glob.glob( + os.path.join(validators_directory, "**/*.py"), recursive=True + ): if os.path.isfile(path): relative_path = os.path.relpath(path, start=validators_directory) module_path = ".".join([module.__name__] + relative_path[:-3].split("/")) diff --git a/seed/fastapi/oauth-client-credentials-default/resources/auth/service/get_token_request.py b/seed/fastapi/oauth-client-credentials-default/resources/auth/service/get_token_request.py index 34518876da2..db414d34232 100644 --- a/seed/fastapi/oauth-client-credentials-default/resources/auth/service/get_token_request.py +++ b/seed/fastapi/oauth-client-credentials-default/resources/auth/service/get_token_request.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class GetTokenRequest(UniversalBaseModel): client_id: str @@ -13,7 +12,9 @@ class GetTokenRequest(UniversalBaseModel): grant_type: typing.Literal["client_credentials"] = "client_credentials" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/oauth-client-credentials-default/resources/auth/service/service.py b/seed/fastapi/oauth-client-credentials-default/resources/auth/service/service.py index 9d203585833..0a0cd7a07a1 100644 --- a/seed/fastapi/oauth-client-credentials-default/resources/auth/service/service.py +++ b/seed/fastapi/oauth-client-credentials-default/resources/auth/service/service.py @@ -1,18 +1,16 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.abstract_fern_service import AbstractFernService +from .get_token_request import GetTokenRequest +from ..types.token_response import TokenResponse import abc -import functools +import fastapi import inspect -import logging import typing - -import fastapi - -from ....core.abstract_fern_service import AbstractFernService from ....core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools from ....core.route_args import get_route_args -from ..types.token_response import TokenResponse -from .get_token_request import GetTokenRequest class AbstractAuthService(AbstractFernService): @@ -25,8 +23,7 @@ class AbstractAuthService(AbstractFernService): """ @abc.abstractmethod - def get_token(self, *, body: GetTokenRequest) -> TokenResponse: - ... + def get_token(self, *, body: GetTokenRequest) -> TokenResponse: ... """ Below are internal methods used by Fern to register your implementation. @@ -41,14 +38,20 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_get_token(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_token) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) else: new_parameters.append(parameter) - setattr(cls.get_token, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_token, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_token) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> TokenResponse: diff --git a/seed/fastapi/oauth-client-credentials-default/resources/auth/types/token_response.py b/seed/fastapi/oauth-client-credentials-default/resources/auth/types/token_response.py index e4c616abbd8..6fd45225228 100644 --- a/seed/fastapi/oauth-client-credentials-default/resources/auth/types/token_response.py +++ b/seed/fastapi/oauth-client-credentials-default/resources/auth/types/token_response.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class TokenResponse(UniversalBaseModel): """ @@ -16,7 +15,9 @@ class TokenResponse(UniversalBaseModel): expires_in: int if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/oauth-client-credentials-default/security.py b/seed/fastapi/oauth-client-credentials-default/security.py index bab014441e1..4ccabc21106 100644 --- a/seed/fastapi/oauth-client-credentials-default/security.py +++ b/seed/fastapi/oauth-client-credentials-default/security.py @@ -1,8 +1,8 @@ # This file was auto-generated by Fern from our API Definition. +from .core.security.bearer import BearerToken import fastapi - -from .core.security.bearer import BearerToken, HTTPBearer +from .core.security.bearer import HTTPBearer ApiAuth = BearerToken diff --git a/seed/fastapi/oauth-client-credentials-environment-variables/core/abstract_fern_service.py b/seed/fastapi/oauth-client-credentials-environment-variables/core/abstract_fern_service.py index da7c8dc49c4..9966b4876da 100644 --- a/seed/fastapi/oauth-client-credentials-environment-variables/core/abstract_fern_service.py +++ b/seed/fastapi/oauth-client-credentials-environment-variables/core/abstract_fern_service.py @@ -7,5 +7,4 @@ class AbstractFernService(abc.ABC): @classmethod - def _init_fern(cls, router: fastapi.APIRouter) -> None: - ... + def _init_fern(cls, router: fastapi.APIRouter) -> None: ... diff --git a/seed/fastapi/oauth-client-credentials-environment-variables/core/datetime_utils.py b/seed/fastapi/oauth-client-credentials-environment-variables/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/fastapi/oauth-client-credentials-environment-variables/core/datetime_utils.py +++ b/seed/fastapi/oauth-client-credentials-environment-variables/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/fastapi/oauth-client-credentials-environment-variables/core/exceptions/__init__.py b/seed/fastapi/oauth-client-credentials-environment-variables/core/exceptions/__init__.py index 297d6e06f5f..dae4b8980c1 100644 --- a/seed/fastapi/oauth-client-credentials-environment-variables/core/exceptions/__init__.py +++ b/seed/fastapi/oauth-client-credentials-environment-variables/core/exceptions/__init__.py @@ -1,7 +1,11 @@ # This file was auto-generated by Fern from our API Definition. from .fern_http_exception import FernHTTPException -from .handlers import default_exception_handler, fern_http_exception_handler, http_exception_handler +from .handlers import ( + default_exception_handler, + fern_http_exception_handler, + http_exception_handler, +) from .unauthorized import UnauthorizedException __all__ = [ diff --git a/seed/fastapi/oauth-client-credentials-environment-variables/core/exceptions/fern_http_exception.py b/seed/fastapi/oauth-client-credentials-environment-variables/core/exceptions/fern_http_exception.py index bdf03862487..81610359a7f 100644 --- a/seed/fastapi/oauth-client-credentials-environment-variables/core/exceptions/fern_http_exception.py +++ b/seed/fastapi/oauth-client-credentials-environment-variables/core/exceptions/fern_http_exception.py @@ -1,14 +1,16 @@ # This file was auto-generated by Fern from our API Definition. import abc -import typing - import fastapi +import typing class FernHTTPException(abc.ABC, fastapi.HTTPException): def __init__( - self, status_code: int, name: typing.Optional[str] = None, content: typing.Optional[typing.Any] = None + self, + status_code: int, + name: typing.Optional[str] = None, + content: typing.Optional[typing.Any] = None, ): super().__init__(status_code=status_code) self.name = name @@ -17,4 +19,6 @@ def __init__( def to_json_response(self) -> fastapi.responses.JSONResponse: content = fastapi.encoders.jsonable_encoder(self.content, exclude_none=True) - return fastapi.responses.JSONResponse(content=content, status_code=self.status_code) + return fastapi.responses.JSONResponse( + content=content, status_code=self.status_code + ) diff --git a/seed/fastapi/oauth-client-credentials-environment-variables/core/exceptions/handlers.py b/seed/fastapi/oauth-client-credentials-environment-variables/core/exceptions/handlers.py index 6d8c4155c5a..ae1c2741f06 100644 --- a/seed/fastapi/oauth-client-credentials-environment-variables/core/exceptions/handlers.py +++ b/seed/fastapi/oauth-client-credentials-environment-variables/core/exceptions/handlers.py @@ -2,32 +2,49 @@ import logging -import fastapi import starlette import starlette.exceptions +import fastapi + from .fern_http_exception import FernHTTPException def fern_http_exception_handler( - request: fastapi.requests.Request, exc: FernHTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: FernHTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) return exc.to_json_response() def http_exception_handler( - request: fastapi.requests.Request, exc: starlette.exceptions.HTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: starlette.exceptions.HTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=exc.status_code, content=exc.detail).to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=exc.status_code, content=exc.detail + ).to_json_response() def default_exception_handler( - request: fastapi.requests.Request, exc: Exception, skip_log: bool = False + request: fastapi.requests.Request, + exc: Exception, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=500, content="Internal Server Error").to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=500, content="Internal Server Error" + ).to_json_response() diff --git a/seed/fastapi/oauth-client-credentials-environment-variables/core/pydantic_utilities.py b/seed/fastapi/oauth-client-credentials-environment-variables/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/fastapi/oauth-client-credentials-environment-variables/core/pydantic_utilities.py +++ b/seed/fastapi/oauth-client-credentials-environment-variables/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/fastapi/oauth-client-credentials-environment-variables/core/route_args.py b/seed/fastapi/oauth-client-credentials-environment-variables/core/route_args.py index 4228e2fe05d..bd940bf4ddd 100644 --- a/seed/fastapi/oauth-client-credentials-environment-variables/core/route_args.py +++ b/seed/fastapi/oauth-client-credentials-environment-variables/core/route_args.py @@ -20,9 +20,15 @@ class RouteArgs(typing_extensions.TypedDict): DEFAULT_ROUTE_ARGS = RouteArgs(openapi_extra=None, tags=None, include_in_schema=True) -def get_route_args(endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str) -> RouteArgs: - unwrapped = inspect.unwrap(endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY))) - route_args = typing.cast(RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS)) +def get_route_args( + endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str +) -> RouteArgs: + unwrapped = inspect.unwrap( + endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY)) + ) + route_args = typing.cast( + RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS) + ) if route_args["tags"] is None: return RouteArgs( openapi_extra=route_args["openapi_extra"], @@ -56,7 +62,11 @@ def decorator(endpoint_function: T) -> T: setattr( endpoint_function, FERN_CONFIG_KEY, - RouteArgs(openapi_extra=openapi_extra, tags=tags, include_in_schema=include_in_schema), + RouteArgs( + openapi_extra=openapi_extra, + tags=tags, + include_in_schema=include_in_schema, + ), ) return endpoint_function diff --git a/seed/fastapi/oauth-client-credentials-environment-variables/register.py b/seed/fastapi/oauth-client-credentials-environment-variables/register.py index 1f622e78ae3..43cd5cf4660 100644 --- a/seed/fastapi/oauth-client-credentials-environment-variables/register.py +++ b/seed/fastapi/oauth-client-credentials-environment-variables/register.py @@ -1,31 +1,33 @@ # This file was auto-generated by Fern from our API Definition. -import glob -import importlib -import os -import types -import typing - import fastapi -import starlette.exceptions +from .resources.auth.service.service import AbstractAuthService +import typing from fastapi import params - -from .core.abstract_fern_service import AbstractFernService -from .core.exceptions import default_exception_handler, fern_http_exception_handler, http_exception_handler from .core.exceptions.fern_http_exception import FernHTTPException -from .resources.auth.service.service import AbstractAuthService +from .core.exceptions import fern_http_exception_handler +import starlette.exceptions +from .core.exceptions import http_exception_handler +from .core.exceptions import default_exception_handler +from .core.abstract_fern_service import AbstractFernService +import types +import os +import glob +import importlib def register( _app: fastapi.FastAPI, *, auth: AbstractAuthService, - dependencies: typing.Optional[typing.Sequence[params.Depends]] = None + dependencies: typing.Optional[typing.Sequence[params.Depends]] = None, ) -> None: _app.include_router(__register_service(auth), dependencies=dependencies) _app.add_exception_handler(FernHTTPException, fern_http_exception_handler) # type: ignore - _app.add_exception_handler(starlette.exceptions.HTTPException, http_exception_handler) # type: ignore + _app.add_exception_handler( + starlette.exceptions.HTTPException, http_exception_handler + ) # type: ignore _app.add_exception_handler(Exception, default_exception_handler) # type: ignore @@ -37,7 +39,9 @@ def __register_service(service: AbstractFernService) -> fastapi.APIRouter: def register_validators(module: types.ModuleType) -> None: validators_directory: str = os.path.dirname(module.__file__) # type: ignore - for path in glob.glob(os.path.join(validators_directory, "**/*.py"), recursive=True): + for path in glob.glob( + os.path.join(validators_directory, "**/*.py"), recursive=True + ): if os.path.isfile(path): relative_path = os.path.relpath(path, start=validators_directory) module_path = ".".join([module.__name__] + relative_path[:-3].split("/")) diff --git a/seed/fastapi/oauth-client-credentials-environment-variables/resources/auth/service/get_token_request.py b/seed/fastapi/oauth-client-credentials-environment-variables/resources/auth/service/get_token_request.py index a1cfab2f2dd..5511562b405 100644 --- a/seed/fastapi/oauth-client-credentials-environment-variables/resources/auth/service/get_token_request.py +++ b/seed/fastapi/oauth-client-credentials-environment-variables/resources/auth/service/get_token_request.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class GetTokenRequest(UniversalBaseModel): client_id: str @@ -15,7 +14,9 @@ class GetTokenRequest(UniversalBaseModel): scope: typing.Optional[str] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/oauth-client-credentials-environment-variables/resources/auth/service/refresh_token_request.py b/seed/fastapi/oauth-client-credentials-environment-variables/resources/auth/service/refresh_token_request.py index 00abf9cc6bb..c2f9656444b 100644 --- a/seed/fastapi/oauth-client-credentials-environment-variables/resources/auth/service/refresh_token_request.py +++ b/seed/fastapi/oauth-client-credentials-environment-variables/resources/auth/service/refresh_token_request.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class RefreshTokenRequest(UniversalBaseModel): client_id: str @@ -16,7 +15,9 @@ class RefreshTokenRequest(UniversalBaseModel): scope: typing.Optional[str] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/oauth-client-credentials-environment-variables/resources/auth/service/service.py b/seed/fastapi/oauth-client-credentials-environment-variables/resources/auth/service/service.py index 3530eee9d5f..9f944eb9c79 100644 --- a/seed/fastapi/oauth-client-credentials-environment-variables/resources/auth/service/service.py +++ b/seed/fastapi/oauth-client-credentials-environment-variables/resources/auth/service/service.py @@ -1,19 +1,17 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.abstract_fern_service import AbstractFernService +from .get_token_request import GetTokenRequest +from ..types.token_response import TokenResponse import abc -import functools +from .refresh_token_request import RefreshTokenRequest +import fastapi import inspect -import logging import typing - -import fastapi - -from ....core.abstract_fern_service import AbstractFernService from ....core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools from ....core.route_args import get_route_args -from ..types.token_response import TokenResponse -from .get_token_request import GetTokenRequest -from .refresh_token_request import RefreshTokenRequest class AbstractAuthService(AbstractFernService): @@ -26,12 +24,12 @@ class AbstractAuthService(AbstractFernService): """ @abc.abstractmethod - def get_token_with_client_credentials(self, *, body: GetTokenRequest) -> TokenResponse: - ... + def get_token_with_client_credentials( + self, *, body: GetTokenRequest + ) -> TokenResponse: ... @abc.abstractmethod - def refresh_token(self, *, body: RefreshTokenRequest) -> TokenResponse: - ... + def refresh_token(self, *, body: RefreshTokenRequest) -> TokenResponse: ... """ Below are internal methods used by Fern to register your implementation. @@ -44,10 +42,14 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: cls.__init_refresh_token(router=router) @classmethod - def __init_get_token_with_client_credentials(cls, router: fastapi.APIRouter) -> None: + def __init_get_token_with_client_credentials( + cls, router: fastapi.APIRouter + ) -> None: endpoint_function = inspect.signature(cls.get_token_with_client_credentials) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": @@ -55,7 +57,9 @@ def __init_get_token_with_client_credentials(cls, router: fastapi.APIRouter) -> else: new_parameters.append(parameter) setattr( - cls.get_token_with_client_credentials, "__signature__", endpoint_function.replace(parameters=new_parameters) + cls.get_token_with_client_credentials, + "__signature__", + endpoint_function.replace(parameters=new_parameters), ) @functools.wraps(cls.get_token_with_client_credentials) @@ -85,14 +89,20 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> TokenResponse: def __init_refresh_token(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.refresh_token) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) else: new_parameters.append(parameter) - setattr(cls.refresh_token, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.refresh_token, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.refresh_token) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> TokenResponse: diff --git a/seed/fastapi/oauth-client-credentials-environment-variables/resources/auth/types/token_response.py b/seed/fastapi/oauth-client-credentials-environment-variables/resources/auth/types/token_response.py index a810183a8fb..f0efeef6600 100644 --- a/seed/fastapi/oauth-client-credentials-environment-variables/resources/auth/types/token_response.py +++ b/seed/fastapi/oauth-client-credentials-environment-variables/resources/auth/types/token_response.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class TokenResponse(UniversalBaseModel): """ @@ -17,7 +16,9 @@ class TokenResponse(UniversalBaseModel): refresh_token: typing.Optional[str] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/oauth-client-credentials-environment-variables/security.py b/seed/fastapi/oauth-client-credentials-environment-variables/security.py index bab014441e1..4ccabc21106 100644 --- a/seed/fastapi/oauth-client-credentials-environment-variables/security.py +++ b/seed/fastapi/oauth-client-credentials-environment-variables/security.py @@ -1,8 +1,8 @@ # This file was auto-generated by Fern from our API Definition. +from .core.security.bearer import BearerToken import fastapi - -from .core.security.bearer import BearerToken, HTTPBearer +from .core.security.bearer import HTTPBearer ApiAuth = BearerToken diff --git a/seed/fastapi/oauth-client-credentials-nested-root/core/abstract_fern_service.py b/seed/fastapi/oauth-client-credentials-nested-root/core/abstract_fern_service.py index da7c8dc49c4..9966b4876da 100644 --- a/seed/fastapi/oauth-client-credentials-nested-root/core/abstract_fern_service.py +++ b/seed/fastapi/oauth-client-credentials-nested-root/core/abstract_fern_service.py @@ -7,5 +7,4 @@ class AbstractFernService(abc.ABC): @classmethod - def _init_fern(cls, router: fastapi.APIRouter) -> None: - ... + def _init_fern(cls, router: fastapi.APIRouter) -> None: ... diff --git a/seed/fastapi/oauth-client-credentials-nested-root/core/datetime_utils.py b/seed/fastapi/oauth-client-credentials-nested-root/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/fastapi/oauth-client-credentials-nested-root/core/datetime_utils.py +++ b/seed/fastapi/oauth-client-credentials-nested-root/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/fastapi/oauth-client-credentials-nested-root/core/exceptions/__init__.py b/seed/fastapi/oauth-client-credentials-nested-root/core/exceptions/__init__.py index 297d6e06f5f..dae4b8980c1 100644 --- a/seed/fastapi/oauth-client-credentials-nested-root/core/exceptions/__init__.py +++ b/seed/fastapi/oauth-client-credentials-nested-root/core/exceptions/__init__.py @@ -1,7 +1,11 @@ # This file was auto-generated by Fern from our API Definition. from .fern_http_exception import FernHTTPException -from .handlers import default_exception_handler, fern_http_exception_handler, http_exception_handler +from .handlers import ( + default_exception_handler, + fern_http_exception_handler, + http_exception_handler, +) from .unauthorized import UnauthorizedException __all__ = [ diff --git a/seed/fastapi/oauth-client-credentials-nested-root/core/exceptions/fern_http_exception.py b/seed/fastapi/oauth-client-credentials-nested-root/core/exceptions/fern_http_exception.py index bdf03862487..81610359a7f 100644 --- a/seed/fastapi/oauth-client-credentials-nested-root/core/exceptions/fern_http_exception.py +++ b/seed/fastapi/oauth-client-credentials-nested-root/core/exceptions/fern_http_exception.py @@ -1,14 +1,16 @@ # This file was auto-generated by Fern from our API Definition. import abc -import typing - import fastapi +import typing class FernHTTPException(abc.ABC, fastapi.HTTPException): def __init__( - self, status_code: int, name: typing.Optional[str] = None, content: typing.Optional[typing.Any] = None + self, + status_code: int, + name: typing.Optional[str] = None, + content: typing.Optional[typing.Any] = None, ): super().__init__(status_code=status_code) self.name = name @@ -17,4 +19,6 @@ def __init__( def to_json_response(self) -> fastapi.responses.JSONResponse: content = fastapi.encoders.jsonable_encoder(self.content, exclude_none=True) - return fastapi.responses.JSONResponse(content=content, status_code=self.status_code) + return fastapi.responses.JSONResponse( + content=content, status_code=self.status_code + ) diff --git a/seed/fastapi/oauth-client-credentials-nested-root/core/exceptions/handlers.py b/seed/fastapi/oauth-client-credentials-nested-root/core/exceptions/handlers.py index 6d8c4155c5a..ae1c2741f06 100644 --- a/seed/fastapi/oauth-client-credentials-nested-root/core/exceptions/handlers.py +++ b/seed/fastapi/oauth-client-credentials-nested-root/core/exceptions/handlers.py @@ -2,32 +2,49 @@ import logging -import fastapi import starlette import starlette.exceptions +import fastapi + from .fern_http_exception import FernHTTPException def fern_http_exception_handler( - request: fastapi.requests.Request, exc: FernHTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: FernHTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) return exc.to_json_response() def http_exception_handler( - request: fastapi.requests.Request, exc: starlette.exceptions.HTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: starlette.exceptions.HTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=exc.status_code, content=exc.detail).to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=exc.status_code, content=exc.detail + ).to_json_response() def default_exception_handler( - request: fastapi.requests.Request, exc: Exception, skip_log: bool = False + request: fastapi.requests.Request, + exc: Exception, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=500, content="Internal Server Error").to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=500, content="Internal Server Error" + ).to_json_response() diff --git a/seed/fastapi/oauth-client-credentials-nested-root/core/pydantic_utilities.py b/seed/fastapi/oauth-client-credentials-nested-root/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/fastapi/oauth-client-credentials-nested-root/core/pydantic_utilities.py +++ b/seed/fastapi/oauth-client-credentials-nested-root/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/fastapi/oauth-client-credentials-nested-root/core/route_args.py b/seed/fastapi/oauth-client-credentials-nested-root/core/route_args.py index 4228e2fe05d..bd940bf4ddd 100644 --- a/seed/fastapi/oauth-client-credentials-nested-root/core/route_args.py +++ b/seed/fastapi/oauth-client-credentials-nested-root/core/route_args.py @@ -20,9 +20,15 @@ class RouteArgs(typing_extensions.TypedDict): DEFAULT_ROUTE_ARGS = RouteArgs(openapi_extra=None, tags=None, include_in_schema=True) -def get_route_args(endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str) -> RouteArgs: - unwrapped = inspect.unwrap(endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY))) - route_args = typing.cast(RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS)) +def get_route_args( + endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str +) -> RouteArgs: + unwrapped = inspect.unwrap( + endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY)) + ) + route_args = typing.cast( + RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS) + ) if route_args["tags"] is None: return RouteArgs( openapi_extra=route_args["openapi_extra"], @@ -56,7 +62,11 @@ def decorator(endpoint_function: T) -> T: setattr( endpoint_function, FERN_CONFIG_KEY, - RouteArgs(openapi_extra=openapi_extra, tags=tags, include_in_schema=include_in_schema), + RouteArgs( + openapi_extra=openapi_extra, + tags=tags, + include_in_schema=include_in_schema, + ), ) return endpoint_function diff --git a/seed/fastapi/oauth-client-credentials-nested-root/register.py b/seed/fastapi/oauth-client-credentials-nested-root/register.py index 1f622e78ae3..43cd5cf4660 100644 --- a/seed/fastapi/oauth-client-credentials-nested-root/register.py +++ b/seed/fastapi/oauth-client-credentials-nested-root/register.py @@ -1,31 +1,33 @@ # This file was auto-generated by Fern from our API Definition. -import glob -import importlib -import os -import types -import typing - import fastapi -import starlette.exceptions +from .resources.auth.service.service import AbstractAuthService +import typing from fastapi import params - -from .core.abstract_fern_service import AbstractFernService -from .core.exceptions import default_exception_handler, fern_http_exception_handler, http_exception_handler from .core.exceptions.fern_http_exception import FernHTTPException -from .resources.auth.service.service import AbstractAuthService +from .core.exceptions import fern_http_exception_handler +import starlette.exceptions +from .core.exceptions import http_exception_handler +from .core.exceptions import default_exception_handler +from .core.abstract_fern_service import AbstractFernService +import types +import os +import glob +import importlib def register( _app: fastapi.FastAPI, *, auth: AbstractAuthService, - dependencies: typing.Optional[typing.Sequence[params.Depends]] = None + dependencies: typing.Optional[typing.Sequence[params.Depends]] = None, ) -> None: _app.include_router(__register_service(auth), dependencies=dependencies) _app.add_exception_handler(FernHTTPException, fern_http_exception_handler) # type: ignore - _app.add_exception_handler(starlette.exceptions.HTTPException, http_exception_handler) # type: ignore + _app.add_exception_handler( + starlette.exceptions.HTTPException, http_exception_handler + ) # type: ignore _app.add_exception_handler(Exception, default_exception_handler) # type: ignore @@ -37,7 +39,9 @@ def __register_service(service: AbstractFernService) -> fastapi.APIRouter: def register_validators(module: types.ModuleType) -> None: validators_directory: str = os.path.dirname(module.__file__) # type: ignore - for path in glob.glob(os.path.join(validators_directory, "**/*.py"), recursive=True): + for path in glob.glob( + os.path.join(validators_directory, "**/*.py"), recursive=True + ): if os.path.isfile(path): relative_path = os.path.relpath(path, start=validators_directory) module_path = ".".join([module.__name__] + relative_path[:-3].split("/")) diff --git a/seed/fastapi/oauth-client-credentials-nested-root/resources/auth/service/get_token_request.py b/seed/fastapi/oauth-client-credentials-nested-root/resources/auth/service/get_token_request.py index a1cfab2f2dd..5511562b405 100644 --- a/seed/fastapi/oauth-client-credentials-nested-root/resources/auth/service/get_token_request.py +++ b/seed/fastapi/oauth-client-credentials-nested-root/resources/auth/service/get_token_request.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class GetTokenRequest(UniversalBaseModel): client_id: str @@ -15,7 +14,9 @@ class GetTokenRequest(UniversalBaseModel): scope: typing.Optional[str] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/oauth-client-credentials-nested-root/resources/auth/service/service.py b/seed/fastapi/oauth-client-credentials-nested-root/resources/auth/service/service.py index 9d203585833..0a0cd7a07a1 100644 --- a/seed/fastapi/oauth-client-credentials-nested-root/resources/auth/service/service.py +++ b/seed/fastapi/oauth-client-credentials-nested-root/resources/auth/service/service.py @@ -1,18 +1,16 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.abstract_fern_service import AbstractFernService +from .get_token_request import GetTokenRequest +from ..types.token_response import TokenResponse import abc -import functools +import fastapi import inspect -import logging import typing - -import fastapi - -from ....core.abstract_fern_service import AbstractFernService from ....core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools from ....core.route_args import get_route_args -from ..types.token_response import TokenResponse -from .get_token_request import GetTokenRequest class AbstractAuthService(AbstractFernService): @@ -25,8 +23,7 @@ class AbstractAuthService(AbstractFernService): """ @abc.abstractmethod - def get_token(self, *, body: GetTokenRequest) -> TokenResponse: - ... + def get_token(self, *, body: GetTokenRequest) -> TokenResponse: ... """ Below are internal methods used by Fern to register your implementation. @@ -41,14 +38,20 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_get_token(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_token) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) else: new_parameters.append(parameter) - setattr(cls.get_token, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_token, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_token) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> TokenResponse: diff --git a/seed/fastapi/oauth-client-credentials-nested-root/resources/auth/types/token_response.py b/seed/fastapi/oauth-client-credentials-nested-root/resources/auth/types/token_response.py index a810183a8fb..f0efeef6600 100644 --- a/seed/fastapi/oauth-client-credentials-nested-root/resources/auth/types/token_response.py +++ b/seed/fastapi/oauth-client-credentials-nested-root/resources/auth/types/token_response.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class TokenResponse(UniversalBaseModel): """ @@ -17,7 +16,9 @@ class TokenResponse(UniversalBaseModel): refresh_token: typing.Optional[str] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/oauth-client-credentials-nested-root/security.py b/seed/fastapi/oauth-client-credentials-nested-root/security.py index bab014441e1..4ccabc21106 100644 --- a/seed/fastapi/oauth-client-credentials-nested-root/security.py +++ b/seed/fastapi/oauth-client-credentials-nested-root/security.py @@ -1,8 +1,8 @@ # This file was auto-generated by Fern from our API Definition. +from .core.security.bearer import BearerToken import fastapi - -from .core.security.bearer import BearerToken, HTTPBearer +from .core.security.bearer import HTTPBearer ApiAuth = BearerToken diff --git a/seed/fastapi/oauth-client-credentials/core/abstract_fern_service.py b/seed/fastapi/oauth-client-credentials/core/abstract_fern_service.py index da7c8dc49c4..9966b4876da 100644 --- a/seed/fastapi/oauth-client-credentials/core/abstract_fern_service.py +++ b/seed/fastapi/oauth-client-credentials/core/abstract_fern_service.py @@ -7,5 +7,4 @@ class AbstractFernService(abc.ABC): @classmethod - def _init_fern(cls, router: fastapi.APIRouter) -> None: - ... + def _init_fern(cls, router: fastapi.APIRouter) -> None: ... diff --git a/seed/fastapi/oauth-client-credentials/core/datetime_utils.py b/seed/fastapi/oauth-client-credentials/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/fastapi/oauth-client-credentials/core/datetime_utils.py +++ b/seed/fastapi/oauth-client-credentials/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/fastapi/oauth-client-credentials/core/exceptions/__init__.py b/seed/fastapi/oauth-client-credentials/core/exceptions/__init__.py index 297d6e06f5f..dae4b8980c1 100644 --- a/seed/fastapi/oauth-client-credentials/core/exceptions/__init__.py +++ b/seed/fastapi/oauth-client-credentials/core/exceptions/__init__.py @@ -1,7 +1,11 @@ # This file was auto-generated by Fern from our API Definition. from .fern_http_exception import FernHTTPException -from .handlers import default_exception_handler, fern_http_exception_handler, http_exception_handler +from .handlers import ( + default_exception_handler, + fern_http_exception_handler, + http_exception_handler, +) from .unauthorized import UnauthorizedException __all__ = [ diff --git a/seed/fastapi/oauth-client-credentials/core/exceptions/fern_http_exception.py b/seed/fastapi/oauth-client-credentials/core/exceptions/fern_http_exception.py index bdf03862487..81610359a7f 100644 --- a/seed/fastapi/oauth-client-credentials/core/exceptions/fern_http_exception.py +++ b/seed/fastapi/oauth-client-credentials/core/exceptions/fern_http_exception.py @@ -1,14 +1,16 @@ # This file was auto-generated by Fern from our API Definition. import abc -import typing - import fastapi +import typing class FernHTTPException(abc.ABC, fastapi.HTTPException): def __init__( - self, status_code: int, name: typing.Optional[str] = None, content: typing.Optional[typing.Any] = None + self, + status_code: int, + name: typing.Optional[str] = None, + content: typing.Optional[typing.Any] = None, ): super().__init__(status_code=status_code) self.name = name @@ -17,4 +19,6 @@ def __init__( def to_json_response(self) -> fastapi.responses.JSONResponse: content = fastapi.encoders.jsonable_encoder(self.content, exclude_none=True) - return fastapi.responses.JSONResponse(content=content, status_code=self.status_code) + return fastapi.responses.JSONResponse( + content=content, status_code=self.status_code + ) diff --git a/seed/fastapi/oauth-client-credentials/core/exceptions/handlers.py b/seed/fastapi/oauth-client-credentials/core/exceptions/handlers.py index 6d8c4155c5a..ae1c2741f06 100644 --- a/seed/fastapi/oauth-client-credentials/core/exceptions/handlers.py +++ b/seed/fastapi/oauth-client-credentials/core/exceptions/handlers.py @@ -2,32 +2,49 @@ import logging -import fastapi import starlette import starlette.exceptions +import fastapi + from .fern_http_exception import FernHTTPException def fern_http_exception_handler( - request: fastapi.requests.Request, exc: FernHTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: FernHTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) return exc.to_json_response() def http_exception_handler( - request: fastapi.requests.Request, exc: starlette.exceptions.HTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: starlette.exceptions.HTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=exc.status_code, content=exc.detail).to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=exc.status_code, content=exc.detail + ).to_json_response() def default_exception_handler( - request: fastapi.requests.Request, exc: Exception, skip_log: bool = False + request: fastapi.requests.Request, + exc: Exception, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=500, content="Internal Server Error").to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=500, content="Internal Server Error" + ).to_json_response() diff --git a/seed/fastapi/oauth-client-credentials/core/pydantic_utilities.py b/seed/fastapi/oauth-client-credentials/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/fastapi/oauth-client-credentials/core/pydantic_utilities.py +++ b/seed/fastapi/oauth-client-credentials/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/fastapi/oauth-client-credentials/core/route_args.py b/seed/fastapi/oauth-client-credentials/core/route_args.py index 4228e2fe05d..bd940bf4ddd 100644 --- a/seed/fastapi/oauth-client-credentials/core/route_args.py +++ b/seed/fastapi/oauth-client-credentials/core/route_args.py @@ -20,9 +20,15 @@ class RouteArgs(typing_extensions.TypedDict): DEFAULT_ROUTE_ARGS = RouteArgs(openapi_extra=None, tags=None, include_in_schema=True) -def get_route_args(endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str) -> RouteArgs: - unwrapped = inspect.unwrap(endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY))) - route_args = typing.cast(RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS)) +def get_route_args( + endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str +) -> RouteArgs: + unwrapped = inspect.unwrap( + endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY)) + ) + route_args = typing.cast( + RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS) + ) if route_args["tags"] is None: return RouteArgs( openapi_extra=route_args["openapi_extra"], @@ -56,7 +62,11 @@ def decorator(endpoint_function: T) -> T: setattr( endpoint_function, FERN_CONFIG_KEY, - RouteArgs(openapi_extra=openapi_extra, tags=tags, include_in_schema=include_in_schema), + RouteArgs( + openapi_extra=openapi_extra, + tags=tags, + include_in_schema=include_in_schema, + ), ) return endpoint_function diff --git a/seed/fastapi/oauth-client-credentials/register.py b/seed/fastapi/oauth-client-credentials/register.py index 1f622e78ae3..43cd5cf4660 100644 --- a/seed/fastapi/oauth-client-credentials/register.py +++ b/seed/fastapi/oauth-client-credentials/register.py @@ -1,31 +1,33 @@ # This file was auto-generated by Fern from our API Definition. -import glob -import importlib -import os -import types -import typing - import fastapi -import starlette.exceptions +from .resources.auth.service.service import AbstractAuthService +import typing from fastapi import params - -from .core.abstract_fern_service import AbstractFernService -from .core.exceptions import default_exception_handler, fern_http_exception_handler, http_exception_handler from .core.exceptions.fern_http_exception import FernHTTPException -from .resources.auth.service.service import AbstractAuthService +from .core.exceptions import fern_http_exception_handler +import starlette.exceptions +from .core.exceptions import http_exception_handler +from .core.exceptions import default_exception_handler +from .core.abstract_fern_service import AbstractFernService +import types +import os +import glob +import importlib def register( _app: fastapi.FastAPI, *, auth: AbstractAuthService, - dependencies: typing.Optional[typing.Sequence[params.Depends]] = None + dependencies: typing.Optional[typing.Sequence[params.Depends]] = None, ) -> None: _app.include_router(__register_service(auth), dependencies=dependencies) _app.add_exception_handler(FernHTTPException, fern_http_exception_handler) # type: ignore - _app.add_exception_handler(starlette.exceptions.HTTPException, http_exception_handler) # type: ignore + _app.add_exception_handler( + starlette.exceptions.HTTPException, http_exception_handler + ) # type: ignore _app.add_exception_handler(Exception, default_exception_handler) # type: ignore @@ -37,7 +39,9 @@ def __register_service(service: AbstractFernService) -> fastapi.APIRouter: def register_validators(module: types.ModuleType) -> None: validators_directory: str = os.path.dirname(module.__file__) # type: ignore - for path in glob.glob(os.path.join(validators_directory, "**/*.py"), recursive=True): + for path in glob.glob( + os.path.join(validators_directory, "**/*.py"), recursive=True + ): if os.path.isfile(path): relative_path = os.path.relpath(path, start=validators_directory) module_path = ".".join([module.__name__] + relative_path[:-3].split("/")) diff --git a/seed/fastapi/oauth-client-credentials/resources/auth/service/get_token_request.py b/seed/fastapi/oauth-client-credentials/resources/auth/service/get_token_request.py index a1cfab2f2dd..5511562b405 100644 --- a/seed/fastapi/oauth-client-credentials/resources/auth/service/get_token_request.py +++ b/seed/fastapi/oauth-client-credentials/resources/auth/service/get_token_request.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class GetTokenRequest(UniversalBaseModel): client_id: str @@ -15,7 +14,9 @@ class GetTokenRequest(UniversalBaseModel): scope: typing.Optional[str] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/oauth-client-credentials/resources/auth/service/refresh_token_request.py b/seed/fastapi/oauth-client-credentials/resources/auth/service/refresh_token_request.py index 00abf9cc6bb..c2f9656444b 100644 --- a/seed/fastapi/oauth-client-credentials/resources/auth/service/refresh_token_request.py +++ b/seed/fastapi/oauth-client-credentials/resources/auth/service/refresh_token_request.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class RefreshTokenRequest(UniversalBaseModel): client_id: str @@ -16,7 +15,9 @@ class RefreshTokenRequest(UniversalBaseModel): scope: typing.Optional[str] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/oauth-client-credentials/resources/auth/service/service.py b/seed/fastapi/oauth-client-credentials/resources/auth/service/service.py index 3530eee9d5f..9f944eb9c79 100644 --- a/seed/fastapi/oauth-client-credentials/resources/auth/service/service.py +++ b/seed/fastapi/oauth-client-credentials/resources/auth/service/service.py @@ -1,19 +1,17 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.abstract_fern_service import AbstractFernService +from .get_token_request import GetTokenRequest +from ..types.token_response import TokenResponse import abc -import functools +from .refresh_token_request import RefreshTokenRequest +import fastapi import inspect -import logging import typing - -import fastapi - -from ....core.abstract_fern_service import AbstractFernService from ....core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools from ....core.route_args import get_route_args -from ..types.token_response import TokenResponse -from .get_token_request import GetTokenRequest -from .refresh_token_request import RefreshTokenRequest class AbstractAuthService(AbstractFernService): @@ -26,12 +24,12 @@ class AbstractAuthService(AbstractFernService): """ @abc.abstractmethod - def get_token_with_client_credentials(self, *, body: GetTokenRequest) -> TokenResponse: - ... + def get_token_with_client_credentials( + self, *, body: GetTokenRequest + ) -> TokenResponse: ... @abc.abstractmethod - def refresh_token(self, *, body: RefreshTokenRequest) -> TokenResponse: - ... + def refresh_token(self, *, body: RefreshTokenRequest) -> TokenResponse: ... """ Below are internal methods used by Fern to register your implementation. @@ -44,10 +42,14 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: cls.__init_refresh_token(router=router) @classmethod - def __init_get_token_with_client_credentials(cls, router: fastapi.APIRouter) -> None: + def __init_get_token_with_client_credentials( + cls, router: fastapi.APIRouter + ) -> None: endpoint_function = inspect.signature(cls.get_token_with_client_credentials) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": @@ -55,7 +57,9 @@ def __init_get_token_with_client_credentials(cls, router: fastapi.APIRouter) -> else: new_parameters.append(parameter) setattr( - cls.get_token_with_client_credentials, "__signature__", endpoint_function.replace(parameters=new_parameters) + cls.get_token_with_client_credentials, + "__signature__", + endpoint_function.replace(parameters=new_parameters), ) @functools.wraps(cls.get_token_with_client_credentials) @@ -85,14 +89,20 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> TokenResponse: def __init_refresh_token(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.refresh_token) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) else: new_parameters.append(parameter) - setattr(cls.refresh_token, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.refresh_token, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.refresh_token) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> TokenResponse: diff --git a/seed/fastapi/oauth-client-credentials/resources/auth/types/token_response.py b/seed/fastapi/oauth-client-credentials/resources/auth/types/token_response.py index a810183a8fb..f0efeef6600 100644 --- a/seed/fastapi/oauth-client-credentials/resources/auth/types/token_response.py +++ b/seed/fastapi/oauth-client-credentials/resources/auth/types/token_response.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class TokenResponse(UniversalBaseModel): """ @@ -17,7 +16,9 @@ class TokenResponse(UniversalBaseModel): refresh_token: typing.Optional[str] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/oauth-client-credentials/security.py b/seed/fastapi/oauth-client-credentials/security.py index bab014441e1..4ccabc21106 100644 --- a/seed/fastapi/oauth-client-credentials/security.py +++ b/seed/fastapi/oauth-client-credentials/security.py @@ -1,8 +1,8 @@ # This file was auto-generated by Fern from our API Definition. +from .core.security.bearer import BearerToken import fastapi - -from .core.security.bearer import BearerToken, HTTPBearer +from .core.security.bearer import HTTPBearer ApiAuth = BearerToken diff --git a/seed/fastapi/object/core/abstract_fern_service.py b/seed/fastapi/object/core/abstract_fern_service.py index da7c8dc49c4..9966b4876da 100644 --- a/seed/fastapi/object/core/abstract_fern_service.py +++ b/seed/fastapi/object/core/abstract_fern_service.py @@ -7,5 +7,4 @@ class AbstractFernService(abc.ABC): @classmethod - def _init_fern(cls, router: fastapi.APIRouter) -> None: - ... + def _init_fern(cls, router: fastapi.APIRouter) -> None: ... diff --git a/seed/fastapi/object/core/datetime_utils.py b/seed/fastapi/object/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/fastapi/object/core/datetime_utils.py +++ b/seed/fastapi/object/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/fastapi/object/core/exceptions/__init__.py b/seed/fastapi/object/core/exceptions/__init__.py index 297d6e06f5f..dae4b8980c1 100644 --- a/seed/fastapi/object/core/exceptions/__init__.py +++ b/seed/fastapi/object/core/exceptions/__init__.py @@ -1,7 +1,11 @@ # This file was auto-generated by Fern from our API Definition. from .fern_http_exception import FernHTTPException -from .handlers import default_exception_handler, fern_http_exception_handler, http_exception_handler +from .handlers import ( + default_exception_handler, + fern_http_exception_handler, + http_exception_handler, +) from .unauthorized import UnauthorizedException __all__ = [ diff --git a/seed/fastapi/object/core/exceptions/fern_http_exception.py b/seed/fastapi/object/core/exceptions/fern_http_exception.py index bdf03862487..81610359a7f 100644 --- a/seed/fastapi/object/core/exceptions/fern_http_exception.py +++ b/seed/fastapi/object/core/exceptions/fern_http_exception.py @@ -1,14 +1,16 @@ # This file was auto-generated by Fern from our API Definition. import abc -import typing - import fastapi +import typing class FernHTTPException(abc.ABC, fastapi.HTTPException): def __init__( - self, status_code: int, name: typing.Optional[str] = None, content: typing.Optional[typing.Any] = None + self, + status_code: int, + name: typing.Optional[str] = None, + content: typing.Optional[typing.Any] = None, ): super().__init__(status_code=status_code) self.name = name @@ -17,4 +19,6 @@ def __init__( def to_json_response(self) -> fastapi.responses.JSONResponse: content = fastapi.encoders.jsonable_encoder(self.content, exclude_none=True) - return fastapi.responses.JSONResponse(content=content, status_code=self.status_code) + return fastapi.responses.JSONResponse( + content=content, status_code=self.status_code + ) diff --git a/seed/fastapi/object/core/exceptions/handlers.py b/seed/fastapi/object/core/exceptions/handlers.py index 6d8c4155c5a..ae1c2741f06 100644 --- a/seed/fastapi/object/core/exceptions/handlers.py +++ b/seed/fastapi/object/core/exceptions/handlers.py @@ -2,32 +2,49 @@ import logging -import fastapi import starlette import starlette.exceptions +import fastapi + from .fern_http_exception import FernHTTPException def fern_http_exception_handler( - request: fastapi.requests.Request, exc: FernHTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: FernHTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) return exc.to_json_response() def http_exception_handler( - request: fastapi.requests.Request, exc: starlette.exceptions.HTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: starlette.exceptions.HTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=exc.status_code, content=exc.detail).to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=exc.status_code, content=exc.detail + ).to_json_response() def default_exception_handler( - request: fastapi.requests.Request, exc: Exception, skip_log: bool = False + request: fastapi.requests.Request, + exc: Exception, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=500, content="Internal Server Error").to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=500, content="Internal Server Error" + ).to_json_response() diff --git a/seed/fastapi/object/core/pydantic_utilities.py b/seed/fastapi/object/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/fastapi/object/core/pydantic_utilities.py +++ b/seed/fastapi/object/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/fastapi/object/core/route_args.py b/seed/fastapi/object/core/route_args.py index 4228e2fe05d..bd940bf4ddd 100644 --- a/seed/fastapi/object/core/route_args.py +++ b/seed/fastapi/object/core/route_args.py @@ -20,9 +20,15 @@ class RouteArgs(typing_extensions.TypedDict): DEFAULT_ROUTE_ARGS = RouteArgs(openapi_extra=None, tags=None, include_in_schema=True) -def get_route_args(endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str) -> RouteArgs: - unwrapped = inspect.unwrap(endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY))) - route_args = typing.cast(RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS)) +def get_route_args( + endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str +) -> RouteArgs: + unwrapped = inspect.unwrap( + endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY)) + ) + route_args = typing.cast( + RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS) + ) if route_args["tags"] is None: return RouteArgs( openapi_extra=route_args["openapi_extra"], @@ -56,7 +62,11 @@ def decorator(endpoint_function: T) -> T: setattr( endpoint_function, FERN_CONFIG_KEY, - RouteArgs(openapi_extra=openapi_extra, tags=tags, include_in_schema=include_in_schema), + RouteArgs( + openapi_extra=openapi_extra, + tags=tags, + include_in_schema=include_in_schema, + ), ) return endpoint_function diff --git a/seed/fastapi/object/register.py b/seed/fastapi/object/register.py index 6f6e6707f03..a536c0ce4e4 100644 --- a/seed/fastapi/object/register.py +++ b/seed/fastapi/object/register.py @@ -1,23 +1,29 @@ # This file was auto-generated by Fern from our API Definition. -import glob -import importlib -import os -import types -import typing - import fastapi -import starlette.exceptions +import typing from fastapi import params - -from .core.abstract_fern_service import AbstractFernService -from .core.exceptions import default_exception_handler, fern_http_exception_handler, http_exception_handler from .core.exceptions.fern_http_exception import FernHTTPException +from .core.exceptions import fern_http_exception_handler +import starlette.exceptions +from .core.exceptions import http_exception_handler +from .core.exceptions import default_exception_handler +from .core.abstract_fern_service import AbstractFernService +import types +import os +import glob +import importlib -def register(_app: fastapi.FastAPI, *, dependencies: typing.Optional[typing.Sequence[params.Depends]] = None) -> None: +def register( + _app: fastapi.FastAPI, + *, + dependencies: typing.Optional[typing.Sequence[params.Depends]] = None, +) -> None: _app.add_exception_handler(FernHTTPException, fern_http_exception_handler) # type: ignore - _app.add_exception_handler(starlette.exceptions.HTTPException, http_exception_handler) # type: ignore + _app.add_exception_handler( + starlette.exceptions.HTTPException, http_exception_handler + ) # type: ignore _app.add_exception_handler(Exception, default_exception_handler) # type: ignore @@ -29,7 +35,9 @@ def __register_service(service: AbstractFernService) -> fastapi.APIRouter: def register_validators(module: types.ModuleType) -> None: validators_directory: str = os.path.dirname(module.__file__) # type: ignore - for path in glob.glob(os.path.join(validators_directory, "**/*.py"), recursive=True): + for path in glob.glob( + os.path.join(validators_directory, "**/*.py"), recursive=True + ): if os.path.isfile(path): relative_path = os.path.relpath(path, start=validators_directory) module_path = ".".join([module.__name__] + relative_path[:-3].split("/")) diff --git a/seed/fastapi/object/types/name.py b/seed/fastapi/object/types/name.py index 8daa3c6ddc5..2c3a9a2b478 100644 --- a/seed/fastapi/object/types/name.py +++ b/seed/fastapi/object/types/name.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from ..core.pydantic_utilities import UniversalBaseModel +from ..core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class Name(UniversalBaseModel): """ @@ -23,7 +22,9 @@ class Name(UniversalBaseModel): value: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/object/types/type.py b/seed/fastapi/object/types/type.py index 7bad1da97bb..41d06164e11 100644 --- a/seed/fastapi/object/types/type.py +++ b/seed/fastapi/object/types/type.py @@ -1,13 +1,12 @@ # This file was auto-generated by Fern from our API Definition. +from ..core.pydantic_utilities import UniversalBaseModel import datetime as dt -import typing import uuid - -import pydantic - -from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +import typing from .name import Name +from ..core.pydantic_utilities import IS_PYDANTIC_V2 +import pydantic class Type(UniversalBaseModel): @@ -88,7 +87,9 @@ class Type(UniversalBaseModel): twentythree: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/objects-with-imports/core/abstract_fern_service.py b/seed/fastapi/objects-with-imports/core/abstract_fern_service.py index da7c8dc49c4..9966b4876da 100644 --- a/seed/fastapi/objects-with-imports/core/abstract_fern_service.py +++ b/seed/fastapi/objects-with-imports/core/abstract_fern_service.py @@ -7,5 +7,4 @@ class AbstractFernService(abc.ABC): @classmethod - def _init_fern(cls, router: fastapi.APIRouter) -> None: - ... + def _init_fern(cls, router: fastapi.APIRouter) -> None: ... diff --git a/seed/fastapi/objects-with-imports/core/datetime_utils.py b/seed/fastapi/objects-with-imports/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/fastapi/objects-with-imports/core/datetime_utils.py +++ b/seed/fastapi/objects-with-imports/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/fastapi/objects-with-imports/core/exceptions/__init__.py b/seed/fastapi/objects-with-imports/core/exceptions/__init__.py index 297d6e06f5f..dae4b8980c1 100644 --- a/seed/fastapi/objects-with-imports/core/exceptions/__init__.py +++ b/seed/fastapi/objects-with-imports/core/exceptions/__init__.py @@ -1,7 +1,11 @@ # This file was auto-generated by Fern from our API Definition. from .fern_http_exception import FernHTTPException -from .handlers import default_exception_handler, fern_http_exception_handler, http_exception_handler +from .handlers import ( + default_exception_handler, + fern_http_exception_handler, + http_exception_handler, +) from .unauthorized import UnauthorizedException __all__ = [ diff --git a/seed/fastapi/objects-with-imports/core/exceptions/fern_http_exception.py b/seed/fastapi/objects-with-imports/core/exceptions/fern_http_exception.py index bdf03862487..81610359a7f 100644 --- a/seed/fastapi/objects-with-imports/core/exceptions/fern_http_exception.py +++ b/seed/fastapi/objects-with-imports/core/exceptions/fern_http_exception.py @@ -1,14 +1,16 @@ # This file was auto-generated by Fern from our API Definition. import abc -import typing - import fastapi +import typing class FernHTTPException(abc.ABC, fastapi.HTTPException): def __init__( - self, status_code: int, name: typing.Optional[str] = None, content: typing.Optional[typing.Any] = None + self, + status_code: int, + name: typing.Optional[str] = None, + content: typing.Optional[typing.Any] = None, ): super().__init__(status_code=status_code) self.name = name @@ -17,4 +19,6 @@ def __init__( def to_json_response(self) -> fastapi.responses.JSONResponse: content = fastapi.encoders.jsonable_encoder(self.content, exclude_none=True) - return fastapi.responses.JSONResponse(content=content, status_code=self.status_code) + return fastapi.responses.JSONResponse( + content=content, status_code=self.status_code + ) diff --git a/seed/fastapi/objects-with-imports/core/exceptions/handlers.py b/seed/fastapi/objects-with-imports/core/exceptions/handlers.py index 6d8c4155c5a..ae1c2741f06 100644 --- a/seed/fastapi/objects-with-imports/core/exceptions/handlers.py +++ b/seed/fastapi/objects-with-imports/core/exceptions/handlers.py @@ -2,32 +2,49 @@ import logging -import fastapi import starlette import starlette.exceptions +import fastapi + from .fern_http_exception import FernHTTPException def fern_http_exception_handler( - request: fastapi.requests.Request, exc: FernHTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: FernHTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) return exc.to_json_response() def http_exception_handler( - request: fastapi.requests.Request, exc: starlette.exceptions.HTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: starlette.exceptions.HTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=exc.status_code, content=exc.detail).to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=exc.status_code, content=exc.detail + ).to_json_response() def default_exception_handler( - request: fastapi.requests.Request, exc: Exception, skip_log: bool = False + request: fastapi.requests.Request, + exc: Exception, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=500, content="Internal Server Error").to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=500, content="Internal Server Error" + ).to_json_response() diff --git a/seed/fastapi/objects-with-imports/core/pydantic_utilities.py b/seed/fastapi/objects-with-imports/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/fastapi/objects-with-imports/core/pydantic_utilities.py +++ b/seed/fastapi/objects-with-imports/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/fastapi/objects-with-imports/core/route_args.py b/seed/fastapi/objects-with-imports/core/route_args.py index 4228e2fe05d..bd940bf4ddd 100644 --- a/seed/fastapi/objects-with-imports/core/route_args.py +++ b/seed/fastapi/objects-with-imports/core/route_args.py @@ -20,9 +20,15 @@ class RouteArgs(typing_extensions.TypedDict): DEFAULT_ROUTE_ARGS = RouteArgs(openapi_extra=None, tags=None, include_in_schema=True) -def get_route_args(endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str) -> RouteArgs: - unwrapped = inspect.unwrap(endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY))) - route_args = typing.cast(RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS)) +def get_route_args( + endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str +) -> RouteArgs: + unwrapped = inspect.unwrap( + endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY)) + ) + route_args = typing.cast( + RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS) + ) if route_args["tags"] is None: return RouteArgs( openapi_extra=route_args["openapi_extra"], @@ -56,7 +62,11 @@ def decorator(endpoint_function: T) -> T: setattr( endpoint_function, FERN_CONFIG_KEY, - RouteArgs(openapi_extra=openapi_extra, tags=tags, include_in_schema=include_in_schema), + RouteArgs( + openapi_extra=openapi_extra, + tags=tags, + include_in_schema=include_in_schema, + ), ) return endpoint_function diff --git a/seed/fastapi/objects-with-imports/register.py b/seed/fastapi/objects-with-imports/register.py index 6f6e6707f03..a536c0ce4e4 100644 --- a/seed/fastapi/objects-with-imports/register.py +++ b/seed/fastapi/objects-with-imports/register.py @@ -1,23 +1,29 @@ # This file was auto-generated by Fern from our API Definition. -import glob -import importlib -import os -import types -import typing - import fastapi -import starlette.exceptions +import typing from fastapi import params - -from .core.abstract_fern_service import AbstractFernService -from .core.exceptions import default_exception_handler, fern_http_exception_handler, http_exception_handler from .core.exceptions.fern_http_exception import FernHTTPException +from .core.exceptions import fern_http_exception_handler +import starlette.exceptions +from .core.exceptions import http_exception_handler +from .core.exceptions import default_exception_handler +from .core.abstract_fern_service import AbstractFernService +import types +import os +import glob +import importlib -def register(_app: fastapi.FastAPI, *, dependencies: typing.Optional[typing.Sequence[params.Depends]] = None) -> None: +def register( + _app: fastapi.FastAPI, + *, + dependencies: typing.Optional[typing.Sequence[params.Depends]] = None, +) -> None: _app.add_exception_handler(FernHTTPException, fern_http_exception_handler) # type: ignore - _app.add_exception_handler(starlette.exceptions.HTTPException, http_exception_handler) # type: ignore + _app.add_exception_handler( + starlette.exceptions.HTTPException, http_exception_handler + ) # type: ignore _app.add_exception_handler(Exception, default_exception_handler) # type: ignore @@ -29,7 +35,9 @@ def __register_service(service: AbstractFernService) -> fastapi.APIRouter: def register_validators(module: types.ModuleType) -> None: validators_directory: str = os.path.dirname(module.__file__) # type: ignore - for path in glob.glob(os.path.join(validators_directory, "**/*.py"), recursive=True): + for path in glob.glob( + os.path.join(validators_directory, "**/*.py"), recursive=True + ): if os.path.isfile(path): relative_path = os.path.relpath(path, start=validators_directory) module_path = ".".join([module.__name__] + relative_path[:-3].split("/")) diff --git a/seed/fastapi/objects-with-imports/resources/commons/resources/metadata/types/metadata.py b/seed/fastapi/objects-with-imports/resources/commons/resources/metadata/types/metadata.py index 39bccb29108..f2c79558c46 100644 --- a/seed/fastapi/objects-with-imports/resources/commons/resources/metadata/types/metadata.py +++ b/seed/fastapi/objects-with-imports/resources/commons/resources/metadata/types/metadata.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from ......core.pydantic_utilities import UniversalBaseModel import typing - +from ......core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class Metadata(UniversalBaseModel): """ @@ -25,7 +24,9 @@ class Metadata(UniversalBaseModel): data: typing.Optional[typing.Dict[str, str]] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/objects-with-imports/resources/file/resources/directory/types/directory.py b/seed/fastapi/objects-with-imports/resources/file/resources/directory/types/directory.py index 7eaebcad1fe..4e6204344d6 100644 --- a/seed/fastapi/objects-with-imports/resources/file/resources/directory/types/directory.py +++ b/seed/fastapi/objects-with-imports/resources/file/resources/directory/types/directory.py @@ -1,13 +1,12 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ......core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel, update_forward_refs from ....types.file import File +from ......core.pydantic_utilities import IS_PYDANTIC_V2 +import pydantic +from ......core.pydantic_utilities import update_forward_refs class Directory(UniversalBaseModel): @@ -48,7 +47,9 @@ class Directory(UniversalBaseModel): directories: typing.Optional[typing.List[Directory]] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/objects-with-imports/resources/file/types/file.py b/seed/fastapi/objects-with-imports/resources/file/types/file.py index 8963106e234..55a0fb80777 100644 --- a/seed/fastapi/objects-with-imports/resources/file/types/file.py +++ b/seed/fastapi/objects-with-imports/resources/file/types/file.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel +from .file_info import FileInfo +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .file_info import FileInfo - class File(UniversalBaseModel): """ @@ -26,7 +25,9 @@ class File(UniversalBaseModel): info: FileInfo if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/objects-with-imports/resources/file/types/file_info.py b/seed/fastapi/objects-with-imports/resources/file/types/file_info.py index 07bed3291c2..baffc5ea57a 100644 --- a/seed/fastapi/objects-with-imports/resources/file/types/file_info.py +++ b/seed/fastapi/objects-with-imports/resources/file/types/file_info.py @@ -25,7 +25,11 @@ class FileInfo(str, enum.Enum): A directory (e.g. foo/). """ - def visit(self, regular: typing.Callable[[], T_Result], directory: typing.Callable[[], T_Result]) -> T_Result: + def visit( + self, + regular: typing.Callable[[], T_Result], + directory: typing.Callable[[], T_Result], + ) -> T_Result: if self is FileInfo.REGULAR: return regular() if self is FileInfo.DIRECTORY: diff --git a/seed/fastapi/objects-with-imports/types/node.py b/seed/fastapi/objects-with-imports/types/node.py index 41adb0f5c02..f4213ca190b 100644 --- a/seed/fastapi/objects-with-imports/types/node.py +++ b/seed/fastapi/objects-with-imports/types/node.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from ..core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from ..resources.commons.resources.metadata.types.metadata import Metadata +from ..core.pydantic_utilities import IS_PYDANTIC_V2 +import pydantic class Node(UniversalBaseModel): @@ -32,7 +31,9 @@ class Node(UniversalBaseModel): metadata: typing.Optional[Metadata] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/objects-with-imports/types/tree.py b/seed/fastapi/objects-with-imports/types/tree.py index 0f2c2759385..874f9ffa426 100644 --- a/seed/fastapi/objects-with-imports/types/tree.py +++ b/seed/fastapi/objects-with-imports/types/tree.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from ..core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .node import Node +from ..core.pydantic_utilities import IS_PYDANTIC_V2 +import pydantic class Tree(UniversalBaseModel): @@ -42,7 +41,9 @@ class Tree(UniversalBaseModel): nodes: typing.Optional[typing.List[Node]] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/optional/core/abstract_fern_service.py b/seed/fastapi/optional/core/abstract_fern_service.py index da7c8dc49c4..9966b4876da 100644 --- a/seed/fastapi/optional/core/abstract_fern_service.py +++ b/seed/fastapi/optional/core/abstract_fern_service.py @@ -7,5 +7,4 @@ class AbstractFernService(abc.ABC): @classmethod - def _init_fern(cls, router: fastapi.APIRouter) -> None: - ... + def _init_fern(cls, router: fastapi.APIRouter) -> None: ... diff --git a/seed/fastapi/optional/core/datetime_utils.py b/seed/fastapi/optional/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/fastapi/optional/core/datetime_utils.py +++ b/seed/fastapi/optional/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/fastapi/optional/core/exceptions/__init__.py b/seed/fastapi/optional/core/exceptions/__init__.py index 297d6e06f5f..dae4b8980c1 100644 --- a/seed/fastapi/optional/core/exceptions/__init__.py +++ b/seed/fastapi/optional/core/exceptions/__init__.py @@ -1,7 +1,11 @@ # This file was auto-generated by Fern from our API Definition. from .fern_http_exception import FernHTTPException -from .handlers import default_exception_handler, fern_http_exception_handler, http_exception_handler +from .handlers import ( + default_exception_handler, + fern_http_exception_handler, + http_exception_handler, +) from .unauthorized import UnauthorizedException __all__ = [ diff --git a/seed/fastapi/optional/core/exceptions/fern_http_exception.py b/seed/fastapi/optional/core/exceptions/fern_http_exception.py index bdf03862487..81610359a7f 100644 --- a/seed/fastapi/optional/core/exceptions/fern_http_exception.py +++ b/seed/fastapi/optional/core/exceptions/fern_http_exception.py @@ -1,14 +1,16 @@ # This file was auto-generated by Fern from our API Definition. import abc -import typing - import fastapi +import typing class FernHTTPException(abc.ABC, fastapi.HTTPException): def __init__( - self, status_code: int, name: typing.Optional[str] = None, content: typing.Optional[typing.Any] = None + self, + status_code: int, + name: typing.Optional[str] = None, + content: typing.Optional[typing.Any] = None, ): super().__init__(status_code=status_code) self.name = name @@ -17,4 +19,6 @@ def __init__( def to_json_response(self) -> fastapi.responses.JSONResponse: content = fastapi.encoders.jsonable_encoder(self.content, exclude_none=True) - return fastapi.responses.JSONResponse(content=content, status_code=self.status_code) + return fastapi.responses.JSONResponse( + content=content, status_code=self.status_code + ) diff --git a/seed/fastapi/optional/core/exceptions/handlers.py b/seed/fastapi/optional/core/exceptions/handlers.py index 6d8c4155c5a..ae1c2741f06 100644 --- a/seed/fastapi/optional/core/exceptions/handlers.py +++ b/seed/fastapi/optional/core/exceptions/handlers.py @@ -2,32 +2,49 @@ import logging -import fastapi import starlette import starlette.exceptions +import fastapi + from .fern_http_exception import FernHTTPException def fern_http_exception_handler( - request: fastapi.requests.Request, exc: FernHTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: FernHTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) return exc.to_json_response() def http_exception_handler( - request: fastapi.requests.Request, exc: starlette.exceptions.HTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: starlette.exceptions.HTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=exc.status_code, content=exc.detail).to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=exc.status_code, content=exc.detail + ).to_json_response() def default_exception_handler( - request: fastapi.requests.Request, exc: Exception, skip_log: bool = False + request: fastapi.requests.Request, + exc: Exception, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=500, content="Internal Server Error").to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=500, content="Internal Server Error" + ).to_json_response() diff --git a/seed/fastapi/optional/core/pydantic_utilities.py b/seed/fastapi/optional/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/fastapi/optional/core/pydantic_utilities.py +++ b/seed/fastapi/optional/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/fastapi/optional/core/route_args.py b/seed/fastapi/optional/core/route_args.py index 4228e2fe05d..bd940bf4ddd 100644 --- a/seed/fastapi/optional/core/route_args.py +++ b/seed/fastapi/optional/core/route_args.py @@ -20,9 +20,15 @@ class RouteArgs(typing_extensions.TypedDict): DEFAULT_ROUTE_ARGS = RouteArgs(openapi_extra=None, tags=None, include_in_schema=True) -def get_route_args(endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str) -> RouteArgs: - unwrapped = inspect.unwrap(endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY))) - route_args = typing.cast(RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS)) +def get_route_args( + endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str +) -> RouteArgs: + unwrapped = inspect.unwrap( + endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY)) + ) + route_args = typing.cast( + RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS) + ) if route_args["tags"] is None: return RouteArgs( openapi_extra=route_args["openapi_extra"], @@ -56,7 +62,11 @@ def decorator(endpoint_function: T) -> T: setattr( endpoint_function, FERN_CONFIG_KEY, - RouteArgs(openapi_extra=openapi_extra, tags=tags, include_in_schema=include_in_schema), + RouteArgs( + openapi_extra=openapi_extra, + tags=tags, + include_in_schema=include_in_schema, + ), ) return endpoint_function diff --git a/seed/fastapi/optional/register.py b/seed/fastapi/optional/register.py index 1146a9cf107..ec9ea42fc1f 100644 --- a/seed/fastapi/optional/register.py +++ b/seed/fastapi/optional/register.py @@ -1,31 +1,33 @@ # This file was auto-generated by Fern from our API Definition. -import glob -import importlib -import os -import types -import typing - import fastapi -import starlette.exceptions +from .resources.optional.service.service import AbstractOptionalService +import typing from fastapi import params - -from .core.abstract_fern_service import AbstractFernService -from .core.exceptions import default_exception_handler, fern_http_exception_handler, http_exception_handler from .core.exceptions.fern_http_exception import FernHTTPException -from .resources.optional.service.service import AbstractOptionalService +from .core.exceptions import fern_http_exception_handler +import starlette.exceptions +from .core.exceptions import http_exception_handler +from .core.exceptions import default_exception_handler +from .core.abstract_fern_service import AbstractFernService +import types +import os +import glob +import importlib def register( _app: fastapi.FastAPI, *, optional: AbstractOptionalService, - dependencies: typing.Optional[typing.Sequence[params.Depends]] = None + dependencies: typing.Optional[typing.Sequence[params.Depends]] = None, ) -> None: _app.include_router(__register_service(optional), dependencies=dependencies) _app.add_exception_handler(FernHTTPException, fern_http_exception_handler) # type: ignore - _app.add_exception_handler(starlette.exceptions.HTTPException, http_exception_handler) # type: ignore + _app.add_exception_handler( + starlette.exceptions.HTTPException, http_exception_handler + ) # type: ignore _app.add_exception_handler(Exception, default_exception_handler) # type: ignore @@ -37,7 +39,9 @@ def __register_service(service: AbstractFernService) -> fastapi.APIRouter: def register_validators(module: types.ModuleType) -> None: validators_directory: str = os.path.dirname(module.__file__) # type: ignore - for path in glob.glob(os.path.join(validators_directory, "**/*.py"), recursive=True): + for path in glob.glob( + os.path.join(validators_directory, "**/*.py"), recursive=True + ): if os.path.isfile(path): relative_path = os.path.relpath(path, start=validators_directory) module_path = ".".join([module.__name__] + relative_path[:-3].split("/")) diff --git a/seed/fastapi/optional/resources/optional/service/service.py b/seed/fastapi/optional/resources/optional/service/service.py index e491d19b6b2..dfbe0fb7566 100644 --- a/seed/fastapi/optional/resources/optional/service/service.py +++ b/seed/fastapi/optional/resources/optional/service/service.py @@ -1,15 +1,13 @@ # This file was auto-generated by Fern from our API Definition. -import abc -import functools -import inspect -import logging +from ....core.abstract_fern_service import AbstractFernService import typing - +import abc import fastapi - -from ....core.abstract_fern_service import AbstractFernService +import inspect from ....core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools from ....core.route_args import get_route_args @@ -23,8 +21,9 @@ class AbstractOptionalService(AbstractFernService): """ @abc.abstractmethod - def send_optional_body(self, *, body: typing.Optional[typing.Dict[str, typing.Any]] = None) -> str: - ... + def send_optional_body( + self, *, body: typing.Optional[typing.Dict[str, typing.Any]] = None + ) -> str: ... """ Below are internal methods used by Fern to register your implementation. @@ -39,14 +38,20 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_send_optional_body(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.send_optional_body) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) else: new_parameters.append(parameter) - setattr(cls.send_optional_body, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.send_optional_body, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.send_optional_body) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> str: diff --git a/seed/fastapi/package-yml/core/abstract_fern_service.py b/seed/fastapi/package-yml/core/abstract_fern_service.py index da7c8dc49c4..9966b4876da 100644 --- a/seed/fastapi/package-yml/core/abstract_fern_service.py +++ b/seed/fastapi/package-yml/core/abstract_fern_service.py @@ -7,5 +7,4 @@ class AbstractFernService(abc.ABC): @classmethod - def _init_fern(cls, router: fastapi.APIRouter) -> None: - ... + def _init_fern(cls, router: fastapi.APIRouter) -> None: ... diff --git a/seed/fastapi/package-yml/core/datetime_utils.py b/seed/fastapi/package-yml/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/fastapi/package-yml/core/datetime_utils.py +++ b/seed/fastapi/package-yml/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/fastapi/package-yml/core/exceptions/__init__.py b/seed/fastapi/package-yml/core/exceptions/__init__.py index 297d6e06f5f..dae4b8980c1 100644 --- a/seed/fastapi/package-yml/core/exceptions/__init__.py +++ b/seed/fastapi/package-yml/core/exceptions/__init__.py @@ -1,7 +1,11 @@ # This file was auto-generated by Fern from our API Definition. from .fern_http_exception import FernHTTPException -from .handlers import default_exception_handler, fern_http_exception_handler, http_exception_handler +from .handlers import ( + default_exception_handler, + fern_http_exception_handler, + http_exception_handler, +) from .unauthorized import UnauthorizedException __all__ = [ diff --git a/seed/fastapi/package-yml/core/exceptions/fern_http_exception.py b/seed/fastapi/package-yml/core/exceptions/fern_http_exception.py index bdf03862487..81610359a7f 100644 --- a/seed/fastapi/package-yml/core/exceptions/fern_http_exception.py +++ b/seed/fastapi/package-yml/core/exceptions/fern_http_exception.py @@ -1,14 +1,16 @@ # This file was auto-generated by Fern from our API Definition. import abc -import typing - import fastapi +import typing class FernHTTPException(abc.ABC, fastapi.HTTPException): def __init__( - self, status_code: int, name: typing.Optional[str] = None, content: typing.Optional[typing.Any] = None + self, + status_code: int, + name: typing.Optional[str] = None, + content: typing.Optional[typing.Any] = None, ): super().__init__(status_code=status_code) self.name = name @@ -17,4 +19,6 @@ def __init__( def to_json_response(self) -> fastapi.responses.JSONResponse: content = fastapi.encoders.jsonable_encoder(self.content, exclude_none=True) - return fastapi.responses.JSONResponse(content=content, status_code=self.status_code) + return fastapi.responses.JSONResponse( + content=content, status_code=self.status_code + ) diff --git a/seed/fastapi/package-yml/core/exceptions/handlers.py b/seed/fastapi/package-yml/core/exceptions/handlers.py index 6d8c4155c5a..ae1c2741f06 100644 --- a/seed/fastapi/package-yml/core/exceptions/handlers.py +++ b/seed/fastapi/package-yml/core/exceptions/handlers.py @@ -2,32 +2,49 @@ import logging -import fastapi import starlette import starlette.exceptions +import fastapi + from .fern_http_exception import FernHTTPException def fern_http_exception_handler( - request: fastapi.requests.Request, exc: FernHTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: FernHTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) return exc.to_json_response() def http_exception_handler( - request: fastapi.requests.Request, exc: starlette.exceptions.HTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: starlette.exceptions.HTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=exc.status_code, content=exc.detail).to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=exc.status_code, content=exc.detail + ).to_json_response() def default_exception_handler( - request: fastapi.requests.Request, exc: Exception, skip_log: bool = False + request: fastapi.requests.Request, + exc: Exception, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=500, content="Internal Server Error").to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=500, content="Internal Server Error" + ).to_json_response() diff --git a/seed/fastapi/package-yml/core/pydantic_utilities.py b/seed/fastapi/package-yml/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/fastapi/package-yml/core/pydantic_utilities.py +++ b/seed/fastapi/package-yml/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/fastapi/package-yml/core/route_args.py b/seed/fastapi/package-yml/core/route_args.py index 4228e2fe05d..bd940bf4ddd 100644 --- a/seed/fastapi/package-yml/core/route_args.py +++ b/seed/fastapi/package-yml/core/route_args.py @@ -20,9 +20,15 @@ class RouteArgs(typing_extensions.TypedDict): DEFAULT_ROUTE_ARGS = RouteArgs(openapi_extra=None, tags=None, include_in_schema=True) -def get_route_args(endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str) -> RouteArgs: - unwrapped = inspect.unwrap(endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY))) - route_args = typing.cast(RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS)) +def get_route_args( + endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str +) -> RouteArgs: + unwrapped = inspect.unwrap( + endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY)) + ) + route_args = typing.cast( + RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS) + ) if route_args["tags"] is None: return RouteArgs( openapi_extra=route_args["openapi_extra"], @@ -56,7 +62,11 @@ def decorator(endpoint_function: T) -> T: setattr( endpoint_function, FERN_CONFIG_KEY, - RouteArgs(openapi_extra=openapi_extra, tags=tags, include_in_schema=include_in_schema), + RouteArgs( + openapi_extra=openapi_extra, + tags=tags, + include_in_schema=include_in_schema, + ), ) return endpoint_function diff --git a/seed/fastapi/package-yml/register.py b/seed/fastapi/package-yml/register.py index c588a94787f..392f0186682 100644 --- a/seed/fastapi/package-yml/register.py +++ b/seed/fastapi/package-yml/register.py @@ -1,20 +1,20 @@ # This file was auto-generated by Fern from our API Definition. -import glob -import importlib -import os -import types -import typing - import fastapi -import starlette.exceptions +from .service.service import AbstractRootService +from .resources.service.service.service import AbstractServiceService +import typing from fastapi import params - -from .core.abstract_fern_service import AbstractFernService -from .core.exceptions import default_exception_handler, fern_http_exception_handler, http_exception_handler from .core.exceptions.fern_http_exception import FernHTTPException -from .resources.service.service.service import AbstractServiceService -from .service.service import AbstractRootService +from .core.exceptions import fern_http_exception_handler +import starlette.exceptions +from .core.exceptions import http_exception_handler +from .core.exceptions import default_exception_handler +from .core.abstract_fern_service import AbstractFernService +import types +import os +import glob +import importlib def register( @@ -22,13 +22,15 @@ def register( *, root: AbstractRootService, service: AbstractServiceService, - dependencies: typing.Optional[typing.Sequence[params.Depends]] = None + dependencies: typing.Optional[typing.Sequence[params.Depends]] = None, ) -> None: _app.include_router(__register_service(root), dependencies=dependencies) _app.include_router(__register_service(service), dependencies=dependencies) _app.add_exception_handler(FernHTTPException, fern_http_exception_handler) # type: ignore - _app.add_exception_handler(starlette.exceptions.HTTPException, http_exception_handler) # type: ignore + _app.add_exception_handler( + starlette.exceptions.HTTPException, http_exception_handler + ) # type: ignore _app.add_exception_handler(Exception, default_exception_handler) # type: ignore @@ -40,7 +42,9 @@ def __register_service(service: AbstractFernService) -> fastapi.APIRouter: def register_validators(module: types.ModuleType) -> None: validators_directory: str = os.path.dirname(module.__file__) # type: ignore - for path in glob.glob(os.path.join(validators_directory, "**/*.py"), recursive=True): + for path in glob.glob( + os.path.join(validators_directory, "**/*.py"), recursive=True + ): if os.path.isfile(path): relative_path = os.path.relpath(path, start=validators_directory) module_path = ".".join([module.__name__] + relative_path[:-3].split("/")) diff --git a/seed/fastapi/package-yml/resources/service/service/service.py b/seed/fastapi/package-yml/resources/service/service/service.py index 0a8ba159fab..30413b0fd8c 100644 --- a/seed/fastapi/package-yml/resources/service/service/service.py +++ b/seed/fastapi/package-yml/resources/service/service/service.py @@ -1,16 +1,14 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.abstract_fern_service import AbstractFernService import abc -import functools +import fastapi import inspect -import logging import typing - -import fastapi -import starlette - -from ....core.abstract_fern_service import AbstractFernService from ....core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools +import starlette from ....core.route_args import get_route_args @@ -24,8 +22,7 @@ class AbstractServiceService(AbstractFernService): """ @abc.abstractmethod - def nop(self, *, nested_id: str) -> None: - ... + def nop(self, *, nested_id: str) -> None: ... """ Below are internal methods used by Fern to register your implementation. @@ -40,14 +37,20 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_nop(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.nop) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "nested_id": new_parameters.append(parameter.replace(default=fastapi.Path(...))) else: new_parameters.append(parameter) - setattr(cls.nop, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.nop, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.nop) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> None: diff --git a/seed/fastapi/package-yml/service/service.py b/seed/fastapi/package-yml/service/service.py index a0a4decd914..e958728b213 100644 --- a/seed/fastapi/package-yml/service/service.py +++ b/seed/fastapi/package-yml/service/service.py @@ -1,17 +1,15 @@ # This file was auto-generated by Fern from our API Definition. +from ..core.abstract_fern_service import AbstractFernService +from ..types.echo_request import EchoRequest import abc -import functools +import fastapi import inspect -import logging import typing - -import fastapi - -from ..core.abstract_fern_service import AbstractFernService from ..core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools from ..core.route_args import get_route_args -from ..types.echo_request import EchoRequest class AbstractRootService(AbstractFernService): @@ -24,8 +22,7 @@ class AbstractRootService(AbstractFernService): """ @abc.abstractmethod - def echo(self, *, body: EchoRequest) -> str: - ... + def echo(self, *, body: EchoRequest) -> str: ... """ Below are internal methods used by Fern to register your implementation. @@ -40,14 +37,20 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_echo(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.echo) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) else: new_parameters.append(parameter) - setattr(cls.echo, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.echo, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.echo) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> str: diff --git a/seed/fastapi/package-yml/types/echo_request.py b/seed/fastapi/package-yml/types/echo_request.py index c9fafd06362..f644927acbe 100644 --- a/seed/fastapi/package-yml/types/echo_request.py +++ b/seed/fastapi/package-yml/types/echo_request.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from ..core.pydantic_utilities import UniversalBaseModel +from ..core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class EchoRequest(UniversalBaseModel): name: str size: int if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/pagination/core/abstract_fern_service.py b/seed/fastapi/pagination/core/abstract_fern_service.py index da7c8dc49c4..9966b4876da 100644 --- a/seed/fastapi/pagination/core/abstract_fern_service.py +++ b/seed/fastapi/pagination/core/abstract_fern_service.py @@ -7,5 +7,4 @@ class AbstractFernService(abc.ABC): @classmethod - def _init_fern(cls, router: fastapi.APIRouter) -> None: - ... + def _init_fern(cls, router: fastapi.APIRouter) -> None: ... diff --git a/seed/fastapi/pagination/core/datetime_utils.py b/seed/fastapi/pagination/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/fastapi/pagination/core/datetime_utils.py +++ b/seed/fastapi/pagination/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/fastapi/pagination/core/exceptions/__init__.py b/seed/fastapi/pagination/core/exceptions/__init__.py index 297d6e06f5f..dae4b8980c1 100644 --- a/seed/fastapi/pagination/core/exceptions/__init__.py +++ b/seed/fastapi/pagination/core/exceptions/__init__.py @@ -1,7 +1,11 @@ # This file was auto-generated by Fern from our API Definition. from .fern_http_exception import FernHTTPException -from .handlers import default_exception_handler, fern_http_exception_handler, http_exception_handler +from .handlers import ( + default_exception_handler, + fern_http_exception_handler, + http_exception_handler, +) from .unauthorized import UnauthorizedException __all__ = [ diff --git a/seed/fastapi/pagination/core/exceptions/fern_http_exception.py b/seed/fastapi/pagination/core/exceptions/fern_http_exception.py index bdf03862487..81610359a7f 100644 --- a/seed/fastapi/pagination/core/exceptions/fern_http_exception.py +++ b/seed/fastapi/pagination/core/exceptions/fern_http_exception.py @@ -1,14 +1,16 @@ # This file was auto-generated by Fern from our API Definition. import abc -import typing - import fastapi +import typing class FernHTTPException(abc.ABC, fastapi.HTTPException): def __init__( - self, status_code: int, name: typing.Optional[str] = None, content: typing.Optional[typing.Any] = None + self, + status_code: int, + name: typing.Optional[str] = None, + content: typing.Optional[typing.Any] = None, ): super().__init__(status_code=status_code) self.name = name @@ -17,4 +19,6 @@ def __init__( def to_json_response(self) -> fastapi.responses.JSONResponse: content = fastapi.encoders.jsonable_encoder(self.content, exclude_none=True) - return fastapi.responses.JSONResponse(content=content, status_code=self.status_code) + return fastapi.responses.JSONResponse( + content=content, status_code=self.status_code + ) diff --git a/seed/fastapi/pagination/core/exceptions/handlers.py b/seed/fastapi/pagination/core/exceptions/handlers.py index 6d8c4155c5a..ae1c2741f06 100644 --- a/seed/fastapi/pagination/core/exceptions/handlers.py +++ b/seed/fastapi/pagination/core/exceptions/handlers.py @@ -2,32 +2,49 @@ import logging -import fastapi import starlette import starlette.exceptions +import fastapi + from .fern_http_exception import FernHTTPException def fern_http_exception_handler( - request: fastapi.requests.Request, exc: FernHTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: FernHTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) return exc.to_json_response() def http_exception_handler( - request: fastapi.requests.Request, exc: starlette.exceptions.HTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: starlette.exceptions.HTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=exc.status_code, content=exc.detail).to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=exc.status_code, content=exc.detail + ).to_json_response() def default_exception_handler( - request: fastapi.requests.Request, exc: Exception, skip_log: bool = False + request: fastapi.requests.Request, + exc: Exception, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=500, content="Internal Server Error").to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=500, content="Internal Server Error" + ).to_json_response() diff --git a/seed/fastapi/pagination/core/pydantic_utilities.py b/seed/fastapi/pagination/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/fastapi/pagination/core/pydantic_utilities.py +++ b/seed/fastapi/pagination/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/fastapi/pagination/core/route_args.py b/seed/fastapi/pagination/core/route_args.py index 4228e2fe05d..bd940bf4ddd 100644 --- a/seed/fastapi/pagination/core/route_args.py +++ b/seed/fastapi/pagination/core/route_args.py @@ -20,9 +20,15 @@ class RouteArgs(typing_extensions.TypedDict): DEFAULT_ROUTE_ARGS = RouteArgs(openapi_extra=None, tags=None, include_in_schema=True) -def get_route_args(endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str) -> RouteArgs: - unwrapped = inspect.unwrap(endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY))) - route_args = typing.cast(RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS)) +def get_route_args( + endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str +) -> RouteArgs: + unwrapped = inspect.unwrap( + endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY)) + ) + route_args = typing.cast( + RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS) + ) if route_args["tags"] is None: return RouteArgs( openapi_extra=route_args["openapi_extra"], @@ -56,7 +62,11 @@ def decorator(endpoint_function: T) -> T: setattr( endpoint_function, FERN_CONFIG_KEY, - RouteArgs(openapi_extra=openapi_extra, tags=tags, include_in_schema=include_in_schema), + RouteArgs( + openapi_extra=openapi_extra, + tags=tags, + include_in_schema=include_in_schema, + ), ) return endpoint_function diff --git a/seed/fastapi/pagination/register.py b/seed/fastapi/pagination/register.py index 8a51fa75c51..89e54f8a8ff 100644 --- a/seed/fastapi/pagination/register.py +++ b/seed/fastapi/pagination/register.py @@ -1,31 +1,33 @@ # This file was auto-generated by Fern from our API Definition. -import glob -import importlib -import os -import types -import typing - import fastapi -import starlette.exceptions +from .resources.users.service.service import AbstractUsersService +import typing from fastapi import params - -from .core.abstract_fern_service import AbstractFernService -from .core.exceptions import default_exception_handler, fern_http_exception_handler, http_exception_handler from .core.exceptions.fern_http_exception import FernHTTPException -from .resources.users.service.service import AbstractUsersService +from .core.exceptions import fern_http_exception_handler +import starlette.exceptions +from .core.exceptions import http_exception_handler +from .core.exceptions import default_exception_handler +from .core.abstract_fern_service import AbstractFernService +import types +import os +import glob +import importlib def register( _app: fastapi.FastAPI, *, users: AbstractUsersService, - dependencies: typing.Optional[typing.Sequence[params.Depends]] = None + dependencies: typing.Optional[typing.Sequence[params.Depends]] = None, ) -> None: _app.include_router(__register_service(users), dependencies=dependencies) _app.add_exception_handler(FernHTTPException, fern_http_exception_handler) # type: ignore - _app.add_exception_handler(starlette.exceptions.HTTPException, http_exception_handler) # type: ignore + _app.add_exception_handler( + starlette.exceptions.HTTPException, http_exception_handler + ) # type: ignore _app.add_exception_handler(Exception, default_exception_handler) # type: ignore @@ -37,7 +39,9 @@ def __register_service(service: AbstractFernService) -> fastapi.APIRouter: def register_validators(module: types.ModuleType) -> None: validators_directory: str = os.path.dirname(module.__file__) # type: ignore - for path in glob.glob(os.path.join(validators_directory, "**/*.py"), recursive=True): + for path in glob.glob( + os.path.join(validators_directory, "**/*.py"), recursive=True + ): if os.path.isfile(path): relative_path = os.path.relpath(path, start=validators_directory) module_path = ".".join([module.__name__] + relative_path[:-3].split("/")) diff --git a/seed/fastapi/pagination/resources/users/__init__.py b/seed/fastapi/pagination/resources/users/__init__.py index 949bddc6cf6..2de908d5f7a 100644 --- a/seed/fastapi/pagination/resources/users/__init__.py +++ b/seed/fastapi/pagination/resources/users/__init__.py @@ -1,6 +1,9 @@ # This file was auto-generated by Fern from our API Definition. -from .service import ListUsersBodyCursorPaginationRequest, ListUsersBodyOffsetPaginationRequest +from .service import ( + ListUsersBodyCursorPaginationRequest, + ListUsersBodyOffsetPaginationRequest, +) from .types import ( ListUsersExtendedResponse, ListUsersPaginationResponse, diff --git a/seed/fastapi/pagination/resources/users/service/__init__.py b/seed/fastapi/pagination/resources/users/service/__init__.py index d11054d72af..e33af37b67a 100644 --- a/seed/fastapi/pagination/resources/users/service/__init__.py +++ b/seed/fastapi/pagination/resources/users/service/__init__.py @@ -1,7 +1,15 @@ # This file was auto-generated by Fern from our API Definition. -from .list_users_body_cursor_pagination_request import ListUsersBodyCursorPaginationRequest -from .list_users_body_offset_pagination_request import ListUsersBodyOffsetPaginationRequest +from .list_users_body_cursor_pagination_request import ( + ListUsersBodyCursorPaginationRequest, +) +from .list_users_body_offset_pagination_request import ( + ListUsersBodyOffsetPaginationRequest, +) from .service import AbstractUsersService -__all__ = ["AbstractUsersService", "ListUsersBodyCursorPaginationRequest", "ListUsersBodyOffsetPaginationRequest"] +__all__ = [ + "AbstractUsersService", + "ListUsersBodyCursorPaginationRequest", + "ListUsersBodyOffsetPaginationRequest", +] diff --git a/seed/fastapi/pagination/resources/users/service/list_users_body_cursor_pagination_request.py b/seed/fastapi/pagination/resources/users/service/list_users_body_cursor_pagination_request.py index 1855478f440..53ceeefb457 100644 --- a/seed/fastapi/pagination/resources/users/service/list_users_body_cursor_pagination_request.py +++ b/seed/fastapi/pagination/resources/users/service/list_users_body_cursor_pagination_request.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from ..types.with_cursor import WithCursor +import pydantic +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class ListUsersBodyCursorPaginationRequest(UniversalBaseModel): @@ -16,7 +15,9 @@ class ListUsersBodyCursorPaginationRequest(UniversalBaseModel): """ if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/pagination/resources/users/service/list_users_body_offset_pagination_request.py b/seed/fastapi/pagination/resources/users/service/list_users_body_offset_pagination_request.py index 25e2644c345..18bdb14b914 100644 --- a/seed/fastapi/pagination/resources/users/service/list_users_body_offset_pagination_request.py +++ b/seed/fastapi/pagination/resources/users/service/list_users_body_offset_pagination_request.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from ..types.with_page import WithPage +import pydantic +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class ListUsersBodyOffsetPaginationRequest(UniversalBaseModel): @@ -16,7 +15,9 @@ class ListUsersBodyOffsetPaginationRequest(UniversalBaseModel): """ if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/pagination/resources/users/service/service.py b/seed/fastapi/pagination/resources/users/service/service.py index ea1f342b11d..a738f2e0f8e 100644 --- a/seed/fastapi/pagination/resources/users/service/service.py +++ b/seed/fastapi/pagination/resources/users/service/service.py @@ -1,24 +1,26 @@ # This file was auto-generated by Fern from our API Definition. -import abc -import functools -import inspect -import logging +from ....core.abstract_fern_service import AbstractFernService import typing +from ..types.order import Order +from ..types.list_users_pagination_response import ListUsersPaginationResponse +import abc +from .list_users_body_cursor_pagination_request import ( + ListUsersBodyCursorPaginationRequest, +) +from .list_users_body_offset_pagination_request import ( + ListUsersBodyOffsetPaginationRequest, +) import uuid - +from ..types.list_users_extended_response import ListUsersExtendedResponse +from ....types.username_cursor import UsernameCursor +from ..types.username_container import UsernameContainer import fastapi - -from ....core.abstract_fern_service import AbstractFernService +import inspect from ....core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools from ....core.route_args import get_route_args -from ....types.username_cursor import UsernameCursor -from ..types.list_users_extended_response import ListUsersExtendedResponse -from ..types.list_users_pagination_response import ListUsersPaginationResponse -from ..types.order import Order -from ..types.username_container import UsernameContainer -from .list_users_body_cursor_pagination_request import ListUsersBodyCursorPaginationRequest -from .list_users_body_offset_pagination_request import ListUsersBodyOffsetPaginationRequest class AbstractUsersService(AbstractFernService): @@ -38,14 +40,12 @@ def list_with_cursor_pagination( per_page: typing.Optional[int] = None, order: typing.Optional[Order] = None, starting_after: typing.Optional[str] = None, - ) -> ListUsersPaginationResponse: - ... + ) -> ListUsersPaginationResponse: ... @abc.abstractmethod def list_with_body_cursor_pagination( self, *, body: ListUsersBodyCursorPaginationRequest - ) -> ListUsersPaginationResponse: - ... + ) -> ListUsersPaginationResponse: ... @abc.abstractmethod def list_with_offset_pagination( @@ -55,14 +55,12 @@ def list_with_offset_pagination( per_page: typing.Optional[int] = None, order: typing.Optional[Order] = None, starting_after: typing.Optional[str] = None, - ) -> ListUsersPaginationResponse: - ... + ) -> ListUsersPaginationResponse: ... @abc.abstractmethod def list_with_body_offset_pagination( self, *, body: ListUsersBodyOffsetPaginationRequest - ) -> ListUsersPaginationResponse: - ... + ) -> ListUsersPaginationResponse: ... @abc.abstractmethod def list_with_offset_step_pagination( @@ -71,20 +69,22 @@ def list_with_offset_step_pagination( page: typing.Optional[int] = None, limit: typing.Optional[int] = None, order: typing.Optional[Order] = None, - ) -> ListUsersPaginationResponse: - ... + ) -> ListUsersPaginationResponse: ... @abc.abstractmethod - def list_with_extended_results(self, *, cursor: typing.Optional[uuid.UUID] = None) -> ListUsersExtendedResponse: - ... + def list_with_extended_results( + self, *, cursor: typing.Optional[uuid.UUID] = None + ) -> ListUsersExtendedResponse: ... @abc.abstractmethod - def list_usernames(self, *, starting_after: typing.Optional[str] = None) -> UsernameCursor: - ... + def list_usernames( + self, *, starting_after: typing.Optional[str] = None + ) -> UsernameCursor: ... @abc.abstractmethod - def list_with_global_config(self, *, offset: typing.Optional[int] = None) -> UsernameContainer: - ... + def list_with_global_config( + self, *, offset: typing.Optional[int] = None + ) -> UsernameContainer: ... """ Below are internal methods used by Fern to register your implementation. @@ -106,19 +106,31 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_list_with_cursor_pagination(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.list_with_cursor_pagination) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "page": new_parameters.append( - parameter.replace(default=fastapi.Query(default=None, description="Defaults to first page")) + parameter.replace( + default=fastapi.Query( + default=None, description="Defaults to first page" + ) + ) ) elif parameter_name == "per_page": new_parameters.append( - parameter.replace(default=fastapi.Query(default=None, description="Defaults to per page")) + parameter.replace( + default=fastapi.Query( + default=None, description="Defaults to per page" + ) + ) ) elif parameter_name == "order": - new_parameters.append(parameter.replace(default=fastapi.Query(default=None))) + new_parameters.append( + parameter.replace(default=fastapi.Query(default=None)) + ) elif parameter_name == "starting_after": new_parameters.append( parameter.replace( @@ -130,10 +142,16 @@ def __init_list_with_cursor_pagination(cls, router: fastapi.APIRouter) -> None: ) else: new_parameters.append(parameter) - setattr(cls.list_with_cursor_pagination, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.list_with_cursor_pagination, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.list_with_cursor_pagination) - def wrapper(*args: typing.Any, **kwargs: typing.Any) -> ListUsersPaginationResponse: + def wrapper( + *args: typing.Any, **kwargs: typing.Any + ) -> ListUsersPaginationResponse: try: return cls.list_with_cursor_pagination(*args, **kwargs) except FernHTTPException as e: @@ -159,7 +177,9 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> ListUsersPaginationRespo def __init_list_with_body_cursor_pagination(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.list_with_body_cursor_pagination) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": @@ -167,11 +187,15 @@ def __init_list_with_body_cursor_pagination(cls, router: fastapi.APIRouter) -> N else: new_parameters.append(parameter) setattr( - cls.list_with_body_cursor_pagination, "__signature__", endpoint_function.replace(parameters=new_parameters) + cls.list_with_body_cursor_pagination, + "__signature__", + endpoint_function.replace(parameters=new_parameters), ) @functools.wraps(cls.list_with_body_cursor_pagination) - def wrapper(*args: typing.Any, **kwargs: typing.Any) -> ListUsersPaginationResponse: + def wrapper( + *args: typing.Any, **kwargs: typing.Any + ) -> ListUsersPaginationResponse: try: return cls.list_with_body_cursor_pagination(*args, **kwargs) except FernHTTPException as e: @@ -197,19 +221,31 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> ListUsersPaginationRespo def __init_list_with_offset_pagination(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.list_with_offset_pagination) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "page": new_parameters.append( - parameter.replace(default=fastapi.Query(default=None, description="Defaults to first page")) + parameter.replace( + default=fastapi.Query( + default=None, description="Defaults to first page" + ) + ) ) elif parameter_name == "per_page": new_parameters.append( - parameter.replace(default=fastapi.Query(default=None, description="Defaults to per page")) + parameter.replace( + default=fastapi.Query( + default=None, description="Defaults to per page" + ) + ) ) elif parameter_name == "order": - new_parameters.append(parameter.replace(default=fastapi.Query(default=None))) + new_parameters.append( + parameter.replace(default=fastapi.Query(default=None)) + ) elif parameter_name == "starting_after": new_parameters.append( parameter.replace( @@ -221,10 +257,16 @@ def __init_list_with_offset_pagination(cls, router: fastapi.APIRouter) -> None: ) else: new_parameters.append(parameter) - setattr(cls.list_with_offset_pagination, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.list_with_offset_pagination, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.list_with_offset_pagination) - def wrapper(*args: typing.Any, **kwargs: typing.Any) -> ListUsersPaginationResponse: + def wrapper( + *args: typing.Any, **kwargs: typing.Any + ) -> ListUsersPaginationResponse: try: return cls.list_with_offset_pagination(*args, **kwargs) except FernHTTPException as e: @@ -250,7 +292,9 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> ListUsersPaginationRespo def __init_list_with_body_offset_pagination(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.list_with_body_offset_pagination) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": @@ -258,11 +302,15 @@ def __init_list_with_body_offset_pagination(cls, router: fastapi.APIRouter) -> N else: new_parameters.append(parameter) setattr( - cls.list_with_body_offset_pagination, "__signature__", endpoint_function.replace(parameters=new_parameters) + cls.list_with_body_offset_pagination, + "__signature__", + endpoint_function.replace(parameters=new_parameters), ) @functools.wraps(cls.list_with_body_offset_pagination) - def wrapper(*args: typing.Any, **kwargs: typing.Any) -> ListUsersPaginationResponse: + def wrapper( + *args: typing.Any, **kwargs: typing.Any + ) -> ListUsersPaginationResponse: try: return cls.list_with_body_offset_pagination(*args, **kwargs) except FernHTTPException as e: @@ -288,12 +336,18 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> ListUsersPaginationRespo def __init_list_with_offset_step_pagination(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.list_with_offset_step_pagination) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "page": new_parameters.append( - parameter.replace(default=fastapi.Query(default=None, description="Defaults to first page")) + parameter.replace( + default=fastapi.Query( + default=None, description="Defaults to first page" + ) + ) ) elif parameter_name == "limit": new_parameters.append( @@ -305,15 +359,21 @@ def __init_list_with_offset_step_pagination(cls, router: fastapi.APIRouter) -> N ) ) elif parameter_name == "order": - new_parameters.append(parameter.replace(default=fastapi.Query(default=None))) + new_parameters.append( + parameter.replace(default=fastapi.Query(default=None)) + ) else: new_parameters.append(parameter) setattr( - cls.list_with_offset_step_pagination, "__signature__", endpoint_function.replace(parameters=new_parameters) + cls.list_with_offset_step_pagination, + "__signature__", + endpoint_function.replace(parameters=new_parameters), ) @functools.wraps(cls.list_with_offset_step_pagination) - def wrapper(*args: typing.Any, **kwargs: typing.Any) -> ListUsersPaginationResponse: + def wrapper( + *args: typing.Any, **kwargs: typing.Any + ) -> ListUsersPaginationResponse: try: return cls.list_with_offset_step_pagination(*args, **kwargs) except FernHTTPException as e: @@ -339,17 +399,27 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> ListUsersPaginationRespo def __init_list_with_extended_results(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.list_with_extended_results) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "cursor": - new_parameters.append(parameter.replace(default=fastapi.Query(default=None))) + new_parameters.append( + parameter.replace(default=fastapi.Query(default=None)) + ) else: new_parameters.append(parameter) - setattr(cls.list_with_extended_results, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.list_with_extended_results, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.list_with_extended_results) - def wrapper(*args: typing.Any, **kwargs: typing.Any) -> ListUsersExtendedResponse: + def wrapper( + *args: typing.Any, **kwargs: typing.Any + ) -> ListUsersExtendedResponse: try: return cls.list_with_extended_results(*args, **kwargs) except FernHTTPException as e: @@ -375,7 +445,9 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> ListUsersExtendedRespons def __init_list_usernames(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.list_usernames) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "starting_after": @@ -389,7 +461,11 @@ def __init_list_usernames(cls, router: fastapi.APIRouter) -> None: ) else: new_parameters.append(parameter) - setattr(cls.list_usernames, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.list_usernames, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.list_usernames) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> UsernameCursor: @@ -418,14 +494,22 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> UsernameCursor: def __init_list_with_global_config(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.list_with_global_config) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "offset": - new_parameters.append(parameter.replace(default=fastapi.Query(default=None))) + new_parameters.append( + parameter.replace(default=fastapi.Query(default=None)) + ) else: new_parameters.append(parameter) - setattr(cls.list_with_global_config, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.list_with_global_config, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.list_with_global_config) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> UsernameContainer: diff --git a/seed/fastapi/pagination/resources/users/types/list_users_extended_response.py b/seed/fastapi/pagination/resources/users/types/list_users_extended_response.py index 3b762695b84..839803a982c 100644 --- a/seed/fastapi/pagination/resources/users/types/list_users_extended_response.py +++ b/seed/fastapi/pagination/resources/users/types/list_users_extended_response.py @@ -1,11 +1,9 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from .user_page import UserPage import pydantic - from ....core.pydantic_utilities import IS_PYDANTIC_V2 -from .user_page import UserPage +import typing class ListUsersExtendedResponse(UserPage): @@ -15,7 +13,9 @@ class ListUsersExtendedResponse(UserPage): """ if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/pagination/resources/users/types/list_users_pagination_response.py b/seed/fastapi/pagination/resources/users/types/list_users_pagination_response.py index 6c39a19fb9c..c5d244f35af 100644 --- a/seed/fastapi/pagination/resources/users/types/list_users_pagination_response.py +++ b/seed/fastapi/pagination/resources/users/types/list_users_pagination_response.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .page import Page +import pydantic from .user import User +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class ListUsersPaginationResponse(UniversalBaseModel): @@ -19,7 +18,9 @@ class ListUsersPaginationResponse(UniversalBaseModel): data: typing.List[User] if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/pagination/resources/users/types/next_page.py b/seed/fastapi/pagination/resources/users/types/next_page.py index b11737fc181..b19a5ebc920 100644 --- a/seed/fastapi/pagination/resources/users/types/next_page.py +++ b/seed/fastapi/pagination/resources/users/types/next_page.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class NextPage(UniversalBaseModel): page: int starting_after: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/pagination/resources/users/types/order.py b/seed/fastapi/pagination/resources/users/types/order.py index b1ff15120e8..2d2aea94883 100644 --- a/seed/fastapi/pagination/resources/users/types/order.py +++ b/seed/fastapi/pagination/resources/users/types/order.py @@ -10,7 +10,9 @@ class Order(str, enum.Enum): ASC = "asc" DESC = "desc" - def visit(self, asc: typing.Callable[[], T_Result], desc: typing.Callable[[], T_Result]) -> T_Result: + def visit( + self, asc: typing.Callable[[], T_Result], desc: typing.Callable[[], T_Result] + ) -> T_Result: if self is Order.ASC: return asc() if self is Order.DESC: diff --git a/seed/fastapi/pagination/resources/users/types/page.py b/seed/fastapi/pagination/resources/users/types/page.py index cdec717eff0..e8dc813d035 100644 --- a/seed/fastapi/pagination/resources/users/types/page.py +++ b/seed/fastapi/pagination/resources/users/types/page.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ....core.pydantic_utilities import UniversalBaseModel import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +import typing from .next_page import NextPage +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class Page(UniversalBaseModel): @@ -19,7 +18,9 @@ class Page(UniversalBaseModel): total_page: int if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/pagination/resources/users/types/user.py b/seed/fastapi/pagination/resources/users/types/user.py index c862ea14b0d..5bc0e8b41e6 100644 --- a/seed/fastapi/pagination/resources/users/types/user.py +++ b/seed/fastapi/pagination/resources/users/types/user.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class User(UniversalBaseModel): name: str id: int if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/pagination/resources/users/types/user_list_container.py b/seed/fastapi/pagination/resources/users/types/user_list_container.py index 6fa95e435c3..6f519d6bbae 100644 --- a/seed/fastapi/pagination/resources/users/types/user_list_container.py +++ b/seed/fastapi/pagination/resources/users/types/user_list_container.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .user import User +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import pydantic class UserListContainer(UniversalBaseModel): users: typing.List[User] if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/pagination/resources/users/types/user_page.py b/seed/fastapi/pagination/resources/users/types/user_page.py index 6c409f7d6ab..31d33ca066b 100644 --- a/seed/fastapi/pagination/resources/users/types/user_page.py +++ b/seed/fastapi/pagination/resources/users/types/user_page.py @@ -1,20 +1,21 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel +from .user_list_container import UserListContainer import typing import uuid - +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .user_list_container import UserListContainer - class UserPage(UniversalBaseModel): data: UserListContainer next: typing.Optional[uuid.UUID] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/pagination/resources/users/types/username_container.py b/seed/fastapi/pagination/resources/users/types/username_container.py index ab121bef264..4282cbce0e6 100644 --- a/seed/fastapi/pagination/resources/users/types/username_container.py +++ b/seed/fastapi/pagination/resources/users/types/username_container.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class UsernameContainer(UniversalBaseModel): results: typing.List[str] if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/pagination/resources/users/types/with_cursor.py b/seed/fastapi/pagination/resources/users/types/with_cursor.py index d22da0a0161..06407bcd6d6 100644 --- a/seed/fastapi/pagination/resources/users/types/with_cursor.py +++ b/seed/fastapi/pagination/resources/users/types/with_cursor.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class WithCursor(UniversalBaseModel): cursor: typing.Optional[str] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/pagination/resources/users/types/with_page.py b/seed/fastapi/pagination/resources/users/types/with_page.py index 874f2017ba6..c3dd3faa093 100644 --- a/seed/fastapi/pagination/resources/users/types/with_page.py +++ b/seed/fastapi/pagination/resources/users/types/with_page.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class WithPage(UniversalBaseModel): page: typing.Optional[int] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/pagination/security.py b/seed/fastapi/pagination/security.py index bab014441e1..4ccabc21106 100644 --- a/seed/fastapi/pagination/security.py +++ b/seed/fastapi/pagination/security.py @@ -1,8 +1,8 @@ # This file was auto-generated by Fern from our API Definition. +from .core.security.bearer import BearerToken import fastapi - -from .core.security.bearer import BearerToken, HTTPBearer +from .core.security.bearer import HTTPBearer ApiAuth = BearerToken diff --git a/seed/fastapi/pagination/types/username_cursor.py b/seed/fastapi/pagination/types/username_cursor.py index fcbeb662c4e..cc468f2cfb2 100644 --- a/seed/fastapi/pagination/types/username_cursor.py +++ b/seed/fastapi/pagination/types/username_cursor.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from ..core.pydantic_utilities import UniversalBaseModel +from .username_page import UsernamePage +from ..core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .username_page import UsernamePage - class UsernameCursor(UniversalBaseModel): cursor: UsernamePage if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/pagination/types/username_page.py b/seed/fastapi/pagination/types/username_page.py index fe811db7428..c86319b5fc0 100644 --- a/seed/fastapi/pagination/types/username_page.py +++ b/seed/fastapi/pagination/types/username_page.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from ..core.pydantic_utilities import UniversalBaseModel import typing - +from ..core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class UsernamePage(UniversalBaseModel): after: typing.Optional[str] = None data: typing.List[str] if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/plain-text/core/abstract_fern_service.py b/seed/fastapi/plain-text/core/abstract_fern_service.py index da7c8dc49c4..9966b4876da 100644 --- a/seed/fastapi/plain-text/core/abstract_fern_service.py +++ b/seed/fastapi/plain-text/core/abstract_fern_service.py @@ -7,5 +7,4 @@ class AbstractFernService(abc.ABC): @classmethod - def _init_fern(cls, router: fastapi.APIRouter) -> None: - ... + def _init_fern(cls, router: fastapi.APIRouter) -> None: ... diff --git a/seed/fastapi/plain-text/core/datetime_utils.py b/seed/fastapi/plain-text/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/fastapi/plain-text/core/datetime_utils.py +++ b/seed/fastapi/plain-text/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/fastapi/plain-text/core/exceptions/__init__.py b/seed/fastapi/plain-text/core/exceptions/__init__.py index 297d6e06f5f..dae4b8980c1 100644 --- a/seed/fastapi/plain-text/core/exceptions/__init__.py +++ b/seed/fastapi/plain-text/core/exceptions/__init__.py @@ -1,7 +1,11 @@ # This file was auto-generated by Fern from our API Definition. from .fern_http_exception import FernHTTPException -from .handlers import default_exception_handler, fern_http_exception_handler, http_exception_handler +from .handlers import ( + default_exception_handler, + fern_http_exception_handler, + http_exception_handler, +) from .unauthorized import UnauthorizedException __all__ = [ diff --git a/seed/fastapi/plain-text/core/exceptions/fern_http_exception.py b/seed/fastapi/plain-text/core/exceptions/fern_http_exception.py index bdf03862487..81610359a7f 100644 --- a/seed/fastapi/plain-text/core/exceptions/fern_http_exception.py +++ b/seed/fastapi/plain-text/core/exceptions/fern_http_exception.py @@ -1,14 +1,16 @@ # This file was auto-generated by Fern from our API Definition. import abc -import typing - import fastapi +import typing class FernHTTPException(abc.ABC, fastapi.HTTPException): def __init__( - self, status_code: int, name: typing.Optional[str] = None, content: typing.Optional[typing.Any] = None + self, + status_code: int, + name: typing.Optional[str] = None, + content: typing.Optional[typing.Any] = None, ): super().__init__(status_code=status_code) self.name = name @@ -17,4 +19,6 @@ def __init__( def to_json_response(self) -> fastapi.responses.JSONResponse: content = fastapi.encoders.jsonable_encoder(self.content, exclude_none=True) - return fastapi.responses.JSONResponse(content=content, status_code=self.status_code) + return fastapi.responses.JSONResponse( + content=content, status_code=self.status_code + ) diff --git a/seed/fastapi/plain-text/core/exceptions/handlers.py b/seed/fastapi/plain-text/core/exceptions/handlers.py index 6d8c4155c5a..ae1c2741f06 100644 --- a/seed/fastapi/plain-text/core/exceptions/handlers.py +++ b/seed/fastapi/plain-text/core/exceptions/handlers.py @@ -2,32 +2,49 @@ import logging -import fastapi import starlette import starlette.exceptions +import fastapi + from .fern_http_exception import FernHTTPException def fern_http_exception_handler( - request: fastapi.requests.Request, exc: FernHTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: FernHTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) return exc.to_json_response() def http_exception_handler( - request: fastapi.requests.Request, exc: starlette.exceptions.HTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: starlette.exceptions.HTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=exc.status_code, content=exc.detail).to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=exc.status_code, content=exc.detail + ).to_json_response() def default_exception_handler( - request: fastapi.requests.Request, exc: Exception, skip_log: bool = False + request: fastapi.requests.Request, + exc: Exception, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=500, content="Internal Server Error").to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=500, content="Internal Server Error" + ).to_json_response() diff --git a/seed/fastapi/plain-text/core/pydantic_utilities.py b/seed/fastapi/plain-text/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/fastapi/plain-text/core/pydantic_utilities.py +++ b/seed/fastapi/plain-text/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/fastapi/plain-text/core/route_args.py b/seed/fastapi/plain-text/core/route_args.py index 4228e2fe05d..bd940bf4ddd 100644 --- a/seed/fastapi/plain-text/core/route_args.py +++ b/seed/fastapi/plain-text/core/route_args.py @@ -20,9 +20,15 @@ class RouteArgs(typing_extensions.TypedDict): DEFAULT_ROUTE_ARGS = RouteArgs(openapi_extra=None, tags=None, include_in_schema=True) -def get_route_args(endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str) -> RouteArgs: - unwrapped = inspect.unwrap(endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY))) - route_args = typing.cast(RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS)) +def get_route_args( + endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str +) -> RouteArgs: + unwrapped = inspect.unwrap( + endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY)) + ) + route_args = typing.cast( + RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS) + ) if route_args["tags"] is None: return RouteArgs( openapi_extra=route_args["openapi_extra"], @@ -56,7 +62,11 @@ def decorator(endpoint_function: T) -> T: setattr( endpoint_function, FERN_CONFIG_KEY, - RouteArgs(openapi_extra=openapi_extra, tags=tags, include_in_schema=include_in_schema), + RouteArgs( + openapi_extra=openapi_extra, + tags=tags, + include_in_schema=include_in_schema, + ), ) return endpoint_function diff --git a/seed/fastapi/plain-text/register.py b/seed/fastapi/plain-text/register.py index ebdfdf9318d..1d60bbe4d5d 100644 --- a/seed/fastapi/plain-text/register.py +++ b/seed/fastapi/plain-text/register.py @@ -1,31 +1,33 @@ # This file was auto-generated by Fern from our API Definition. -import glob -import importlib -import os -import types -import typing - import fastapi -import starlette.exceptions +from .resources.service.service.service import AbstractServiceService +import typing from fastapi import params - -from .core.abstract_fern_service import AbstractFernService -from .core.exceptions import default_exception_handler, fern_http_exception_handler, http_exception_handler from .core.exceptions.fern_http_exception import FernHTTPException -from .resources.service.service.service import AbstractServiceService +from .core.exceptions import fern_http_exception_handler +import starlette.exceptions +from .core.exceptions import http_exception_handler +from .core.exceptions import default_exception_handler +from .core.abstract_fern_service import AbstractFernService +import types +import os +import glob +import importlib def register( _app: fastapi.FastAPI, *, service: AbstractServiceService, - dependencies: typing.Optional[typing.Sequence[params.Depends]] = None + dependencies: typing.Optional[typing.Sequence[params.Depends]] = None, ) -> None: _app.include_router(__register_service(service), dependencies=dependencies) _app.add_exception_handler(FernHTTPException, fern_http_exception_handler) # type: ignore - _app.add_exception_handler(starlette.exceptions.HTTPException, http_exception_handler) # type: ignore + _app.add_exception_handler( + starlette.exceptions.HTTPException, http_exception_handler + ) # type: ignore _app.add_exception_handler(Exception, default_exception_handler) # type: ignore @@ -37,7 +39,9 @@ def __register_service(service: AbstractFernService) -> fastapi.APIRouter: def register_validators(module: types.ModuleType) -> None: validators_directory: str = os.path.dirname(module.__file__) # type: ignore - for path in glob.glob(os.path.join(validators_directory, "**/*.py"), recursive=True): + for path in glob.glob( + os.path.join(validators_directory, "**/*.py"), recursive=True + ): if os.path.isfile(path): relative_path = os.path.relpath(path, start=validators_directory) module_path = ".".join([module.__name__] + relative_path[:-3].split("/")) diff --git a/seed/fastapi/plain-text/resources/service/service/service.py b/seed/fastapi/plain-text/resources/service/service/service.py index f9adf3fc652..08b33ce7ab8 100644 --- a/seed/fastapi/plain-text/resources/service/service/service.py +++ b/seed/fastapi/plain-text/resources/service/service/service.py @@ -1,15 +1,13 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.abstract_fern_service import AbstractFernService import abc -import functools +import fastapi import inspect -import logging import typing - -import fastapi - -from ....core.abstract_fern_service import AbstractFernService from ....core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools from ....core.route_args import get_route_args @@ -23,8 +21,7 @@ class AbstractServiceService(AbstractFernService): """ @abc.abstractmethod - def get_text(self) -> str: - ... + def get_text(self) -> str: ... """ Below are internal methods used by Fern to register your implementation. @@ -39,12 +36,18 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_get_text(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_text) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) else: new_parameters.append(parameter) - setattr(cls.get_text, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_text, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_text) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> str: diff --git a/seed/fastapi/query-parameters/core/abstract_fern_service.py b/seed/fastapi/query-parameters/core/abstract_fern_service.py index da7c8dc49c4..9966b4876da 100644 --- a/seed/fastapi/query-parameters/core/abstract_fern_service.py +++ b/seed/fastapi/query-parameters/core/abstract_fern_service.py @@ -7,5 +7,4 @@ class AbstractFernService(abc.ABC): @classmethod - def _init_fern(cls, router: fastapi.APIRouter) -> None: - ... + def _init_fern(cls, router: fastapi.APIRouter) -> None: ... diff --git a/seed/fastapi/query-parameters/core/datetime_utils.py b/seed/fastapi/query-parameters/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/fastapi/query-parameters/core/datetime_utils.py +++ b/seed/fastapi/query-parameters/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/fastapi/query-parameters/core/exceptions/__init__.py b/seed/fastapi/query-parameters/core/exceptions/__init__.py index 297d6e06f5f..dae4b8980c1 100644 --- a/seed/fastapi/query-parameters/core/exceptions/__init__.py +++ b/seed/fastapi/query-parameters/core/exceptions/__init__.py @@ -1,7 +1,11 @@ # This file was auto-generated by Fern from our API Definition. from .fern_http_exception import FernHTTPException -from .handlers import default_exception_handler, fern_http_exception_handler, http_exception_handler +from .handlers import ( + default_exception_handler, + fern_http_exception_handler, + http_exception_handler, +) from .unauthorized import UnauthorizedException __all__ = [ diff --git a/seed/fastapi/query-parameters/core/exceptions/fern_http_exception.py b/seed/fastapi/query-parameters/core/exceptions/fern_http_exception.py index bdf03862487..a5925c21510 100644 --- a/seed/fastapi/query-parameters/core/exceptions/fern_http_exception.py +++ b/seed/fastapi/query-parameters/core/exceptions/fern_http_exception.py @@ -8,7 +8,10 @@ class FernHTTPException(abc.ABC, fastapi.HTTPException): def __init__( - self, status_code: int, name: typing.Optional[str] = None, content: typing.Optional[typing.Any] = None + self, + status_code: int, + name: typing.Optional[str] = None, + content: typing.Optional[typing.Any] = None, ): super().__init__(status_code=status_code) self.name = name @@ -17,4 +20,6 @@ def __init__( def to_json_response(self) -> fastapi.responses.JSONResponse: content = fastapi.encoders.jsonable_encoder(self.content, exclude_none=True) - return fastapi.responses.JSONResponse(content=content, status_code=self.status_code) + return fastapi.responses.JSONResponse( + content=content, status_code=self.status_code + ) diff --git a/seed/fastapi/query-parameters/core/exceptions/handlers.py b/seed/fastapi/query-parameters/core/exceptions/handlers.py index fe5ac5419c7..6e7a82773f6 100644 --- a/seed/fastapi/query-parameters/core/exceptions/handlers.py +++ b/seed/fastapi/query-parameters/core/exceptions/handlers.py @@ -12,21 +12,33 @@ def fern_http_exception_handler( request: fastapi.requests.Request, exc: FernHTTPException, skip_log: bool = False ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) return exc.to_json_response() def http_exception_handler( - request: fastapi.requests.Request, exc: starlette.exceptions.HTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: starlette.exceptions.HTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=exc.status_code, content=exc.detail).to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=exc.status_code, content=exc.detail + ).to_json_response() def default_exception_handler( request: fastapi.requests.Request, exc: Exception, skip_log: bool = False ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=500, content="Internal Server Error").to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=500, content="Internal Server Error" + ).to_json_response() diff --git a/seed/fastapi/query-parameters/core/route_args.py b/seed/fastapi/query-parameters/core/route_args.py index 4228e2fe05d..bd940bf4ddd 100644 --- a/seed/fastapi/query-parameters/core/route_args.py +++ b/seed/fastapi/query-parameters/core/route_args.py @@ -20,9 +20,15 @@ class RouteArgs(typing_extensions.TypedDict): DEFAULT_ROUTE_ARGS = RouteArgs(openapi_extra=None, tags=None, include_in_schema=True) -def get_route_args(endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str) -> RouteArgs: - unwrapped = inspect.unwrap(endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY))) - route_args = typing.cast(RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS)) +def get_route_args( + endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str +) -> RouteArgs: + unwrapped = inspect.unwrap( + endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY)) + ) + route_args = typing.cast( + RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS) + ) if route_args["tags"] is None: return RouteArgs( openapi_extra=route_args["openapi_extra"], @@ -56,7 +62,11 @@ def decorator(endpoint_function: T) -> T: setattr( endpoint_function, FERN_CONFIG_KEY, - RouteArgs(openapi_extra=openapi_extra, tags=tags, include_in_schema=include_in_schema), + RouteArgs( + openapi_extra=openapi_extra, + tags=tags, + include_in_schema=include_in_schema, + ), ) return endpoint_function diff --git a/seed/fastapi/query-parameters/register.py b/seed/fastapi/query-parameters/register.py index a085236e5dc..4ebc095323c 100644 --- a/seed/fastapi/query-parameters/register.py +++ b/seed/fastapi/query-parameters/register.py @@ -11,7 +11,11 @@ from fastapi import params from .core.abstract_fern_service import AbstractFernService -from .core.exceptions import default_exception_handler, fern_http_exception_handler, http_exception_handler +from .core.exceptions import ( + default_exception_handler, + fern_http_exception_handler, + http_exception_handler, +) from .core.exceptions.fern_http_exception import FernHTTPException from .resources.user.service.service import AbstractUserService @@ -20,12 +24,14 @@ def register( _app: fastapi.FastAPI, *, user: AbstractUserService, - dependencies: typing.Optional[typing.Sequence[params.Depends]] = None + dependencies: typing.Optional[typing.Sequence[params.Depends]] = None, ) -> None: _app.include_router(__register_service(user), dependencies=dependencies) _app.add_exception_handler(FernHTTPException, fern_http_exception_handler) - _app.add_exception_handler(starlette.exceptions.HTTPException, http_exception_handler) + _app.add_exception_handler( + starlette.exceptions.HTTPException, http_exception_handler + ) _app.add_exception_handler(Exception, default_exception_handler) @@ -37,7 +43,9 @@ def __register_service(service: AbstractFernService) -> fastapi.APIRouter: def register_validators(module: types.ModuleType) -> None: validators_directory: str = os.path.dirname(module.__file__) # type: ignore - for path in glob.glob(os.path.join(validators_directory, "**/*.py"), recursive=True): + for path in glob.glob( + os.path.join(validators_directory, "**/*.py"), recursive=True + ): if os.path.isfile(path): relative_path = os.path.relpath(path, start=validators_directory) module_path = ".".join([module.__name__] + relative_path[:-3].split("/")) diff --git a/seed/fastapi/query-parameters/resources/user/service/service.py b/seed/fastapi/query-parameters/resources/user/service/service.py index a3aa4543fd8..346bc189d71 100644 --- a/seed/fastapi/query-parameters/resources/user/service/service.py +++ b/seed/fastapi/query-parameters/resources/user/service/service.py @@ -36,8 +36,7 @@ def get_username( bytes: str, optional_string: typing.Optional[str] = None, filter: typing.List[str], - ) -> User: - ... + ) -> User: ... """ Below are internal methods used by Fern to register your implementation. @@ -52,26 +51,48 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_get_username(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_username) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "limit": - new_parameters.append(parameter.replace(default=fastapi.Query(default=...))) + new_parameters.append( + parameter.replace(default=fastapi.Query(default=...)) + ) elif parameter_name == "id": - new_parameters.append(parameter.replace(default=fastapi.Query(default=...))) + new_parameters.append( + parameter.replace(default=fastapi.Query(default=...)) + ) elif parameter_name == "date": - new_parameters.append(parameter.replace(default=fastapi.Query(default=...))) + new_parameters.append( + parameter.replace(default=fastapi.Query(default=...)) + ) elif parameter_name == "deadline": - new_parameters.append(parameter.replace(default=fastapi.Query(default=...))) + new_parameters.append( + parameter.replace(default=fastapi.Query(default=...)) + ) elif parameter_name == "bytes": - new_parameters.append(parameter.replace(default=fastapi.Query(default=...))) + new_parameters.append( + parameter.replace(default=fastapi.Query(default=...)) + ) elif parameter_name == "optional_string": - new_parameters.append(parameter.replace(default=fastapi.Query(default=None, alias="optionalString"))) + new_parameters.append( + parameter.replace( + default=fastapi.Query(default=None, alias="optionalString") + ) + ) elif parameter_name == "filter": - new_parameters.append(parameter.replace(default=fastapi.Query(default=[]))) + new_parameters.append( + parameter.replace(default=fastapi.Query(default=[])) + ) else: new_parameters.append(parameter) - setattr(cls.get_username, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_username, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_username) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> User: diff --git a/seed/fastapi/query-parameters/resources/user/types/nested_user.py b/seed/fastapi/query-parameters/resources/user/types/nested_user.py index 271b13f2c7c..31048d0f534 100644 --- a/seed/fastapi/query-parameters/resources/user/types/nested_user.py +++ b/seed/fastapi/query-parameters/resources/user/types/nested_user.py @@ -17,11 +17,19 @@ class NestedUser(pydantic.BaseModel): user: User def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/fastapi/query-parameters/resources/user/types/user.py b/seed/fastapi/query-parameters/resources/user/types/user.py index 6a8d29f4245..2c3716164f9 100644 --- a/seed/fastapi/query-parameters/resources/user/types/user.py +++ b/seed/fastapi/query-parameters/resources/user/types/user.py @@ -16,11 +16,19 @@ class User(pydantic.BaseModel): tags: typing.List[str] def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/fastapi/reserved-keywords/core/abstract_fern_service.py b/seed/fastapi/reserved-keywords/core/abstract_fern_service.py index da7c8dc49c4..9966b4876da 100644 --- a/seed/fastapi/reserved-keywords/core/abstract_fern_service.py +++ b/seed/fastapi/reserved-keywords/core/abstract_fern_service.py @@ -7,5 +7,4 @@ class AbstractFernService(abc.ABC): @classmethod - def _init_fern(cls, router: fastapi.APIRouter) -> None: - ... + def _init_fern(cls, router: fastapi.APIRouter) -> None: ... diff --git a/seed/fastapi/reserved-keywords/core/datetime_utils.py b/seed/fastapi/reserved-keywords/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/fastapi/reserved-keywords/core/datetime_utils.py +++ b/seed/fastapi/reserved-keywords/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/fastapi/reserved-keywords/core/exceptions/__init__.py b/seed/fastapi/reserved-keywords/core/exceptions/__init__.py index 297d6e06f5f..dae4b8980c1 100644 --- a/seed/fastapi/reserved-keywords/core/exceptions/__init__.py +++ b/seed/fastapi/reserved-keywords/core/exceptions/__init__.py @@ -1,7 +1,11 @@ # This file was auto-generated by Fern from our API Definition. from .fern_http_exception import FernHTTPException -from .handlers import default_exception_handler, fern_http_exception_handler, http_exception_handler +from .handlers import ( + default_exception_handler, + fern_http_exception_handler, + http_exception_handler, +) from .unauthorized import UnauthorizedException __all__ = [ diff --git a/seed/fastapi/reserved-keywords/core/exceptions/fern_http_exception.py b/seed/fastapi/reserved-keywords/core/exceptions/fern_http_exception.py index 0770211f75c..24ee7b0cc25 100644 --- a/seed/fastapi/reserved-keywords/core/exceptions/fern_http_exception.py +++ b/seed/fastapi/reserved-keywords/core/exceptions/fern_http_exception.py @@ -1,21 +1,21 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - import abc -import http -import typing -import uuid - import fastapi -import pydantic - +import typing from ..pydantic_utilities import UniversalBaseModel +import pydantic +import uuid +import http class FernHTTPException(abc.ABC, fastapi.HTTPException): def __init__( - self, status_code: int, name: typing.Optional[str] = None, content: typing.Optional[typing.Any] = None + self, + status_code: int, + name: typing.Optional[str] = None, + content: typing.Optional[typing.Any] = None, ): super().__init__(status_code=status_code) self.name = name @@ -23,13 +23,20 @@ def __init__( self.content = content class Body(UniversalBaseModel): - error_name: typing.Optional[str] = pydantic.Field(alias="errorName", default=None) - error_instance_id: uuid.UUID = pydantic.Field(alias="errorInstanceId", default_factory=uuid.uuid4) + error_name: typing.Optional[str] = pydantic.Field( + alias="errorName", default=None + ) + error_instance_id: uuid.UUID = pydantic.Field( + alias="errorInstanceId", default_factory=uuid.uuid4 + ) content: typing.Optional[typing.Any] = None def to_json_response(self) -> fastapi.responses.JSONResponse: body = FernHTTPException.Body( - error_name=self.name, content=self.content or http.HTTPStatus(self.status_code).phrase + error_name=self.name, + content=self.content or http.HTTPStatus(self.status_code).phrase, ) content = fastapi.encoders.jsonable_encoder(body, exclude_none=True) - return fastapi.responses.JSONResponse(content=content, status_code=self.status_code) + return fastapi.responses.JSONResponse( + content=content, status_code=self.status_code + ) diff --git a/seed/fastapi/reserved-keywords/core/exceptions/handlers.py b/seed/fastapi/reserved-keywords/core/exceptions/handlers.py index 6d8c4155c5a..ae1c2741f06 100644 --- a/seed/fastapi/reserved-keywords/core/exceptions/handlers.py +++ b/seed/fastapi/reserved-keywords/core/exceptions/handlers.py @@ -2,32 +2,49 @@ import logging -import fastapi import starlette import starlette.exceptions +import fastapi + from .fern_http_exception import FernHTTPException def fern_http_exception_handler( - request: fastapi.requests.Request, exc: FernHTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: FernHTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) return exc.to_json_response() def http_exception_handler( - request: fastapi.requests.Request, exc: starlette.exceptions.HTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: starlette.exceptions.HTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=exc.status_code, content=exc.detail).to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=exc.status_code, content=exc.detail + ).to_json_response() def default_exception_handler( - request: fastapi.requests.Request, exc: Exception, skip_log: bool = False + request: fastapi.requests.Request, + exc: Exception, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=500, content="Internal Server Error").to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=500, content="Internal Server Error" + ).to_json_response() diff --git a/seed/fastapi/reserved-keywords/core/pydantic_utilities.py b/seed/fastapi/reserved-keywords/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/fastapi/reserved-keywords/core/pydantic_utilities.py +++ b/seed/fastapi/reserved-keywords/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/fastapi/reserved-keywords/core/route_args.py b/seed/fastapi/reserved-keywords/core/route_args.py index 4228e2fe05d..bd940bf4ddd 100644 --- a/seed/fastapi/reserved-keywords/core/route_args.py +++ b/seed/fastapi/reserved-keywords/core/route_args.py @@ -20,9 +20,15 @@ class RouteArgs(typing_extensions.TypedDict): DEFAULT_ROUTE_ARGS = RouteArgs(openapi_extra=None, tags=None, include_in_schema=True) -def get_route_args(endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str) -> RouteArgs: - unwrapped = inspect.unwrap(endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY))) - route_args = typing.cast(RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS)) +def get_route_args( + endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str +) -> RouteArgs: + unwrapped = inspect.unwrap( + endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY)) + ) + route_args = typing.cast( + RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS) + ) if route_args["tags"] is None: return RouteArgs( openapi_extra=route_args["openapi_extra"], @@ -56,7 +62,11 @@ def decorator(endpoint_function: T) -> T: setattr( endpoint_function, FERN_CONFIG_KEY, - RouteArgs(openapi_extra=openapi_extra, tags=tags, include_in_schema=include_in_schema), + RouteArgs( + openapi_extra=openapi_extra, + tags=tags, + include_in_schema=include_in_schema, + ), ) return endpoint_function diff --git a/seed/fastapi/reserved-keywords/register.py b/seed/fastapi/reserved-keywords/register.py index 13b0c44457f..f90dbdaeaa7 100644 --- a/seed/fastapi/reserved-keywords/register.py +++ b/seed/fastapi/reserved-keywords/register.py @@ -1,31 +1,33 @@ # This file was auto-generated by Fern from our API Definition. -import glob -import importlib -import os -import types -import typing - import fastapi -import starlette.exceptions +from .resources.package.service.service import AbstractPackageService +import typing from fastapi import params - -from .core.abstract_fern_service import AbstractFernService -from .core.exceptions import default_exception_handler, fern_http_exception_handler, http_exception_handler from .core.exceptions.fern_http_exception import FernHTTPException -from .resources.package.service.service import AbstractPackageService +from .core.exceptions import fern_http_exception_handler +import starlette.exceptions +from .core.exceptions import http_exception_handler +from .core.exceptions import default_exception_handler +from .core.abstract_fern_service import AbstractFernService +import types +import os +import glob +import importlib def register( _app: fastapi.FastAPI, *, package: AbstractPackageService, - dependencies: typing.Optional[typing.Sequence[params.Depends]] = None + dependencies: typing.Optional[typing.Sequence[params.Depends]] = None, ) -> None: _app.include_router(__register_service(package), dependencies=dependencies) _app.add_exception_handler(FernHTTPException, fern_http_exception_handler) # type: ignore - _app.add_exception_handler(starlette.exceptions.HTTPException, http_exception_handler) # type: ignore + _app.add_exception_handler( + starlette.exceptions.HTTPException, http_exception_handler + ) # type: ignore _app.add_exception_handler(Exception, default_exception_handler) # type: ignore @@ -37,7 +39,9 @@ def __register_service(service: AbstractFernService) -> fastapi.APIRouter: def register_validators(module: types.ModuleType) -> None: validators_directory: str = os.path.dirname(module.__file__) # type: ignore - for path in glob.glob(os.path.join(validators_directory, "**/*.py"), recursive=True): + for path in glob.glob( + os.path.join(validators_directory, "**/*.py"), recursive=True + ): if os.path.isfile(path): relative_path = os.path.relpath(path, start=validators_directory) module_path = ".".join([module.__name__] + relative_path[:-3].split("/")) diff --git a/seed/fastapi/reserved-keywords/resources/package/service/service.py b/seed/fastapi/reserved-keywords/resources/package/service/service.py index 5eb667b2d83..b80bd467b8d 100644 --- a/seed/fastapi/reserved-keywords/resources/package/service/service.py +++ b/seed/fastapi/reserved-keywords/resources/package/service/service.py @@ -1,16 +1,14 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.abstract_fern_service import AbstractFernService import abc -import functools +import fastapi import inspect -import logging import typing - -import fastapi -import starlette - -from ....core.abstract_fern_service import AbstractFernService from ....core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools +import starlette from ....core.route_args import get_route_args @@ -24,8 +22,7 @@ class AbstractPackageService(AbstractFernService): """ @abc.abstractmethod - def test(self, *, for_: str) -> None: - ... + def test(self, *, for_: str) -> None: ... """ Below are internal methods used by Fern to register your implementation. @@ -40,14 +37,22 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_test(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.test) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "for_": - new_parameters.append(parameter.replace(default=fastapi.Query(default=..., alias="for"))) + new_parameters.append( + parameter.replace(default=fastapi.Query(default=..., alias="for")) + ) else: new_parameters.append(parameter) - setattr(cls.test, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.test, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.test) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> None: diff --git a/seed/fastapi/reserved-keywords/resources/package/types/package.py b/seed/fastapi/reserved-keywords/resources/package/types/package.py index 650e605b4f0..0d55380e438 100644 --- a/seed/fastapi/reserved-keywords/resources/package/types/package.py +++ b/seed/fastapi/reserved-keywords/resources/package/types/package.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class Package(UniversalBaseModel): name: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/reserved-keywords/resources/package/types/record.py b/seed/fastapi/reserved-keywords/resources/package/types/record.py index 208d5f8d318..ee4d5e290e0 100644 --- a/seed/fastapi/reserved-keywords/resources/package/types/record.py +++ b/seed/fastapi/reserved-keywords/resources/package/types/record.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class Record(UniversalBaseModel): @@ -12,7 +11,9 @@ class Record(UniversalBaseModel): f_3_d: int = pydantic.Field(alias="3d") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/server-sent-events/core/abstract_fern_service.py b/seed/fastapi/server-sent-events/core/abstract_fern_service.py index da7c8dc49c4..9966b4876da 100644 --- a/seed/fastapi/server-sent-events/core/abstract_fern_service.py +++ b/seed/fastapi/server-sent-events/core/abstract_fern_service.py @@ -7,5 +7,4 @@ class AbstractFernService(abc.ABC): @classmethod - def _init_fern(cls, router: fastapi.APIRouter) -> None: - ... + def _init_fern(cls, router: fastapi.APIRouter) -> None: ... diff --git a/seed/fastapi/server-sent-events/core/datetime_utils.py b/seed/fastapi/server-sent-events/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/fastapi/server-sent-events/core/datetime_utils.py +++ b/seed/fastapi/server-sent-events/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/fastapi/server-sent-events/core/exceptions/__init__.py b/seed/fastapi/server-sent-events/core/exceptions/__init__.py index 297d6e06f5f..dae4b8980c1 100644 --- a/seed/fastapi/server-sent-events/core/exceptions/__init__.py +++ b/seed/fastapi/server-sent-events/core/exceptions/__init__.py @@ -1,7 +1,11 @@ # This file was auto-generated by Fern from our API Definition. from .fern_http_exception import FernHTTPException -from .handlers import default_exception_handler, fern_http_exception_handler, http_exception_handler +from .handlers import ( + default_exception_handler, + fern_http_exception_handler, + http_exception_handler, +) from .unauthorized import UnauthorizedException __all__ = [ diff --git a/seed/fastapi/server-sent-events/core/exceptions/fern_http_exception.py b/seed/fastapi/server-sent-events/core/exceptions/fern_http_exception.py index bdf03862487..a5925c21510 100644 --- a/seed/fastapi/server-sent-events/core/exceptions/fern_http_exception.py +++ b/seed/fastapi/server-sent-events/core/exceptions/fern_http_exception.py @@ -8,7 +8,10 @@ class FernHTTPException(abc.ABC, fastapi.HTTPException): def __init__( - self, status_code: int, name: typing.Optional[str] = None, content: typing.Optional[typing.Any] = None + self, + status_code: int, + name: typing.Optional[str] = None, + content: typing.Optional[typing.Any] = None, ): super().__init__(status_code=status_code) self.name = name @@ -17,4 +20,6 @@ def __init__( def to_json_response(self) -> fastapi.responses.JSONResponse: content = fastapi.encoders.jsonable_encoder(self.content, exclude_none=True) - return fastapi.responses.JSONResponse(content=content, status_code=self.status_code) + return fastapi.responses.JSONResponse( + content=content, status_code=self.status_code + ) diff --git a/seed/fastapi/server-sent-events/core/exceptions/handlers.py b/seed/fastapi/server-sent-events/core/exceptions/handlers.py index fe5ac5419c7..6e7a82773f6 100644 --- a/seed/fastapi/server-sent-events/core/exceptions/handlers.py +++ b/seed/fastapi/server-sent-events/core/exceptions/handlers.py @@ -12,21 +12,33 @@ def fern_http_exception_handler( request: fastapi.requests.Request, exc: FernHTTPException, skip_log: bool = False ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) return exc.to_json_response() def http_exception_handler( - request: fastapi.requests.Request, exc: starlette.exceptions.HTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: starlette.exceptions.HTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=exc.status_code, content=exc.detail).to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=exc.status_code, content=exc.detail + ).to_json_response() def default_exception_handler( request: fastapi.requests.Request, exc: Exception, skip_log: bool = False ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=500, content="Internal Server Error").to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=500, content="Internal Server Error" + ).to_json_response() diff --git a/seed/fastapi/server-sent-events/core/route_args.py b/seed/fastapi/server-sent-events/core/route_args.py index 4228e2fe05d..bd940bf4ddd 100644 --- a/seed/fastapi/server-sent-events/core/route_args.py +++ b/seed/fastapi/server-sent-events/core/route_args.py @@ -20,9 +20,15 @@ class RouteArgs(typing_extensions.TypedDict): DEFAULT_ROUTE_ARGS = RouteArgs(openapi_extra=None, tags=None, include_in_schema=True) -def get_route_args(endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str) -> RouteArgs: - unwrapped = inspect.unwrap(endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY))) - route_args = typing.cast(RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS)) +def get_route_args( + endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str +) -> RouteArgs: + unwrapped = inspect.unwrap( + endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY)) + ) + route_args = typing.cast( + RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS) + ) if route_args["tags"] is None: return RouteArgs( openapi_extra=route_args["openapi_extra"], @@ -56,7 +62,11 @@ def decorator(endpoint_function: T) -> T: setattr( endpoint_function, FERN_CONFIG_KEY, - RouteArgs(openapi_extra=openapi_extra, tags=tags, include_in_schema=include_in_schema), + RouteArgs( + openapi_extra=openapi_extra, + tags=tags, + include_in_schema=include_in_schema, + ), ) return endpoint_function diff --git a/seed/fastapi/server-sent-events/register.py b/seed/fastapi/server-sent-events/register.py index 8cc57080a17..62d7751ee00 100644 --- a/seed/fastapi/server-sent-events/register.py +++ b/seed/fastapi/server-sent-events/register.py @@ -11,7 +11,11 @@ from fastapi import params from .core.abstract_fern_service import AbstractFernService -from .core.exceptions import default_exception_handler, fern_http_exception_handler, http_exception_handler +from .core.exceptions import ( + default_exception_handler, + fern_http_exception_handler, + http_exception_handler, +) from .core.exceptions.fern_http_exception import FernHTTPException from .resources.completions.service.service import AbstractCompletionsService @@ -20,12 +24,14 @@ def register( _app: fastapi.FastAPI, *, completions: AbstractCompletionsService, - dependencies: typing.Optional[typing.Sequence[params.Depends]] = None + dependencies: typing.Optional[typing.Sequence[params.Depends]] = None, ) -> None: _app.include_router(__register_service(completions), dependencies=dependencies) _app.add_exception_handler(FernHTTPException, fern_http_exception_handler) - _app.add_exception_handler(starlette.exceptions.HTTPException, http_exception_handler) + _app.add_exception_handler( + starlette.exceptions.HTTPException, http_exception_handler + ) _app.add_exception_handler(Exception, default_exception_handler) @@ -37,7 +43,9 @@ def __register_service(service: AbstractFernService) -> fastapi.APIRouter: def register_validators(module: types.ModuleType) -> None: validators_directory: str = os.path.dirname(module.__file__) # type: ignore - for path in glob.glob(os.path.join(validators_directory, "**/*.py"), recursive=True): + for path in glob.glob( + os.path.join(validators_directory, "**/*.py"), recursive=True + ): if os.path.isfile(path): relative_path = os.path.relpath(path, start=validators_directory) module_path = ".".join([module.__name__] + relative_path[:-3].split("/")) diff --git a/seed/fastapi/server-sent-events/resources/completions/service/service.py b/seed/fastapi/server-sent-events/resources/completions/service/service.py index 17751e0443e..ddbcf2c2dec 100644 --- a/seed/fastapi/server-sent-events/resources/completions/service/service.py +++ b/seed/fastapi/server-sent-events/resources/completions/service/service.py @@ -25,8 +25,7 @@ class AbstractCompletionsService(AbstractFernService): """ @abc.abstractmethod - def stream(self, *, body: StreamCompletionRequest) -> None: - ... + def stream(self, *, body: StreamCompletionRequest) -> None: ... """ Below are internal methods used by Fern to register your implementation. @@ -41,14 +40,20 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_stream(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.stream) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) else: new_parameters.append(parameter) - setattr(cls.stream, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.stream, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.stream) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> None: diff --git a/seed/fastapi/server-sent-events/resources/completions/service/stream_completion_request.py b/seed/fastapi/server-sent-events/resources/completions/service/stream_completion_request.py index edabe78e5d7..ce9b255a67b 100644 --- a/seed/fastapi/server-sent-events/resources/completions/service/stream_completion_request.py +++ b/seed/fastapi/server-sent-events/resources/completions/service/stream_completion_request.py @@ -11,11 +11,19 @@ class StreamCompletionRequest(pydantic_v1.BaseModel): query: str def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/fastapi/server-sent-events/resources/completions/types/streamed_completion.py b/seed/fastapi/server-sent-events/resources/completions/types/streamed_completion.py index aa44c70c4a7..c333b9ec125 100644 --- a/seed/fastapi/server-sent-events/resources/completions/types/streamed_completion.py +++ b/seed/fastapi/server-sent-events/resources/completions/types/streamed_completion.py @@ -12,11 +12,19 @@ class StreamedCompletion(pydantic_v1.BaseModel): tokens: typing.Optional[int] = None def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/fastapi/single-url-environment-default/core/abstract_fern_service.py b/seed/fastapi/single-url-environment-default/core/abstract_fern_service.py index da7c8dc49c4..9966b4876da 100644 --- a/seed/fastapi/single-url-environment-default/core/abstract_fern_service.py +++ b/seed/fastapi/single-url-environment-default/core/abstract_fern_service.py @@ -7,5 +7,4 @@ class AbstractFernService(abc.ABC): @classmethod - def _init_fern(cls, router: fastapi.APIRouter) -> None: - ... + def _init_fern(cls, router: fastapi.APIRouter) -> None: ... diff --git a/seed/fastapi/single-url-environment-default/core/datetime_utils.py b/seed/fastapi/single-url-environment-default/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/fastapi/single-url-environment-default/core/datetime_utils.py +++ b/seed/fastapi/single-url-environment-default/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/fastapi/single-url-environment-default/core/exceptions/__init__.py b/seed/fastapi/single-url-environment-default/core/exceptions/__init__.py index 297d6e06f5f..dae4b8980c1 100644 --- a/seed/fastapi/single-url-environment-default/core/exceptions/__init__.py +++ b/seed/fastapi/single-url-environment-default/core/exceptions/__init__.py @@ -1,7 +1,11 @@ # This file was auto-generated by Fern from our API Definition. from .fern_http_exception import FernHTTPException -from .handlers import default_exception_handler, fern_http_exception_handler, http_exception_handler +from .handlers import ( + default_exception_handler, + fern_http_exception_handler, + http_exception_handler, +) from .unauthorized import UnauthorizedException __all__ = [ diff --git a/seed/fastapi/single-url-environment-default/core/exceptions/fern_http_exception.py b/seed/fastapi/single-url-environment-default/core/exceptions/fern_http_exception.py index bdf03862487..81610359a7f 100644 --- a/seed/fastapi/single-url-environment-default/core/exceptions/fern_http_exception.py +++ b/seed/fastapi/single-url-environment-default/core/exceptions/fern_http_exception.py @@ -1,14 +1,16 @@ # This file was auto-generated by Fern from our API Definition. import abc -import typing - import fastapi +import typing class FernHTTPException(abc.ABC, fastapi.HTTPException): def __init__( - self, status_code: int, name: typing.Optional[str] = None, content: typing.Optional[typing.Any] = None + self, + status_code: int, + name: typing.Optional[str] = None, + content: typing.Optional[typing.Any] = None, ): super().__init__(status_code=status_code) self.name = name @@ -17,4 +19,6 @@ def __init__( def to_json_response(self) -> fastapi.responses.JSONResponse: content = fastapi.encoders.jsonable_encoder(self.content, exclude_none=True) - return fastapi.responses.JSONResponse(content=content, status_code=self.status_code) + return fastapi.responses.JSONResponse( + content=content, status_code=self.status_code + ) diff --git a/seed/fastapi/single-url-environment-default/core/exceptions/handlers.py b/seed/fastapi/single-url-environment-default/core/exceptions/handlers.py index 6d8c4155c5a..ae1c2741f06 100644 --- a/seed/fastapi/single-url-environment-default/core/exceptions/handlers.py +++ b/seed/fastapi/single-url-environment-default/core/exceptions/handlers.py @@ -2,32 +2,49 @@ import logging -import fastapi import starlette import starlette.exceptions +import fastapi + from .fern_http_exception import FernHTTPException def fern_http_exception_handler( - request: fastapi.requests.Request, exc: FernHTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: FernHTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) return exc.to_json_response() def http_exception_handler( - request: fastapi.requests.Request, exc: starlette.exceptions.HTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: starlette.exceptions.HTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=exc.status_code, content=exc.detail).to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=exc.status_code, content=exc.detail + ).to_json_response() def default_exception_handler( - request: fastapi.requests.Request, exc: Exception, skip_log: bool = False + request: fastapi.requests.Request, + exc: Exception, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=500, content="Internal Server Error").to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=500, content="Internal Server Error" + ).to_json_response() diff --git a/seed/fastapi/single-url-environment-default/core/pydantic_utilities.py b/seed/fastapi/single-url-environment-default/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/fastapi/single-url-environment-default/core/pydantic_utilities.py +++ b/seed/fastapi/single-url-environment-default/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/fastapi/single-url-environment-default/core/route_args.py b/seed/fastapi/single-url-environment-default/core/route_args.py index 4228e2fe05d..bd940bf4ddd 100644 --- a/seed/fastapi/single-url-environment-default/core/route_args.py +++ b/seed/fastapi/single-url-environment-default/core/route_args.py @@ -20,9 +20,15 @@ class RouteArgs(typing_extensions.TypedDict): DEFAULT_ROUTE_ARGS = RouteArgs(openapi_extra=None, tags=None, include_in_schema=True) -def get_route_args(endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str) -> RouteArgs: - unwrapped = inspect.unwrap(endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY))) - route_args = typing.cast(RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS)) +def get_route_args( + endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str +) -> RouteArgs: + unwrapped = inspect.unwrap( + endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY)) + ) + route_args = typing.cast( + RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS) + ) if route_args["tags"] is None: return RouteArgs( openapi_extra=route_args["openapi_extra"], @@ -56,7 +62,11 @@ def decorator(endpoint_function: T) -> T: setattr( endpoint_function, FERN_CONFIG_KEY, - RouteArgs(openapi_extra=openapi_extra, tags=tags, include_in_schema=include_in_schema), + RouteArgs( + openapi_extra=openapi_extra, + tags=tags, + include_in_schema=include_in_schema, + ), ) return endpoint_function diff --git a/seed/fastapi/single-url-environment-default/register.py b/seed/fastapi/single-url-environment-default/register.py index a8d6d7007ab..02e06d071ed 100644 --- a/seed/fastapi/single-url-environment-default/register.py +++ b/seed/fastapi/single-url-environment-default/register.py @@ -1,31 +1,33 @@ # This file was auto-generated by Fern from our API Definition. -import glob -import importlib -import os -import types -import typing - import fastapi -import starlette.exceptions +from .resources.dummy.service.service import AbstractDummyService +import typing from fastapi import params - -from .core.abstract_fern_service import AbstractFernService -from .core.exceptions import default_exception_handler, fern_http_exception_handler, http_exception_handler from .core.exceptions.fern_http_exception import FernHTTPException -from .resources.dummy.service.service import AbstractDummyService +from .core.exceptions import fern_http_exception_handler +import starlette.exceptions +from .core.exceptions import http_exception_handler +from .core.exceptions import default_exception_handler +from .core.abstract_fern_service import AbstractFernService +import types +import os +import glob +import importlib def register( _app: fastapi.FastAPI, *, dummy: AbstractDummyService, - dependencies: typing.Optional[typing.Sequence[params.Depends]] = None + dependencies: typing.Optional[typing.Sequence[params.Depends]] = None, ) -> None: _app.include_router(__register_service(dummy), dependencies=dependencies) _app.add_exception_handler(FernHTTPException, fern_http_exception_handler) # type: ignore - _app.add_exception_handler(starlette.exceptions.HTTPException, http_exception_handler) # type: ignore + _app.add_exception_handler( + starlette.exceptions.HTTPException, http_exception_handler + ) # type: ignore _app.add_exception_handler(Exception, default_exception_handler) # type: ignore @@ -37,7 +39,9 @@ def __register_service(service: AbstractFernService) -> fastapi.APIRouter: def register_validators(module: types.ModuleType) -> None: validators_directory: str = os.path.dirname(module.__file__) # type: ignore - for path in glob.glob(os.path.join(validators_directory, "**/*.py"), recursive=True): + for path in glob.glob( + os.path.join(validators_directory, "**/*.py"), recursive=True + ): if os.path.isfile(path): relative_path = os.path.relpath(path, start=validators_directory) module_path = ".".join([module.__name__] + relative_path[:-3].split("/")) diff --git a/seed/fastapi/single-url-environment-default/resources/dummy/service/service.py b/seed/fastapi/single-url-environment-default/resources/dummy/service/service.py index f7ebe94cb58..59d060eed53 100644 --- a/seed/fastapi/single-url-environment-default/resources/dummy/service/service.py +++ b/seed/fastapi/single-url-environment-default/resources/dummy/service/service.py @@ -1,17 +1,16 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.abstract_fern_service import AbstractFernService +from ....security import ApiAuth import abc -import functools +import fastapi import inspect -import logging import typing - -import fastapi - -from ....core.abstract_fern_service import AbstractFernService +from ....security import FernAuth from ....core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools from ....core.route_args import get_route_args -from ....security import ApiAuth, FernAuth class AbstractDummyService(AbstractFernService): @@ -24,8 +23,7 @@ class AbstractDummyService(AbstractFernService): """ @abc.abstractmethod - def get_dummy(self, *, auth: ApiAuth) -> str: - ... + def get_dummy(self, *, auth: ApiAuth) -> str: ... """ Below are internal methods used by Fern to register your implementation. @@ -40,14 +38,22 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_get_dummy(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_dummy) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_dummy, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_dummy, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_dummy) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> str: diff --git a/seed/fastapi/single-url-environment-default/security.py b/seed/fastapi/single-url-environment-default/security.py index bab014441e1..4ccabc21106 100644 --- a/seed/fastapi/single-url-environment-default/security.py +++ b/seed/fastapi/single-url-environment-default/security.py @@ -1,8 +1,8 @@ # This file was auto-generated by Fern from our API Definition. +from .core.security.bearer import BearerToken import fastapi - -from .core.security.bearer import BearerToken, HTTPBearer +from .core.security.bearer import HTTPBearer ApiAuth = BearerToken diff --git a/seed/fastapi/single-url-environment-no-default/core/abstract_fern_service.py b/seed/fastapi/single-url-environment-no-default/core/abstract_fern_service.py index da7c8dc49c4..9966b4876da 100644 --- a/seed/fastapi/single-url-environment-no-default/core/abstract_fern_service.py +++ b/seed/fastapi/single-url-environment-no-default/core/abstract_fern_service.py @@ -7,5 +7,4 @@ class AbstractFernService(abc.ABC): @classmethod - def _init_fern(cls, router: fastapi.APIRouter) -> None: - ... + def _init_fern(cls, router: fastapi.APIRouter) -> None: ... diff --git a/seed/fastapi/single-url-environment-no-default/core/datetime_utils.py b/seed/fastapi/single-url-environment-no-default/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/fastapi/single-url-environment-no-default/core/datetime_utils.py +++ b/seed/fastapi/single-url-environment-no-default/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/fastapi/single-url-environment-no-default/core/exceptions/__init__.py b/seed/fastapi/single-url-environment-no-default/core/exceptions/__init__.py index 297d6e06f5f..dae4b8980c1 100644 --- a/seed/fastapi/single-url-environment-no-default/core/exceptions/__init__.py +++ b/seed/fastapi/single-url-environment-no-default/core/exceptions/__init__.py @@ -1,7 +1,11 @@ # This file was auto-generated by Fern from our API Definition. from .fern_http_exception import FernHTTPException -from .handlers import default_exception_handler, fern_http_exception_handler, http_exception_handler +from .handlers import ( + default_exception_handler, + fern_http_exception_handler, + http_exception_handler, +) from .unauthorized import UnauthorizedException __all__ = [ diff --git a/seed/fastapi/single-url-environment-no-default/core/exceptions/fern_http_exception.py b/seed/fastapi/single-url-environment-no-default/core/exceptions/fern_http_exception.py index bdf03862487..81610359a7f 100644 --- a/seed/fastapi/single-url-environment-no-default/core/exceptions/fern_http_exception.py +++ b/seed/fastapi/single-url-environment-no-default/core/exceptions/fern_http_exception.py @@ -1,14 +1,16 @@ # This file was auto-generated by Fern from our API Definition. import abc -import typing - import fastapi +import typing class FernHTTPException(abc.ABC, fastapi.HTTPException): def __init__( - self, status_code: int, name: typing.Optional[str] = None, content: typing.Optional[typing.Any] = None + self, + status_code: int, + name: typing.Optional[str] = None, + content: typing.Optional[typing.Any] = None, ): super().__init__(status_code=status_code) self.name = name @@ -17,4 +19,6 @@ def __init__( def to_json_response(self) -> fastapi.responses.JSONResponse: content = fastapi.encoders.jsonable_encoder(self.content, exclude_none=True) - return fastapi.responses.JSONResponse(content=content, status_code=self.status_code) + return fastapi.responses.JSONResponse( + content=content, status_code=self.status_code + ) diff --git a/seed/fastapi/single-url-environment-no-default/core/exceptions/handlers.py b/seed/fastapi/single-url-environment-no-default/core/exceptions/handlers.py index 6d8c4155c5a..ae1c2741f06 100644 --- a/seed/fastapi/single-url-environment-no-default/core/exceptions/handlers.py +++ b/seed/fastapi/single-url-environment-no-default/core/exceptions/handlers.py @@ -2,32 +2,49 @@ import logging -import fastapi import starlette import starlette.exceptions +import fastapi + from .fern_http_exception import FernHTTPException def fern_http_exception_handler( - request: fastapi.requests.Request, exc: FernHTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: FernHTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) return exc.to_json_response() def http_exception_handler( - request: fastapi.requests.Request, exc: starlette.exceptions.HTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: starlette.exceptions.HTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=exc.status_code, content=exc.detail).to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=exc.status_code, content=exc.detail + ).to_json_response() def default_exception_handler( - request: fastapi.requests.Request, exc: Exception, skip_log: bool = False + request: fastapi.requests.Request, + exc: Exception, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=500, content="Internal Server Error").to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=500, content="Internal Server Error" + ).to_json_response() diff --git a/seed/fastapi/single-url-environment-no-default/core/pydantic_utilities.py b/seed/fastapi/single-url-environment-no-default/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/fastapi/single-url-environment-no-default/core/pydantic_utilities.py +++ b/seed/fastapi/single-url-environment-no-default/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/fastapi/single-url-environment-no-default/core/route_args.py b/seed/fastapi/single-url-environment-no-default/core/route_args.py index 4228e2fe05d..bd940bf4ddd 100644 --- a/seed/fastapi/single-url-environment-no-default/core/route_args.py +++ b/seed/fastapi/single-url-environment-no-default/core/route_args.py @@ -20,9 +20,15 @@ class RouteArgs(typing_extensions.TypedDict): DEFAULT_ROUTE_ARGS = RouteArgs(openapi_extra=None, tags=None, include_in_schema=True) -def get_route_args(endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str) -> RouteArgs: - unwrapped = inspect.unwrap(endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY))) - route_args = typing.cast(RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS)) +def get_route_args( + endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str +) -> RouteArgs: + unwrapped = inspect.unwrap( + endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY)) + ) + route_args = typing.cast( + RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS) + ) if route_args["tags"] is None: return RouteArgs( openapi_extra=route_args["openapi_extra"], @@ -56,7 +62,11 @@ def decorator(endpoint_function: T) -> T: setattr( endpoint_function, FERN_CONFIG_KEY, - RouteArgs(openapi_extra=openapi_extra, tags=tags, include_in_schema=include_in_schema), + RouteArgs( + openapi_extra=openapi_extra, + tags=tags, + include_in_schema=include_in_schema, + ), ) return endpoint_function diff --git a/seed/fastapi/single-url-environment-no-default/register.py b/seed/fastapi/single-url-environment-no-default/register.py index a8d6d7007ab..02e06d071ed 100644 --- a/seed/fastapi/single-url-environment-no-default/register.py +++ b/seed/fastapi/single-url-environment-no-default/register.py @@ -1,31 +1,33 @@ # This file was auto-generated by Fern from our API Definition. -import glob -import importlib -import os -import types -import typing - import fastapi -import starlette.exceptions +from .resources.dummy.service.service import AbstractDummyService +import typing from fastapi import params - -from .core.abstract_fern_service import AbstractFernService -from .core.exceptions import default_exception_handler, fern_http_exception_handler, http_exception_handler from .core.exceptions.fern_http_exception import FernHTTPException -from .resources.dummy.service.service import AbstractDummyService +from .core.exceptions import fern_http_exception_handler +import starlette.exceptions +from .core.exceptions import http_exception_handler +from .core.exceptions import default_exception_handler +from .core.abstract_fern_service import AbstractFernService +import types +import os +import glob +import importlib def register( _app: fastapi.FastAPI, *, dummy: AbstractDummyService, - dependencies: typing.Optional[typing.Sequence[params.Depends]] = None + dependencies: typing.Optional[typing.Sequence[params.Depends]] = None, ) -> None: _app.include_router(__register_service(dummy), dependencies=dependencies) _app.add_exception_handler(FernHTTPException, fern_http_exception_handler) # type: ignore - _app.add_exception_handler(starlette.exceptions.HTTPException, http_exception_handler) # type: ignore + _app.add_exception_handler( + starlette.exceptions.HTTPException, http_exception_handler + ) # type: ignore _app.add_exception_handler(Exception, default_exception_handler) # type: ignore @@ -37,7 +39,9 @@ def __register_service(service: AbstractFernService) -> fastapi.APIRouter: def register_validators(module: types.ModuleType) -> None: validators_directory: str = os.path.dirname(module.__file__) # type: ignore - for path in glob.glob(os.path.join(validators_directory, "**/*.py"), recursive=True): + for path in glob.glob( + os.path.join(validators_directory, "**/*.py"), recursive=True + ): if os.path.isfile(path): relative_path = os.path.relpath(path, start=validators_directory) module_path = ".".join([module.__name__] + relative_path[:-3].split("/")) diff --git a/seed/fastapi/single-url-environment-no-default/resources/dummy/service/service.py b/seed/fastapi/single-url-environment-no-default/resources/dummy/service/service.py index f7ebe94cb58..59d060eed53 100644 --- a/seed/fastapi/single-url-environment-no-default/resources/dummy/service/service.py +++ b/seed/fastapi/single-url-environment-no-default/resources/dummy/service/service.py @@ -1,17 +1,16 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.abstract_fern_service import AbstractFernService +from ....security import ApiAuth import abc -import functools +import fastapi import inspect -import logging import typing - -import fastapi - -from ....core.abstract_fern_service import AbstractFernService +from ....security import FernAuth from ....core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools from ....core.route_args import get_route_args -from ....security import ApiAuth, FernAuth class AbstractDummyService(AbstractFernService): @@ -24,8 +23,7 @@ class AbstractDummyService(AbstractFernService): """ @abc.abstractmethod - def get_dummy(self, *, auth: ApiAuth) -> str: - ... + def get_dummy(self, *, auth: ApiAuth) -> str: ... """ Below are internal methods used by Fern to register your implementation. @@ -40,14 +38,22 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_get_dummy(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_dummy) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_dummy, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_dummy, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_dummy) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> str: diff --git a/seed/fastapi/single-url-environment-no-default/security.py b/seed/fastapi/single-url-environment-no-default/security.py index bab014441e1..4ccabc21106 100644 --- a/seed/fastapi/single-url-environment-no-default/security.py +++ b/seed/fastapi/single-url-environment-no-default/security.py @@ -1,8 +1,8 @@ # This file was auto-generated by Fern from our API Definition. +from .core.security.bearer import BearerToken import fastapi - -from .core.security.bearer import BearerToken, HTTPBearer +from .core.security.bearer import HTTPBearer ApiAuth = BearerToken diff --git a/seed/fastapi/trace/core/abstract_fern_service.py b/seed/fastapi/trace/core/abstract_fern_service.py index da7c8dc49c4..9966b4876da 100644 --- a/seed/fastapi/trace/core/abstract_fern_service.py +++ b/seed/fastapi/trace/core/abstract_fern_service.py @@ -7,5 +7,4 @@ class AbstractFernService(abc.ABC): @classmethod - def _init_fern(cls, router: fastapi.APIRouter) -> None: - ... + def _init_fern(cls, router: fastapi.APIRouter) -> None: ... diff --git a/seed/fastapi/trace/core/datetime_utils.py b/seed/fastapi/trace/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/fastapi/trace/core/datetime_utils.py +++ b/seed/fastapi/trace/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/fastapi/trace/core/exceptions/__init__.py b/seed/fastapi/trace/core/exceptions/__init__.py index 297d6e06f5f..dae4b8980c1 100644 --- a/seed/fastapi/trace/core/exceptions/__init__.py +++ b/seed/fastapi/trace/core/exceptions/__init__.py @@ -1,7 +1,11 @@ # This file was auto-generated by Fern from our API Definition. from .fern_http_exception import FernHTTPException -from .handlers import default_exception_handler, fern_http_exception_handler, http_exception_handler +from .handlers import ( + default_exception_handler, + fern_http_exception_handler, + http_exception_handler, +) from .unauthorized import UnauthorizedException __all__ = [ diff --git a/seed/fastapi/trace/core/exceptions/fern_http_exception.py b/seed/fastapi/trace/core/exceptions/fern_http_exception.py index 0770211f75c..24ee7b0cc25 100644 --- a/seed/fastapi/trace/core/exceptions/fern_http_exception.py +++ b/seed/fastapi/trace/core/exceptions/fern_http_exception.py @@ -1,21 +1,21 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - import abc -import http -import typing -import uuid - import fastapi -import pydantic - +import typing from ..pydantic_utilities import UniversalBaseModel +import pydantic +import uuid +import http class FernHTTPException(abc.ABC, fastapi.HTTPException): def __init__( - self, status_code: int, name: typing.Optional[str] = None, content: typing.Optional[typing.Any] = None + self, + status_code: int, + name: typing.Optional[str] = None, + content: typing.Optional[typing.Any] = None, ): super().__init__(status_code=status_code) self.name = name @@ -23,13 +23,20 @@ def __init__( self.content = content class Body(UniversalBaseModel): - error_name: typing.Optional[str] = pydantic.Field(alias="errorName", default=None) - error_instance_id: uuid.UUID = pydantic.Field(alias="errorInstanceId", default_factory=uuid.uuid4) + error_name: typing.Optional[str] = pydantic.Field( + alias="errorName", default=None + ) + error_instance_id: uuid.UUID = pydantic.Field( + alias="errorInstanceId", default_factory=uuid.uuid4 + ) content: typing.Optional[typing.Any] = None def to_json_response(self) -> fastapi.responses.JSONResponse: body = FernHTTPException.Body( - error_name=self.name, content=self.content or http.HTTPStatus(self.status_code).phrase + error_name=self.name, + content=self.content or http.HTTPStatus(self.status_code).phrase, ) content = fastapi.encoders.jsonable_encoder(body, exclude_none=True) - return fastapi.responses.JSONResponse(content=content, status_code=self.status_code) + return fastapi.responses.JSONResponse( + content=content, status_code=self.status_code + ) diff --git a/seed/fastapi/trace/core/exceptions/handlers.py b/seed/fastapi/trace/core/exceptions/handlers.py index 6d8c4155c5a..ae1c2741f06 100644 --- a/seed/fastapi/trace/core/exceptions/handlers.py +++ b/seed/fastapi/trace/core/exceptions/handlers.py @@ -2,32 +2,49 @@ import logging -import fastapi import starlette import starlette.exceptions +import fastapi + from .fern_http_exception import FernHTTPException def fern_http_exception_handler( - request: fastapi.requests.Request, exc: FernHTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: FernHTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) return exc.to_json_response() def http_exception_handler( - request: fastapi.requests.Request, exc: starlette.exceptions.HTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: starlette.exceptions.HTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=exc.status_code, content=exc.detail).to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=exc.status_code, content=exc.detail + ).to_json_response() def default_exception_handler( - request: fastapi.requests.Request, exc: Exception, skip_log: bool = False + request: fastapi.requests.Request, + exc: Exception, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=500, content="Internal Server Error").to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=500, content="Internal Server Error" + ).to_json_response() diff --git a/seed/fastapi/trace/core/pydantic_utilities.py b/seed/fastapi/trace/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/fastapi/trace/core/pydantic_utilities.py +++ b/seed/fastapi/trace/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/fastapi/trace/core/route_args.py b/seed/fastapi/trace/core/route_args.py index 4228e2fe05d..bd940bf4ddd 100644 --- a/seed/fastapi/trace/core/route_args.py +++ b/seed/fastapi/trace/core/route_args.py @@ -20,9 +20,15 @@ class RouteArgs(typing_extensions.TypedDict): DEFAULT_ROUTE_ARGS = RouteArgs(openapi_extra=None, tags=None, include_in_schema=True) -def get_route_args(endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str) -> RouteArgs: - unwrapped = inspect.unwrap(endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY))) - route_args = typing.cast(RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS)) +def get_route_args( + endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str +) -> RouteArgs: + unwrapped = inspect.unwrap( + endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY)) + ) + route_args = typing.cast( + RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS) + ) if route_args["tags"] is None: return RouteArgs( openapi_extra=route_args["openapi_extra"], @@ -56,7 +62,11 @@ def decorator(endpoint_function: T) -> T: setattr( endpoint_function, FERN_CONFIG_KEY, - RouteArgs(openapi_extra=openapi_extra, tags=tags, include_in_schema=include_in_schema), + RouteArgs( + openapi_extra=openapi_extra, + tags=tags, + include_in_schema=include_in_schema, + ), ) return endpoint_function diff --git a/seed/fastapi/trace/register.py b/seed/fastapi/trace/register.py index b330219dd0d..d321f81a451 100644 --- a/seed/fastapi/trace/register.py +++ b/seed/fastapi/trace/register.py @@ -1,18 +1,7 @@ # This file was auto-generated by Fern from our API Definition. -import glob -import importlib -import os -import types -import typing - import fastapi -import starlette.exceptions -from fastapi import params - -from .core.abstract_fern_service import AbstractFernService -from .core.exceptions import default_exception_handler, fern_http_exception_handler, http_exception_handler -from .core.exceptions.fern_http_exception import FernHTTPException +from .resources.v_2.service.service import AbstractV2Service from .resources.admin.service.service import AbstractAdminService from .resources.homepage.service.service import AbstractHomepageService from .resources.migration.service.service import AbstractMigrationService @@ -21,8 +10,21 @@ from .resources.submission.service.service import AbstractSubmissionService from .resources.sysprop.service.service import AbstractSyspropService from .resources.v_2.resources.problem.service.service import AbstractV2ProblemService -from .resources.v_2.resources.v_3.resources.problem.service.service import AbstractV2V3ProblemService -from .resources.v_2.service.service import AbstractV2Service +from .resources.v_2.resources.v_3.resources.problem.service.service import ( + AbstractV2V3ProblemService, +) +import typing +from fastapi import params +from .core.exceptions.fern_http_exception import FernHTTPException +from .core.exceptions import fern_http_exception_handler +import starlette.exceptions +from .core.exceptions import http_exception_handler +from .core.exceptions import default_exception_handler +from .core.abstract_fern_service import AbstractFernService +import types +import os +import glob +import importlib def register( @@ -38,7 +40,7 @@ def register( sysprop: AbstractSyspropService, v_2_problem: AbstractV2ProblemService, v_2_v_3_problem: AbstractV2V3ProblemService, - dependencies: typing.Optional[typing.Sequence[params.Depends]] = None + dependencies: typing.Optional[typing.Sequence[params.Depends]] = None, ) -> None: _app.include_router(__register_service(v_2), dependencies=dependencies) _app.include_router(__register_service(admin), dependencies=dependencies) @@ -52,7 +54,9 @@ def register( _app.include_router(__register_service(v_2_v_3_problem), dependencies=dependencies) _app.add_exception_handler(FernHTTPException, fern_http_exception_handler) # type: ignore - _app.add_exception_handler(starlette.exceptions.HTTPException, http_exception_handler) # type: ignore + _app.add_exception_handler( + starlette.exceptions.HTTPException, http_exception_handler + ) # type: ignore _app.add_exception_handler(Exception, default_exception_handler) # type: ignore @@ -64,7 +68,9 @@ def __register_service(service: AbstractFernService) -> fastapi.APIRouter: def register_validators(module: types.ModuleType) -> None: validators_directory: str = os.path.dirname(module.__file__) # type: ignore - for path in glob.glob(os.path.join(validators_directory, "**/*.py"), recursive=True): + for path in glob.glob( + os.path.join(validators_directory, "**/*.py"), recursive=True + ): if os.path.isfile(path): relative_path = os.path.relpath(path, start=validators_directory) module_path = ".".join([module.__name__] + relative_path[:-3].split("/")) diff --git a/seed/fastapi/trace/resources/admin/service/__init__.py b/seed/fastapi/trace/resources/admin/service/__init__.py index 6bfa4b92878..f4ef9b76ed9 100644 --- a/seed/fastapi/trace/resources/admin/service/__init__.py +++ b/seed/fastapi/trace/resources/admin/service/__init__.py @@ -4,4 +4,8 @@ from .store_traced_test_case_request import StoreTracedTestCaseRequest from .store_traced_workspace_request import StoreTracedWorkspaceRequest -__all__ = ["AbstractAdminService", "StoreTracedTestCaseRequest", "StoreTracedWorkspaceRequest"] +__all__ = [ + "AbstractAdminService", + "StoreTracedTestCaseRequest", + "StoreTracedWorkspaceRequest", +] diff --git a/seed/fastapi/trace/resources/admin/service/service.py b/seed/fastapi/trace/resources/admin/service/service.py index ef3fc63d35a..af3c8550d26 100644 --- a/seed/fastapi/trace/resources/admin/service/service.py +++ b/seed/fastapi/trace/resources/admin/service/service.py @@ -1,25 +1,23 @@ # This file was auto-generated by Fern from our API Definition. -import abc -import functools -import inspect -import logging -import typing -import uuid - -import fastapi -import starlette - from ....core.abstract_fern_service import AbstractFernService -from ....core.exceptions.fern_http_exception import FernHTTPException -from ....core.route_args import get_route_args from ...submission.types.test_submission_status import TestSubmissionStatus +import uuid +import typing +import abc from ...submission.types.test_submission_update import TestSubmissionUpdate -from ...submission.types.trace_response_v_2 import TraceResponseV2 from ...submission.types.workspace_submission_status import WorkspaceSubmissionStatus from ...submission.types.workspace_submission_update import WorkspaceSubmissionUpdate from .store_traced_test_case_request import StoreTracedTestCaseRequest +from ...submission.types.trace_response_v_2 import TraceResponseV2 from .store_traced_workspace_request import StoreTracedWorkspaceRequest +import fastapi +import inspect +from ....core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools +import starlette +from ....core.route_args import get_route_args class AbstractAdminService(AbstractFernService): @@ -33,27 +31,39 @@ class AbstractAdminService(AbstractFernService): @abc.abstractmethod def update_test_submission_status( - self, *, body: TestSubmissionStatus, submission_id: uuid.UUID, x_random_header: typing.Optional[str] = None - ) -> None: - ... + self, + *, + body: TestSubmissionStatus, + submission_id: uuid.UUID, + x_random_header: typing.Optional[str] = None, + ) -> None: ... @abc.abstractmethod def send_test_submission_update( - self, *, body: TestSubmissionUpdate, submission_id: uuid.UUID, x_random_header: typing.Optional[str] = None - ) -> None: - ... + self, + *, + body: TestSubmissionUpdate, + submission_id: uuid.UUID, + x_random_header: typing.Optional[str] = None, + ) -> None: ... @abc.abstractmethod def update_workspace_submission_status( - self, *, body: WorkspaceSubmissionStatus, submission_id: uuid.UUID, x_random_header: typing.Optional[str] = None - ) -> None: - ... + self, + *, + body: WorkspaceSubmissionStatus, + submission_id: uuid.UUID, + x_random_header: typing.Optional[str] = None, + ) -> None: ... @abc.abstractmethod def send_workspace_submission_update( - self, *, body: WorkspaceSubmissionUpdate, submission_id: uuid.UUID, x_random_header: typing.Optional[str] = None - ) -> None: - ... + self, + *, + body: WorkspaceSubmissionUpdate, + submission_id: uuid.UUID, + x_random_header: typing.Optional[str] = None, + ) -> None: ... @abc.abstractmethod def store_traced_test_case( @@ -63,8 +73,7 @@ def store_traced_test_case( submission_id: uuid.UUID, test_case_id: str, x_random_header: typing.Optional[str] = None, - ) -> None: - ... + ) -> None: ... @abc.abstractmethod def store_traced_test_case_v_2( @@ -74,8 +83,7 @@ def store_traced_test_case_v_2( submission_id: uuid.UUID, test_case_id: str, x_random_header: typing.Optional[str] = None, - ) -> None: - ... + ) -> None: ... @abc.abstractmethod def store_traced_workspace( @@ -84,8 +92,7 @@ def store_traced_workspace( body: StoreTracedWorkspaceRequest, submission_id: uuid.UUID, x_random_header: typing.Optional[str] = None, - ) -> None: - ... + ) -> None: ... @abc.abstractmethod def store_traced_workspace_v_2( @@ -94,8 +101,7 @@ def store_traced_workspace_v_2( body: typing.List[TraceResponseV2], submission_id: uuid.UUID, x_random_header: typing.Optional[str] = None, - ) -> None: - ... + ) -> None: ... """ Below are internal methods used by Fern to register your implementation. @@ -117,7 +123,9 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_update_test_submission_status(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.update_test_submission_status) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": @@ -125,11 +133,17 @@ def __init_update_test_submission_status(cls, router: fastapi.APIRouter) -> None elif parameter_name == "submission_id": new_parameters.append(parameter.replace(default=fastapi.Path(...))) elif parameter_name == "x_random_header": - new_parameters.append(parameter.replace(default=fastapi.Header(default=None, alias="X-Random-Header"))) + new_parameters.append( + parameter.replace( + default=fastapi.Header(default=None, alias="X-Random-Header") + ) + ) else: new_parameters.append(parameter) setattr( - cls.update_test_submission_status, "__signature__", endpoint_function.replace(parameters=new_parameters) + cls.update_test_submission_status, + "__signature__", + endpoint_function.replace(parameters=new_parameters), ) @functools.wraps(cls.update_test_submission_status) @@ -160,7 +174,9 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> None: def __init_send_test_submission_update(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.send_test_submission_update) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": @@ -168,10 +184,18 @@ def __init_send_test_submission_update(cls, router: fastapi.APIRouter) -> None: elif parameter_name == "submission_id": new_parameters.append(parameter.replace(default=fastapi.Path(...))) elif parameter_name == "x_random_header": - new_parameters.append(parameter.replace(default=fastapi.Header(default=None, alias="X-Random-Header"))) + new_parameters.append( + parameter.replace( + default=fastapi.Header(default=None, alias="X-Random-Header") + ) + ) else: new_parameters.append(parameter) - setattr(cls.send_test_submission_update, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.send_test_submission_update, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.send_test_submission_update) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> None: @@ -198,10 +222,14 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> None: )(wrapper) @classmethod - def __init_update_workspace_submission_status(cls, router: fastapi.APIRouter) -> None: + def __init_update_workspace_submission_status( + cls, router: fastapi.APIRouter + ) -> None: endpoint_function = inspect.signature(cls.update_workspace_submission_status) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": @@ -209,7 +237,11 @@ def __init_update_workspace_submission_status(cls, router: fastapi.APIRouter) -> elif parameter_name == "submission_id": new_parameters.append(parameter.replace(default=fastapi.Path(...))) elif parameter_name == "x_random_header": - new_parameters.append(parameter.replace(default=fastapi.Header(default=None, alias="X-Random-Header"))) + new_parameters.append( + parameter.replace( + default=fastapi.Header(default=None, alias="X-Random-Header") + ) + ) else: new_parameters.append(parameter) setattr( @@ -239,14 +271,18 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> None: response_model=None, status_code=starlette.status.HTTP_204_NO_CONTENT, description=AbstractAdminService.update_workspace_submission_status.__doc__, - **get_route_args(cls.update_workspace_submission_status, default_tag="admin"), + **get_route_args( + cls.update_workspace_submission_status, default_tag="admin" + ), )(wrapper) @classmethod def __init_send_workspace_submission_update(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.send_workspace_submission_update) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": @@ -254,11 +290,17 @@ def __init_send_workspace_submission_update(cls, router: fastapi.APIRouter) -> N elif parameter_name == "submission_id": new_parameters.append(parameter.replace(default=fastapi.Path(...))) elif parameter_name == "x_random_header": - new_parameters.append(parameter.replace(default=fastapi.Header(default=None, alias="X-Random-Header"))) + new_parameters.append( + parameter.replace( + default=fastapi.Header(default=None, alias="X-Random-Header") + ) + ) else: new_parameters.append(parameter) setattr( - cls.send_workspace_submission_update, "__signature__", endpoint_function.replace(parameters=new_parameters) + cls.send_workspace_submission_update, + "__signature__", + endpoint_function.replace(parameters=new_parameters), ) @functools.wraps(cls.send_workspace_submission_update) @@ -289,7 +331,9 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> None: def __init_store_traced_test_case(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.store_traced_test_case) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": @@ -299,10 +343,18 @@ def __init_store_traced_test_case(cls, router: fastapi.APIRouter) -> None: elif parameter_name == "test_case_id": new_parameters.append(parameter.replace(default=fastapi.Path(...))) elif parameter_name == "x_random_header": - new_parameters.append(parameter.replace(default=fastapi.Header(default=None, alias="X-Random-Header"))) + new_parameters.append( + parameter.replace( + default=fastapi.Header(default=None, alias="X-Random-Header") + ) + ) else: new_parameters.append(parameter) - setattr(cls.store_traced_test_case, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.store_traced_test_case, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.store_traced_test_case) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> None: @@ -332,7 +384,9 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> None: def __init_store_traced_test_case_v_2(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.store_traced_test_case_v_2) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": @@ -342,10 +396,18 @@ def __init_store_traced_test_case_v_2(cls, router: fastapi.APIRouter) -> None: elif parameter_name == "test_case_id": new_parameters.append(parameter.replace(default=fastapi.Path(...))) elif parameter_name == "x_random_header": - new_parameters.append(parameter.replace(default=fastapi.Header(default=None, alias="X-Random-Header"))) + new_parameters.append( + parameter.replace( + default=fastapi.Header(default=None, alias="X-Random-Header") + ) + ) else: new_parameters.append(parameter) - setattr(cls.store_traced_test_case_v_2, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.store_traced_test_case_v_2, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.store_traced_test_case_v_2) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> None: @@ -375,7 +437,9 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> None: def __init_store_traced_workspace(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.store_traced_workspace) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": @@ -383,10 +447,18 @@ def __init_store_traced_workspace(cls, router: fastapi.APIRouter) -> None: elif parameter_name == "submission_id": new_parameters.append(parameter.replace(default=fastapi.Path(...))) elif parameter_name == "x_random_header": - new_parameters.append(parameter.replace(default=fastapi.Header(default=None, alias="X-Random-Header"))) + new_parameters.append( + parameter.replace( + default=fastapi.Header(default=None, alias="X-Random-Header") + ) + ) else: new_parameters.append(parameter) - setattr(cls.store_traced_workspace, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.store_traced_workspace, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.store_traced_workspace) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> None: @@ -416,7 +488,9 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> None: def __init_store_traced_workspace_v_2(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.store_traced_workspace_v_2) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": @@ -424,10 +498,18 @@ def __init_store_traced_workspace_v_2(cls, router: fastapi.APIRouter) -> None: elif parameter_name == "submission_id": new_parameters.append(parameter.replace(default=fastapi.Path(...))) elif parameter_name == "x_random_header": - new_parameters.append(parameter.replace(default=fastapi.Header(default=None, alias="X-Random-Header"))) + new_parameters.append( + parameter.replace( + default=fastapi.Header(default=None, alias="X-Random-Header") + ) + ) else: new_parameters.append(parameter) - setattr(cls.store_traced_workspace_v_2, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.store_traced_workspace_v_2, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.store_traced_workspace_v_2) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> None: diff --git a/seed/fastapi/trace/resources/admin/service/store_traced_test_case_request.py b/seed/fastapi/trace/resources/admin/service/store_traced_test_case_request.py index 9eb0346c4b5..dff238c9cc5 100644 --- a/seed/fastapi/trace/resources/admin/service/store_traced_test_case_request.py +++ b/seed/fastapi/trace/resources/admin/service/store_traced_test_case_request.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import UniversalBaseModel from ...submission.types.test_case_result_with_stdout import TestCaseResultWithStdout +import typing from ...submission.types.trace_response import TraceResponse +import pydantic +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class StoreTracedTestCaseRequest(UniversalBaseModel): @@ -14,7 +13,9 @@ class StoreTracedTestCaseRequest(UniversalBaseModel): trace_responses: typing.List[TraceResponse] = pydantic.Field(alias="traceResponses") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/admin/service/store_traced_workspace_request.py b/seed/fastapi/trace/resources/admin/service/store_traced_workspace_request.py index 381f2a0eaa8..5b11045150a 100644 --- a/seed/fastapi/trace/resources/admin/service/store_traced_workspace_request.py +++ b/seed/fastapi/trace/resources/admin/service/store_traced_workspace_request.py @@ -1,20 +1,23 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ....core.pydantic_utilities import UniversalBaseModel +from ...submission.types.workspace_run_details import WorkspaceRunDetails import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +import typing from ...submission.types.trace_response import TraceResponse -from ...submission.types.workspace_run_details import WorkspaceRunDetails +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class StoreTracedWorkspaceRequest(UniversalBaseModel): - workspace_run_details: WorkspaceRunDetails = pydantic.Field(alias="workspaceRunDetails") + workspace_run_details: WorkspaceRunDetails = pydantic.Field( + alias="workspaceRunDetails" + ) trace_responses: typing.List[TraceResponse] = pydantic.Field(alias="traceResponses") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/admin/types/test.py b/seed/fastapi/trace/resources/admin/types/test.py index 5f5084ffa1f..b0301892b20 100644 --- a/seed/fastapi/trace/resources/admin/types/test.py +++ b/seed/fastapi/trace/resources/admin/types/test.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +from ....core.pydantic_utilities import UniversalRootModel import typing - -import pydantic import typing_extensions - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel, UniversalRootModel, update_forward_refs +import pydantic +from ....core.pydantic_utilities import UniversalBaseModel +from ....core.pydantic_utilities import update_forward_refs T_Result = typing.TypeVar("T_Result") @@ -30,18 +30,25 @@ class Test(UniversalRootModel): factory: typing.ClassVar[_Factory] = _Factory() if IS_PYDANTIC_V2: - root: typing_extensions.Annotated[typing.Union[_Test.And, _Test.Or], pydantic.Field(discriminator="type")] + root: typing_extensions.Annotated[ + typing.Union[_Test.And, _Test.Or], pydantic.Field(discriminator="type") + ] def get_as_union(self) -> typing.Union[_Test.And, _Test.Or]: return self.root - else: - __root__: typing_extensions.Annotated[typing.Union[_Test.And, _Test.Or], pydantic.Field(discriminator="type")] + __root__: typing_extensions.Annotated[ + typing.Union[_Test.And, _Test.Or], pydantic.Field(discriminator="type") + ] def get_as_union(self) -> typing.Union[_Test.And, _Test.Or]: return self.__root__ - def visit(self, and_: typing.Callable[[bool], T_Result], or_: typing.Callable[[bool], T_Result]) -> T_Result: + def visit( + self, + and_: typing.Callable[[bool], T_Result], + or_: typing.Callable[[bool], T_Result], + ) -> T_Result: unioned_value = self.get_as_union() if unioned_value.type == "and": return and_(unioned_value.value) diff --git a/seed/fastapi/trace/resources/commons/types/binary_tree_node_and_tree_value.py b/seed/fastapi/trace/resources/commons/types/binary_tree_node_and_tree_value.py index 0390d89866a..004a3f59ac6 100644 --- a/seed/fastapi/trace/resources/commons/types/binary_tree_node_and_tree_value.py +++ b/seed/fastapi/trace/resources/commons/types/binary_tree_node_and_tree_value.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ....core.pydantic_utilities import UniversalBaseModel +from .node_id import NodeId import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .binary_tree_value import BinaryTreeValue -from .node_id import NodeId +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class BinaryTreeNodeAndTreeValue(UniversalBaseModel): @@ -14,7 +13,9 @@ class BinaryTreeNodeAndTreeValue(UniversalBaseModel): full_tree: BinaryTreeValue = pydantic.Field(alias="fullTree") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/commons/types/binary_tree_node_value.py b/seed/fastapi/trace/resources/commons/types/binary_tree_node_value.py index 7a0c099f15a..68b2e5c2933 100644 --- a/seed/fastapi/trace/resources/commons/types/binary_tree_node_value.py +++ b/seed/fastapi/trace/resources/commons/types/binary_tree_node_value.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import UniversalBaseModel from .node_id import NodeId +import pydantic +import typing +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class BinaryTreeNodeValue(UniversalBaseModel): @@ -15,7 +14,9 @@ class BinaryTreeNodeValue(UniversalBaseModel): left: typing.Optional[NodeId] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/commons/types/binary_tree_value.py b/seed/fastapi/trace/resources/commons/types/binary_tree_value.py index 7145a014831..f3c9da1d747 100644 --- a/seed/fastapi/trace/resources/commons/types/binary_tree_value.py +++ b/seed/fastapi/trace/resources/commons/types/binary_tree_value.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .binary_tree_node_value import BinaryTreeNodeValue from .node_id import NodeId +from .binary_tree_node_value import BinaryTreeNodeValue +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import pydantic class BinaryTreeValue(UniversalBaseModel): @@ -14,7 +13,9 @@ class BinaryTreeValue(UniversalBaseModel): nodes: typing.Dict[NodeId, BinaryTreeNodeValue] if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/commons/types/debug_key_value_pairs.py b/seed/fastapi/trace/resources/commons/types/debug_key_value_pairs.py index b2d51f4a170..30075eed660 100644 --- a/seed/fastapi/trace/resources/commons/types/debug_key_value_pairs.py +++ b/seed/fastapi/trace/resources/commons/types/debug_key_value_pairs.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ....core.pydantic_utilities import UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel, update_forward_refs +from ....core.pydantic_utilities import update_forward_refs class DebugKeyValuePairs(UniversalBaseModel): @@ -14,7 +13,9 @@ class DebugKeyValuePairs(UniversalBaseModel): value: DebugVariableValue if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/commons/types/debug_map_value.py b/seed/fastapi/trace/resources/commons/types/debug_map_value.py index 04957cb984d..769da9a6fd3 100644 --- a/seed/fastapi/trace/resources/commons/types/debug_map_value.py +++ b/seed/fastapi/trace/resources/commons/types/debug_map_value.py @@ -1,19 +1,22 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ....core.pydantic_utilities import UniversalBaseModel import typing - import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel, update_forward_refs +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +from ....core.pydantic_utilities import update_forward_refs class DebugMapValue(UniversalBaseModel): - key_value_pairs: typing.List[DebugKeyValuePairs] = pydantic.Field(alias="keyValuePairs") + key_value_pairs: typing.List[DebugKeyValuePairs] = pydantic.Field( + alias="keyValuePairs" + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/commons/types/debug_variable_value.py b/seed/fastapi/trace/resources/commons/types/debug_variable_value.py index 2c88b6bd825..2de14cf11f4 100644 --- a/seed/fastapi/trace/resources/commons/types/debug_variable_value.py +++ b/seed/fastapi/trace/resources/commons/types/debug_variable_value.py @@ -1,17 +1,19 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import typing - -import pydantic -import typing_extensions - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel, UniversalRootModel, update_forward_refs from .binary_tree_node_and_tree_value import BinaryTreeNodeAndTreeValue -from .doubly_linked_list_node_and_list_value import DoublyLinkedListNodeAndListValue -from .generic_value import GenericValue as resources_commons_types_generic_value_GenericValue from .singly_linked_list_node_and_list_value import SinglyLinkedListNodeAndListValue +from .doubly_linked_list_node_and_list_value import DoublyLinkedListNodeAndListValue +from .generic_value import ( + GenericValue as resources_commons_types_generic_value_GenericValue, +) +from ....core.pydantic_utilities import UniversalRootModel +import typing_extensions +import pydantic +from ....core.pydantic_utilities import UniversalBaseModel +from ....core.pydantic_utilities import update_forward_refs T_Result = typing.TypeVar("T_Result") @@ -19,51 +21,89 @@ class _Factory: def integer_value(self, value: int) -> DebugVariableValue: if IS_PYDANTIC_V2: - return DebugVariableValue(root=_DebugVariableValue.IntegerValue(type="integerValue", value=value)) + return DebugVariableValue( + root=_DebugVariableValue.IntegerValue(type="integerValue", value=value) + ) else: - return DebugVariableValue(__root__=_DebugVariableValue.IntegerValue(type="integerValue", value=value)) + return DebugVariableValue( + __root__=_DebugVariableValue.IntegerValue( + type="integerValue", value=value + ) + ) def boolean_value(self, value: bool) -> DebugVariableValue: if IS_PYDANTIC_V2: - return DebugVariableValue(root=_DebugVariableValue.BooleanValue(type="booleanValue", value=value)) + return DebugVariableValue( + root=_DebugVariableValue.BooleanValue(type="booleanValue", value=value) + ) else: - return DebugVariableValue(__root__=_DebugVariableValue.BooleanValue(type="booleanValue", value=value)) + return DebugVariableValue( + __root__=_DebugVariableValue.BooleanValue( + type="booleanValue", value=value + ) + ) def double_value(self, value: float) -> DebugVariableValue: if IS_PYDANTIC_V2: - return DebugVariableValue(root=_DebugVariableValue.DoubleValue(type="doubleValue", value=value)) + return DebugVariableValue( + root=_DebugVariableValue.DoubleValue(type="doubleValue", value=value) + ) else: - return DebugVariableValue(__root__=_DebugVariableValue.DoubleValue(type="doubleValue", value=value)) + return DebugVariableValue( + __root__=_DebugVariableValue.DoubleValue( + type="doubleValue", value=value + ) + ) def string_value(self, value: str) -> DebugVariableValue: if IS_PYDANTIC_V2: - return DebugVariableValue(root=_DebugVariableValue.StringValue(type="stringValue", value=value)) + return DebugVariableValue( + root=_DebugVariableValue.StringValue(type="stringValue", value=value) + ) else: - return DebugVariableValue(__root__=_DebugVariableValue.StringValue(type="stringValue", value=value)) + return DebugVariableValue( + __root__=_DebugVariableValue.StringValue( + type="stringValue", value=value + ) + ) def char_value(self, value: str) -> DebugVariableValue: if IS_PYDANTIC_V2: - return DebugVariableValue(root=_DebugVariableValue.CharValue(type="charValue", value=value)) + return DebugVariableValue( + root=_DebugVariableValue.CharValue(type="charValue", value=value) + ) else: - return DebugVariableValue(__root__=_DebugVariableValue.CharValue(type="charValue", value=value)) + return DebugVariableValue( + __root__=_DebugVariableValue.CharValue(type="charValue", value=value) + ) def map_value(self, value: DebugMapValue) -> DebugVariableValue: if IS_PYDANTIC_V2: return DebugVariableValue( - root=_DebugVariableValue.MapValue(**value.dict(exclude_unset=True), type="mapValue") + root=_DebugVariableValue.MapValue( + **value.dict(exclude_unset=True), type="mapValue" + ) ) else: return DebugVariableValue( - __root__=_DebugVariableValue.MapValue(**value.dict(exclude_unset=True), type="mapValue") + __root__=_DebugVariableValue.MapValue( + **value.dict(exclude_unset=True), type="mapValue" + ) ) def list_value(self, value: typing.List[DebugVariableValue]) -> DebugVariableValue: if IS_PYDANTIC_V2: - return DebugVariableValue(root=_DebugVariableValue.ListValue(type="listValue", value=value)) + return DebugVariableValue( + root=_DebugVariableValue.ListValue(type="listValue", value=value) + ) else: - return DebugVariableValue(__root__=_DebugVariableValue.ListValue(type="listValue", value=value)) + return DebugVariableValue( + __root__=_DebugVariableValue.ListValue(type="listValue", value=value) + ) - def binary_tree_node_value(self, value: BinaryTreeNodeAndTreeValue) -> DebugVariableValue: + def binary_tree_node_value( + self, value: BinaryTreeNodeAndTreeValue + ) -> DebugVariableValue: if IS_PYDANTIC_V2: return DebugVariableValue( root=_DebugVariableValue.BinaryTreeNodeValue( @@ -77,7 +117,9 @@ def binary_tree_node_value(self, value: BinaryTreeNodeAndTreeValue) -> DebugVari ) ) - def singly_linked_list_node_value(self, value: SinglyLinkedListNodeAndListValue) -> DebugVariableValue: + def singly_linked_list_node_value( + self, value: SinglyLinkedListNodeAndListValue + ) -> DebugVariableValue: if IS_PYDANTIC_V2: return DebugVariableValue( root=_DebugVariableValue.SinglyLinkedListNodeValue( @@ -91,7 +133,9 @@ def singly_linked_list_node_value(self, value: SinglyLinkedListNodeAndListValue) ) ) - def doubly_linked_list_node_value(self, value: DoublyLinkedListNodeAndListValue) -> DebugVariableValue: + def doubly_linked_list_node_value( + self, value: DoublyLinkedListNodeAndListValue + ) -> DebugVariableValue: if IS_PYDANTIC_V2: return DebugVariableValue( root=_DebugVariableValue.DoublyLinkedListNodeValue( @@ -107,24 +151,38 @@ def doubly_linked_list_node_value(self, value: DoublyLinkedListNodeAndListValue) def undefined_value(self) -> DebugVariableValue: if IS_PYDANTIC_V2: - return DebugVariableValue(root=_DebugVariableValue.UndefinedValue(type="undefinedValue")) + return DebugVariableValue( + root=_DebugVariableValue.UndefinedValue(type="undefinedValue") + ) else: - return DebugVariableValue(__root__=_DebugVariableValue.UndefinedValue(type="undefinedValue")) + return DebugVariableValue( + __root__=_DebugVariableValue.UndefinedValue(type="undefinedValue") + ) def null_value(self) -> DebugVariableValue: if IS_PYDANTIC_V2: - return DebugVariableValue(root=_DebugVariableValue.NullValue(type="nullValue")) + return DebugVariableValue( + root=_DebugVariableValue.NullValue(type="nullValue") + ) else: - return DebugVariableValue(__root__=_DebugVariableValue.NullValue(type="nullValue")) + return DebugVariableValue( + __root__=_DebugVariableValue.NullValue(type="nullValue") + ) - def generic_value(self, value: resources_commons_types_generic_value_GenericValue) -> DebugVariableValue: + def generic_value( + self, value: resources_commons_types_generic_value_GenericValue + ) -> DebugVariableValue: if IS_PYDANTIC_V2: return DebugVariableValue( - root=_DebugVariableValue.GenericValue(**value.dict(exclude_unset=True), type="genericValue") + root=_DebugVariableValue.GenericValue( + **value.dict(exclude_unset=True), type="genericValue" + ) ) else: return DebugVariableValue( - __root__=_DebugVariableValue.GenericValue(**value.dict(exclude_unset=True), type="genericValue") + __root__=_DebugVariableValue.GenericValue( + **value.dict(exclude_unset=True), type="genericValue" + ) ) @@ -169,7 +227,6 @@ def get_as_union( _DebugVariableValue.GenericValue, ]: return self.root - else: __root__: typing_extensions.Annotated[ typing.Union[ @@ -219,11 +276,17 @@ def visit( map_value: typing.Callable[[DebugMapValue], T_Result], list_value: typing.Callable[[typing.List[DebugVariableValue]], T_Result], binary_tree_node_value: typing.Callable[[BinaryTreeNodeAndTreeValue], T_Result], - singly_linked_list_node_value: typing.Callable[[SinglyLinkedListNodeAndListValue], T_Result], - doubly_linked_list_node_value: typing.Callable[[DoublyLinkedListNodeAndListValue], T_Result], + singly_linked_list_node_value: typing.Callable[ + [SinglyLinkedListNodeAndListValue], T_Result + ], + doubly_linked_list_node_value: typing.Callable[ + [DoublyLinkedListNodeAndListValue], T_Result + ], undefined_value: typing.Callable[[], T_Result], null_value: typing.Callable[[], T_Result], - generic_value: typing.Callable[[resources_commons_types_generic_value_GenericValue], T_Result], + generic_value: typing.Callable[ + [resources_commons_types_generic_value_GenericValue], T_Result + ], ) -> T_Result: unioned_value = self.get_as_union() if unioned_value.type == "integerValue": @@ -237,20 +300,30 @@ def visit( if unioned_value.type == "charValue": return char_value(unioned_value.value) if unioned_value.type == "mapValue": - return map_value(DebugMapValue(**unioned_value.dict(exclude_unset=True, exclude={"type"}))) + return map_value( + DebugMapValue( + **unioned_value.dict(exclude_unset=True, exclude={"type"}) + ) + ) if unioned_value.type == "listValue": return list_value(unioned_value.value) if unioned_value.type == "binaryTreeNodeValue": return binary_tree_node_value( - BinaryTreeNodeAndTreeValue(**unioned_value.dict(exclude_unset=True, exclude={"type"})) + BinaryTreeNodeAndTreeValue( + **unioned_value.dict(exclude_unset=True, exclude={"type"}) + ) ) if unioned_value.type == "singlyLinkedListNodeValue": return singly_linked_list_node_value( - SinglyLinkedListNodeAndListValue(**unioned_value.dict(exclude_unset=True, exclude={"type"})) + SinglyLinkedListNodeAndListValue( + **unioned_value.dict(exclude_unset=True, exclude={"type"}) + ) ) if unioned_value.type == "doublyLinkedListNodeValue": return doubly_linked_list_node_value( - DoublyLinkedListNodeAndListValue(**unioned_value.dict(exclude_unset=True, exclude={"type"})) + DoublyLinkedListNodeAndListValue( + **unioned_value.dict(exclude_unset=True, exclude={"type"}) + ) ) if unioned_value.type == "undefinedValue": return undefined_value() @@ -264,8 +337,8 @@ def visit( ) -from .debug_key_value_pairs import DebugKeyValuePairs # noqa: E402 from .debug_map_value import DebugMapValue # noqa: E402 +from .debug_key_value_pairs import DebugKeyValuePairs # noqa: E402 class _DebugVariableValue: diff --git a/seed/fastapi/trace/resources/commons/types/doubly_linked_list_node_and_list_value.py b/seed/fastapi/trace/resources/commons/types/doubly_linked_list_node_and_list_value.py index aeaaf282387..e2ab78cd45a 100644 --- a/seed/fastapi/trace/resources/commons/types/doubly_linked_list_node_and_list_value.py +++ b/seed/fastapi/trace/resources/commons/types/doubly_linked_list_node_and_list_value.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ....core.pydantic_utilities import UniversalBaseModel +from .node_id import NodeId import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .doubly_linked_list_value import DoublyLinkedListValue -from .node_id import NodeId +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class DoublyLinkedListNodeAndListValue(UniversalBaseModel): @@ -14,7 +13,9 @@ class DoublyLinkedListNodeAndListValue(UniversalBaseModel): full_list: DoublyLinkedListValue = pydantic.Field(alias="fullList") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/commons/types/doubly_linked_list_node_value.py b/seed/fastapi/trace/resources/commons/types/doubly_linked_list_node_value.py index 363b9413fbe..3768edd7409 100644 --- a/seed/fastapi/trace/resources/commons/types/doubly_linked_list_node_value.py +++ b/seed/fastapi/trace/resources/commons/types/doubly_linked_list_node_value.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import UniversalBaseModel from .node_id import NodeId +import pydantic +import typing +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class DoublyLinkedListNodeValue(UniversalBaseModel): @@ -15,7 +14,9 @@ class DoublyLinkedListNodeValue(UniversalBaseModel): prev: typing.Optional[NodeId] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/commons/types/doubly_linked_list_value.py b/seed/fastapi/trace/resources/commons/types/doubly_linked_list_value.py index 384c3531ba0..cf512ef0ab6 100644 --- a/seed/fastapi/trace/resources/commons/types/doubly_linked_list_value.py +++ b/seed/fastapi/trace/resources/commons/types/doubly_linked_list_value.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .doubly_linked_list_node_value import DoublyLinkedListNodeValue from .node_id import NodeId +from .doubly_linked_list_node_value import DoublyLinkedListNodeValue +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import pydantic class DoublyLinkedListValue(UniversalBaseModel): @@ -14,7 +13,9 @@ class DoublyLinkedListValue(UniversalBaseModel): nodes: typing.Dict[NodeId, DoublyLinkedListNodeValue] if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/commons/types/file_info.py b/seed/fastapi/trace/resources/commons/types/file_info.py index cf794b4c7b2..4e8a19da13c 100644 --- a/seed/fastapi/trace/resources/commons/types/file_info.py +++ b/seed/fastapi/trace/resources/commons/types/file_info.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class FileInfo(UniversalBaseModel): filename: str contents: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/commons/types/generic_value.py b/seed/fastapi/trace/resources/commons/types/generic_value.py index ce258e3dabb..175bf04b95f 100644 --- a/seed/fastapi/trace/resources/commons/types/generic_value.py +++ b/seed/fastapi/trace/resources/commons/types/generic_value.py @@ -1,18 +1,21 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class GenericValue(UniversalBaseModel): - stringified_type: typing.Optional[str] = pydantic.Field(alias="stringifiedType", default=None) + stringified_type: typing.Optional[str] = pydantic.Field( + alias="stringifiedType", default=None + ) stringified_value: str = pydantic.Field(alias="stringifiedValue") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/commons/types/key_value_pair.py b/seed/fastapi/trace/resources/commons/types/key_value_pair.py index 5b8200e7f6d..73c97bd096c 100644 --- a/seed/fastapi/trace/resources/commons/types/key_value_pair.py +++ b/seed/fastapi/trace/resources/commons/types/key_value_pair.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ....core.pydantic_utilities import UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel, update_forward_refs +from ....core.pydantic_utilities import update_forward_refs class KeyValuePair(UniversalBaseModel): @@ -14,7 +13,9 @@ class KeyValuePair(UniversalBaseModel): value: VariableValue if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/commons/types/list_type.py b/seed/fastapi/trace/resources/commons/types/list_type.py index 966fd41793f..51fbdb3569f 100644 --- a/seed/fastapi/trace/resources/commons/types/list_type.py +++ b/seed/fastapi/trace/resources/commons/types/list_type.py @@ -1,23 +1,26 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - -import typing - +from ....core.pydantic_utilities import UniversalBaseModel import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel, update_forward_refs +import typing +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +from ....core.pydantic_utilities import update_forward_refs class ListType(UniversalBaseModel): value_type: VariableType = pydantic.Field(alias="valueType") - is_fixed_length: typing.Optional[bool] = pydantic.Field(alias="isFixedLength", default=None) + is_fixed_length: typing.Optional[bool] = pydantic.Field( + alias="isFixedLength", default=None + ) """ Whether this list is fixed-size (for languages that supports fixed-size lists). Defaults to false. """ if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/commons/types/map_type.py b/seed/fastapi/trace/resources/commons/types/map_type.py index 7fb522bfc1e..72153daa9e6 100644 --- a/seed/fastapi/trace/resources/commons/types/map_type.py +++ b/seed/fastapi/trace/resources/commons/types/map_type.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - -import typing - +from ....core.pydantic_utilities import UniversalBaseModel import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel, update_forward_refs +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing +from ....core.pydantic_utilities import update_forward_refs class MapType(UniversalBaseModel): @@ -14,7 +13,9 @@ class MapType(UniversalBaseModel): value_type: VariableType = pydantic.Field(alias="valueType") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/commons/types/map_value.py b/seed/fastapi/trace/resources/commons/types/map_value.py index 28e195e2394..34bcf174998 100644 --- a/seed/fastapi/trace/resources/commons/types/map_value.py +++ b/seed/fastapi/trace/resources/commons/types/map_value.py @@ -1,19 +1,20 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ....core.pydantic_utilities import UniversalBaseModel import typing - import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel, update_forward_refs +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +from ....core.pydantic_utilities import update_forward_refs class MapValue(UniversalBaseModel): key_value_pairs: typing.List[KeyValuePair] = pydantic.Field(alias="keyValuePairs") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/commons/types/singly_linked_list_node_and_list_value.py b/seed/fastapi/trace/resources/commons/types/singly_linked_list_node_and_list_value.py index 2da47265c30..e91f58d0a3c 100644 --- a/seed/fastapi/trace/resources/commons/types/singly_linked_list_node_and_list_value.py +++ b/seed/fastapi/trace/resources/commons/types/singly_linked_list_node_and_list_value.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import UniversalBaseModel from .node_id import NodeId +import pydantic from .singly_linked_list_value import SinglyLinkedListValue +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class SinglyLinkedListNodeAndListValue(UniversalBaseModel): @@ -14,7 +13,9 @@ class SinglyLinkedListNodeAndListValue(UniversalBaseModel): full_list: SinglyLinkedListValue = pydantic.Field(alias="fullList") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/commons/types/singly_linked_list_node_value.py b/seed/fastapi/trace/resources/commons/types/singly_linked_list_node_value.py index e15b1081ef9..b0e3389daa3 100644 --- a/seed/fastapi/trace/resources/commons/types/singly_linked_list_node_value.py +++ b/seed/fastapi/trace/resources/commons/types/singly_linked_list_node_value.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import UniversalBaseModel from .node_id import NodeId +import pydantic +import typing +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class SinglyLinkedListNodeValue(UniversalBaseModel): @@ -14,7 +13,9 @@ class SinglyLinkedListNodeValue(UniversalBaseModel): next: typing.Optional[NodeId] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/commons/types/singly_linked_list_value.py b/seed/fastapi/trace/resources/commons/types/singly_linked_list_value.py index a6475c74e5a..18c76d08f51 100644 --- a/seed/fastapi/trace/resources/commons/types/singly_linked_list_value.py +++ b/seed/fastapi/trace/resources/commons/types/singly_linked_list_value.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .node_id import NodeId from .singly_linked_list_node_value import SinglyLinkedListNodeValue +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import pydantic class SinglyLinkedListValue(UniversalBaseModel): @@ -14,7 +13,9 @@ class SinglyLinkedListValue(UniversalBaseModel): nodes: typing.Dict[NodeId, SinglyLinkedListNodeValue] if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/commons/types/test_case.py b/seed/fastapi/trace/resources/commons/types/test_case.py index fd5364fb761..6d11ef9307c 100644 --- a/seed/fastapi/trace/resources/commons/types/test_case.py +++ b/seed/fastapi/trace/resources/commons/types/test_case.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .variable_value import VariableValue +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import pydantic class TestCase(UniversalBaseModel): @@ -13,7 +12,9 @@ class TestCase(UniversalBaseModel): params: typing.List[VariableValue] if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/commons/types/test_case_with_expected_result.py b/seed/fastapi/trace/resources/commons/types/test_case_with_expected_result.py index bb75bcb4281..fb58e1bd46b 100644 --- a/seed/fastapi/trace/resources/commons/types/test_case_with_expected_result.py +++ b/seed/fastapi/trace/resources/commons/types/test_case_with_expected_result.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import UniversalBaseModel from .test_case import TestCase +import pydantic from .variable_value import VariableValue +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class TestCaseWithExpectedResult(UniversalBaseModel): @@ -14,7 +13,9 @@ class TestCaseWithExpectedResult(UniversalBaseModel): expected_result: VariableValue = pydantic.Field(alias="expectedResult") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/commons/types/variable_type.py b/seed/fastapi/trace/resources/commons/types/variable_type.py index c8b33a0e96d..8c09b591f06 100644 --- a/seed/fastapi/trace/resources/commons/types/variable_type.py +++ b/seed/fastapi/trace/resources/commons/types/variable_type.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +from ....core.pydantic_utilities import UniversalRootModel import typing - -import pydantic import typing_extensions - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel, UniversalRootModel, update_forward_refs +import pydantic +from ....core.pydantic_utilities import UniversalBaseModel +from ....core.pydantic_utilities import update_forward_refs T_Result = typing.TypeVar("T_Result") @@ -43,35 +43,65 @@ def char_type(self) -> VariableType: else: return VariableType(__root__=_VariableType.CharType(type="charType")) - def list_type(self, value: resources_commons_types_list_type_ListType) -> VariableType: + def list_type( + self, value: resources_commons_types_list_type_ListType + ) -> VariableType: if IS_PYDANTIC_V2: - return VariableType(root=_VariableType.ListType(**value.dict(exclude_unset=True), type="listType")) + return VariableType( + root=_VariableType.ListType( + **value.dict(exclude_unset=True), type="listType" + ) + ) else: - return VariableType(__root__=_VariableType.ListType(**value.dict(exclude_unset=True), type="listType")) + return VariableType( + __root__=_VariableType.ListType( + **value.dict(exclude_unset=True), type="listType" + ) + ) def map_type(self, value: resources_commons_types_map_type_MapType) -> VariableType: if IS_PYDANTIC_V2: - return VariableType(root=_VariableType.MapType(**value.dict(exclude_unset=True), type="mapType")) + return VariableType( + root=_VariableType.MapType( + **value.dict(exclude_unset=True), type="mapType" + ) + ) else: - return VariableType(__root__=_VariableType.MapType(**value.dict(exclude_unset=True), type="mapType")) + return VariableType( + __root__=_VariableType.MapType( + **value.dict(exclude_unset=True), type="mapType" + ) + ) def binary_tree_type(self) -> VariableType: if IS_PYDANTIC_V2: - return VariableType(root=_VariableType.BinaryTreeType(type="binaryTreeType")) + return VariableType( + root=_VariableType.BinaryTreeType(type="binaryTreeType") + ) else: - return VariableType(__root__=_VariableType.BinaryTreeType(type="binaryTreeType")) + return VariableType( + __root__=_VariableType.BinaryTreeType(type="binaryTreeType") + ) def singly_linked_list_type(self) -> VariableType: if IS_PYDANTIC_V2: - return VariableType(root=_VariableType.SinglyLinkedListType(type="singlyLinkedListType")) + return VariableType( + root=_VariableType.SinglyLinkedListType(type="singlyLinkedListType") + ) else: - return VariableType(__root__=_VariableType.SinglyLinkedListType(type="singlyLinkedListType")) + return VariableType( + __root__=_VariableType.SinglyLinkedListType(type="singlyLinkedListType") + ) def doubly_linked_list_type(self) -> VariableType: if IS_PYDANTIC_V2: - return VariableType(root=_VariableType.DoublyLinkedListType(type="doublyLinkedListType")) + return VariableType( + root=_VariableType.DoublyLinkedListType(type="doublyLinkedListType") + ) else: - return VariableType(__root__=_VariableType.DoublyLinkedListType(type="doublyLinkedListType")) + return VariableType( + __root__=_VariableType.DoublyLinkedListType(type="doublyLinkedListType") + ) class VariableType(UniversalRootModel): @@ -109,7 +139,6 @@ def get_as_union( _VariableType.DoublyLinkedListType, ]: return self.root - else: __root__: typing_extensions.Annotated[ typing.Union[ @@ -150,7 +179,9 @@ def visit( boolean_type: typing.Callable[[], T_Result], string_type: typing.Callable[[], T_Result], char_type: typing.Callable[[], T_Result], - list_type: typing.Callable[[resources_commons_types_list_type_ListType], T_Result], + list_type: typing.Callable[ + [resources_commons_types_list_type_ListType], T_Result + ], map_type: typing.Callable[[resources_commons_types_map_type_MapType], T_Result], binary_tree_type: typing.Callable[[], T_Result], singly_linked_list_type: typing.Callable[[], T_Result], @@ -169,11 +200,15 @@ def visit( return char_type() if unioned_value.type == "listType": return list_type( - resources_commons_types_list_type_ListType(**unioned_value.dict(exclude_unset=True, exclude={"type"})) + resources_commons_types_list_type_ListType( + **unioned_value.dict(exclude_unset=True, exclude={"type"}) + ) ) if unioned_value.type == "mapType": return map_type( - resources_commons_types_map_type_MapType(**unioned_value.dict(exclude_unset=True, exclude={"type"})) + resources_commons_types_map_type_MapType( + **unioned_value.dict(exclude_unset=True, exclude={"type"}) + ) ) if unioned_value.type == "binaryTreeType": return binary_tree_type() diff --git a/seed/fastapi/trace/resources/commons/types/variable_value.py b/seed/fastapi/trace/resources/commons/types/variable_value.py index e3f85930d0f..dd31ab61d0e 100644 --- a/seed/fastapi/trace/resources/commons/types/variable_value.py +++ b/seed/fastapi/trace/resources/commons/types/variable_value.py @@ -1,20 +1,22 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import typing - -import pydantic -import typing_extensions - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel, UniversalRootModel, update_forward_refs -from .binary_tree_value import BinaryTreeValue as resources_commons_types_binary_tree_value_BinaryTreeValue -from .doubly_linked_list_value import ( - DoublyLinkedListValue as resources_commons_types_doubly_linked_list_value_DoublyLinkedListValue, +from .binary_tree_value import ( + BinaryTreeValue as resources_commons_types_binary_tree_value_BinaryTreeValue, ) from .singly_linked_list_value import ( SinglyLinkedListValue as resources_commons_types_singly_linked_list_value_SinglyLinkedListValue, ) +from .doubly_linked_list_value import ( + DoublyLinkedListValue as resources_commons_types_doubly_linked_list_value_DoublyLinkedListValue, +) +from ....core.pydantic_utilities import UniversalRootModel +import typing_extensions +import pydantic +from ....core.pydantic_utilities import UniversalBaseModel +from ....core.pydantic_utilities import update_forward_refs T_Result = typing.TypeVar("T_Result") @@ -22,58 +24,99 @@ class _Factory: def integer_value(self, value: int) -> VariableValue: if IS_PYDANTIC_V2: - return VariableValue(root=_VariableValue.IntegerValue(type="integerValue", value=value)) + return VariableValue( + root=_VariableValue.IntegerValue(type="integerValue", value=value) + ) else: - return VariableValue(__root__=_VariableValue.IntegerValue(type="integerValue", value=value)) + return VariableValue( + __root__=_VariableValue.IntegerValue(type="integerValue", value=value) + ) def boolean_value(self, value: bool) -> VariableValue: if IS_PYDANTIC_V2: - return VariableValue(root=_VariableValue.BooleanValue(type="booleanValue", value=value)) + return VariableValue( + root=_VariableValue.BooleanValue(type="booleanValue", value=value) + ) else: - return VariableValue(__root__=_VariableValue.BooleanValue(type="booleanValue", value=value)) + return VariableValue( + __root__=_VariableValue.BooleanValue(type="booleanValue", value=value) + ) def double_value(self, value: float) -> VariableValue: if IS_PYDANTIC_V2: - return VariableValue(root=_VariableValue.DoubleValue(type="doubleValue", value=value)) + return VariableValue( + root=_VariableValue.DoubleValue(type="doubleValue", value=value) + ) else: - return VariableValue(__root__=_VariableValue.DoubleValue(type="doubleValue", value=value)) + return VariableValue( + __root__=_VariableValue.DoubleValue(type="doubleValue", value=value) + ) def string_value(self, value: str) -> VariableValue: if IS_PYDANTIC_V2: - return VariableValue(root=_VariableValue.StringValue(type="stringValue", value=value)) + return VariableValue( + root=_VariableValue.StringValue(type="stringValue", value=value) + ) else: - return VariableValue(__root__=_VariableValue.StringValue(type="stringValue", value=value)) + return VariableValue( + __root__=_VariableValue.StringValue(type="stringValue", value=value) + ) def char_value(self, value: str) -> VariableValue: if IS_PYDANTIC_V2: - return VariableValue(root=_VariableValue.CharValue(type="charValue", value=value)) + return VariableValue( + root=_VariableValue.CharValue(type="charValue", value=value) + ) else: - return VariableValue(__root__=_VariableValue.CharValue(type="charValue", value=value)) + return VariableValue( + __root__=_VariableValue.CharValue(type="charValue", value=value) + ) - def map_value(self, value: resources_commons_types_map_value_MapValue) -> VariableValue: + def map_value( + self, value: resources_commons_types_map_value_MapValue + ) -> VariableValue: if IS_PYDANTIC_V2: - return VariableValue(root=_VariableValue.MapValue(**value.dict(exclude_unset=True), type="mapValue")) + return VariableValue( + root=_VariableValue.MapValue( + **value.dict(exclude_unset=True), type="mapValue" + ) + ) else: - return VariableValue(__root__=_VariableValue.MapValue(**value.dict(exclude_unset=True), type="mapValue")) + return VariableValue( + __root__=_VariableValue.MapValue( + **value.dict(exclude_unset=True), type="mapValue" + ) + ) def list_value(self, value: typing.List[VariableValue]) -> VariableValue: if IS_PYDANTIC_V2: - return VariableValue(root=_VariableValue.ListValue(type="listValue", value=value)) + return VariableValue( + root=_VariableValue.ListValue(type="listValue", value=value) + ) else: - return VariableValue(__root__=_VariableValue.ListValue(type="listValue", value=value)) + return VariableValue( + __root__=_VariableValue.ListValue(type="listValue", value=value) + ) - def binary_tree_value(self, value: resources_commons_types_binary_tree_value_BinaryTreeValue) -> VariableValue: + def binary_tree_value( + self, value: resources_commons_types_binary_tree_value_BinaryTreeValue + ) -> VariableValue: if IS_PYDANTIC_V2: return VariableValue( - root=_VariableValue.BinaryTreeValue(**value.dict(exclude_unset=True), type="binaryTreeValue") + root=_VariableValue.BinaryTreeValue( + **value.dict(exclude_unset=True), type="binaryTreeValue" + ) ) else: return VariableValue( - __root__=_VariableValue.BinaryTreeValue(**value.dict(exclude_unset=True), type="binaryTreeValue") + __root__=_VariableValue.BinaryTreeValue( + **value.dict(exclude_unset=True), type="binaryTreeValue" + ) ) def singly_linked_list_value( - self, value: resources_commons_types_singly_linked_list_value_SinglyLinkedListValue + self, + value: resources_commons_types_singly_linked_list_value_SinglyLinkedListValue, ) -> VariableValue: if IS_PYDANTIC_V2: return VariableValue( @@ -89,7 +132,8 @@ def singly_linked_list_value( ) def doubly_linked_list_value( - self, value: resources_commons_types_doubly_linked_list_value_DoublyLinkedListValue + self, + value: resources_commons_types_doubly_linked_list_value_DoublyLinkedListValue, ) -> VariableValue: if IS_PYDANTIC_V2: return VariableValue( @@ -148,7 +192,6 @@ def get_as_union( _VariableValue.NullValue, ]: return self.root - else: __root__: typing_extensions.Annotated[ typing.Union[ @@ -191,14 +234,20 @@ def visit( double_value: typing.Callable[[float], T_Result], string_value: typing.Callable[[str], T_Result], char_value: typing.Callable[[str], T_Result], - map_value: typing.Callable[[resources_commons_types_map_value_MapValue], T_Result], + map_value: typing.Callable[ + [resources_commons_types_map_value_MapValue], T_Result + ], list_value: typing.Callable[[typing.List[VariableValue]], T_Result], - binary_tree_value: typing.Callable[[resources_commons_types_binary_tree_value_BinaryTreeValue], T_Result], + binary_tree_value: typing.Callable[ + [resources_commons_types_binary_tree_value_BinaryTreeValue], T_Result + ], singly_linked_list_value: typing.Callable[ - [resources_commons_types_singly_linked_list_value_SinglyLinkedListValue], T_Result + [resources_commons_types_singly_linked_list_value_SinglyLinkedListValue], + T_Result, ], doubly_linked_list_value: typing.Callable[ - [resources_commons_types_doubly_linked_list_value_DoublyLinkedListValue], T_Result + [resources_commons_types_doubly_linked_list_value_DoublyLinkedListValue], + T_Result, ], null_value: typing.Callable[[], T_Result], ) -> T_Result: @@ -215,7 +264,9 @@ def visit( return char_value(unioned_value.value) if unioned_value.type == "mapValue": return map_value( - resources_commons_types_map_value_MapValue(**unioned_value.dict(exclude_unset=True, exclude={"type"})) + resources_commons_types_map_value_MapValue( + **unioned_value.dict(exclude_unset=True, exclude={"type"}) + ) ) if unioned_value.type == "listValue": return list_value(unioned_value.value) @@ -241,8 +292,8 @@ def visit( return null_value() -from .key_value_pair import KeyValuePair # noqa: E402 from .map_value import MapValue as resources_commons_types_map_value_MapValue # noqa: E402 +from .key_value_pair import KeyValuePair # noqa: E402 class _VariableValue: @@ -276,10 +327,14 @@ class ListValue(UniversalBaseModel): class BinaryTreeValue(resources_commons_types_binary_tree_value_BinaryTreeValue): type: typing.Literal["binaryTreeValue"] = "binaryTreeValue" - class SinglyLinkedListValue(resources_commons_types_singly_linked_list_value_SinglyLinkedListValue): + class SinglyLinkedListValue( + resources_commons_types_singly_linked_list_value_SinglyLinkedListValue + ): type: typing.Literal["singlyLinkedListValue"] = "singlyLinkedListValue" - class DoublyLinkedListValue(resources_commons_types_doubly_linked_list_value_DoublyLinkedListValue): + class DoublyLinkedListValue( + resources_commons_types_doubly_linked_list_value_DoublyLinkedListValue + ): type: typing.Literal["doublyLinkedListValue"] = "doublyLinkedListValue" class NullValue(UniversalBaseModel): diff --git a/seed/fastapi/trace/resources/homepage/service/service.py b/seed/fastapi/trace/resources/homepage/service/service.py index febf7c3c0d6..325632a8c69 100644 --- a/seed/fastapi/trace/resources/homepage/service/service.py +++ b/seed/fastapi/trace/resources/homepage/service/service.py @@ -1,18 +1,16 @@ # This file was auto-generated by Fern from our API Definition. -import abc -import functools -import inspect -import logging +from ....core.abstract_fern_service import AbstractFernService import typing - +from ...commons.types.problem_id import ProblemId +import abc import fastapi -import starlette - -from ....core.abstract_fern_service import AbstractFernService +import inspect from ....core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools from ....core.route_args import get_route_args -from ...commons.types.problem_id import ProblemId +import starlette class AbstractHomepageService(AbstractFernService): @@ -25,14 +23,17 @@ class AbstractHomepageService(AbstractFernService): """ @abc.abstractmethod - def get_homepage_problems(self, *, x_random_header: typing.Optional[str] = None) -> typing.Sequence[ProblemId]: - ... + def get_homepage_problems( + self, *, x_random_header: typing.Optional[str] = None + ) -> typing.Sequence[ProblemId]: ... @abc.abstractmethod def set_homepage_problems( - self, *, body: typing.List[ProblemId], x_random_header: typing.Optional[str] = None - ) -> None: - ... + self, + *, + body: typing.List[ProblemId], + x_random_header: typing.Optional[str] = None, + ) -> None: ... """ Below are internal methods used by Fern to register your implementation. @@ -48,17 +49,29 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_get_homepage_problems(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_homepage_problems) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "x_random_header": - new_parameters.append(parameter.replace(default=fastapi.Header(default=None, alias="X-Random-Header"))) + new_parameters.append( + parameter.replace( + default=fastapi.Header(default=None, alias="X-Random-Header") + ) + ) else: new_parameters.append(parameter) - setattr(cls.get_homepage_problems, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_homepage_problems, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_homepage_problems) - def wrapper(*args: typing.Any, **kwargs: typing.Any) -> typing.Sequence[ProblemId]: + def wrapper( + *args: typing.Any, **kwargs: typing.Any + ) -> typing.Sequence[ProblemId]: try: return cls.get_homepage_problems(*args, **kwargs) except FernHTTPException as e: @@ -84,16 +97,26 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> typing.Sequence[ProblemI def __init_set_homepage_problems(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.set_homepage_problems) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "x_random_header": - new_parameters.append(parameter.replace(default=fastapi.Header(default=None, alias="X-Random-Header"))) + new_parameters.append( + parameter.replace( + default=fastapi.Header(default=None, alias="X-Random-Header") + ) + ) else: new_parameters.append(parameter) - setattr(cls.set_homepage_problems, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.set_homepage_problems, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.set_homepage_problems) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> None: diff --git a/seed/fastapi/trace/resources/lang_server/types/lang_server_request.py b/seed/fastapi/trace/resources/lang_server/types/lang_server_request.py index b79ffa77895..40aad916651 100644 --- a/seed/fastapi/trace/resources/lang_server/types/lang_server_request.py +++ b/seed/fastapi/trace/resources/lang_server/types/lang_server_request.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class LangServerRequest(UniversalBaseModel): request: typing.Any if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/lang_server/types/lang_server_response.py b/seed/fastapi/trace/resources/lang_server/types/lang_server_response.py index 99fa1651bf1..86c73a9ce47 100644 --- a/seed/fastapi/trace/resources/lang_server/types/lang_server_response.py +++ b/seed/fastapi/trace/resources/lang_server/types/lang_server_response.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class LangServerResponse(UniversalBaseModel): response: typing.Any if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/migration/service/service.py b/seed/fastapi/trace/resources/migration/service/service.py index c9408af1a02..1a9f6be3bd8 100644 --- a/seed/fastapi/trace/resources/migration/service/service.py +++ b/seed/fastapi/trace/resources/migration/service/service.py @@ -1,17 +1,15 @@ # This file was auto-generated by Fern from our API Definition. -import abc -import functools -import inspect -import logging +from ....core.abstract_fern_service import AbstractFernService import typing - +from ..types.migration import Migration +import abc import fastapi - -from ....core.abstract_fern_service import AbstractFernService +import inspect from ....core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools from ....core.route_args import get_route_args -from ..types.migration import Migration class AbstractMigrationService(AbstractFernService): @@ -26,8 +24,7 @@ class AbstractMigrationService(AbstractFernService): @abc.abstractmethod def get_attempted_migrations( self, *, admin_key_header: str, x_random_header: typing.Optional[str] = None - ) -> typing.Sequence[Migration]: - ... + ) -> typing.Sequence[Migration]: ... """ Below are internal methods used by Fern to register your implementation. @@ -42,19 +39,33 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_get_attempted_migrations(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_attempted_migrations) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "admin_key_header": - new_parameters.append(parameter.replace(default=fastapi.Header(alias="admin-key-header"))) + new_parameters.append( + parameter.replace(default=fastapi.Header(alias="admin-key-header")) + ) elif parameter_name == "x_random_header": - new_parameters.append(parameter.replace(default=fastapi.Header(default=None, alias="X-Random-Header"))) + new_parameters.append( + parameter.replace( + default=fastapi.Header(default=None, alias="X-Random-Header") + ) + ) else: new_parameters.append(parameter) - setattr(cls.get_attempted_migrations, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_attempted_migrations, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_attempted_migrations) - def wrapper(*args: typing.Any, **kwargs: typing.Any) -> typing.Sequence[Migration]: + def wrapper( + *args: typing.Any, **kwargs: typing.Any + ) -> typing.Sequence[Migration]: try: return cls.get_attempted_migrations(*args, **kwargs) except FernHTTPException as e: diff --git a/seed/fastapi/trace/resources/migration/types/migration.py b/seed/fastapi/trace/resources/migration/types/migration.py index 18e02b675b7..adc1dc1e359 100644 --- a/seed/fastapi/trace/resources/migration/types/migration.py +++ b/seed/fastapi/trace/resources/migration/types/migration.py @@ -1,19 +1,20 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel +from .migration_status import MigrationStatus +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .migration_status import MigrationStatus - class Migration(UniversalBaseModel): name: str status: MigrationStatus if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/playlist/service/service.py b/seed/fastapi/trace/resources/playlist/service/service.py index e558352d29d..f3a22243e88 100644 --- a/seed/fastapi/trace/resources/playlist/service/service.py +++ b/seed/fastapi/trace/resources/playlist/service/service.py @@ -1,24 +1,23 @@ # This file was auto-generated by Fern from our API Definition. -import abc +from ....core.abstract_fern_service import AbstractFernService +from ..types.playlist_create_request import PlaylistCreateRequest import datetime as dt -import functools -import inspect -import logging import typing - +from ....security import ApiAuth +from ..types.playlist import Playlist +import abc +from ..types.update_playlist_request import UpdatePlaylistRequest import fastapi -import starlette - -from ....core.abstract_fern_service import AbstractFernService +import inspect +from ....security import FernAuth from ....core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools from ....core.route_args import get_route_args -from ....security import ApiAuth, FernAuth from ..errors.playlist_id_not_found_error import PlaylistIdNotFoundError from ..errors.unauthorized_error import UnauthorizedError -from ..types.playlist import Playlist -from ..types.playlist_create_request import PlaylistCreateRequest -from ..types.update_playlist_request import UpdatePlaylistRequest +import starlette class AbstractPlaylistService(AbstractFernService): @@ -66,7 +65,11 @@ def get_playlists( @abc.abstractmethod def get_playlist( - self, *, service_param: int, playlist_id: str, x_random_header: typing.Optional[str] = None + self, + *, + service_param: int, + playlist_id: str, + x_random_header: typing.Optional[str] = None, ) -> Playlist: """ Returns a playlist @@ -90,7 +93,12 @@ def update_playlist( @abc.abstractmethod def delete_playlist( - self, *, service_param: int, playlist_id: str, x_random_header: typing.Optional[str] = None, auth: ApiAuth + self, + *, + service_param: int, + playlist_id: str, + x_random_header: typing.Optional[str] = None, + auth: ApiAuth, ) -> None: """ Deletes a playlist @@ -114,7 +122,9 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_create_playlist(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.create_playlist) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": @@ -122,16 +132,32 @@ def __init_create_playlist(cls, router: fastapi.APIRouter) -> None: elif parameter_name == "service_param": new_parameters.append(parameter.replace(default=fastapi.Path(...))) elif parameter_name == "datetime": - new_parameters.append(parameter.replace(default=fastapi.Query(default=...))) + new_parameters.append( + parameter.replace(default=fastapi.Query(default=...)) + ) elif parameter_name == "optional_datetime": - new_parameters.append(parameter.replace(default=fastapi.Query(default=None, alias="optionalDatetime"))) + new_parameters.append( + parameter.replace( + default=fastapi.Query(default=None, alias="optionalDatetime") + ) + ) elif parameter_name == "x_random_header": - new_parameters.append(parameter.replace(default=fastapi.Header(default=None, alias="X-Random-Header"))) + new_parameters.append( + parameter.replace( + default=fastapi.Header(default=None, alias="X-Random-Header") + ) + ) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.create_playlist, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.create_playlist, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.create_playlist) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> Playlist: @@ -160,43 +186,73 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> Playlist: def __init_get_playlists(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_playlists) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "service_param": new_parameters.append(parameter.replace(default=fastapi.Path(...))) elif parameter_name == "limit": - new_parameters.append(parameter.replace(default=fastapi.Query(default=None))) + new_parameters.append( + parameter.replace(default=fastapi.Query(default=None)) + ) elif parameter_name == "other_field": new_parameters.append( parameter.replace( - default=fastapi.Query(default=..., alias="otherField", description="i'm another field") + default=fastapi.Query( + default=..., + alias="otherField", + description="i'm another field", + ) ) ) elif parameter_name == "multi_line_docs": new_parameters.append( parameter.replace( default=fastapi.Query( - default=..., alias="multiLineDocs", description="I'm a multiline\ndescription" + default=..., + alias="multiLineDocs", + description="I'm a multiline\ndescription", ) ) ) elif parameter_name == "optional_multiple_field": new_parameters.append( - parameter.replace(default=fastapi.Query(default=None, alias="optionalMultipleField")) + parameter.replace( + default=fastapi.Query( + default=None, alias="optionalMultipleField" + ) + ) ) elif parameter_name == "multiple_field": - new_parameters.append(parameter.replace(default=fastapi.Query(default=[], alias="multipleField"))) + new_parameters.append( + parameter.replace( + default=fastapi.Query(default=[], alias="multipleField") + ) + ) elif parameter_name == "x_random_header": - new_parameters.append(parameter.replace(default=fastapi.Header(default=None, alias="X-Random-Header"))) + new_parameters.append( + parameter.replace( + default=fastapi.Header(default=None, alias="X-Random-Header") + ) + ) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.get_playlists, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_playlists, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_playlists) - def wrapper(*args: typing.Any, **kwargs: typing.Any) -> typing.Sequence[Playlist]: + def wrapper( + *args: typing.Any, **kwargs: typing.Any + ) -> typing.Sequence[Playlist]: try: return cls.get_playlists(*args, **kwargs) except FernHTTPException as e: @@ -222,7 +278,9 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> typing.Sequence[Playlist def __init_get_playlist(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_playlist) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "service_param": @@ -230,10 +288,18 @@ def __init_get_playlist(cls, router: fastapi.APIRouter) -> None: elif parameter_name == "playlist_id": new_parameters.append(parameter.replace(default=fastapi.Path(...))) elif parameter_name == "x_random_header": - new_parameters.append(parameter.replace(default=fastapi.Header(default=None, alias="X-Random-Header"))) + new_parameters.append( + parameter.replace( + default=fastapi.Header(default=None, alias="X-Random-Header") + ) + ) else: new_parameters.append(parameter) - setattr(cls.get_playlist, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_playlist, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_playlist) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> Playlist: @@ -264,7 +330,9 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> Playlist: def __init_update_playlist(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.update_playlist) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": @@ -274,15 +342,27 @@ def __init_update_playlist(cls, router: fastapi.APIRouter) -> None: elif parameter_name == "playlist_id": new_parameters.append(parameter.replace(default=fastapi.Path(...))) elif parameter_name == "x_random_header": - new_parameters.append(parameter.replace(default=fastapi.Header(default=None, alias="X-Random-Header"))) + new_parameters.append( + parameter.replace( + default=fastapi.Header(default=None, alias="X-Random-Header") + ) + ) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.update_playlist, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.update_playlist, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.update_playlist) - def wrapper(*args: typing.Any, **kwargs: typing.Any) -> typing.Optional[Playlist]: + def wrapper( + *args: typing.Any, **kwargs: typing.Any + ) -> typing.Optional[Playlist]: try: return cls.update_playlist(*args, **kwargs) except PlaylistIdNotFoundError as e: @@ -310,7 +390,9 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> typing.Optional[Playlist def __init_delete_playlist(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.delete_playlist) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "service_param": @@ -318,12 +400,22 @@ def __init_delete_playlist(cls, router: fastapi.APIRouter) -> None: elif parameter_name == "playlist_id": new_parameters.append(parameter.replace(default=fastapi.Path(...))) elif parameter_name == "x_random_header": - new_parameters.append(parameter.replace(default=fastapi.Header(default=None, alias="X-Random-Header"))) + new_parameters.append( + parameter.replace( + default=fastapi.Header(default=None, alias="X-Random-Header") + ) + ) elif parameter_name == "auth": - new_parameters.append(parameter.replace(default=fastapi.Depends(FernAuth))) + new_parameters.append( + parameter.replace(default=fastapi.Depends(FernAuth)) + ) else: new_parameters.append(parameter) - setattr(cls.delete_playlist, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.delete_playlist, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.delete_playlist) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> None: diff --git a/seed/fastapi/trace/resources/playlist/types/playlist.py b/seed/fastapi/trace/resources/playlist/types/playlist.py index ba33040d1aa..ca7ff079625 100644 --- a/seed/fastapi/trace/resources/playlist/types/playlist.py +++ b/seed/fastapi/trace/resources/playlist/types/playlist.py @@ -1,13 +1,11 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2 -from ...commons.types.user_id import UserId from .playlist_create_request import PlaylistCreateRequest from .playlist_id import PlaylistId +from ...commons.types.user_id import UserId +import pydantic +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class Playlist(PlaylistCreateRequest): @@ -15,7 +13,9 @@ class Playlist(PlaylistCreateRequest): owner_id: UserId = pydantic.Field(alias="owner-id") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/playlist/types/playlist_create_request.py b/seed/fastapi/trace/resources/playlist/types/playlist_create_request.py index 5622193c193..2dd44b3f406 100644 --- a/seed/fastapi/trace/resources/playlist/types/playlist_create_request.py +++ b/seed/fastapi/trace/resources/playlist/types/playlist_create_request.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from ...commons.types.problem_id import ProblemId +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import pydantic class PlaylistCreateRequest(UniversalBaseModel): @@ -13,7 +12,9 @@ class PlaylistCreateRequest(UniversalBaseModel): problems: typing.List[ProblemId] if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/playlist/types/playlist_id_not_found_error_body.py b/seed/fastapi/trace/resources/playlist/types/playlist_id_not_found_error_body.py index 70affccab0e..1280ea7ebc4 100644 --- a/seed/fastapi/trace/resources/playlist/types/playlist_id_not_found_error_body.py +++ b/seed/fastapi/trace/resources/playlist/types/playlist_id_not_found_error_body.py @@ -1,24 +1,31 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - -import typing - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel, UniversalRootModel, update_forward_refs from .playlist_id import PlaylistId as resources_playlist_types_playlist_id_PlaylistId +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +from ....core.pydantic_utilities import UniversalRootModel +import typing +from ....core.pydantic_utilities import UniversalBaseModel +from ....core.pydantic_utilities import update_forward_refs T_Result = typing.TypeVar("T_Result") class _Factory: - def playlist_id(self, value: resources_playlist_types_playlist_id_PlaylistId) -> PlaylistIdNotFoundErrorBody: + def playlist_id( + self, value: resources_playlist_types_playlist_id_PlaylistId + ) -> PlaylistIdNotFoundErrorBody: if IS_PYDANTIC_V2: return PlaylistIdNotFoundErrorBody( - root=_PlaylistIdNotFoundErrorBody.PlaylistId(type="playlistId", value=value) + root=_PlaylistIdNotFoundErrorBody.PlaylistId( + type="playlistId", value=value + ) ) else: return PlaylistIdNotFoundErrorBody( - __root__=_PlaylistIdNotFoundErrorBody.PlaylistId(type="playlistId", value=value) + __root__=_PlaylistIdNotFoundErrorBody.PlaylistId( + type="playlistId", value=value + ) ) @@ -30,7 +37,6 @@ class PlaylistIdNotFoundErrorBody(UniversalRootModel): def get_as_union(self) -> typing.Union[_PlaylistIdNotFoundErrorBody.PlaylistId]: return self.root - else: __root__: typing.Union[_PlaylistIdNotFoundErrorBody.PlaylistId] @@ -38,7 +44,10 @@ def get_as_union(self) -> typing.Union[_PlaylistIdNotFoundErrorBody.PlaylistId]: return self.__root__ def visit( - self, playlist_id: typing.Callable[[resources_playlist_types_playlist_id_PlaylistId], T_Result] + self, + playlist_id: typing.Callable[ + [resources_playlist_types_playlist_id_PlaylistId], T_Result + ], ) -> T_Result: unioned_value = self.get_as_union() if unioned_value.type == "playlistId": diff --git a/seed/fastapi/trace/resources/playlist/types/reserved_keyword_enum.py b/seed/fastapi/trace/resources/playlist/types/reserved_keyword_enum.py index 25bbf666454..32c8762cb92 100644 --- a/seed/fastapi/trace/resources/playlist/types/reserved_keyword_enum.py +++ b/seed/fastapi/trace/resources/playlist/types/reserved_keyword_enum.py @@ -10,7 +10,9 @@ class ReservedKeywordEnum(str, enum.Enum): IS = "is" AS = "as" - def visit(self, is_: typing.Callable[[], T_Result], as_: typing.Callable[[], T_Result]) -> T_Result: + def visit( + self, is_: typing.Callable[[], T_Result], as_: typing.Callable[[], T_Result] + ) -> T_Result: if self is ReservedKeywordEnum.IS: return is_() if self is ReservedKeywordEnum.AS: diff --git a/seed/fastapi/trace/resources/playlist/types/update_playlist_request.py b/seed/fastapi/trace/resources/playlist/types/update_playlist_request.py index 59254b6990f..209538312c9 100644 --- a/seed/fastapi/trace/resources/playlist/types/update_playlist_request.py +++ b/seed/fastapi/trace/resources/playlist/types/update_playlist_request.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from ...commons.types.problem_id import ProblemId +import pydantic +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class UpdatePlaylistRequest(UniversalBaseModel): @@ -16,7 +15,9 @@ class UpdatePlaylistRequest(UniversalBaseModel): """ if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/problem/service/get_default_starter_files_request.py b/seed/fastapi/trace/resources/problem/service/get_default_starter_files_request.py index 1a322698e46..103d903c659 100644 --- a/seed/fastapi/trace/resources/problem/service/get_default_starter_files_request.py +++ b/seed/fastapi/trace/resources/problem/service/get_default_starter_files_request.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - +from ..types.variable_type_and_name import VariableTypeAndName import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from ...commons.types.variable_type import VariableType -from ..types.variable_type_and_name import VariableTypeAndName +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class GetDefaultStarterFilesRequest(UniversalBaseModel): @@ -23,7 +22,9 @@ class GetDefaultStarterFilesRequest(UniversalBaseModel): """ if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/problem/service/service.py b/seed/fastapi/trace/resources/problem/service/service.py index 14f5597eb7c..90ad2702e52 100644 --- a/seed/fastapi/trace/resources/problem/service/service.py +++ b/seed/fastapi/trace/resources/problem/service/service.py @@ -1,22 +1,20 @@ # This file was auto-generated by Fern from our API Definition. -import abc -import functools -import inspect -import logging -import typing - -import fastapi -import starlette - from ....core.abstract_fern_service import AbstractFernService -from ....core.exceptions.fern_http_exception import FernHTTPException -from ....core.route_args import get_route_args from ..types.create_problem_request import CreateProblemRequest +import typing from ..types.create_problem_response import CreateProblemResponse -from ..types.get_default_starter_files_response import GetDefaultStarterFilesResponse +import abc from ..types.update_problem_response import UpdateProblemResponse from .get_default_starter_files_request import GetDefaultStarterFilesRequest +from ..types.get_default_starter_files_response import GetDefaultStarterFilesResponse +import fastapi +import inspect +from ....core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools +from ....core.route_args import get_route_args +import starlette class AbstractProblemService(AbstractFernService): @@ -30,7 +28,10 @@ class AbstractProblemService(AbstractFernService): @abc.abstractmethod def create_problem( - self, *, body: CreateProblemRequest, x_random_header: typing.Optional[str] = None + self, + *, + body: CreateProblemRequest, + x_random_header: typing.Optional[str] = None, ) -> CreateProblemResponse: """ Creates a problem @@ -39,7 +40,11 @@ def create_problem( @abc.abstractmethod def update_problem( - self, *, body: CreateProblemRequest, problem_id: str, x_random_header: typing.Optional[str] = None + self, + *, + body: CreateProblemRequest, + problem_id: str, + x_random_header: typing.Optional[str] = None, ) -> UpdateProblemResponse: """ Updates a problem @@ -47,7 +52,9 @@ def update_problem( ... @abc.abstractmethod - def delete_problem(self, *, problem_id: str, x_random_header: typing.Optional[str] = None) -> None: + def delete_problem( + self, *, problem_id: str, x_random_header: typing.Optional[str] = None + ) -> None: """ Soft deletes a problem """ @@ -55,7 +62,10 @@ def delete_problem(self, *, problem_id: str, x_random_header: typing.Optional[st @abc.abstractmethod def get_default_starter_files( - self, *, body: GetDefaultStarterFilesRequest, x_random_header: typing.Optional[str] = None + self, + *, + body: GetDefaultStarterFilesRequest, + x_random_header: typing.Optional[str] = None, ) -> GetDefaultStarterFilesResponse: """ Returns default starter files for problem @@ -78,16 +88,26 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_create_problem(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.create_problem) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "x_random_header": - new_parameters.append(parameter.replace(default=fastapi.Header(default=None, alias="X-Random-Header"))) + new_parameters.append( + parameter.replace( + default=fastapi.Header(default=None, alias="X-Random-Header") + ) + ) else: new_parameters.append(parameter) - setattr(cls.create_problem, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.create_problem, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.create_problem) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> CreateProblemResponse: @@ -116,7 +136,9 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> CreateProblemResponse: def __init_update_problem(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.update_problem) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": @@ -124,10 +146,18 @@ def __init_update_problem(cls, router: fastapi.APIRouter) -> None: elif parameter_name == "problem_id": new_parameters.append(parameter.replace(default=fastapi.Path(...))) elif parameter_name == "x_random_header": - new_parameters.append(parameter.replace(default=fastapi.Header(default=None, alias="X-Random-Header"))) + new_parameters.append( + parameter.replace( + default=fastapi.Header(default=None, alias="X-Random-Header") + ) + ) else: new_parameters.append(parameter) - setattr(cls.update_problem, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.update_problem, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.update_problem) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> UpdateProblemResponse: @@ -156,16 +186,26 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> UpdateProblemResponse: def __init_delete_problem(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.delete_problem) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "problem_id": new_parameters.append(parameter.replace(default=fastapi.Path(...))) elif parameter_name == "x_random_header": - new_parameters.append(parameter.replace(default=fastapi.Header(default=None, alias="X-Random-Header"))) + new_parameters.append( + parameter.replace( + default=fastapi.Header(default=None, alias="X-Random-Header") + ) + ) else: new_parameters.append(parameter) - setattr(cls.delete_problem, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.delete_problem, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.delete_problem) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> None: @@ -195,19 +235,31 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> None: def __init_get_default_starter_files(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_default_starter_files) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) elif parameter_name == "x_random_header": - new_parameters.append(parameter.replace(default=fastapi.Header(default=None, alias="X-Random-Header"))) + new_parameters.append( + parameter.replace( + default=fastapi.Header(default=None, alias="X-Random-Header") + ) + ) else: new_parameters.append(parameter) - setattr(cls.get_default_starter_files, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_default_starter_files, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_default_starter_files) - def wrapper(*args: typing.Any, **kwargs: typing.Any) -> GetDefaultStarterFilesResponse: + def wrapper( + *args: typing.Any, **kwargs: typing.Any + ) -> GetDefaultStarterFilesResponse: try: return cls.get_default_starter_files(*args, **kwargs) except FernHTTPException as e: diff --git a/seed/fastapi/trace/resources/problem/types/create_problem_error.py b/seed/fastapi/trace/resources/problem/types/create_problem_error.py index 3c61d47c520..5d2693eca08 100644 --- a/seed/fastapi/trace/resources/problem/types/create_problem_error.py +++ b/seed/fastapi/trace/resources/problem/types/create_problem_error.py @@ -1,13 +1,12 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from .generic_create_problem_error import GenericCreateProblemError +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +from ....core.pydantic_utilities import UniversalRootModel import typing - import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalRootModel, update_forward_refs -from .generic_create_problem_error import GenericCreateProblemError +from ....core.pydantic_utilities import update_forward_refs T_Result = typing.TypeVar("T_Result") @@ -16,11 +15,15 @@ class _Factory: def generic(self, value: GenericCreateProblemError) -> CreateProblemError: if IS_PYDANTIC_V2: return CreateProblemError( - root=_CreateProblemError.Generic(**value.dict(exclude_unset=True), error_type="generic") + root=_CreateProblemError.Generic( + **value.dict(exclude_unset=True), error_type="generic" + ) ) else: return CreateProblemError( - __root__=_CreateProblemError.Generic(**value.dict(exclude_unset=True), error_type="generic") + __root__=_CreateProblemError.Generic( + **value.dict(exclude_unset=True), error_type="generic" + ) ) @@ -32,22 +35,29 @@ class CreateProblemError(UniversalRootModel): def get_as_union(self) -> typing.Union[_CreateProblemError.Generic]: return self.root - else: __root__: typing.Union[_CreateProblemError.Generic] def get_as_union(self) -> typing.Union[_CreateProblemError.Generic]: return self.__root__ - def visit(self, generic: typing.Callable[[GenericCreateProblemError], T_Result]) -> T_Result: + def visit( + self, generic: typing.Callable[[GenericCreateProblemError], T_Result] + ) -> T_Result: unioned_value = self.get_as_union() if unioned_value.error_type == "generic": - return generic(GenericCreateProblemError(**unioned_value.dict(exclude_unset=True, exclude={"_type"}))) + return generic( + GenericCreateProblemError( + **unioned_value.dict(exclude_unset=True, exclude={"_type"}) + ) + ) class _CreateProblemError: class Generic(GenericCreateProblemError): - error_type: typing.Literal["generic"] = pydantic.Field(alias="_type", default="generic") + error_type: typing.Literal["generic"] = pydantic.Field( + alias="_type", default="generic" + ) update_forward_refs(CreateProblemError) diff --git a/seed/fastapi/trace/resources/problem/types/create_problem_request.py b/seed/fastapi/trace/resources/problem/types/create_problem_request.py index 95252c12813..fd521fb9adb 100644 --- a/seed/fastapi/trace/resources/problem/types/create_problem_request.py +++ b/seed/fastapi/trace/resources/problem/types/create_problem_request.py @@ -1,16 +1,15 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ....core.pydantic_utilities import UniversalBaseModel import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from ...commons.types.language import Language -from ...commons.types.test_case_with_expected_result import TestCaseWithExpectedResult -from ...commons.types.variable_type import VariableType from .problem_description import ProblemDescription +import typing +from ...commons.types.language import Language from .problem_files import ProblemFiles from .variable_type_and_name import VariableTypeAndName +from ...commons.types.variable_type import VariableType +from ...commons.types.test_case_with_expected_result import TestCaseWithExpectedResult +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class CreateProblemRequest(UniversalBaseModel): @@ -23,7 +22,9 @@ class CreateProblemRequest(UniversalBaseModel): method_name: str = pydantic.Field(alias="methodName") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/problem/types/create_problem_response.py b/seed/fastapi/trace/resources/problem/types/create_problem_response.py index 05e2efc1d25..00c9d188c67 100644 --- a/seed/fastapi/trace/resources/problem/types/create_problem_response.py +++ b/seed/fastapi/trace/resources/problem/types/create_problem_response.py @@ -1,15 +1,15 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - -import typing - -import pydantic -import typing_extensions - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel, UniversalRootModel, update_forward_refs from ...commons.types.problem_id import ProblemId +from ....core.pydantic_utilities import IS_PYDANTIC_V2 from .create_problem_error import CreateProblemError +from ....core.pydantic_utilities import UniversalRootModel +import typing +import typing_extensions +import pydantic +from ....core.pydantic_utilities import UniversalBaseModel +from ....core.pydantic_utilities import update_forward_refs T_Result = typing.TypeVar("T_Result") @@ -17,15 +17,23 @@ class _Factory: def success(self, value: ProblemId) -> CreateProblemResponse: if IS_PYDANTIC_V2: - return CreateProblemResponse(root=_CreateProblemResponse.Success(type="success", value=value)) + return CreateProblemResponse( + root=_CreateProblemResponse.Success(type="success", value=value) + ) else: - return CreateProblemResponse(__root__=_CreateProblemResponse.Success(type="success", value=value)) + return CreateProblemResponse( + __root__=_CreateProblemResponse.Success(type="success", value=value) + ) def error(self, value: CreateProblemError) -> CreateProblemResponse: if IS_PYDANTIC_V2: - return CreateProblemResponse(root=_CreateProblemResponse.Error(type="error", value=value)) + return CreateProblemResponse( + root=_CreateProblemResponse.Error(type="error", value=value) + ) else: - return CreateProblemResponse(__root__=_CreateProblemResponse.Error(type="error", value=value)) + return CreateProblemResponse( + __root__=_CreateProblemResponse.Error(type="error", value=value) + ) class CreateProblemResponse(UniversalRootModel): @@ -37,20 +45,25 @@ class CreateProblemResponse(UniversalRootModel): pydantic.Field(discriminator="type"), ] - def get_as_union(self) -> typing.Union[_CreateProblemResponse.Success, _CreateProblemResponse.Error]: + def get_as_union( + self, + ) -> typing.Union[_CreateProblemResponse.Success, _CreateProblemResponse.Error]: return self.root - else: __root__: typing_extensions.Annotated[ typing.Union[_CreateProblemResponse.Success, _CreateProblemResponse.Error], pydantic.Field(discriminator="type"), ] - def get_as_union(self) -> typing.Union[_CreateProblemResponse.Success, _CreateProblemResponse.Error]: + def get_as_union( + self, + ) -> typing.Union[_CreateProblemResponse.Success, _CreateProblemResponse.Error]: return self.__root__ def visit( - self, success: typing.Callable[[ProblemId], T_Result], error: typing.Callable[[CreateProblemError], T_Result] + self, + success: typing.Callable[[ProblemId], T_Result], + error: typing.Callable[[CreateProblemError], T_Result], ) -> T_Result: unioned_value = self.get_as_union() if unioned_value.type == "success": diff --git a/seed/fastapi/trace/resources/problem/types/generic_create_problem_error.py b/seed/fastapi/trace/resources/problem/types/generic_create_problem_error.py index bb17720b459..ddeb4f4eeb6 100644 --- a/seed/fastapi/trace/resources/problem/types/generic_create_problem_error.py +++ b/seed/fastapi/trace/resources/problem/types/generic_create_problem_error.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class GenericCreateProblemError(UniversalBaseModel): message: str @@ -13,7 +12,9 @@ class GenericCreateProblemError(UniversalBaseModel): stacktrace: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/problem/types/get_default_starter_files_response.py b/seed/fastapi/trace/resources/problem/types/get_default_starter_files_response.py index eba346d8a4c..bd013c52491 100644 --- a/seed/fastapi/trace/resources/problem/types/get_default_starter_files_response.py +++ b/seed/fastapi/trace/resources/problem/types/get_default_starter_files_response.py @@ -1,19 +1,20 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from ...commons.types.language import Language from .problem_files import ProblemFiles +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import pydantic class GetDefaultStarterFilesResponse(UniversalBaseModel): files: typing.Dict[Language, ProblemFiles] if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/problem/types/problem_description.py b/seed/fastapi/trace/resources/problem/types/problem_description.py index 403500ad390..1c453238449 100644 --- a/seed/fastapi/trace/resources/problem/types/problem_description.py +++ b/seed/fastapi/trace/resources/problem/types/problem_description.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .problem_description_board import ProblemDescriptionBoard +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import pydantic class ProblemDescription(UniversalBaseModel): boards: typing.List[ProblemDescriptionBoard] if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/problem/types/problem_description_board.py b/seed/fastapi/trace/resources/problem/types/problem_description_board.py index 7c03600d6f0..2771bf2a2eb 100644 --- a/seed/fastapi/trace/resources/problem/types/problem_description_board.py +++ b/seed/fastapi/trace/resources/problem/types/problem_description_board.py @@ -1,14 +1,14 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +from ...commons.types.variable_value import VariableValue +from ....core.pydantic_utilities import UniversalRootModel import typing - -import pydantic import typing_extensions - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel, UniversalRootModel, update_forward_refs -from ...commons.types.variable_value import VariableValue +import pydantic +from ....core.pydantic_utilities import UniversalBaseModel +from ....core.pydantic_utilities import update_forward_refs T_Result = typing.TypeVar("T_Result") @@ -16,21 +16,35 @@ class _Factory: def html(self, value: str) -> ProblemDescriptionBoard: if IS_PYDANTIC_V2: - return ProblemDescriptionBoard(root=_ProblemDescriptionBoard.Html(type="html", value=value)) + return ProblemDescriptionBoard( + root=_ProblemDescriptionBoard.Html(type="html", value=value) + ) else: - return ProblemDescriptionBoard(__root__=_ProblemDescriptionBoard.Html(type="html", value=value)) + return ProblemDescriptionBoard( + __root__=_ProblemDescriptionBoard.Html(type="html", value=value) + ) def variable(self, value: VariableValue) -> ProblemDescriptionBoard: if IS_PYDANTIC_V2: - return ProblemDescriptionBoard(root=_ProblemDescriptionBoard.Variable(type="variable", value=value)) + return ProblemDescriptionBoard( + root=_ProblemDescriptionBoard.Variable(type="variable", value=value) + ) else: - return ProblemDescriptionBoard(__root__=_ProblemDescriptionBoard.Variable(type="variable", value=value)) + return ProblemDescriptionBoard( + __root__=_ProblemDescriptionBoard.Variable(type="variable", value=value) + ) def test_case_id(self, value: str) -> ProblemDescriptionBoard: if IS_PYDANTIC_V2: - return ProblemDescriptionBoard(root=_ProblemDescriptionBoard.TestCaseId(type="testCaseId", value=value)) + return ProblemDescriptionBoard( + root=_ProblemDescriptionBoard.TestCaseId(type="testCaseId", value=value) + ) else: - return ProblemDescriptionBoard(__root__=_ProblemDescriptionBoard.TestCaseId(type="testCaseId", value=value)) + return ProblemDescriptionBoard( + __root__=_ProblemDescriptionBoard.TestCaseId( + type="testCaseId", value=value + ) + ) class ProblemDescriptionBoard(UniversalRootModel): @@ -39,7 +53,9 @@ class ProblemDescriptionBoard(UniversalRootModel): if IS_PYDANTIC_V2: root: typing_extensions.Annotated[ typing.Union[ - _ProblemDescriptionBoard.Html, _ProblemDescriptionBoard.Variable, _ProblemDescriptionBoard.TestCaseId + _ProblemDescriptionBoard.Html, + _ProblemDescriptionBoard.Variable, + _ProblemDescriptionBoard.TestCaseId, ], pydantic.Field(discriminator="type"), ] @@ -47,14 +63,17 @@ class ProblemDescriptionBoard(UniversalRootModel): def get_as_union( self, ) -> typing.Union[ - _ProblemDescriptionBoard.Html, _ProblemDescriptionBoard.Variable, _ProblemDescriptionBoard.TestCaseId + _ProblemDescriptionBoard.Html, + _ProblemDescriptionBoard.Variable, + _ProblemDescriptionBoard.TestCaseId, ]: return self.root - else: __root__: typing_extensions.Annotated[ typing.Union[ - _ProblemDescriptionBoard.Html, _ProblemDescriptionBoard.Variable, _ProblemDescriptionBoard.TestCaseId + _ProblemDescriptionBoard.Html, + _ProblemDescriptionBoard.Variable, + _ProblemDescriptionBoard.TestCaseId, ], pydantic.Field(discriminator="type"), ] @@ -62,7 +81,9 @@ def get_as_union( def get_as_union( self, ) -> typing.Union[ - _ProblemDescriptionBoard.Html, _ProblemDescriptionBoard.Variable, _ProblemDescriptionBoard.TestCaseId + _ProblemDescriptionBoard.Html, + _ProblemDescriptionBoard.Variable, + _ProblemDescriptionBoard.TestCaseId, ]: return self.__root__ diff --git a/seed/fastapi/trace/resources/problem/types/problem_files.py b/seed/fastapi/trace/resources/problem/types/problem_files.py index f4cca95d7ff..57cac57ed98 100644 --- a/seed/fastapi/trace/resources/problem/types/problem_files.py +++ b/seed/fastapi/trace/resources/problem/types/problem_files.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import UniversalBaseModel from ...commons.types.file_info import FileInfo +import pydantic +import typing +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class ProblemFiles(UniversalBaseModel): @@ -13,7 +12,9 @@ class ProblemFiles(UniversalBaseModel): read_only_files: typing.List[FileInfo] = pydantic.Field(alias="readOnlyFiles") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/problem/types/problem_info.py b/seed/fastapi/trace/resources/problem/types/problem_info.py index e73b4f92315..61b02139b35 100644 --- a/seed/fastapi/trace/resources/problem/types/problem_info.py +++ b/seed/fastapi/trace/resources/problem/types/problem_info.py @@ -1,17 +1,16 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from ...commons.types.language import Language +from ....core.pydantic_utilities import UniversalBaseModel from ...commons.types.problem_id import ProblemId -from ...commons.types.test_case_with_expected_result import TestCaseWithExpectedResult -from ...commons.types.variable_type import VariableType +import pydantic from .problem_description import ProblemDescription +import typing +from ...commons.types.language import Language from .problem_files import ProblemFiles from .variable_type_and_name import VariableTypeAndName +from ...commons.types.variable_type import VariableType +from ...commons.types.test_case_with_expected_result import TestCaseWithExpectedResult +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class ProblemInfo(UniversalBaseModel): @@ -27,7 +26,9 @@ class ProblemInfo(UniversalBaseModel): supports_custom_test_cases: bool = pydantic.Field(alias="supportsCustomTestCases") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/problem/types/update_problem_response.py b/seed/fastapi/trace/resources/problem/types/update_problem_response.py index 647b97c4d34..32c18fef51a 100644 --- a/seed/fastapi/trace/resources/problem/types/update_problem_response.py +++ b/seed/fastapi/trace/resources/problem/types/update_problem_response.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ....core.pydantic_utilities import UniversalBaseModel import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class UpdateProblemResponse(UniversalBaseModel): problem_version: int = pydantic.Field(alias="problemVersion") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/problem/types/variable_type_and_name.py b/seed/fastapi/trace/resources/problem/types/variable_type_and_name.py index 56711208813..de757a6a2d6 100644 --- a/seed/fastapi/trace/resources/problem/types/variable_type_and_name.py +++ b/seed/fastapi/trace/resources/problem/types/variable_type_and_name.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import UniversalBaseModel from ...commons.types.variable_type import VariableType +import pydantic +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class VariableTypeAndName(UniversalBaseModel): @@ -13,7 +12,9 @@ class VariableTypeAndName(UniversalBaseModel): name: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/submission/service/service.py b/seed/fastapi/trace/resources/submission/service/service.py index d2ff28b1adf..4c5159ea43f 100644 --- a/seed/fastapi/trace/resources/submission/service/service.py +++ b/seed/fastapi/trace/resources/submission/service/service.py @@ -1,20 +1,20 @@ # This file was auto-generated by Fern from our API Definition. -import abc -import functools -import inspect -import logging +from ....core.abstract_fern_service import AbstractFernService +from ...commons.types.language import Language import typing - +from ..types.execution_session_response import ExecutionSessionResponse +import abc +from ..types.get_execution_session_state_response import ( + GetExecutionSessionStateResponse, +) import fastapi -import starlette - -from ....core.abstract_fern_service import AbstractFernService +import inspect from ....core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools from ....core.route_args import get_route_args -from ...commons.types.language import Language -from ..types.execution_session_response import ExecutionSessionResponse -from ..types.get_execution_session_state_response import GetExecutionSessionStateResponse +import starlette class AbstractSubmissionService(AbstractFernService): @@ -45,7 +45,9 @@ def get_execution_session( ... @abc.abstractmethod - def stop_execution_session(self, *, session_id: str, x_random_header: typing.Optional[str] = None) -> None: + def stop_execution_session( + self, *, session_id: str, x_random_header: typing.Optional[str] = None + ) -> None: """ Stops execution session. """ @@ -54,8 +56,7 @@ def stop_execution_session(self, *, session_id: str, x_random_header: typing.Opt @abc.abstractmethod def get_execution_sessions_state( self, *, x_random_header: typing.Optional[str] = None - ) -> GetExecutionSessionStateResponse: - ... + ) -> GetExecutionSessionStateResponse: ... """ Below are internal methods used by Fern to register your implementation. @@ -73,19 +74,31 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_create_execution_session(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.create_execution_session) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "language": new_parameters.append(parameter.replace(default=fastapi.Path(...))) elif parameter_name == "x_random_header": - new_parameters.append(parameter.replace(default=fastapi.Header(default=None, alias="X-Random-Header"))) + new_parameters.append( + parameter.replace( + default=fastapi.Header(default=None, alias="X-Random-Header") + ) + ) else: new_parameters.append(parameter) - setattr(cls.create_execution_session, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.create_execution_session, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.create_execution_session) - def wrapper(*args: typing.Any, **kwargs: typing.Any) -> ExecutionSessionResponse: + def wrapper( + *args: typing.Any, **kwargs: typing.Any + ) -> ExecutionSessionResponse: try: return cls.create_execution_session(*args, **kwargs) except FernHTTPException as e: @@ -111,19 +124,31 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> ExecutionSessionResponse def __init_get_execution_session(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_execution_session) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "session_id": new_parameters.append(parameter.replace(default=fastapi.Path(...))) elif parameter_name == "x_random_header": - new_parameters.append(parameter.replace(default=fastapi.Header(default=None, alias="X-Random-Header"))) + new_parameters.append( + parameter.replace( + default=fastapi.Header(default=None, alias="X-Random-Header") + ) + ) else: new_parameters.append(parameter) - setattr(cls.get_execution_session, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_execution_session, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_execution_session) - def wrapper(*args: typing.Any, **kwargs: typing.Any) -> typing.Optional[ExecutionSessionResponse]: + def wrapper( + *args: typing.Any, **kwargs: typing.Any + ) -> typing.Optional[ExecutionSessionResponse]: try: return cls.get_execution_session(*args, **kwargs) except FernHTTPException as e: @@ -149,16 +174,26 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> typing.Optional[Executio def __init_stop_execution_session(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.stop_execution_session) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "session_id": new_parameters.append(parameter.replace(default=fastapi.Path(...))) elif parameter_name == "x_random_header": - new_parameters.append(parameter.replace(default=fastapi.Header(default=None, alias="X-Random-Header"))) + new_parameters.append( + parameter.replace( + default=fastapi.Header(default=None, alias="X-Random-Header") + ) + ) else: new_parameters.append(parameter) - setattr(cls.stop_execution_session, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.stop_execution_session, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.stop_execution_session) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> None: @@ -188,17 +223,29 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> None: def __init_get_execution_sessions_state(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_execution_sessions_state) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "x_random_header": - new_parameters.append(parameter.replace(default=fastapi.Header(default=None, alias="X-Random-Header"))) + new_parameters.append( + parameter.replace( + default=fastapi.Header(default=None, alias="X-Random-Header") + ) + ) else: new_parameters.append(parameter) - setattr(cls.get_execution_sessions_state, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_execution_sessions_state, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_execution_sessions_state) - def wrapper(*args: typing.Any, **kwargs: typing.Any) -> GetExecutionSessionStateResponse: + def wrapper( + *args: typing.Any, **kwargs: typing.Any + ) -> GetExecutionSessionStateResponse: try: return cls.get_execution_sessions_state(*args, **kwargs) except FernHTTPException as e: @@ -217,5 +264,7 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> GetExecutionSessionState path="/sessions/execution-sessions-state", response_model=GetExecutionSessionStateResponse, description=AbstractSubmissionService.get_execution_sessions_state.__doc__, - **get_route_args(cls.get_execution_sessions_state, default_tag="submission"), + **get_route_args( + cls.get_execution_sessions_state, default_tag="submission" + ), )(wrapper) diff --git a/seed/fastapi/trace/resources/submission/types/actual_result.py b/seed/fastapi/trace/resources/submission/types/actual_result.py index 6b82a3f6b07..9b00bec4964 100644 --- a/seed/fastapi/trace/resources/submission/types/actual_result.py +++ b/seed/fastapi/trace/resources/submission/types/actual_result.py @@ -1,16 +1,18 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - -import typing - -import pydantic -import typing_extensions - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel, UniversalRootModel, update_forward_refs from ...commons.types.variable_value import VariableValue +from ....core.pydantic_utilities import IS_PYDANTIC_V2 from .exception_info import ExceptionInfo -from .exception_v_2 import ExceptionV2 as resources_submission_types_exception_v_2_ExceptionV2 +from .exception_v_2 import ( + ExceptionV2 as resources_submission_types_exception_v_2_ExceptionV2, +) +from ....core.pydantic_utilities import UniversalRootModel +import typing +import typing_extensions +import pydantic +from ....core.pydantic_utilities import UniversalBaseModel +from ....core.pydantic_utilities import update_forward_refs T_Result = typing.TypeVar("T_Result") @@ -24,15 +26,29 @@ def value(self, value: VariableValue) -> ActualResult: def exception(self, value: ExceptionInfo) -> ActualResult: if IS_PYDANTIC_V2: - return ActualResult(root=_ActualResult.Exception(**value.dict(exclude_unset=True), type="exception")) + return ActualResult( + root=_ActualResult.Exception( + **value.dict(exclude_unset=True), type="exception" + ) + ) else: - return ActualResult(__root__=_ActualResult.Exception(**value.dict(exclude_unset=True), type="exception")) - - def exception_v_2(self, value: resources_submission_types_exception_v_2_ExceptionV2) -> ActualResult: + return ActualResult( + __root__=_ActualResult.Exception( + **value.dict(exclude_unset=True), type="exception" + ) + ) + + def exception_v_2( + self, value: resources_submission_types_exception_v_2_ExceptionV2 + ) -> ActualResult: if IS_PYDANTIC_V2: - return ActualResult(root=_ActualResult.ExceptionV2(type="exceptionV2", value=value)) + return ActualResult( + root=_ActualResult.ExceptionV2(type="exceptionV2", value=value) + ) else: - return ActualResult(__root__=_ActualResult.ExceptionV2(type="exceptionV2", value=value)) + return ActualResult( + __root__=_ActualResult.ExceptionV2(type="exceptionV2", value=value) + ) class ActualResult(UniversalRootModel): @@ -40,33 +56,50 @@ class ActualResult(UniversalRootModel): if IS_PYDANTIC_V2: root: typing_extensions.Annotated[ - typing.Union[_ActualResult.Value, _ActualResult.Exception, _ActualResult.ExceptionV2], + typing.Union[ + _ActualResult.Value, _ActualResult.Exception, _ActualResult.ExceptionV2 + ], pydantic.Field(discriminator="type"), ] - def get_as_union(self) -> typing.Union[_ActualResult.Value, _ActualResult.Exception, _ActualResult.ExceptionV2]: + def get_as_union( + self, + ) -> typing.Union[ + _ActualResult.Value, _ActualResult.Exception, _ActualResult.ExceptionV2 + ]: return self.root - else: __root__: typing_extensions.Annotated[ - typing.Union[_ActualResult.Value, _ActualResult.Exception, _ActualResult.ExceptionV2], + typing.Union[ + _ActualResult.Value, _ActualResult.Exception, _ActualResult.ExceptionV2 + ], pydantic.Field(discriminator="type"), ] - def get_as_union(self) -> typing.Union[_ActualResult.Value, _ActualResult.Exception, _ActualResult.ExceptionV2]: + def get_as_union( + self, + ) -> typing.Union[ + _ActualResult.Value, _ActualResult.Exception, _ActualResult.ExceptionV2 + ]: return self.__root__ def visit( self, value: typing.Callable[[VariableValue], T_Result], exception: typing.Callable[[ExceptionInfo], T_Result], - exception_v_2: typing.Callable[[resources_submission_types_exception_v_2_ExceptionV2], T_Result], + exception_v_2: typing.Callable[ + [resources_submission_types_exception_v_2_ExceptionV2], T_Result + ], ) -> T_Result: unioned_value = self.get_as_union() if unioned_value.type == "value": return value(unioned_value.value) if unioned_value.type == "exception": - return exception(ExceptionInfo(**unioned_value.dict(exclude_unset=True, exclude={"type"}))) + return exception( + ExceptionInfo( + **unioned_value.dict(exclude_unset=True, exclude={"type"}) + ) + ) if unioned_value.type == "exceptionV2": return exception_v_2(unioned_value.value) diff --git a/seed/fastapi/trace/resources/submission/types/building_executor_response.py b/seed/fastapi/trace/resources/submission/types/building_executor_response.py index 90d54dab713..d08d0d07c1f 100644 --- a/seed/fastapi/trace/resources/submission/types/building_executor_response.py +++ b/seed/fastapi/trace/resources/submission/types/building_executor_response.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ....core.pydantic_utilities import UniversalBaseModel +from .submission_id import SubmissionId import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .execution_session_status import ExecutionSessionStatus -from .submission_id import SubmissionId +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class BuildingExecutorResponse(UniversalBaseModel): @@ -14,7 +13,9 @@ class BuildingExecutorResponse(UniversalBaseModel): status: ExecutionSessionStatus if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/submission/types/code_execution_update.py b/seed/fastapi/trace/resources/submission/types/code_execution_update.py index 4ea0130e6c6..75dfc5abdc6 100644 --- a/seed/fastapi/trace/resources/submission/types/code_execution_update.py +++ b/seed/fastapi/trace/resources/submission/types/code_execution_update.py @@ -1,24 +1,23 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - -import typing - -import pydantic -import typing_extensions - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalRootModel, update_forward_refs from .building_executor_response import BuildingExecutorResponse +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +from .running_response import RunningResponse from .errored_response import ErroredResponse -from .finished_response import FinishedResponse +from .stopped_response import StoppedResponse from .graded_response import GradedResponse from .graded_response_v_2 import GradedResponseV2 -from .invalid_request_response import InvalidRequestResponse -from .recorded_response_notification import RecordedResponseNotification -from .recording_response_notification import RecordingResponseNotification -from .running_response import RunningResponse -from .stopped_response import StoppedResponse from .workspace_ran_response import WorkspaceRanResponse +from .recording_response_notification import RecordingResponseNotification +from .recorded_response_notification import RecordedResponseNotification +from .invalid_request_response import InvalidRequestResponse +from .finished_response import FinishedResponse +from ....core.pydantic_utilities import UniversalRootModel +import typing +import typing_extensions +import pydantic +from ....core.pydantic_utilities import update_forward_refs T_Result = typing.TypeVar("T_Result") @@ -27,7 +26,9 @@ class _Factory: def building_executor(self, value: BuildingExecutorResponse) -> CodeExecutionUpdate: if IS_PYDANTIC_V2: return CodeExecutionUpdate( - root=_CodeExecutionUpdate.BuildingExecutor(**value.dict(exclude_unset=True), type="buildingExecutor") + root=_CodeExecutionUpdate.BuildingExecutor( + **value.dict(exclude_unset=True), type="buildingExecutor" + ) ) else: return CodeExecutionUpdate( @@ -39,101 +40,141 @@ def building_executor(self, value: BuildingExecutorResponse) -> CodeExecutionUpd def running(self, value: RunningResponse) -> CodeExecutionUpdate: if IS_PYDANTIC_V2: return CodeExecutionUpdate( - root=_CodeExecutionUpdate.Running(**value.dict(exclude_unset=True), type="running") + root=_CodeExecutionUpdate.Running( + **value.dict(exclude_unset=True), type="running" + ) ) else: return CodeExecutionUpdate( - __root__=_CodeExecutionUpdate.Running(**value.dict(exclude_unset=True), type="running") + __root__=_CodeExecutionUpdate.Running( + **value.dict(exclude_unset=True), type="running" + ) ) def errored(self, value: ErroredResponse) -> CodeExecutionUpdate: if IS_PYDANTIC_V2: return CodeExecutionUpdate( - root=_CodeExecutionUpdate.Errored(**value.dict(exclude_unset=True), type="errored") + root=_CodeExecutionUpdate.Errored( + **value.dict(exclude_unset=True), type="errored" + ) ) else: return CodeExecutionUpdate( - __root__=_CodeExecutionUpdate.Errored(**value.dict(exclude_unset=True), type="errored") + __root__=_CodeExecutionUpdate.Errored( + **value.dict(exclude_unset=True), type="errored" + ) ) def stopped(self, value: StoppedResponse) -> CodeExecutionUpdate: if IS_PYDANTIC_V2: return CodeExecutionUpdate( - root=_CodeExecutionUpdate.Stopped(**value.dict(exclude_unset=True), type="stopped") + root=_CodeExecutionUpdate.Stopped( + **value.dict(exclude_unset=True), type="stopped" + ) ) else: return CodeExecutionUpdate( - __root__=_CodeExecutionUpdate.Stopped(**value.dict(exclude_unset=True), type="stopped") + __root__=_CodeExecutionUpdate.Stopped( + **value.dict(exclude_unset=True), type="stopped" + ) ) def graded(self, value: GradedResponse) -> CodeExecutionUpdate: if IS_PYDANTIC_V2: return CodeExecutionUpdate( - root=_CodeExecutionUpdate.Graded(**value.dict(exclude_unset=True), type="graded") + root=_CodeExecutionUpdate.Graded( + **value.dict(exclude_unset=True), type="graded" + ) ) else: return CodeExecutionUpdate( - __root__=_CodeExecutionUpdate.Graded(**value.dict(exclude_unset=True), type="graded") + __root__=_CodeExecutionUpdate.Graded( + **value.dict(exclude_unset=True), type="graded" + ) ) def graded_v_2(self, value: GradedResponseV2) -> CodeExecutionUpdate: if IS_PYDANTIC_V2: return CodeExecutionUpdate( - root=_CodeExecutionUpdate.GradedV2(**value.dict(exclude_unset=True), type="gradedV2") + root=_CodeExecutionUpdate.GradedV2( + **value.dict(exclude_unset=True), type="gradedV2" + ) ) else: return CodeExecutionUpdate( - __root__=_CodeExecutionUpdate.GradedV2(**value.dict(exclude_unset=True), type="gradedV2") + __root__=_CodeExecutionUpdate.GradedV2( + **value.dict(exclude_unset=True), type="gradedV2" + ) ) def workspace_ran(self, value: WorkspaceRanResponse) -> CodeExecutionUpdate: if IS_PYDANTIC_V2: return CodeExecutionUpdate( - root=_CodeExecutionUpdate.WorkspaceRan(**value.dict(exclude_unset=True), type="workspaceRan") + root=_CodeExecutionUpdate.WorkspaceRan( + **value.dict(exclude_unset=True), type="workspaceRan" + ) ) else: return CodeExecutionUpdate( - __root__=_CodeExecutionUpdate.WorkspaceRan(**value.dict(exclude_unset=True), type="workspaceRan") + __root__=_CodeExecutionUpdate.WorkspaceRan( + **value.dict(exclude_unset=True), type="workspaceRan" + ) ) def recording(self, value: RecordingResponseNotification) -> CodeExecutionUpdate: if IS_PYDANTIC_V2: return CodeExecutionUpdate( - root=_CodeExecutionUpdate.Recording(**value.dict(exclude_unset=True), type="recording") + root=_CodeExecutionUpdate.Recording( + **value.dict(exclude_unset=True), type="recording" + ) ) else: return CodeExecutionUpdate( - __root__=_CodeExecutionUpdate.Recording(**value.dict(exclude_unset=True), type="recording") + __root__=_CodeExecutionUpdate.Recording( + **value.dict(exclude_unset=True), type="recording" + ) ) def recorded(self, value: RecordedResponseNotification) -> CodeExecutionUpdate: if IS_PYDANTIC_V2: return CodeExecutionUpdate( - root=_CodeExecutionUpdate.Recorded(**value.dict(exclude_unset=True), type="recorded") + root=_CodeExecutionUpdate.Recorded( + **value.dict(exclude_unset=True), type="recorded" + ) ) else: return CodeExecutionUpdate( - __root__=_CodeExecutionUpdate.Recorded(**value.dict(exclude_unset=True), type="recorded") + __root__=_CodeExecutionUpdate.Recorded( + **value.dict(exclude_unset=True), type="recorded" + ) ) def invalid_request(self, value: InvalidRequestResponse) -> CodeExecutionUpdate: if IS_PYDANTIC_V2: return CodeExecutionUpdate( - root=_CodeExecutionUpdate.InvalidRequest(**value.dict(exclude_unset=True), type="invalidRequest") + root=_CodeExecutionUpdate.InvalidRequest( + **value.dict(exclude_unset=True), type="invalidRequest" + ) ) else: return CodeExecutionUpdate( - __root__=_CodeExecutionUpdate.InvalidRequest(**value.dict(exclude_unset=True), type="invalidRequest") + __root__=_CodeExecutionUpdate.InvalidRequest( + **value.dict(exclude_unset=True), type="invalidRequest" + ) ) def finished(self, value: FinishedResponse) -> CodeExecutionUpdate: if IS_PYDANTIC_V2: return CodeExecutionUpdate( - root=_CodeExecutionUpdate.Finished(**value.dict(exclude_unset=True), type="finished") + root=_CodeExecutionUpdate.Finished( + **value.dict(exclude_unset=True), type="finished" + ) ) else: return CodeExecutionUpdate( - __root__=_CodeExecutionUpdate.Finished(**value.dict(exclude_unset=True), type="finished") + __root__=_CodeExecutionUpdate.Finished( + **value.dict(exclude_unset=True), type="finished" + ) ) @@ -174,7 +215,6 @@ def get_as_union( _CodeExecutionUpdate.Finished, ]: return self.root - else: __root__: typing_extensions.Annotated[ typing.Union[ @@ -227,28 +267,70 @@ def visit( unioned_value = self.get_as_union() if unioned_value.type == "buildingExecutor": return building_executor( - BuildingExecutorResponse(**unioned_value.dict(exclude_unset=True, exclude={"type"})) + BuildingExecutorResponse( + **unioned_value.dict(exclude_unset=True, exclude={"type"}) + ) ) if unioned_value.type == "running": - return running(RunningResponse(**unioned_value.dict(exclude_unset=True, exclude={"type"}))) + return running( + RunningResponse( + **unioned_value.dict(exclude_unset=True, exclude={"type"}) + ) + ) if unioned_value.type == "errored": - return errored(ErroredResponse(**unioned_value.dict(exclude_unset=True, exclude={"type"}))) + return errored( + ErroredResponse( + **unioned_value.dict(exclude_unset=True, exclude={"type"}) + ) + ) if unioned_value.type == "stopped": - return stopped(StoppedResponse(**unioned_value.dict(exclude_unset=True, exclude={"type"}))) + return stopped( + StoppedResponse( + **unioned_value.dict(exclude_unset=True, exclude={"type"}) + ) + ) if unioned_value.type == "graded": - return graded(GradedResponse(**unioned_value.dict(exclude_unset=True, exclude={"type"}))) + return graded( + GradedResponse( + **unioned_value.dict(exclude_unset=True, exclude={"type"}) + ) + ) if unioned_value.type == "gradedV2": - return graded_v_2(GradedResponseV2(**unioned_value.dict(exclude_unset=True, exclude={"type"}))) + return graded_v_2( + GradedResponseV2( + **unioned_value.dict(exclude_unset=True, exclude={"type"}) + ) + ) if unioned_value.type == "workspaceRan": - return workspace_ran(WorkspaceRanResponse(**unioned_value.dict(exclude_unset=True, exclude={"type"}))) + return workspace_ran( + WorkspaceRanResponse( + **unioned_value.dict(exclude_unset=True, exclude={"type"}) + ) + ) if unioned_value.type == "recording": - return recording(RecordingResponseNotification(**unioned_value.dict(exclude_unset=True, exclude={"type"}))) + return recording( + RecordingResponseNotification( + **unioned_value.dict(exclude_unset=True, exclude={"type"}) + ) + ) if unioned_value.type == "recorded": - return recorded(RecordedResponseNotification(**unioned_value.dict(exclude_unset=True, exclude={"type"}))) + return recorded( + RecordedResponseNotification( + **unioned_value.dict(exclude_unset=True, exclude={"type"}) + ) + ) if unioned_value.type == "invalidRequest": - return invalid_request(InvalidRequestResponse(**unioned_value.dict(exclude_unset=True, exclude={"type"}))) + return invalid_request( + InvalidRequestResponse( + **unioned_value.dict(exclude_unset=True, exclude={"type"}) + ) + ) if unioned_value.type == "finished": - return finished(FinishedResponse(**unioned_value.dict(exclude_unset=True, exclude={"type"}))) + return finished( + FinishedResponse( + **unioned_value.dict(exclude_unset=True, exclude={"type"}) + ) + ) class _CodeExecutionUpdate: diff --git a/seed/fastapi/trace/resources/submission/types/compile_error.py b/seed/fastapi/trace/resources/submission/types/compile_error.py index 027524b48fb..a2fc7e76383 100644 --- a/seed/fastapi/trace/resources/submission/types/compile_error.py +++ b/seed/fastapi/trace/resources/submission/types/compile_error.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class CompileError(UniversalBaseModel): message: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/submission/types/custom_test_cases_unsupported.py b/seed/fastapi/trace/resources/submission/types/custom_test_cases_unsupported.py index 12bc8276ea3..05da470169e 100644 --- a/seed/fastapi/trace/resources/submission/types/custom_test_cases_unsupported.py +++ b/seed/fastapi/trace/resources/submission/types/custom_test_cases_unsupported.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import UniversalBaseModel from ...commons.types.problem_id import ProblemId +import pydantic from .submission_id import SubmissionId +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class CustomTestCasesUnsupported(UniversalBaseModel): @@ -14,7 +13,9 @@ class CustomTestCasesUnsupported(UniversalBaseModel): submission_id: SubmissionId = pydantic.Field(alias="submissionId") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/submission/types/error_info.py b/seed/fastapi/trace/resources/submission/types/error_info.py index e3940311a6e..62d0b0ec79e 100644 --- a/seed/fastapi/trace/resources/submission/types/error_info.py +++ b/seed/fastapi/trace/resources/submission/types/error_info.py @@ -1,38 +1,73 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from .compile_error import ( + CompileError as resources_submission_types_compile_error_CompileError, +) +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +from .runtime_error import ( + RuntimeError as resources_submission_types_runtime_error_RuntimeError, +) +from .internal_error import ( + InternalError as resources_submission_types_internal_error_InternalError, +) +from ....core.pydantic_utilities import UniversalRootModel import typing - -import pydantic import typing_extensions - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalRootModel, update_forward_refs -from .compile_error import CompileError as resources_submission_types_compile_error_CompileError -from .internal_error import InternalError as resources_submission_types_internal_error_InternalError -from .runtime_error import RuntimeError as resources_submission_types_runtime_error_RuntimeError +import pydantic +from ....core.pydantic_utilities import update_forward_refs T_Result = typing.TypeVar("T_Result") class _Factory: - def compile_error(self, value: resources_submission_types_compile_error_CompileError) -> ErrorInfo: + def compile_error( + self, value: resources_submission_types_compile_error_CompileError + ) -> ErrorInfo: if IS_PYDANTIC_V2: - return ErrorInfo(root=_ErrorInfo.CompileError(**value.dict(exclude_unset=True), type="compileError")) + return ErrorInfo( + root=_ErrorInfo.CompileError( + **value.dict(exclude_unset=True), type="compileError" + ) + ) else: - return ErrorInfo(__root__=_ErrorInfo.CompileError(**value.dict(exclude_unset=True), type="compileError")) + return ErrorInfo( + __root__=_ErrorInfo.CompileError( + **value.dict(exclude_unset=True), type="compileError" + ) + ) - def runtime_error(self, value: resources_submission_types_runtime_error_RuntimeError) -> ErrorInfo: + def runtime_error( + self, value: resources_submission_types_runtime_error_RuntimeError + ) -> ErrorInfo: if IS_PYDANTIC_V2: - return ErrorInfo(root=_ErrorInfo.RuntimeError(**value.dict(exclude_unset=True), type="runtimeError")) + return ErrorInfo( + root=_ErrorInfo.RuntimeError( + **value.dict(exclude_unset=True), type="runtimeError" + ) + ) else: - return ErrorInfo(__root__=_ErrorInfo.RuntimeError(**value.dict(exclude_unset=True), type="runtimeError")) + return ErrorInfo( + __root__=_ErrorInfo.RuntimeError( + **value.dict(exclude_unset=True), type="runtimeError" + ) + ) - def internal_error(self, value: resources_submission_types_internal_error_InternalError) -> ErrorInfo: + def internal_error( + self, value: resources_submission_types_internal_error_InternalError + ) -> ErrorInfo: if IS_PYDANTIC_V2: - return ErrorInfo(root=_ErrorInfo.InternalError(**value.dict(exclude_unset=True), type="internalError")) + return ErrorInfo( + root=_ErrorInfo.InternalError( + **value.dict(exclude_unset=True), type="internalError" + ) + ) else: - return ErrorInfo(__root__=_ErrorInfo.InternalError(**value.dict(exclude_unset=True), type="internalError")) + return ErrorInfo( + __root__=_ErrorInfo.InternalError( + **value.dict(exclude_unset=True), type="internalError" + ) + ) class ErrorInfo(UniversalRootModel): @@ -40,31 +75,48 @@ class ErrorInfo(UniversalRootModel): if IS_PYDANTIC_V2: root: typing_extensions.Annotated[ - typing.Union[_ErrorInfo.CompileError, _ErrorInfo.RuntimeError, _ErrorInfo.InternalError], + typing.Union[ + _ErrorInfo.CompileError, + _ErrorInfo.RuntimeError, + _ErrorInfo.InternalError, + ], pydantic.Field(discriminator="type"), ] def get_as_union( self, - ) -> typing.Union[_ErrorInfo.CompileError, _ErrorInfo.RuntimeError, _ErrorInfo.InternalError]: + ) -> typing.Union[ + _ErrorInfo.CompileError, _ErrorInfo.RuntimeError, _ErrorInfo.InternalError + ]: return self.root - else: __root__: typing_extensions.Annotated[ - typing.Union[_ErrorInfo.CompileError, _ErrorInfo.RuntimeError, _ErrorInfo.InternalError], + typing.Union[ + _ErrorInfo.CompileError, + _ErrorInfo.RuntimeError, + _ErrorInfo.InternalError, + ], pydantic.Field(discriminator="type"), ] def get_as_union( self, - ) -> typing.Union[_ErrorInfo.CompileError, _ErrorInfo.RuntimeError, _ErrorInfo.InternalError]: + ) -> typing.Union[ + _ErrorInfo.CompileError, _ErrorInfo.RuntimeError, _ErrorInfo.InternalError + ]: return self.__root__ def visit( self, - compile_error: typing.Callable[[resources_submission_types_compile_error_CompileError], T_Result], - runtime_error: typing.Callable[[resources_submission_types_runtime_error_RuntimeError], T_Result], - internal_error: typing.Callable[[resources_submission_types_internal_error_InternalError], T_Result], + compile_error: typing.Callable[ + [resources_submission_types_compile_error_CompileError], T_Result + ], + runtime_error: typing.Callable[ + [resources_submission_types_runtime_error_RuntimeError], T_Result + ], + internal_error: typing.Callable[ + [resources_submission_types_internal_error_InternalError], T_Result + ], ) -> T_Result: unioned_value = self.get_as_union() if unioned_value.type == "compileError": diff --git a/seed/fastapi/trace/resources/submission/types/errored_response.py b/seed/fastapi/trace/resources/submission/types/errored_response.py index 45e7bb1d2ec..37cd4b1cdb7 100644 --- a/seed/fastapi/trace/resources/submission/types/errored_response.py +++ b/seed/fastapi/trace/resources/submission/types/errored_response.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ....core.pydantic_utilities import UniversalBaseModel +from .submission_id import SubmissionId import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .error_info import ErrorInfo -from .submission_id import SubmissionId +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class ErroredResponse(UniversalBaseModel): @@ -14,7 +13,9 @@ class ErroredResponse(UniversalBaseModel): error_info: ErrorInfo = pydantic.Field(alias="errorInfo") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/submission/types/exception_info.py b/seed/fastapi/trace/resources/submission/types/exception_info.py index b14f0dae906..46bd0e19406 100644 --- a/seed/fastapi/trace/resources/submission/types/exception_info.py +++ b/seed/fastapi/trace/resources/submission/types/exception_info.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ....core.pydantic_utilities import UniversalBaseModel import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class ExceptionInfo(UniversalBaseModel): @@ -13,7 +12,9 @@ class ExceptionInfo(UniversalBaseModel): exception_stacktrace: str = pydantic.Field(alias="exceptionStacktrace") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/submission/types/exception_v_2.py b/seed/fastapi/trace/resources/submission/types/exception_v_2.py index 702bbf85296..b1e743bb460 100644 --- a/seed/fastapi/trace/resources/submission/types/exception_v_2.py +++ b/seed/fastapi/trace/resources/submission/types/exception_v_2.py @@ -1,14 +1,14 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from .exception_info import ExceptionInfo +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +from ....core.pydantic_utilities import UniversalRootModel import typing - -import pydantic import typing_extensions - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel, UniversalRootModel, update_forward_refs -from .exception_info import ExceptionInfo +import pydantic +from ....core.pydantic_utilities import UniversalBaseModel +from ....core.pydantic_utilities import update_forward_refs T_Result = typing.TypeVar("T_Result") @@ -16,9 +16,17 @@ class _Factory: def generic(self, value: ExceptionInfo) -> ExceptionV2: if IS_PYDANTIC_V2: - return ExceptionV2(root=_ExceptionV2.Generic(**value.dict(exclude_unset=True), type="generic")) + return ExceptionV2( + root=_ExceptionV2.Generic( + **value.dict(exclude_unset=True), type="generic" + ) + ) else: - return ExceptionV2(__root__=_ExceptionV2.Generic(**value.dict(exclude_unset=True), type="generic")) + return ExceptionV2( + __root__=_ExceptionV2.Generic( + **value.dict(exclude_unset=True), type="generic" + ) + ) def timeout(self) -> ExceptionV2: if IS_PYDANTIC_V2: @@ -32,26 +40,37 @@ class ExceptionV2(UniversalRootModel): if IS_PYDANTIC_V2: root: typing_extensions.Annotated[ - typing.Union[_ExceptionV2.Generic, _ExceptionV2.Timeout], pydantic.Field(discriminator="type") + typing.Union[_ExceptionV2.Generic, _ExceptionV2.Timeout], + pydantic.Field(discriminator="type"), ] - def get_as_union(self) -> typing.Union[_ExceptionV2.Generic, _ExceptionV2.Timeout]: + def get_as_union( + self, + ) -> typing.Union[_ExceptionV2.Generic, _ExceptionV2.Timeout]: return self.root - else: __root__: typing_extensions.Annotated[ - typing.Union[_ExceptionV2.Generic, _ExceptionV2.Timeout], pydantic.Field(discriminator="type") + typing.Union[_ExceptionV2.Generic, _ExceptionV2.Timeout], + pydantic.Field(discriminator="type"), ] - def get_as_union(self) -> typing.Union[_ExceptionV2.Generic, _ExceptionV2.Timeout]: + def get_as_union( + self, + ) -> typing.Union[_ExceptionV2.Generic, _ExceptionV2.Timeout]: return self.__root__ def visit( - self, generic: typing.Callable[[ExceptionInfo], T_Result], timeout: typing.Callable[[], T_Result] + self, + generic: typing.Callable[[ExceptionInfo], T_Result], + timeout: typing.Callable[[], T_Result], ) -> T_Result: unioned_value = self.get_as_union() if unioned_value.type == "generic": - return generic(ExceptionInfo(**unioned_value.dict(exclude_unset=True, exclude={"type"}))) + return generic( + ExceptionInfo( + **unioned_value.dict(exclude_unset=True, exclude={"type"}) + ) + ) if unioned_value.type == "timeout": return timeout() diff --git a/seed/fastapi/trace/resources/submission/types/execution_session_response.py b/seed/fastapi/trace/resources/submission/types/execution_session_response.py index 74cb2a8961b..09c865bd8a2 100644 --- a/seed/fastapi/trace/resources/submission/types/execution_session_response.py +++ b/seed/fastapi/trace/resources/submission/types/execution_session_response.py @@ -1,22 +1,25 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ....core.pydantic_utilities import UniversalBaseModel import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +import typing from ...commons.types.language import Language from .execution_session_status import ExecutionSessionStatus +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class ExecutionSessionResponse(UniversalBaseModel): session_id: str = pydantic.Field(alias="sessionId") - execution_session_url: typing.Optional[str] = pydantic.Field(alias="executionSessionUrl", default=None) + execution_session_url: typing.Optional[str] = pydantic.Field( + alias="executionSessionUrl", default=None + ) language: Language status: ExecutionSessionStatus if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/submission/types/execution_session_state.py b/seed/fastapi/trace/resources/submission/types/execution_session_state.py index bd7577d7a07..78a44ee2dd8 100644 --- a/seed/fastapi/trace/resources/submission/types/execution_session_state.py +++ b/seed/fastapi/trace/resources/submission/types/execution_session_state.py @@ -1,16 +1,17 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from ...commons.types.language import Language from .execution_session_status import ExecutionSessionStatus +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class ExecutionSessionState(UniversalBaseModel): - last_time_contacted: typing.Optional[str] = pydantic.Field(alias="lastTimeContacted", default=None) + last_time_contacted: typing.Optional[str] = pydantic.Field( + alias="lastTimeContacted", default=None + ) session_id: str = pydantic.Field(alias="sessionId") """ The auto-generated session id. Formatted as a uuid. @@ -22,7 +23,9 @@ class ExecutionSessionState(UniversalBaseModel): status: ExecutionSessionStatus if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/submission/types/existing_submission_executing.py b/seed/fastapi/trace/resources/submission/types/existing_submission_executing.py index 3ecf739e751..246331e2997 100644 --- a/seed/fastapi/trace/resources/submission/types/existing_submission_executing.py +++ b/seed/fastapi/trace/resources/submission/types/existing_submission_executing.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import UniversalBaseModel from .submission_id import SubmissionId +import pydantic +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class ExistingSubmissionExecuting(UniversalBaseModel): submission_id: SubmissionId = pydantic.Field(alias="submissionId") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/submission/types/expression_location.py b/seed/fastapi/trace/resources/submission/types/expression_location.py index 921c7a774a0..bdf642d1e0c 100644 --- a/seed/fastapi/trace/resources/submission/types/expression_location.py +++ b/seed/fastapi/trace/resources/submission/types/expression_location.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class ExpressionLocation(UniversalBaseModel): start: int offset: int if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/submission/types/finished_response.py b/seed/fastapi/trace/resources/submission/types/finished_response.py index fcb26fa5300..b19f51deef9 100644 --- a/seed/fastapi/trace/resources/submission/types/finished_response.py +++ b/seed/fastapi/trace/resources/submission/types/finished_response.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import UniversalBaseModel from .submission_id import SubmissionId +import pydantic +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class FinishedResponse(UniversalBaseModel): submission_id: SubmissionId = pydantic.Field(alias="submissionId") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/submission/types/get_execution_session_state_response.py b/seed/fastapi/trace/resources/submission/types/get_execution_session_state_response.py index 23ceb955707..fe66643394c 100644 --- a/seed/fastapi/trace/resources/submission/types/get_execution_session_state_response.py +++ b/seed/fastapi/trace/resources/submission/types/get_execution_session_state_response.py @@ -1,20 +1,23 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .execution_session_state import ExecutionSessionState +import pydantic +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class GetExecutionSessionStateResponse(UniversalBaseModel): states: typing.Dict[str, ExecutionSessionState] - num_warming_instances: typing.Optional[int] = pydantic.Field(alias="numWarmingInstances", default=None) + num_warming_instances: typing.Optional[int] = pydantic.Field( + alias="numWarmingInstances", default=None + ) warming_session_ids: typing.List[str] = pydantic.Field(alias="warmingSessionIds") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/submission/types/get_submission_state_response.py b/seed/fastapi/trace/resources/submission/types/get_submission_state_response.py index 29151ca83cc..3b03587bbfb 100644 --- a/seed/fastapi/trace/resources/submission/types/get_submission_state_response.py +++ b/seed/fastapi/trace/resources/submission/types/get_submission_state_response.py @@ -1,23 +1,28 @@ # This file was auto-generated by Fern from our API Definition. -import datetime as dt +from ....core.pydantic_utilities import UniversalBaseModel import typing - +import datetime as dt import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from ...commons.types.language import Language from .submission_type_state import SubmissionTypeState +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class GetSubmissionStateResponse(UniversalBaseModel): - time_submitted: typing.Optional[dt.datetime] = pydantic.Field(alias="timeSubmitted", default=None) + time_submitted: typing.Optional[dt.datetime] = pydantic.Field( + alias="timeSubmitted", default=None + ) submission: str language: Language - submission_type_state: SubmissionTypeState = pydantic.Field(alias="submissionTypeState") + submission_type_state: SubmissionTypeState = pydantic.Field( + alias="submissionTypeState" + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/submission/types/get_trace_responses_page_request.py b/seed/fastapi/trace/resources/submission/types/get_trace_responses_page_request.py index 9bc7e94a623..744c5cb9451 100644 --- a/seed/fastapi/trace/resources/submission/types/get_trace_responses_page_request.py +++ b/seed/fastapi/trace/resources/submission/types/get_trace_responses_page_request.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class GetTraceResponsesPageRequest(UniversalBaseModel): offset: typing.Optional[int] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/submission/types/graded_response.py b/seed/fastapi/trace/resources/submission/types/graded_response.py index 3bcdec9d8ad..2632b80b2d0 100644 --- a/seed/fastapi/trace/resources/submission/types/graded_response.py +++ b/seed/fastapi/trace/resources/submission/types/graded_response.py @@ -1,20 +1,23 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import UniversalBaseModel from .submission_id import SubmissionId +import pydantic +import typing from .test_case_result_with_stdout import TestCaseResultWithStdout +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class GradedResponse(UniversalBaseModel): submission_id: SubmissionId = pydantic.Field(alias="submissionId") - test_cases: typing.Dict[str, TestCaseResultWithStdout] = pydantic.Field(alias="testCases") + test_cases: typing.Dict[str, TestCaseResultWithStdout] = pydantic.Field( + alias="testCases" + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/submission/types/graded_response_v_2.py b/seed/fastapi/trace/resources/submission/types/graded_response_v_2.py index 8e31994bc52..ad62219c41c 100644 --- a/seed/fastapi/trace/resources/submission/types/graded_response_v_2.py +++ b/seed/fastapi/trace/resources/submission/types/graded_response_v_2.py @@ -1,21 +1,24 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ....core.pydantic_utilities import UniversalBaseModel +from .submission_id import SubmissionId import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +import typing from ...v_2.resources.problem.types.test_case_id import TestCaseId -from .submission_id import SubmissionId from .test_case_grade import TestCaseGrade +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class GradedResponseV2(UniversalBaseModel): submission_id: SubmissionId = pydantic.Field(alias="submissionId") - test_cases: typing.Dict[TestCaseId, TestCaseGrade] = pydantic.Field(alias="testCases") + test_cases: typing.Dict[TestCaseId, TestCaseGrade] = pydantic.Field( + alias="testCases" + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/submission/types/graded_test_case_update.py b/seed/fastapi/trace/resources/submission/types/graded_test_case_update.py index 903761986a4..1a9b4b93ca4 100644 --- a/seed/fastapi/trace/resources/submission/types/graded_test_case_update.py +++ b/seed/fastapi/trace/resources/submission/types/graded_test_case_update.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import UniversalBaseModel from ...v_2.resources.problem.types.test_case_id import TestCaseId +import pydantic from .test_case_grade import TestCaseGrade +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class GradedTestCaseUpdate(UniversalBaseModel): @@ -14,7 +13,9 @@ class GradedTestCaseUpdate(UniversalBaseModel): grade: TestCaseGrade if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/submission/types/initialize_problem_request.py b/seed/fastapi/trace/resources/submission/types/initialize_problem_request.py index e41d9a3eb87..bd0537b37e6 100644 --- a/seed/fastapi/trace/resources/submission/types/initialize_problem_request.py +++ b/seed/fastapi/trace/resources/submission/types/initialize_problem_request.py @@ -1,19 +1,22 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import UniversalBaseModel from ...commons.types.problem_id import ProblemId +import pydantic +import typing +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class InitializeProblemRequest(UniversalBaseModel): problem_id: ProblemId = pydantic.Field(alias="problemId") - problem_version: typing.Optional[int] = pydantic.Field(alias="problemVersion", default=None) + problem_version: typing.Optional[int] = pydantic.Field( + alias="problemVersion", default=None + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/submission/types/internal_error.py b/seed/fastapi/trace/resources/submission/types/internal_error.py index 18cd6ac67fc..c08272abcc8 100644 --- a/seed/fastapi/trace/resources/submission/types/internal_error.py +++ b/seed/fastapi/trace/resources/submission/types/internal_error.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import UniversalBaseModel from .exception_info import ExceptionInfo +import pydantic +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class InternalError(UniversalBaseModel): exception_info: ExceptionInfo = pydantic.Field(alias="exceptionInfo") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/submission/types/invalid_request_cause.py b/seed/fastapi/trace/resources/submission/types/invalid_request_cause.py index bf2fbb5ad2a..964d2eb5d98 100644 --- a/seed/fastapi/trace/resources/submission/types/invalid_request_cause.py +++ b/seed/fastapi/trace/resources/submission/types/invalid_request_cause.py @@ -1,27 +1,27 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - -import typing - -import pydantic -import typing_extensions - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalRootModel, update_forward_refs -from .custom_test_cases_unsupported import ( - CustomTestCasesUnsupported as resources_submission_types_custom_test_cases_unsupported_CustomTestCasesUnsupported, -) from .submission_id_not_found import ( SubmissionIdNotFound as resources_submission_types_submission_id_not_found_SubmissionIdNotFound, ) +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +from .custom_test_cases_unsupported import ( + CustomTestCasesUnsupported as resources_submission_types_custom_test_cases_unsupported_CustomTestCasesUnsupported, +) from .unexpected_language_error import UnexpectedLanguageError +from ....core.pydantic_utilities import UniversalRootModel +import typing +import typing_extensions +import pydantic +from ....core.pydantic_utilities import update_forward_refs T_Result = typing.TypeVar("T_Result") class _Factory: def submission_id_not_found( - self, value: resources_submission_types_submission_id_not_found_SubmissionIdNotFound + self, + value: resources_submission_types_submission_id_not_found_SubmissionIdNotFound, ) -> InvalidRequestCause: if IS_PYDANTIC_V2: return InvalidRequestCause( @@ -37,7 +37,8 @@ def submission_id_not_found( ) def custom_test_cases_unsupported( - self, value: resources_submission_types_custom_test_cases_unsupported_CustomTestCasesUnsupported + self, + value: resources_submission_types_custom_test_cases_unsupported_CustomTestCasesUnsupported, ) -> InvalidRequestCause: if IS_PYDANTIC_V2: return InvalidRequestCause( @@ -52,7 +53,9 @@ def custom_test_cases_unsupported( ) ) - def unexpected_language(self, value: UnexpectedLanguageError) -> InvalidRequestCause: + def unexpected_language( + self, value: UnexpectedLanguageError + ) -> InvalidRequestCause: if IS_PYDANTIC_V2: return InvalidRequestCause( root=_InvalidRequestCause.UnexpectedLanguage( @@ -88,7 +91,6 @@ def get_as_union( _InvalidRequestCause.UnexpectedLanguage, ]: return self.root - else: __root__: typing_extensions.Annotated[ typing.Union[ @@ -111,10 +113,14 @@ def get_as_union( def visit( self, submission_id_not_found: typing.Callable[ - [resources_submission_types_submission_id_not_found_SubmissionIdNotFound], T_Result + [resources_submission_types_submission_id_not_found_SubmissionIdNotFound], + T_Result, ], custom_test_cases_unsupported: typing.Callable[ - [resources_submission_types_custom_test_cases_unsupported_CustomTestCasesUnsupported], T_Result + [ + resources_submission_types_custom_test_cases_unsupported_CustomTestCasesUnsupported + ], + T_Result, ], unexpected_language: typing.Callable[[UnexpectedLanguageError], T_Result], ) -> T_Result: @@ -133,18 +139,24 @@ def visit( ) if unioned_value.type == "unexpectedLanguage": return unexpected_language( - UnexpectedLanguageError(**unioned_value.dict(exclude_unset=True, exclude={"type"})) + UnexpectedLanguageError( + **unioned_value.dict(exclude_unset=True, exclude={"type"}) + ) ) class _InvalidRequestCause: - class SubmissionIdNotFound(resources_submission_types_submission_id_not_found_SubmissionIdNotFound): + class SubmissionIdNotFound( + resources_submission_types_submission_id_not_found_SubmissionIdNotFound + ): type: typing.Literal["submissionIdNotFound"] = "submissionIdNotFound" class CustomTestCasesUnsupported( resources_submission_types_custom_test_cases_unsupported_CustomTestCasesUnsupported ): - type: typing.Literal["customTestCasesUnsupported"] = "customTestCasesUnsupported" + type: typing.Literal["customTestCasesUnsupported"] = ( + "customTestCasesUnsupported" + ) class UnexpectedLanguage(UnexpectedLanguageError): type: typing.Literal["unexpectedLanguage"] = "unexpectedLanguage" diff --git a/seed/fastapi/trace/resources/submission/types/invalid_request_response.py b/seed/fastapi/trace/resources/submission/types/invalid_request_response.py index 33eddee57c3..83cb85e419c 100644 --- a/seed/fastapi/trace/resources/submission/types/invalid_request_response.py +++ b/seed/fastapi/trace/resources/submission/types/invalid_request_response.py @@ -1,20 +1,21 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel +from .submission_request import SubmissionRequest +from .invalid_request_cause import InvalidRequestCause +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .invalid_request_cause import InvalidRequestCause -from .submission_request import SubmissionRequest - class InvalidRequestResponse(UniversalBaseModel): request: SubmissionRequest cause: InvalidRequestCause if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/submission/types/lightweight_stackframe_information.py b/seed/fastapi/trace/resources/submission/types/lightweight_stackframe_information.py index e05a7b63e50..19bdb3c6227 100644 --- a/seed/fastapi/trace/resources/submission/types/lightweight_stackframe_information.py +++ b/seed/fastapi/trace/resources/submission/types/lightweight_stackframe_information.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ....core.pydantic_utilities import UniversalBaseModel import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class LightweightStackframeInformation(UniversalBaseModel): @@ -12,7 +11,9 @@ class LightweightStackframeInformation(UniversalBaseModel): top_stack_frame_method_name: str = pydantic.Field(alias="topStackFrameMethodName") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/submission/types/recorded_response_notification.py b/seed/fastapi/trace/resources/submission/types/recorded_response_notification.py index edf8f26612d..0ee9cc21d10 100644 --- a/seed/fastapi/trace/resources/submission/types/recorded_response_notification.py +++ b/seed/fastapi/trace/resources/submission/types/recorded_response_notification.py @@ -1,20 +1,23 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import UniversalBaseModel from .submission_id import SubmissionId +import pydantic +import typing +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class RecordedResponseNotification(UniversalBaseModel): submission_id: SubmissionId = pydantic.Field(alias="submissionId") trace_responses_size: int = pydantic.Field(alias="traceResponsesSize") - test_case_id: typing.Optional[str] = pydantic.Field(alias="testCaseId", default=None) + test_case_id: typing.Optional[str] = pydantic.Field( + alias="testCaseId", default=None + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/submission/types/recorded_test_case_update.py b/seed/fastapi/trace/resources/submission/types/recorded_test_case_update.py index e6ca92a605b..0959cdd8c80 100644 --- a/seed/fastapi/trace/resources/submission/types/recorded_test_case_update.py +++ b/seed/fastapi/trace/resources/submission/types/recorded_test_case_update.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import UniversalBaseModel from ...v_2.resources.problem.types.test_case_id import TestCaseId +import pydantic +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class RecordedTestCaseUpdate(UniversalBaseModel): @@ -13,7 +12,9 @@ class RecordedTestCaseUpdate(UniversalBaseModel): trace_responses_size: int = pydantic.Field(alias="traceResponsesSize") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/submission/types/recording_response_notification.py b/seed/fastapi/trace/resources/submission/types/recording_response_notification.py index 76af4b208a3..878f1859277 100644 --- a/seed/fastapi/trace/resources/submission/types/recording_response_notification.py +++ b/seed/fastapi/trace/resources/submission/types/recording_response_notification.py @@ -1,24 +1,31 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ....core.pydantic_utilities import UniversalBaseModel +from .submission_id import SubmissionId import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +import typing from .lightweight_stackframe_information import LightweightStackframeInformation -from .submission_id import SubmissionId from .traced_file import TracedFile +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class RecordingResponseNotification(UniversalBaseModel): submission_id: SubmissionId = pydantic.Field(alias="submissionId") - test_case_id: typing.Optional[str] = pydantic.Field(alias="testCaseId", default=None) + test_case_id: typing.Optional[str] = pydantic.Field( + alias="testCaseId", default=None + ) line_number: int = pydantic.Field(alias="lineNumber") - lightweight_stack_info: LightweightStackframeInformation = pydantic.Field(alias="lightweightStackInfo") - traced_file: typing.Optional[TracedFile] = pydantic.Field(alias="tracedFile", default=None) + lightweight_stack_info: LightweightStackframeInformation = pydantic.Field( + alias="lightweightStackInfo" + ) + traced_file: typing.Optional[TracedFile] = pydantic.Field( + alias="tracedFile", default=None + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/submission/types/running_response.py b/seed/fastapi/trace/resources/submission/types/running_response.py index 66b76c3253b..c4f446be659 100644 --- a/seed/fastapi/trace/resources/submission/types/running_response.py +++ b/seed/fastapi/trace/resources/submission/types/running_response.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ....core.pydantic_utilities import UniversalBaseModel +from .submission_id import SubmissionId import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .running_submission_state import RunningSubmissionState -from .submission_id import SubmissionId +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class RunningResponse(UniversalBaseModel): @@ -14,7 +13,9 @@ class RunningResponse(UniversalBaseModel): state: RunningSubmissionState if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/submission/types/runtime_error.py b/seed/fastapi/trace/resources/submission/types/runtime_error.py index eacf0c0e1e2..0e7df61bd60 100644 --- a/seed/fastapi/trace/resources/submission/types/runtime_error.py +++ b/seed/fastapi/trace/resources/submission/types/runtime_error.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class RuntimeError(UniversalBaseModel): message: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/submission/types/scope.py b/seed/fastapi/trace/resources/submission/types/scope.py index ce859fc9714..9fc43044aae 100644 --- a/seed/fastapi/trace/resources/submission/types/scope.py +++ b/seed/fastapi/trace/resources/submission/types/scope.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from ...commons.types.debug_variable_value import DebugVariableValue +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import pydantic class Scope(UniversalBaseModel): variables: typing.Dict[str, DebugVariableValue] if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/submission/types/stack_frame.py b/seed/fastapi/trace/resources/submission/types/stack_frame.py index 48fb4452089..84be11f9e24 100644 --- a/seed/fastapi/trace/resources/submission/types/stack_frame.py +++ b/seed/fastapi/trace/resources/submission/types/stack_frame.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ....core.pydantic_utilities import UniversalBaseModel import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +import typing from .scope import Scope +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class StackFrame(UniversalBaseModel): @@ -14,7 +13,9 @@ class StackFrame(UniversalBaseModel): scopes: typing.List[Scope] if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/submission/types/stack_information.py b/seed/fastapi/trace/resources/submission/types/stack_information.py index e6feba3bda1..30be1efcf50 100644 --- a/seed/fastapi/trace/resources/submission/types/stack_information.py +++ b/seed/fastapi/trace/resources/submission/types/stack_information.py @@ -1,19 +1,22 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ....core.pydantic_utilities import UniversalBaseModel import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +import typing from .stack_frame import StackFrame +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class StackInformation(UniversalBaseModel): num_stack_frames: int = pydantic.Field(alias="numStackFrames") - top_stack_frame: typing.Optional[StackFrame] = pydantic.Field(alias="topStackFrame", default=None) + top_stack_frame: typing.Optional[StackFrame] = pydantic.Field( + alias="topStackFrame", default=None + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/submission/types/stderr_response.py b/seed/fastapi/trace/resources/submission/types/stderr_response.py index 797258a7130..4e0777c4b58 100644 --- a/seed/fastapi/trace/resources/submission/types/stderr_response.py +++ b/seed/fastapi/trace/resources/submission/types/stderr_response.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import UniversalBaseModel from .submission_id import SubmissionId +import pydantic +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class StderrResponse(UniversalBaseModel): @@ -13,7 +12,9 @@ class StderrResponse(UniversalBaseModel): stderr: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/submission/types/stdout_response.py b/seed/fastapi/trace/resources/submission/types/stdout_response.py index 04f5a93d03d..1562bbc1de9 100644 --- a/seed/fastapi/trace/resources/submission/types/stdout_response.py +++ b/seed/fastapi/trace/resources/submission/types/stdout_response.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import UniversalBaseModel from .submission_id import SubmissionId +import pydantic +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class StdoutResponse(UniversalBaseModel): @@ -13,7 +12,9 @@ class StdoutResponse(UniversalBaseModel): stdout: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/submission/types/stop_request.py b/seed/fastapi/trace/resources/submission/types/stop_request.py index 316ea9e7c9f..ba69aef16fd 100644 --- a/seed/fastapi/trace/resources/submission/types/stop_request.py +++ b/seed/fastapi/trace/resources/submission/types/stop_request.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import UniversalBaseModel from .submission_id import SubmissionId +import pydantic +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class StopRequest(UniversalBaseModel): submission_id: SubmissionId = pydantic.Field(alias="submissionId") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/submission/types/stopped_response.py b/seed/fastapi/trace/resources/submission/types/stopped_response.py index 30a6511a331..5b63113e8b8 100644 --- a/seed/fastapi/trace/resources/submission/types/stopped_response.py +++ b/seed/fastapi/trace/resources/submission/types/stopped_response.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import UniversalBaseModel from .submission_id import SubmissionId +import pydantic +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class StoppedResponse(UniversalBaseModel): submission_id: SubmissionId = pydantic.Field(alias="submissionId") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/submission/types/submission_file_info.py b/seed/fastapi/trace/resources/submission/types/submission_file_info.py index f0a4886d9df..82555fcb60c 100644 --- a/seed/fastapi/trace/resources/submission/types/submission_file_info.py +++ b/seed/fastapi/trace/resources/submission/types/submission_file_info.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class SubmissionFileInfo(UniversalBaseModel): directory: str @@ -13,7 +12,9 @@ class SubmissionFileInfo(UniversalBaseModel): contents: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/submission/types/submission_id_not_found.py b/seed/fastapi/trace/resources/submission/types/submission_id_not_found.py index dfd914caaa2..faf88bac8a8 100644 --- a/seed/fastapi/trace/resources/submission/types/submission_id_not_found.py +++ b/seed/fastapi/trace/resources/submission/types/submission_id_not_found.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import UniversalBaseModel from .submission_id import SubmissionId +import pydantic +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class SubmissionIdNotFound(UniversalBaseModel): missing_submission_id: SubmissionId = pydantic.Field(alias="missingSubmissionId") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/submission/types/submission_request.py b/seed/fastapi/trace/resources/submission/types/submission_request.py index 14d1e0886fd..d7ac4332454 100644 --- a/seed/fastapi/trace/resources/submission/types/submission_request.py +++ b/seed/fastapi/trace/resources/submission/types/submission_request.py @@ -1,26 +1,27 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - -import typing - -import pydantic -import typing_extensions - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel, UniversalRootModel, update_forward_refs from .initialize_problem_request import ( InitializeProblemRequest as resources_submission_types_initialize_problem_request_InitializeProblemRequest, ) -from .stop_request import StopRequest +from ....core.pydantic_utilities import IS_PYDANTIC_V2 from .submit_request_v_2 import SubmitRequestV2 from .workspace_submit_request import WorkspaceSubmitRequest +from .stop_request import StopRequest +from ....core.pydantic_utilities import UniversalRootModel +import typing +import typing_extensions +import pydantic +from ....core.pydantic_utilities import UniversalBaseModel +from ....core.pydantic_utilities import update_forward_refs T_Result = typing.TypeVar("T_Result") class _Factory: def initialize_problem_request( - self, value: resources_submission_types_initialize_problem_request_InitializeProblemRequest + self, + value: resources_submission_types_initialize_problem_request_InitializeProblemRequest, ) -> SubmissionRequest: if IS_PYDANTIC_V2: return SubmissionRequest( @@ -38,38 +39,58 @@ def initialize_problem_request( def initialize_workspace_request(self) -> SubmissionRequest: if IS_PYDANTIC_V2: return SubmissionRequest( - root=_SubmissionRequest.InitializeWorkspaceRequest(type="initializeWorkspaceRequest") + root=_SubmissionRequest.InitializeWorkspaceRequest( + type="initializeWorkspaceRequest" + ) ) else: return SubmissionRequest( - __root__=_SubmissionRequest.InitializeWorkspaceRequest(type="initializeWorkspaceRequest") + __root__=_SubmissionRequest.InitializeWorkspaceRequest( + type="initializeWorkspaceRequest" + ) ) def submit_v_2(self, value: SubmitRequestV2) -> SubmissionRequest: if IS_PYDANTIC_V2: return SubmissionRequest( - root=_SubmissionRequest.SubmitV2(**value.dict(exclude_unset=True), type="submitV2") + root=_SubmissionRequest.SubmitV2( + **value.dict(exclude_unset=True), type="submitV2" + ) ) else: return SubmissionRequest( - __root__=_SubmissionRequest.SubmitV2(**value.dict(exclude_unset=True), type="submitV2") + __root__=_SubmissionRequest.SubmitV2( + **value.dict(exclude_unset=True), type="submitV2" + ) ) def workspace_submit(self, value: WorkspaceSubmitRequest) -> SubmissionRequest: if IS_PYDANTIC_V2: return SubmissionRequest( - root=_SubmissionRequest.WorkspaceSubmit(**value.dict(exclude_unset=True), type="workspaceSubmit") + root=_SubmissionRequest.WorkspaceSubmit( + **value.dict(exclude_unset=True), type="workspaceSubmit" + ) ) else: return SubmissionRequest( - __root__=_SubmissionRequest.WorkspaceSubmit(**value.dict(exclude_unset=True), type="workspaceSubmit") + __root__=_SubmissionRequest.WorkspaceSubmit( + **value.dict(exclude_unset=True), type="workspaceSubmit" + ) ) def stop(self, value: StopRequest) -> SubmissionRequest: if IS_PYDANTIC_V2: - return SubmissionRequest(root=_SubmissionRequest.Stop(**value.dict(exclude_unset=True), type="stop")) + return SubmissionRequest( + root=_SubmissionRequest.Stop( + **value.dict(exclude_unset=True), type="stop" + ) + ) else: - return SubmissionRequest(__root__=_SubmissionRequest.Stop(**value.dict(exclude_unset=True), type="stop")) + return SubmissionRequest( + __root__=_SubmissionRequest.Stop( + **value.dict(exclude_unset=True), type="stop" + ) + ) class SubmissionRequest(UniversalRootModel): @@ -97,7 +118,6 @@ def get_as_union( _SubmissionRequest.Stop, ]: return self.root - else: __root__: typing_extensions.Annotated[ typing.Union[ @@ -124,7 +144,10 @@ def get_as_union( def visit( self, initialize_problem_request: typing.Callable[ - [resources_submission_types_initialize_problem_request_InitializeProblemRequest], T_Result + [ + resources_submission_types_initialize_problem_request_InitializeProblemRequest + ], + T_Result, ], initialize_workspace_request: typing.Callable[[], T_Result], submit_v_2: typing.Callable[[SubmitRequestV2], T_Result], @@ -141,19 +164,33 @@ def visit( if unioned_value.type == "initializeWorkspaceRequest": return initialize_workspace_request() if unioned_value.type == "submitV2": - return submit_v_2(SubmitRequestV2(**unioned_value.dict(exclude_unset=True, exclude={"type"}))) + return submit_v_2( + SubmitRequestV2( + **unioned_value.dict(exclude_unset=True, exclude={"type"}) + ) + ) if unioned_value.type == "workspaceSubmit": - return workspace_submit(WorkspaceSubmitRequest(**unioned_value.dict(exclude_unset=True, exclude={"type"}))) + return workspace_submit( + WorkspaceSubmitRequest( + **unioned_value.dict(exclude_unset=True, exclude={"type"}) + ) + ) if unioned_value.type == "stop": - return stop(StopRequest(**unioned_value.dict(exclude_unset=True, exclude={"type"}))) + return stop( + StopRequest(**unioned_value.dict(exclude_unset=True, exclude={"type"})) + ) class _SubmissionRequest: - class InitializeProblemRequest(resources_submission_types_initialize_problem_request_InitializeProblemRequest): + class InitializeProblemRequest( + resources_submission_types_initialize_problem_request_InitializeProblemRequest + ): type: typing.Literal["initializeProblemRequest"] = "initializeProblemRequest" class InitializeWorkspaceRequest(UniversalBaseModel): - type: typing.Literal["initializeWorkspaceRequest"] = "initializeWorkspaceRequest" + type: typing.Literal["initializeWorkspaceRequest"] = ( + "initializeWorkspaceRequest" + ) class SubmitV2(SubmitRequestV2): type: typing.Literal["submitV2"] = "submitV2" diff --git a/seed/fastapi/trace/resources/submission/types/submission_response.py b/seed/fastapi/trace/resources/submission/types/submission_response.py index 4207c6a4fd1..759fe11781d 100644 --- a/seed/fastapi/trace/resources/submission/types/submission_response.py +++ b/seed/fastapi/trace/resources/submission/types/submission_response.py @@ -1,19 +1,19 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - -import typing - -import pydantic -import typing_extensions - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel, UniversalRootModel, update_forward_refs +from ....core.pydantic_utilities import IS_PYDANTIC_V2 from ...commons.types.problem_id import ProblemId +from .exception_info import ExceptionInfo from .code_execution_update import ( CodeExecutionUpdate as resources_submission_types_code_execution_update_CodeExecutionUpdate, ) -from .exception_info import ExceptionInfo from .terminated_response import TerminatedResponse +from ....core.pydantic_utilities import UniversalRootModel +import typing +import typing_extensions +import pydantic +from ....core.pydantic_utilities import UniversalBaseModel +from ....core.pydantic_utilities import update_forward_refs T_Result = typing.TypeVar("T_Result") @@ -21,56 +21,85 @@ class _Factory: def server_initialized(self) -> SubmissionResponse: if IS_PYDANTIC_V2: - return SubmissionResponse(root=_SubmissionResponse.ServerInitialized(type="serverInitialized")) + return SubmissionResponse( + root=_SubmissionResponse.ServerInitialized(type="serverInitialized") + ) else: - return SubmissionResponse(__root__=_SubmissionResponse.ServerInitialized(type="serverInitialized")) + return SubmissionResponse( + __root__=_SubmissionResponse.ServerInitialized(type="serverInitialized") + ) def problem_initialized(self, value: ProblemId) -> SubmissionResponse: if IS_PYDANTIC_V2: return SubmissionResponse( - root=_SubmissionResponse.ProblemInitialized(type="problemInitialized", value=value) + root=_SubmissionResponse.ProblemInitialized( + type="problemInitialized", value=value + ) ) else: return SubmissionResponse( - __root__=_SubmissionResponse.ProblemInitialized(type="problemInitialized", value=value) + __root__=_SubmissionResponse.ProblemInitialized( + type="problemInitialized", value=value + ) ) def workspace_initialized(self) -> SubmissionResponse: if IS_PYDANTIC_V2: - return SubmissionResponse(root=_SubmissionResponse.WorkspaceInitialized(type="workspaceInitialized")) + return SubmissionResponse( + root=_SubmissionResponse.WorkspaceInitialized( + type="workspaceInitialized" + ) + ) else: - return SubmissionResponse(__root__=_SubmissionResponse.WorkspaceInitialized(type="workspaceInitialized")) + return SubmissionResponse( + __root__=_SubmissionResponse.WorkspaceInitialized( + type="workspaceInitialized" + ) + ) def server_errored(self, value: ExceptionInfo) -> SubmissionResponse: if IS_PYDANTIC_V2: return SubmissionResponse( - root=_SubmissionResponse.ServerErrored(**value.dict(exclude_unset=True), type="serverErrored") + root=_SubmissionResponse.ServerErrored( + **value.dict(exclude_unset=True), type="serverErrored" + ) ) else: return SubmissionResponse( - __root__=_SubmissionResponse.ServerErrored(**value.dict(exclude_unset=True), type="serverErrored") + __root__=_SubmissionResponse.ServerErrored( + **value.dict(exclude_unset=True), type="serverErrored" + ) ) def code_execution_update( - self, value: resources_submission_types_code_execution_update_CodeExecutionUpdate + self, + value: resources_submission_types_code_execution_update_CodeExecutionUpdate, ) -> SubmissionResponse: if IS_PYDANTIC_V2: return SubmissionResponse( - root=_SubmissionResponse.CodeExecutionUpdate(type="codeExecutionUpdate", value=value) + root=_SubmissionResponse.CodeExecutionUpdate( + type="codeExecutionUpdate", value=value + ) ) else: return SubmissionResponse( - __root__=_SubmissionResponse.CodeExecutionUpdate(type="codeExecutionUpdate", value=value) + __root__=_SubmissionResponse.CodeExecutionUpdate( + type="codeExecutionUpdate", value=value + ) ) def terminated(self, value: TerminatedResponse) -> SubmissionResponse: if IS_PYDANTIC_V2: return SubmissionResponse( - root=_SubmissionResponse.Terminated(**value.dict(exclude_unset=True), type="terminated") + root=_SubmissionResponse.Terminated( + **value.dict(exclude_unset=True), type="terminated" + ) ) else: return SubmissionResponse( - __root__=_SubmissionResponse.Terminated(**value.dict(exclude_unset=True), type="terminated") + __root__=_SubmissionResponse.Terminated( + **value.dict(exclude_unset=True), type="terminated" + ) ) @@ -101,7 +130,6 @@ def get_as_union( _SubmissionResponse.Terminated, ]: return self.root - else: __root__: typing_extensions.Annotated[ typing.Union[ @@ -134,7 +162,8 @@ def visit( workspace_initialized: typing.Callable[[], T_Result], server_errored: typing.Callable[[ExceptionInfo], T_Result], code_execution_update: typing.Callable[ - [resources_submission_types_code_execution_update_CodeExecutionUpdate], T_Result + [resources_submission_types_code_execution_update_CodeExecutionUpdate], + T_Result, ], terminated: typing.Callable[[TerminatedResponse], T_Result], ) -> T_Result: @@ -146,11 +175,19 @@ def visit( if unioned_value.type == "workspaceInitialized": return workspace_initialized() if unioned_value.type == "serverErrored": - return server_errored(ExceptionInfo(**unioned_value.dict(exclude_unset=True, exclude={"type"}))) + return server_errored( + ExceptionInfo( + **unioned_value.dict(exclude_unset=True, exclude={"type"}) + ) + ) if unioned_value.type == "codeExecutionUpdate": return code_execution_update(unioned_value.value) if unioned_value.type == "terminated": - return terminated(TerminatedResponse(**unioned_value.dict(exclude_unset=True, exclude={"type"}))) + return terminated( + TerminatedResponse( + **unioned_value.dict(exclude_unset=True, exclude={"type"}) + ) + ) class _SubmissionResponse: diff --git a/seed/fastapi/trace/resources/submission/types/submission_status_for_test_case.py b/seed/fastapi/trace/resources/submission/types/submission_status_for_test_case.py index 05118c550a8..6d8b10b49e2 100644 --- a/seed/fastapi/trace/resources/submission/types/submission_status_for_test_case.py +++ b/seed/fastapi/trace/resources/submission/types/submission_status_for_test_case.py @@ -1,16 +1,16 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - -import typing - -import pydantic -import typing_extensions - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel, UniversalRootModel, update_forward_refs -from .test_case_grade import TestCaseGrade from .test_case_result_with_stdout import TestCaseResultWithStdout +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +from .test_case_grade import TestCaseGrade from .traced_test_case import TracedTestCase +from ....core.pydantic_utilities import UniversalRootModel +import typing +import typing_extensions +import pydantic +from ....core.pydantic_utilities import UniversalBaseModel +from ....core.pydantic_utilities import update_forward_refs T_Result = typing.TypeVar("T_Result") @@ -19,29 +19,41 @@ class _Factory: def graded(self, value: TestCaseResultWithStdout) -> SubmissionStatusForTestCase: if IS_PYDANTIC_V2: return SubmissionStatusForTestCase( - root=_SubmissionStatusForTestCase.Graded(**value.dict(exclude_unset=True), type="graded") + root=_SubmissionStatusForTestCase.Graded( + **value.dict(exclude_unset=True), type="graded" + ) ) else: return SubmissionStatusForTestCase( - __root__=_SubmissionStatusForTestCase.Graded(**value.dict(exclude_unset=True), type="graded") + __root__=_SubmissionStatusForTestCase.Graded( + **value.dict(exclude_unset=True), type="graded" + ) ) def graded_v_2(self, value: TestCaseGrade) -> SubmissionStatusForTestCase: if IS_PYDANTIC_V2: - return SubmissionStatusForTestCase(root=_SubmissionStatusForTestCase.GradedV2(type="gradedV2", value=value)) + return SubmissionStatusForTestCase( + root=_SubmissionStatusForTestCase.GradedV2(type="gradedV2", value=value) + ) else: return SubmissionStatusForTestCase( - __root__=_SubmissionStatusForTestCase.GradedV2(type="gradedV2", value=value) + __root__=_SubmissionStatusForTestCase.GradedV2( + type="gradedV2", value=value + ) ) def traced(self, value: TracedTestCase) -> SubmissionStatusForTestCase: if IS_PYDANTIC_V2: return SubmissionStatusForTestCase( - root=_SubmissionStatusForTestCase.Traced(**value.dict(exclude_unset=True), type="traced") + root=_SubmissionStatusForTestCase.Traced( + **value.dict(exclude_unset=True), type="traced" + ) ) else: return SubmissionStatusForTestCase( - __root__=_SubmissionStatusForTestCase.Traced(**value.dict(exclude_unset=True), type="traced") + __root__=_SubmissionStatusForTestCase.Traced( + **value.dict(exclude_unset=True), type="traced" + ) ) @@ -66,7 +78,6 @@ def get_as_union( _SubmissionStatusForTestCase.Traced, ]: return self.root - else: __root__: typing_extensions.Annotated[ typing.Union[ @@ -94,11 +105,19 @@ def visit( ) -> T_Result: unioned_value = self.get_as_union() if unioned_value.type == "graded": - return graded(TestCaseResultWithStdout(**unioned_value.dict(exclude_unset=True, exclude={"type"}))) + return graded( + TestCaseResultWithStdout( + **unioned_value.dict(exclude_unset=True, exclude={"type"}) + ) + ) if unioned_value.type == "gradedV2": return graded_v_2(unioned_value.value) if unioned_value.type == "traced": - return traced(TracedTestCase(**unioned_value.dict(exclude_unset=True, exclude={"type"}))) + return traced( + TracedTestCase( + **unioned_value.dict(exclude_unset=True, exclude={"type"}) + ) + ) class _SubmissionStatusForTestCase: diff --git a/seed/fastapi/trace/resources/submission/types/submission_status_v_2.py b/seed/fastapi/trace/resources/submission/types/submission_status_v_2.py index 344dd0f9690..5cdb559b46b 100644 --- a/seed/fastapi/trace/resources/submission/types/submission_status_v_2.py +++ b/seed/fastapi/trace/resources/submission/types/submission_status_v_2.py @@ -1,15 +1,14 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - -import typing - -import pydantic -import typing_extensions - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalRootModel, update_forward_refs from .test_submission_status_v_2 import TestSubmissionStatusV2 +from ....core.pydantic_utilities import IS_PYDANTIC_V2 from .workspace_submission_status_v_2 import WorkspaceSubmissionStatusV2 +from ....core.pydantic_utilities import UniversalRootModel +import typing +import typing_extensions +import pydantic +from ....core.pydantic_utilities import update_forward_refs T_Result = typing.TypeVar("T_Result") @@ -17,18 +16,30 @@ class _Factory: def test(self, value: TestSubmissionStatusV2) -> SubmissionStatusV2: if IS_PYDANTIC_V2: - return SubmissionStatusV2(root=_SubmissionStatusV2.Test(**value.dict(exclude_unset=True), type="test")) + return SubmissionStatusV2( + root=_SubmissionStatusV2.Test( + **value.dict(exclude_unset=True), type="test" + ) + ) else: - return SubmissionStatusV2(__root__=_SubmissionStatusV2.Test(**value.dict(exclude_unset=True), type="test")) + return SubmissionStatusV2( + __root__=_SubmissionStatusV2.Test( + **value.dict(exclude_unset=True), type="test" + ) + ) def workspace(self, value: WorkspaceSubmissionStatusV2) -> SubmissionStatusV2: if IS_PYDANTIC_V2: return SubmissionStatusV2( - root=_SubmissionStatusV2.Workspace(**value.dict(exclude_unset=True), type="workspace") + root=_SubmissionStatusV2.Workspace( + **value.dict(exclude_unset=True), type="workspace" + ) ) else: return SubmissionStatusV2( - __root__=_SubmissionStatusV2.Workspace(**value.dict(exclude_unset=True), type="workspace") + __root__=_SubmissionStatusV2.Workspace( + **value.dict(exclude_unset=True), type="workspace" + ) ) @@ -37,18 +48,23 @@ class SubmissionStatusV2(UniversalRootModel): if IS_PYDANTIC_V2: root: typing_extensions.Annotated[ - typing.Union[_SubmissionStatusV2.Test, _SubmissionStatusV2.Workspace], pydantic.Field(discriminator="type") + typing.Union[_SubmissionStatusV2.Test, _SubmissionStatusV2.Workspace], + pydantic.Field(discriminator="type"), ] - def get_as_union(self) -> typing.Union[_SubmissionStatusV2.Test, _SubmissionStatusV2.Workspace]: + def get_as_union( + self, + ) -> typing.Union[_SubmissionStatusV2.Test, _SubmissionStatusV2.Workspace]: return self.root - else: __root__: typing_extensions.Annotated[ - typing.Union[_SubmissionStatusV2.Test, _SubmissionStatusV2.Workspace], pydantic.Field(discriminator="type") + typing.Union[_SubmissionStatusV2.Test, _SubmissionStatusV2.Workspace], + pydantic.Field(discriminator="type"), ] - def get_as_union(self) -> typing.Union[_SubmissionStatusV2.Test, _SubmissionStatusV2.Workspace]: + def get_as_union( + self, + ) -> typing.Union[_SubmissionStatusV2.Test, _SubmissionStatusV2.Workspace]: return self.__root__ def visit( @@ -58,9 +74,17 @@ def visit( ) -> T_Result: unioned_value = self.get_as_union() if unioned_value.type == "test": - return test(TestSubmissionStatusV2(**unioned_value.dict(exclude_unset=True, exclude={"type"}))) + return test( + TestSubmissionStatusV2( + **unioned_value.dict(exclude_unset=True, exclude={"type"}) + ) + ) if unioned_value.type == "workspace": - return workspace(WorkspaceSubmissionStatusV2(**unioned_value.dict(exclude_unset=True, exclude={"type"}))) + return workspace( + WorkspaceSubmissionStatusV2( + **unioned_value.dict(exclude_unset=True, exclude={"type"}) + ) + ) class _SubmissionStatusV2: diff --git a/seed/fastapi/trace/resources/submission/types/submission_type_state.py b/seed/fastapi/trace/resources/submission/types/submission_type_state.py index e1761b90747..4cb6734e82e 100644 --- a/seed/fastapi/trace/resources/submission/types/submission_type_state.py +++ b/seed/fastapi/trace/resources/submission/types/submission_type_state.py @@ -1,15 +1,14 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - -import typing - -import pydantic -import typing_extensions - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalRootModel, update_forward_refs from .test_submission_state import TestSubmissionState +from ....core.pydantic_utilities import IS_PYDANTIC_V2 from .workspace_submission_state import WorkspaceSubmissionState +from ....core.pydantic_utilities import UniversalRootModel +import typing +import typing_extensions +import pydantic +from ....core.pydantic_utilities import update_forward_refs T_Result = typing.TypeVar("T_Result") @@ -17,20 +16,30 @@ class _Factory: def test(self, value: TestSubmissionState) -> SubmissionTypeState: if IS_PYDANTIC_V2: - return SubmissionTypeState(root=_SubmissionTypeState.Test(**value.dict(exclude_unset=True), type="test")) + return SubmissionTypeState( + root=_SubmissionTypeState.Test( + **value.dict(exclude_unset=True), type="test" + ) + ) else: return SubmissionTypeState( - __root__=_SubmissionTypeState.Test(**value.dict(exclude_unset=True), type="test") + __root__=_SubmissionTypeState.Test( + **value.dict(exclude_unset=True), type="test" + ) ) def workspace(self, value: WorkspaceSubmissionState) -> SubmissionTypeState: if IS_PYDANTIC_V2: return SubmissionTypeState( - root=_SubmissionTypeState.Workspace(**value.dict(exclude_unset=True), type="workspace") + root=_SubmissionTypeState.Workspace( + **value.dict(exclude_unset=True), type="workspace" + ) ) else: return SubmissionTypeState( - __root__=_SubmissionTypeState.Workspace(**value.dict(exclude_unset=True), type="workspace") + __root__=_SubmissionTypeState.Workspace( + **value.dict(exclude_unset=True), type="workspace" + ) ) @@ -43,16 +52,19 @@ class SubmissionTypeState(UniversalRootModel): pydantic.Field(discriminator="type"), ] - def get_as_union(self) -> typing.Union[_SubmissionTypeState.Test, _SubmissionTypeState.Workspace]: + def get_as_union( + self, + ) -> typing.Union[_SubmissionTypeState.Test, _SubmissionTypeState.Workspace]: return self.root - else: __root__: typing_extensions.Annotated[ typing.Union[_SubmissionTypeState.Test, _SubmissionTypeState.Workspace], pydantic.Field(discriminator="type"), ] - def get_as_union(self) -> typing.Union[_SubmissionTypeState.Test, _SubmissionTypeState.Workspace]: + def get_as_union( + self, + ) -> typing.Union[_SubmissionTypeState.Test, _SubmissionTypeState.Workspace]: return self.__root__ def visit( @@ -62,9 +74,17 @@ def visit( ) -> T_Result: unioned_value = self.get_as_union() if unioned_value.type == "test": - return test(TestSubmissionState(**unioned_value.dict(exclude_unset=True, exclude={"type"}))) + return test( + TestSubmissionState( + **unioned_value.dict(exclude_unset=True, exclude={"type"}) + ) + ) if unioned_value.type == "workspace": - return workspace(WorkspaceSubmissionState(**unioned_value.dict(exclude_unset=True, exclude={"type"}))) + return workspace( + WorkspaceSubmissionState( + **unioned_value.dict(exclude_unset=True, exclude={"type"}) + ) + ) class _SubmissionTypeState: diff --git a/seed/fastapi/trace/resources/submission/types/submit_request_v_2.py b/seed/fastapi/trace/resources/submission/types/submit_request_v_2.py index ec2fb50a381..de672aa01e3 100644 --- a/seed/fastapi/trace/resources/submission/types/submit_request_v_2.py +++ b/seed/fastapi/trace/resources/submission/types/submit_request_v_2.py @@ -1,26 +1,31 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ....core.pydantic_utilities import UniversalBaseModel +from .submission_id import SubmissionId import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from ...commons.types.language import Language -from ...commons.types.problem_id import ProblemId +import typing from .submission_file_info import SubmissionFileInfo -from .submission_id import SubmissionId +from ...commons.types.problem_id import ProblemId +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class SubmitRequestV2(UniversalBaseModel): submission_id: SubmissionId = pydantic.Field(alias="submissionId") language: Language - submission_files: typing.List[SubmissionFileInfo] = pydantic.Field(alias="submissionFiles") + submission_files: typing.List[SubmissionFileInfo] = pydantic.Field( + alias="submissionFiles" + ) problem_id: ProblemId = pydantic.Field(alias="problemId") - problem_version: typing.Optional[int] = pydantic.Field(alias="problemVersion", default=None) + problem_version: typing.Optional[int] = pydantic.Field( + alias="problemVersion", default=None + ) user_id: typing.Optional[str] = pydantic.Field(alias="userId", default=None) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/submission/types/terminated_response.py b/seed/fastapi/trace/resources/submission/types/terminated_response.py index 3b6e435ce14..14806c4e75a 100644 --- a/seed/fastapi/trace/resources/submission/types/terminated_response.py +++ b/seed/fastapi/trace/resources/submission/types/terminated_response.py @@ -1,15 +1,16 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class TerminatedResponse(UniversalBaseModel): if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/submission/types/test_case_grade.py b/seed/fastapi/trace/resources/submission/types/test_case_grade.py index 2b9b36679b2..b0839c77f5a 100644 --- a/seed/fastapi/trace/resources/submission/types/test_case_grade.py +++ b/seed/fastapi/trace/resources/submission/types/test_case_grade.py @@ -1,15 +1,14 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - -import typing - -import pydantic -import typing_extensions - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalRootModel, update_forward_refs from .test_case_hidden_grade import TestCaseHiddenGrade +from ....core.pydantic_utilities import IS_PYDANTIC_V2 from .test_case_non_hidden_grade import TestCaseNonHiddenGrade +from ....core.pydantic_utilities import UniversalRootModel +import typing +import typing_extensions +import pydantic +from ....core.pydantic_utilities import update_forward_refs T_Result = typing.TypeVar("T_Result") @@ -17,15 +16,31 @@ class _Factory: def hidden(self, value: TestCaseHiddenGrade) -> TestCaseGrade: if IS_PYDANTIC_V2: - return TestCaseGrade(root=_TestCaseGrade.Hidden(**value.dict(exclude_unset=True), type="hidden")) + return TestCaseGrade( + root=_TestCaseGrade.Hidden( + **value.dict(exclude_unset=True), type="hidden" + ) + ) else: - return TestCaseGrade(__root__=_TestCaseGrade.Hidden(**value.dict(exclude_unset=True), type="hidden")) + return TestCaseGrade( + __root__=_TestCaseGrade.Hidden( + **value.dict(exclude_unset=True), type="hidden" + ) + ) def non_hidden(self, value: TestCaseNonHiddenGrade) -> TestCaseGrade: if IS_PYDANTIC_V2: - return TestCaseGrade(root=_TestCaseGrade.NonHidden(**value.dict(exclude_unset=True), type="nonHidden")) + return TestCaseGrade( + root=_TestCaseGrade.NonHidden( + **value.dict(exclude_unset=True), type="nonHidden" + ) + ) else: - return TestCaseGrade(__root__=_TestCaseGrade.NonHidden(**value.dict(exclude_unset=True), type="nonHidden")) + return TestCaseGrade( + __root__=_TestCaseGrade.NonHidden( + **value.dict(exclude_unset=True), type="nonHidden" + ) + ) class TestCaseGrade(UniversalRootModel): @@ -33,18 +48,23 @@ class TestCaseGrade(UniversalRootModel): if IS_PYDANTIC_V2: root: typing_extensions.Annotated[ - typing.Union[_TestCaseGrade.Hidden, _TestCaseGrade.NonHidden], pydantic.Field(discriminator="type") + typing.Union[_TestCaseGrade.Hidden, _TestCaseGrade.NonHidden], + pydantic.Field(discriminator="type"), ] - def get_as_union(self) -> typing.Union[_TestCaseGrade.Hidden, _TestCaseGrade.NonHidden]: + def get_as_union( + self, + ) -> typing.Union[_TestCaseGrade.Hidden, _TestCaseGrade.NonHidden]: return self.root - else: __root__: typing_extensions.Annotated[ - typing.Union[_TestCaseGrade.Hidden, _TestCaseGrade.NonHidden], pydantic.Field(discriminator="type") + typing.Union[_TestCaseGrade.Hidden, _TestCaseGrade.NonHidden], + pydantic.Field(discriminator="type"), ] - def get_as_union(self) -> typing.Union[_TestCaseGrade.Hidden, _TestCaseGrade.NonHidden]: + def get_as_union( + self, + ) -> typing.Union[_TestCaseGrade.Hidden, _TestCaseGrade.NonHidden]: return self.__root__ def visit( @@ -54,9 +74,17 @@ def visit( ) -> T_Result: unioned_value = self.get_as_union() if unioned_value.type == "hidden": - return hidden(TestCaseHiddenGrade(**unioned_value.dict(exclude_unset=True, exclude={"type"}))) + return hidden( + TestCaseHiddenGrade( + **unioned_value.dict(exclude_unset=True, exclude={"type"}) + ) + ) if unioned_value.type == "nonHidden": - return non_hidden(TestCaseNonHiddenGrade(**unioned_value.dict(exclude_unset=True, exclude={"type"}))) + return non_hidden( + TestCaseNonHiddenGrade( + **unioned_value.dict(exclude_unset=True, exclude={"type"}) + ) + ) class _TestCaseGrade: diff --git a/seed/fastapi/trace/resources/submission/types/test_case_hidden_grade.py b/seed/fastapi/trace/resources/submission/types/test_case_hidden_grade.py index b502c38c483..f8d7ee47c27 100644 --- a/seed/fastapi/trace/resources/submission/types/test_case_hidden_grade.py +++ b/seed/fastapi/trace/resources/submission/types/test_case_hidden_grade.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class TestCaseHiddenGrade(UniversalBaseModel): passed: bool if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/submission/types/test_case_non_hidden_grade.py b/seed/fastapi/trace/resources/submission/types/test_case_non_hidden_grade.py index c48c8d8ff69..7855f76174f 100644 --- a/seed/fastapi/trace/resources/submission/types/test_case_non_hidden_grade.py +++ b/seed/fastapi/trace/resources/submission/types/test_case_non_hidden_grade.py @@ -1,22 +1,25 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from ...commons.types.variable_value import VariableValue +import pydantic from .exception_v_2 import ExceptionV2 +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class TestCaseNonHiddenGrade(UniversalBaseModel): passed: bool - actual_result: typing.Optional[VariableValue] = pydantic.Field(alias="actualResult", default=None) + actual_result: typing.Optional[VariableValue] = pydantic.Field( + alias="actualResult", default=None + ) exception: typing.Optional[ExceptionV2] = None stdout: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/submission/types/test_case_result.py b/seed/fastapi/trace/resources/submission/types/test_case_result.py index e94b119405a..33724c17b5a 100644 --- a/seed/fastapi/trace/resources/submission/types/test_case_result.py +++ b/seed/fastapi/trace/resources/submission/types/test_case_result.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import UniversalBaseModel from ...commons.types.variable_value import VariableValue +import pydantic from .actual_result import ActualResult +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class TestCaseResult(UniversalBaseModel): @@ -15,7 +14,9 @@ class TestCaseResult(UniversalBaseModel): passed: bool if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/submission/types/test_case_result_with_stdout.py b/seed/fastapi/trace/resources/submission/types/test_case_result_with_stdout.py index be49d781036..33c9b7862d7 100644 --- a/seed/fastapi/trace/resources/submission/types/test_case_result_with_stdout.py +++ b/seed/fastapi/trace/resources/submission/types/test_case_result_with_stdout.py @@ -1,19 +1,20 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel +from .test_case_result import TestCaseResult +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .test_case_result import TestCaseResult - class TestCaseResultWithStdout(UniversalBaseModel): result: TestCaseResult stdout: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/submission/types/test_submission_state.py b/seed/fastapi/trace/resources/submission/types/test_submission_state.py index 89388f14b85..331da72a203 100644 --- a/seed/fastapi/trace/resources/submission/types/test_submission_state.py +++ b/seed/fastapi/trace/resources/submission/types/test_submission_state.py @@ -1,13 +1,12 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import UniversalBaseModel from ...commons.types.problem_id import ProblemId +import pydantic +import typing from ...commons.types.test_case import TestCase from .test_submission_status import TestSubmissionStatus +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class TestSubmissionState(UniversalBaseModel): @@ -17,7 +16,9 @@ class TestSubmissionState(UniversalBaseModel): status: TestSubmissionStatus if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/submission/types/test_submission_status.py b/seed/fastapi/trace/resources/submission/types/test_submission_status.py index f98045fe2ea..152b43078da 100644 --- a/seed/fastapi/trace/resources/submission/types/test_submission_status.py +++ b/seed/fastapi/trace/resources/submission/types/test_submission_status.py @@ -1,16 +1,16 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - -import typing - -import pydantic -import typing_extensions - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel, UniversalRootModel, update_forward_refs +from ....core.pydantic_utilities import IS_PYDANTIC_V2 from .error_info import ErrorInfo from .running_submission_state import RunningSubmissionState +import typing from .submission_status_for_test_case import SubmissionStatusForTestCase +from ....core.pydantic_utilities import UniversalRootModel +import typing_extensions +import pydantic +from ....core.pydantic_utilities import UniversalBaseModel +from ....core.pydantic_utilities import update_forward_refs T_Result = typing.TypeVar("T_Result") @@ -18,30 +18,48 @@ class _Factory: def stopped(self) -> TestSubmissionStatus: if IS_PYDANTIC_V2: - return TestSubmissionStatus(root=_TestSubmissionStatus.Stopped(type="stopped")) + return TestSubmissionStatus( + root=_TestSubmissionStatus.Stopped(type="stopped") + ) else: - return TestSubmissionStatus(__root__=_TestSubmissionStatus.Stopped(type="stopped")) + return TestSubmissionStatus( + __root__=_TestSubmissionStatus.Stopped(type="stopped") + ) def errored(self, value: ErrorInfo) -> TestSubmissionStatus: if IS_PYDANTIC_V2: - return TestSubmissionStatus(root=_TestSubmissionStatus.Errored(type="errored", value=value)) + return TestSubmissionStatus( + root=_TestSubmissionStatus.Errored(type="errored", value=value) + ) else: - return TestSubmissionStatus(__root__=_TestSubmissionStatus.Errored(type="errored", value=value)) + return TestSubmissionStatus( + __root__=_TestSubmissionStatus.Errored(type="errored", value=value) + ) def running(self, value: RunningSubmissionState) -> TestSubmissionStatus: if IS_PYDANTIC_V2: - return TestSubmissionStatus(root=_TestSubmissionStatus.Running(type="running", value=value)) + return TestSubmissionStatus( + root=_TestSubmissionStatus.Running(type="running", value=value) + ) else: - return TestSubmissionStatus(__root__=_TestSubmissionStatus.Running(type="running", value=value)) + return TestSubmissionStatus( + __root__=_TestSubmissionStatus.Running(type="running", value=value) + ) - def test_case_id_to_state(self, value: typing.Dict[str, SubmissionStatusForTestCase]) -> TestSubmissionStatus: + def test_case_id_to_state( + self, value: typing.Dict[str, SubmissionStatusForTestCase] + ) -> TestSubmissionStatus: if IS_PYDANTIC_V2: return TestSubmissionStatus( - root=_TestSubmissionStatus.TestCaseIdToState(type="testCaseIdToState", value=value) + root=_TestSubmissionStatus.TestCaseIdToState( + type="testCaseIdToState", value=value + ) ) else: return TestSubmissionStatus( - __root__=_TestSubmissionStatus.TestCaseIdToState(type="testCaseIdToState", value=value) + __root__=_TestSubmissionStatus.TestCaseIdToState( + type="testCaseIdToState", value=value + ) ) @@ -68,7 +86,6 @@ def get_as_union( _TestSubmissionStatus.TestCaseIdToState, ]: return self.root - else: __root__: typing_extensions.Annotated[ typing.Union[ @@ -95,7 +112,9 @@ def visit( stopped: typing.Callable[[], T_Result], errored: typing.Callable[[ErrorInfo], T_Result], running: typing.Callable[[RunningSubmissionState], T_Result], - test_case_id_to_state: typing.Callable[[typing.Dict[str, SubmissionStatusForTestCase]], T_Result], + test_case_id_to_state: typing.Callable[ + [typing.Dict[str, SubmissionStatusForTestCase]], T_Result + ], ) -> T_Result: unioned_value = self.get_as_union() if unioned_value.type == "stopped": diff --git a/seed/fastapi/trace/resources/submission/types/test_submission_status_v_2.py b/seed/fastapi/trace/resources/submission/types/test_submission_status_v_2.py index 0f1376534bc..cbd8e495560 100644 --- a/seed/fastapi/trace/resources/submission/types/test_submission_status_v_2.py +++ b/seed/fastapi/trace/resources/submission/types/test_submission_status_v_2.py @@ -1,13 +1,12 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from .test_submission_update import TestSubmissionUpdate from ...commons.types.problem_id import ProblemId +import pydantic from ...v_2.resources.problem.types.problem_info_v_2 import ProblemInfoV2 -from .test_submission_update import TestSubmissionUpdate +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class TestSubmissionStatusV2(UniversalBaseModel): @@ -17,7 +16,9 @@ class TestSubmissionStatusV2(UniversalBaseModel): problem_info: ProblemInfoV2 = pydantic.Field(alias="problemInfo") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/submission/types/test_submission_update.py b/seed/fastapi/trace/resources/submission/types/test_submission_update.py index 224cc2439da..7adfb826107 100644 --- a/seed/fastapi/trace/resources/submission/types/test_submission_update.py +++ b/seed/fastapi/trace/resources/submission/types/test_submission_update.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import datetime as dt -import typing - import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .test_submission_update_info import TestSubmissionUpdateInfo +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class TestSubmissionUpdate(UniversalBaseModel): @@ -14,7 +13,9 @@ class TestSubmissionUpdate(UniversalBaseModel): update_info: TestSubmissionUpdateInfo = pydantic.Field(alias="updateInfo") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/submission/types/test_submission_update_info.py b/seed/fastapi/trace/resources/submission/types/test_submission_update_info.py index 72d7a9d2d3d..3ae30d10176 100644 --- a/seed/fastapi/trace/resources/submission/types/test_submission_update_info.py +++ b/seed/fastapi/trace/resources/submission/types/test_submission_update_info.py @@ -1,17 +1,17 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - -import typing - -import pydantic -import typing_extensions - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel, UniversalRootModel, update_forward_refs +from .running_submission_state import RunningSubmissionState +from ....core.pydantic_utilities import IS_PYDANTIC_V2 from .error_info import ErrorInfo from .graded_test_case_update import GradedTestCaseUpdate from .recorded_test_case_update import RecordedTestCaseUpdate -from .running_submission_state import RunningSubmissionState +from ....core.pydantic_utilities import UniversalRootModel +import typing +import typing_extensions +import pydantic +from ....core.pydantic_utilities import UniversalBaseModel +from ....core.pydantic_utilities import update_forward_refs T_Result = typing.TypeVar("T_Result") @@ -19,26 +19,40 @@ class _Factory: def running(self, value: RunningSubmissionState) -> TestSubmissionUpdateInfo: if IS_PYDANTIC_V2: - return TestSubmissionUpdateInfo(root=_TestSubmissionUpdateInfo.Running(type="running", value=value)) + return TestSubmissionUpdateInfo( + root=_TestSubmissionUpdateInfo.Running(type="running", value=value) + ) else: - return TestSubmissionUpdateInfo(__root__=_TestSubmissionUpdateInfo.Running(type="running", value=value)) + return TestSubmissionUpdateInfo( + __root__=_TestSubmissionUpdateInfo.Running(type="running", value=value) + ) def stopped(self) -> TestSubmissionUpdateInfo: if IS_PYDANTIC_V2: - return TestSubmissionUpdateInfo(root=_TestSubmissionUpdateInfo.Stopped(type="stopped")) + return TestSubmissionUpdateInfo( + root=_TestSubmissionUpdateInfo.Stopped(type="stopped") + ) else: - return TestSubmissionUpdateInfo(__root__=_TestSubmissionUpdateInfo.Stopped(type="stopped")) + return TestSubmissionUpdateInfo( + __root__=_TestSubmissionUpdateInfo.Stopped(type="stopped") + ) def errored(self, value: ErrorInfo) -> TestSubmissionUpdateInfo: if IS_PYDANTIC_V2: - return TestSubmissionUpdateInfo(root=_TestSubmissionUpdateInfo.Errored(type="errored", value=value)) + return TestSubmissionUpdateInfo( + root=_TestSubmissionUpdateInfo.Errored(type="errored", value=value) + ) else: - return TestSubmissionUpdateInfo(__root__=_TestSubmissionUpdateInfo.Errored(type="errored", value=value)) + return TestSubmissionUpdateInfo( + __root__=_TestSubmissionUpdateInfo.Errored(type="errored", value=value) + ) def graded_test_case(self, value: GradedTestCaseUpdate) -> TestSubmissionUpdateInfo: if IS_PYDANTIC_V2: return TestSubmissionUpdateInfo( - root=_TestSubmissionUpdateInfo.GradedTestCase(**value.dict(exclude_unset=True), type="gradedTestCase") + root=_TestSubmissionUpdateInfo.GradedTestCase( + **value.dict(exclude_unset=True), type="gradedTestCase" + ) ) else: return TestSubmissionUpdateInfo( @@ -47,7 +61,9 @@ def graded_test_case(self, value: GradedTestCaseUpdate) -> TestSubmissionUpdateI ) ) - def recorded_test_case(self, value: RecordedTestCaseUpdate) -> TestSubmissionUpdateInfo: + def recorded_test_case( + self, value: RecordedTestCaseUpdate + ) -> TestSubmissionUpdateInfo: if IS_PYDANTIC_V2: return TestSubmissionUpdateInfo( root=_TestSubmissionUpdateInfo.RecordedTestCase( @@ -63,9 +79,13 @@ def recorded_test_case(self, value: RecordedTestCaseUpdate) -> TestSubmissionUpd def finished(self) -> TestSubmissionUpdateInfo: if IS_PYDANTIC_V2: - return TestSubmissionUpdateInfo(root=_TestSubmissionUpdateInfo.Finished(type="finished")) + return TestSubmissionUpdateInfo( + root=_TestSubmissionUpdateInfo.Finished(type="finished") + ) else: - return TestSubmissionUpdateInfo(__root__=_TestSubmissionUpdateInfo.Finished(type="finished")) + return TestSubmissionUpdateInfo( + __root__=_TestSubmissionUpdateInfo.Finished(type="finished") + ) class TestSubmissionUpdateInfo(UniversalRootModel): @@ -95,7 +115,6 @@ def get_as_union( _TestSubmissionUpdateInfo.Finished, ]: return self.root - else: __root__: typing_extensions.Annotated[ typing.Union[ @@ -138,10 +157,16 @@ def visit( if unioned_value.type == "errored": return errored(unioned_value.value) if unioned_value.type == "gradedTestCase": - return graded_test_case(GradedTestCaseUpdate(**unioned_value.dict(exclude_unset=True, exclude={"type"}))) + return graded_test_case( + GradedTestCaseUpdate( + **unioned_value.dict(exclude_unset=True, exclude={"type"}) + ) + ) if unioned_value.type == "recordedTestCase": return recorded_test_case( - RecordedTestCaseUpdate(**unioned_value.dict(exclude_unset=True, exclude={"type"})) + RecordedTestCaseUpdate( + **unioned_value.dict(exclude_unset=True, exclude={"type"}) + ) ) if unioned_value.type == "finished": return finished() diff --git a/seed/fastapi/trace/resources/submission/types/trace_response.py b/seed/fastapi/trace/resources/submission/types/trace_response.py index 4bac64c72a3..dfc61c3c6ee 100644 --- a/seed/fastapi/trace/resources/submission/types/trace_response.py +++ b/seed/fastapi/trace/resources/submission/types/trace_response.py @@ -1,26 +1,31 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ....core.pydantic_utilities import UniversalBaseModel +from .submission_id import SubmissionId import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +import typing from ...commons.types.debug_variable_value import DebugVariableValue from .expression_location import ExpressionLocation from .stack_information import StackInformation -from .submission_id import SubmissionId +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class TraceResponse(UniversalBaseModel): submission_id: SubmissionId = pydantic.Field(alias="submissionId") line_number: int = pydantic.Field(alias="lineNumber") - return_value: typing.Optional[DebugVariableValue] = pydantic.Field(alias="returnValue", default=None) - expression_location: typing.Optional[ExpressionLocation] = pydantic.Field(alias="expressionLocation", default=None) + return_value: typing.Optional[DebugVariableValue] = pydantic.Field( + alias="returnValue", default=None + ) + expression_location: typing.Optional[ExpressionLocation] = pydantic.Field( + alias="expressionLocation", default=None + ) stack: StackInformation stdout: typing.Optional[str] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/submission/types/trace_response_v_2.py b/seed/fastapi/trace/resources/submission/types/trace_response_v_2.py index 9c1957771f4..2fcc9aa7e93 100644 --- a/seed/fastapi/trace/resources/submission/types/trace_response_v_2.py +++ b/seed/fastapi/trace/resources/submission/types/trace_response_v_2.py @@ -1,28 +1,33 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ....core.pydantic_utilities import UniversalBaseModel +from .submission_id import SubmissionId import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from .traced_file import TracedFile +import typing from ...commons.types.debug_variable_value import DebugVariableValue from .expression_location import ExpressionLocation from .stack_information import StackInformation -from .submission_id import SubmissionId -from .traced_file import TracedFile +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class TraceResponseV2(UniversalBaseModel): submission_id: SubmissionId = pydantic.Field(alias="submissionId") line_number: int = pydantic.Field(alias="lineNumber") file: TracedFile - return_value: typing.Optional[DebugVariableValue] = pydantic.Field(alias="returnValue", default=None) - expression_location: typing.Optional[ExpressionLocation] = pydantic.Field(alias="expressionLocation", default=None) + return_value: typing.Optional[DebugVariableValue] = pydantic.Field( + alias="returnValue", default=None + ) + expression_location: typing.Optional[ExpressionLocation] = pydantic.Field( + alias="expressionLocation", default=None + ) stack: StackInformation stdout: typing.Optional[str] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/submission/types/trace_responses_page.py b/seed/fastapi/trace/resources/submission/types/trace_responses_page.py index 6d28391e3e4..8dd4cf360a9 100644 --- a/seed/fastapi/trace/resources/submission/types/trace_responses_page.py +++ b/seed/fastapi/trace/resources/submission/types/trace_responses_page.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .trace_response import TraceResponse +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class TraceResponsesPage(UniversalBaseModel): @@ -18,7 +17,9 @@ class TraceResponsesPage(UniversalBaseModel): trace_responses: typing.List[TraceResponse] = pydantic.Field(alias="traceResponses") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/submission/types/trace_responses_page_v_2.py b/seed/fastapi/trace/resources/submission/types/trace_responses_page_v_2.py index 2e59d86aa82..df025fb925f 100644 --- a/seed/fastapi/trace/resources/submission/types/trace_responses_page_v_2.py +++ b/seed/fastapi/trace/resources/submission/types/trace_responses_page_v_2.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .trace_response_v_2 import TraceResponseV2 +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class TraceResponsesPageV2(UniversalBaseModel): @@ -15,10 +14,14 @@ class TraceResponsesPageV2(UniversalBaseModel): The offset is the id of the next trace response to load. """ - trace_responses: typing.List[TraceResponseV2] = pydantic.Field(alias="traceResponses") + trace_responses: typing.List[TraceResponseV2] = pydantic.Field( + alias="traceResponses" + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/submission/types/traced_file.py b/seed/fastapi/trace/resources/submission/types/traced_file.py index 175ea455bdf..4c12b4ec4f9 100644 --- a/seed/fastapi/trace/resources/submission/types/traced_file.py +++ b/seed/fastapi/trace/resources/submission/types/traced_file.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class TracedFile(UniversalBaseModel): filename: str directory: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/submission/types/traced_test_case.py b/seed/fastapi/trace/resources/submission/types/traced_test_case.py index 259af12bf45..a0564b85009 100644 --- a/seed/fastapi/trace/resources/submission/types/traced_test_case.py +++ b/seed/fastapi/trace/resources/submission/types/traced_test_case.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import UniversalBaseModel from .test_case_result_with_stdout import TestCaseResultWithStdout +import pydantic +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class TracedTestCase(UniversalBaseModel): @@ -13,7 +12,9 @@ class TracedTestCase(UniversalBaseModel): trace_responses_size: int = pydantic.Field(alias="traceResponsesSize") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/submission/types/unexpected_language_error.py b/seed/fastapi/trace/resources/submission/types/unexpected_language_error.py index 93d17cac116..146ff80a393 100644 --- a/seed/fastapi/trace/resources/submission/types/unexpected_language_error.py +++ b/seed/fastapi/trace/resources/submission/types/unexpected_language_error.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import UniversalBaseModel from ...commons.types.language import Language +import pydantic +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class UnexpectedLanguageError(UniversalBaseModel): @@ -13,7 +12,9 @@ class UnexpectedLanguageError(UniversalBaseModel): actual_language: Language = pydantic.Field(alias="actualLanguage") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/submission/types/workspace_files.py b/seed/fastapi/trace/resources/submission/types/workspace_files.py index 3cada699f28..4312d97e921 100644 --- a/seed/fastapi/trace/resources/submission/types/workspace_files.py +++ b/seed/fastapi/trace/resources/submission/types/workspace_files.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import UniversalBaseModel from ...commons.types.file_info import FileInfo +import pydantic +import typing +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class WorkspaceFiles(UniversalBaseModel): @@ -13,7 +12,9 @@ class WorkspaceFiles(UniversalBaseModel): read_only_files: typing.List[FileInfo] = pydantic.Field(alias="readOnlyFiles") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/submission/types/workspace_ran_response.py b/seed/fastapi/trace/resources/submission/types/workspace_ran_response.py index e78aff17c05..7b2ca815a60 100644 --- a/seed/fastapi/trace/resources/submission/types/workspace_ran_response.py +++ b/seed/fastapi/trace/resources/submission/types/workspace_ran_response.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import UniversalBaseModel from .submission_id import SubmissionId +import pydantic from .workspace_run_details import WorkspaceRunDetails +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class WorkspaceRanResponse(UniversalBaseModel): @@ -14,7 +13,9 @@ class WorkspaceRanResponse(UniversalBaseModel): run_details: WorkspaceRunDetails = pydantic.Field(alias="runDetails") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/submission/types/workspace_run_details.py b/seed/fastapi/trace/resources/submission/types/workspace_run_details.py index 8c4b05bf1a7..0a7174747bb 100644 --- a/seed/fastapi/trace/resources/submission/types/workspace_run_details.py +++ b/seed/fastapi/trace/resources/submission/types/workspace_run_details.py @@ -1,21 +1,24 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - +from .exception_v_2 import ExceptionV2 import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .exception_info import ExceptionInfo -from .exception_v_2 import ExceptionV2 +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class WorkspaceRunDetails(UniversalBaseModel): - exception_v_2: typing.Optional[ExceptionV2] = pydantic.Field(alias="exceptionV2", default=None) + exception_v_2: typing.Optional[ExceptionV2] = pydantic.Field( + alias="exceptionV2", default=None + ) exception: typing.Optional[ExceptionInfo] = None stdout: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/submission/types/workspace_starter_files_response.py b/seed/fastapi/trace/resources/submission/types/workspace_starter_files_response.py index 8eac430fcb0..d2fde98fc3c 100644 --- a/seed/fastapi/trace/resources/submission/types/workspace_starter_files_response.py +++ b/seed/fastapi/trace/resources/submission/types/workspace_starter_files_response.py @@ -1,19 +1,20 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from ...commons.types.language import Language from .workspace_files import WorkspaceFiles +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import pydantic class WorkspaceStarterFilesResponse(UniversalBaseModel): files: typing.Dict[Language, WorkspaceFiles] if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/submission/types/workspace_starter_files_response_v_2.py b/seed/fastapi/trace/resources/submission/types/workspace_starter_files_response_v_2.py index 8406085ec7b..8e02b05dd78 100644 --- a/seed/fastapi/trace/resources/submission/types/workspace_starter_files_response_v_2.py +++ b/seed/fastapi/trace/resources/submission/types/workspace_starter_files_response_v_2.py @@ -1,19 +1,22 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from ...commons.types.language import Language from ...v_2.resources.problem.types.files import Files +import pydantic +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class WorkspaceStarterFilesResponseV2(UniversalBaseModel): - files_by_language: typing.Dict[Language, Files] = pydantic.Field(alias="filesByLanguage") + files_by_language: typing.Dict[Language, Files] = pydantic.Field( + alias="filesByLanguage" + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/submission/types/workspace_submission_state.py b/seed/fastapi/trace/resources/submission/types/workspace_submission_state.py index 36c45d87864..cbcba2c191e 100644 --- a/seed/fastapi/trace/resources/submission/types/workspace_submission_state.py +++ b/seed/fastapi/trace/resources/submission/types/workspace_submission_state.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel +from .workspace_submission_status import WorkspaceSubmissionStatus +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .workspace_submission_status import WorkspaceSubmissionStatus - class WorkspaceSubmissionState(UniversalBaseModel): status: WorkspaceSubmissionStatus if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/submission/types/workspace_submission_status.py b/seed/fastapi/trace/resources/submission/types/workspace_submission_status.py index 4c2cef054f6..3ac443d0ad0 100644 --- a/seed/fastapi/trace/resources/submission/types/workspace_submission_status.py +++ b/seed/fastapi/trace/resources/submission/types/workspace_submission_status.py @@ -1,16 +1,16 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - -import typing - -import pydantic -import typing_extensions - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel, UniversalRootModel, update_forward_refs +from ....core.pydantic_utilities import IS_PYDANTIC_V2 from .error_info import ErrorInfo from .running_submission_state import RunningSubmissionState from .workspace_run_details import WorkspaceRunDetails +from ....core.pydantic_utilities import UniversalRootModel +import typing +import typing_extensions +import pydantic +from ....core.pydantic_utilities import UniversalBaseModel +from ....core.pydantic_utilities import update_forward_refs T_Result = typing.TypeVar("T_Result") @@ -18,40 +18,60 @@ class _Factory: def stopped(self) -> WorkspaceSubmissionStatus: if IS_PYDANTIC_V2: - return WorkspaceSubmissionStatus(root=_WorkspaceSubmissionStatus.Stopped(type="stopped")) + return WorkspaceSubmissionStatus( + root=_WorkspaceSubmissionStatus.Stopped(type="stopped") + ) else: - return WorkspaceSubmissionStatus(__root__=_WorkspaceSubmissionStatus.Stopped(type="stopped")) + return WorkspaceSubmissionStatus( + __root__=_WorkspaceSubmissionStatus.Stopped(type="stopped") + ) def errored(self, value: ErrorInfo) -> WorkspaceSubmissionStatus: if IS_PYDANTIC_V2: - return WorkspaceSubmissionStatus(root=_WorkspaceSubmissionStatus.Errored(type="errored", value=value)) + return WorkspaceSubmissionStatus( + root=_WorkspaceSubmissionStatus.Errored(type="errored", value=value) + ) else: - return WorkspaceSubmissionStatus(__root__=_WorkspaceSubmissionStatus.Errored(type="errored", value=value)) + return WorkspaceSubmissionStatus( + __root__=_WorkspaceSubmissionStatus.Errored(type="errored", value=value) + ) def running(self, value: RunningSubmissionState) -> WorkspaceSubmissionStatus: if IS_PYDANTIC_V2: - return WorkspaceSubmissionStatus(root=_WorkspaceSubmissionStatus.Running(type="running", value=value)) + return WorkspaceSubmissionStatus( + root=_WorkspaceSubmissionStatus.Running(type="running", value=value) + ) else: - return WorkspaceSubmissionStatus(__root__=_WorkspaceSubmissionStatus.Running(type="running", value=value)) + return WorkspaceSubmissionStatus( + __root__=_WorkspaceSubmissionStatus.Running(type="running", value=value) + ) def ran(self, value: WorkspaceRunDetails) -> WorkspaceSubmissionStatus: if IS_PYDANTIC_V2: return WorkspaceSubmissionStatus( - root=_WorkspaceSubmissionStatus.Ran(**value.dict(exclude_unset=True), type="ran") + root=_WorkspaceSubmissionStatus.Ran( + **value.dict(exclude_unset=True), type="ran" + ) ) else: return WorkspaceSubmissionStatus( - __root__=_WorkspaceSubmissionStatus.Ran(**value.dict(exclude_unset=True), type="ran") + __root__=_WorkspaceSubmissionStatus.Ran( + **value.dict(exclude_unset=True), type="ran" + ) ) def traced(self, value: WorkspaceRunDetails) -> WorkspaceSubmissionStatus: if IS_PYDANTIC_V2: return WorkspaceSubmissionStatus( - root=_WorkspaceSubmissionStatus.Traced(**value.dict(exclude_unset=True), type="traced") + root=_WorkspaceSubmissionStatus.Traced( + **value.dict(exclude_unset=True), type="traced" + ) ) else: return WorkspaceSubmissionStatus( - __root__=_WorkspaceSubmissionStatus.Traced(**value.dict(exclude_unset=True), type="traced") + __root__=_WorkspaceSubmissionStatus.Traced( + **value.dict(exclude_unset=True), type="traced" + ) ) @@ -80,7 +100,6 @@ def get_as_union( _WorkspaceSubmissionStatus.Traced, ]: return self.root - else: __root__: typing_extensions.Annotated[ typing.Union[ @@ -120,9 +139,17 @@ def visit( if unioned_value.type == "running": return running(unioned_value.value) if unioned_value.type == "ran": - return ran(WorkspaceRunDetails(**unioned_value.dict(exclude_unset=True, exclude={"type"}))) + return ran( + WorkspaceRunDetails( + **unioned_value.dict(exclude_unset=True, exclude={"type"}) + ) + ) if unioned_value.type == "traced": - return traced(WorkspaceRunDetails(**unioned_value.dict(exclude_unset=True, exclude={"type"}))) + return traced( + WorkspaceRunDetails( + **unioned_value.dict(exclude_unset=True, exclude={"type"}) + ) + ) class _WorkspaceSubmissionStatus: diff --git a/seed/fastapi/trace/resources/submission/types/workspace_submission_status_v_2.py b/seed/fastapi/trace/resources/submission/types/workspace_submission_status_v_2.py index 32bba42fd4e..cc463996384 100644 --- a/seed/fastapi/trace/resources/submission/types/workspace_submission_status_v_2.py +++ b/seed/fastapi/trace/resources/submission/types/workspace_submission_status_v_2.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .workspace_submission_update import WorkspaceSubmissionUpdate +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import pydantic class WorkspaceSubmissionStatusV2(UniversalBaseModel): updates: typing.List[WorkspaceSubmissionUpdate] if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/submission/types/workspace_submission_update.py b/seed/fastapi/trace/resources/submission/types/workspace_submission_update.py index caf4e6e5454..3b12519bea9 100644 --- a/seed/fastapi/trace/resources/submission/types/workspace_submission_update.py +++ b/seed/fastapi/trace/resources/submission/types/workspace_submission_update.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import datetime as dt -import typing - import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .workspace_submission_update_info import WorkspaceSubmissionUpdateInfo +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class WorkspaceSubmissionUpdate(UniversalBaseModel): @@ -14,7 +13,9 @@ class WorkspaceSubmissionUpdate(UniversalBaseModel): update_info: WorkspaceSubmissionUpdateInfo = pydantic.Field(alias="updateInfo") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/submission/types/workspace_submission_update_info.py b/seed/fastapi/trace/resources/submission/types/workspace_submission_update_info.py index 36e074d2dc7..7686d854f8d 100644 --- a/seed/fastapi/trace/resources/submission/types/workspace_submission_update_info.py +++ b/seed/fastapi/trace/resources/submission/types/workspace_submission_update_info.py @@ -1,17 +1,17 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - -import typing - -import pydantic -import typing_extensions - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel, UniversalRootModel, update_forward_refs -from .error_info import ErrorInfo from .running_submission_state import RunningSubmissionState +from ....core.pydantic_utilities import IS_PYDANTIC_V2 from .workspace_run_details import WorkspaceRunDetails from .workspace_traced_update import WorkspaceTracedUpdate +from .error_info import ErrorInfo +from ....core.pydantic_utilities import UniversalRootModel +import typing +import typing_extensions +import pydantic +from ....core.pydantic_utilities import UniversalBaseModel +from ....core.pydantic_utilities import update_forward_refs T_Result = typing.TypeVar("T_Result") @@ -24,39 +24,57 @@ def running(self, value: RunningSubmissionState) -> WorkspaceSubmissionUpdateInf ) else: return WorkspaceSubmissionUpdateInfo( - __root__=_WorkspaceSubmissionUpdateInfo.Running(type="running", value=value) + __root__=_WorkspaceSubmissionUpdateInfo.Running( + type="running", value=value + ) ) def ran(self, value: WorkspaceRunDetails) -> WorkspaceSubmissionUpdateInfo: if IS_PYDANTIC_V2: return WorkspaceSubmissionUpdateInfo( - root=_WorkspaceSubmissionUpdateInfo.Ran(**value.dict(exclude_unset=True), type="ran") + root=_WorkspaceSubmissionUpdateInfo.Ran( + **value.dict(exclude_unset=True), type="ran" + ) ) else: return WorkspaceSubmissionUpdateInfo( - __root__=_WorkspaceSubmissionUpdateInfo.Ran(**value.dict(exclude_unset=True), type="ran") + __root__=_WorkspaceSubmissionUpdateInfo.Ran( + **value.dict(exclude_unset=True), type="ran" + ) ) def stopped(self) -> WorkspaceSubmissionUpdateInfo: if IS_PYDANTIC_V2: - return WorkspaceSubmissionUpdateInfo(root=_WorkspaceSubmissionUpdateInfo.Stopped(type="stopped")) + return WorkspaceSubmissionUpdateInfo( + root=_WorkspaceSubmissionUpdateInfo.Stopped(type="stopped") + ) else: - return WorkspaceSubmissionUpdateInfo(__root__=_WorkspaceSubmissionUpdateInfo.Stopped(type="stopped")) + return WorkspaceSubmissionUpdateInfo( + __root__=_WorkspaceSubmissionUpdateInfo.Stopped(type="stopped") + ) def traced(self) -> WorkspaceSubmissionUpdateInfo: if IS_PYDANTIC_V2: - return WorkspaceSubmissionUpdateInfo(root=_WorkspaceSubmissionUpdateInfo.Traced(type="traced")) + return WorkspaceSubmissionUpdateInfo( + root=_WorkspaceSubmissionUpdateInfo.Traced(type="traced") + ) else: - return WorkspaceSubmissionUpdateInfo(__root__=_WorkspaceSubmissionUpdateInfo.Traced(type="traced")) + return WorkspaceSubmissionUpdateInfo( + __root__=_WorkspaceSubmissionUpdateInfo.Traced(type="traced") + ) def traced_v_2(self, value: WorkspaceTracedUpdate) -> WorkspaceSubmissionUpdateInfo: if IS_PYDANTIC_V2: return WorkspaceSubmissionUpdateInfo( - root=_WorkspaceSubmissionUpdateInfo.TracedV2(**value.dict(exclude_unset=True), type="tracedV2") + root=_WorkspaceSubmissionUpdateInfo.TracedV2( + **value.dict(exclude_unset=True), type="tracedV2" + ) ) else: return WorkspaceSubmissionUpdateInfo( - __root__=_WorkspaceSubmissionUpdateInfo.TracedV2(**value.dict(exclude_unset=True), type="tracedV2") + __root__=_WorkspaceSubmissionUpdateInfo.TracedV2( + **value.dict(exclude_unset=True), type="tracedV2" + ) ) def errored(self, value: ErrorInfo) -> WorkspaceSubmissionUpdateInfo: @@ -66,14 +84,20 @@ def errored(self, value: ErrorInfo) -> WorkspaceSubmissionUpdateInfo: ) else: return WorkspaceSubmissionUpdateInfo( - __root__=_WorkspaceSubmissionUpdateInfo.Errored(type="errored", value=value) + __root__=_WorkspaceSubmissionUpdateInfo.Errored( + type="errored", value=value + ) ) def finished(self) -> WorkspaceSubmissionUpdateInfo: if IS_PYDANTIC_V2: - return WorkspaceSubmissionUpdateInfo(root=_WorkspaceSubmissionUpdateInfo.Finished(type="finished")) + return WorkspaceSubmissionUpdateInfo( + root=_WorkspaceSubmissionUpdateInfo.Finished(type="finished") + ) else: - return WorkspaceSubmissionUpdateInfo(__root__=_WorkspaceSubmissionUpdateInfo.Finished(type="finished")) + return WorkspaceSubmissionUpdateInfo( + __root__=_WorkspaceSubmissionUpdateInfo.Finished(type="finished") + ) class WorkspaceSubmissionUpdateInfo(UniversalRootModel): @@ -105,7 +129,6 @@ def get_as_union( _WorkspaceSubmissionUpdateInfo.Finished, ]: return self.root - else: __root__: typing_extensions.Annotated[ typing.Union[ @@ -147,13 +170,21 @@ def visit( if unioned_value.type == "running": return running(unioned_value.value) if unioned_value.type == "ran": - return ran(WorkspaceRunDetails(**unioned_value.dict(exclude_unset=True, exclude={"type"}))) + return ran( + WorkspaceRunDetails( + **unioned_value.dict(exclude_unset=True, exclude={"type"}) + ) + ) if unioned_value.type == "stopped": return stopped() if unioned_value.type == "traced": return traced() if unioned_value.type == "tracedV2": - return traced_v_2(WorkspaceTracedUpdate(**unioned_value.dict(exclude_unset=True, exclude={"type"}))) + return traced_v_2( + WorkspaceTracedUpdate( + **unioned_value.dict(exclude_unset=True, exclude={"type"}) + ) + ) if unioned_value.type == "errored": return errored(unioned_value.value) if unioned_value.type == "finished": diff --git a/seed/fastapi/trace/resources/submission/types/workspace_submit_request.py b/seed/fastapi/trace/resources/submission/types/workspace_submit_request.py index fa7ccd3e704..a26eaee2600 100644 --- a/seed/fastapi/trace/resources/submission/types/workspace_submit_request.py +++ b/seed/fastapi/trace/resources/submission/types/workspace_submit_request.py @@ -1,23 +1,26 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ....core.pydantic_utilities import UniversalBaseModel +from .submission_id import SubmissionId import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from ...commons.types.language import Language +import typing from .submission_file_info import SubmissionFileInfo -from .submission_id import SubmissionId +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class WorkspaceSubmitRequest(UniversalBaseModel): submission_id: SubmissionId = pydantic.Field(alias="submissionId") language: Language - submission_files: typing.List[SubmissionFileInfo] = pydantic.Field(alias="submissionFiles") + submission_files: typing.List[SubmissionFileInfo] = pydantic.Field( + alias="submissionFiles" + ) user_id: typing.Optional[str] = pydantic.Field(alias="userId", default=None) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/submission/types/workspace_traced_update.py b/seed/fastapi/trace/resources/submission/types/workspace_traced_update.py index b8ff071b8ff..a8bdf683a96 100644 --- a/seed/fastapi/trace/resources/submission/types/workspace_traced_update.py +++ b/seed/fastapi/trace/resources/submission/types/workspace_traced_update.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ....core.pydantic_utilities import UniversalBaseModel import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class WorkspaceTracedUpdate(UniversalBaseModel): trace_responses_size: int = pydantic.Field(alias="traceResponsesSize") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/sysprop/service/service.py b/seed/fastapi/trace/resources/sysprop/service/service.py index 4c65874a73b..29c728f77c3 100644 --- a/seed/fastapi/trace/resources/sysprop/service/service.py +++ b/seed/fastapi/trace/resources/sysprop/service/service.py @@ -1,18 +1,16 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.abstract_fern_service import AbstractFernService +from ...commons.types.language import Language +import typing import abc -import functools +import fastapi import inspect +from ....core.exceptions.fern_http_exception import FernHTTPException import logging -import typing - -import fastapi +import functools import starlette - -from ....core.abstract_fern_service import AbstractFernService -from ....core.exceptions.fern_http_exception import FernHTTPException from ....core.route_args import get_route_args -from ...commons.types.language import Language class AbstractSyspropService(AbstractFernService): @@ -26,13 +24,17 @@ class AbstractSyspropService(AbstractFernService): @abc.abstractmethod def set_num_warm_instances( - self, *, language: Language, num_warm_instances: int, x_random_header: typing.Optional[str] = None - ) -> None: - ... + self, + *, + language: Language, + num_warm_instances: int, + x_random_header: typing.Optional[str] = None, + ) -> None: ... @abc.abstractmethod - def get_num_warm_instances(self, *, x_random_header: typing.Optional[str] = None) -> typing.Dict[Language, int]: - ... + def get_num_warm_instances( + self, *, x_random_header: typing.Optional[str] = None + ) -> typing.Dict[Language, int]: ... """ Below are internal methods used by Fern to register your implementation. @@ -48,7 +50,9 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_set_num_warm_instances(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.set_num_warm_instances) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "language": @@ -56,10 +60,18 @@ def __init_set_num_warm_instances(cls, router: fastapi.APIRouter) -> None: elif parameter_name == "num_warm_instances": new_parameters.append(parameter.replace(default=fastapi.Path(...))) elif parameter_name == "x_random_header": - new_parameters.append(parameter.replace(default=fastapi.Header(default=None, alias="X-Random-Header"))) + new_parameters.append( + parameter.replace( + default=fastapi.Header(default=None, alias="X-Random-Header") + ) + ) else: new_parameters.append(parameter) - setattr(cls.set_num_warm_instances, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.set_num_warm_instances, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.set_num_warm_instances) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> None: @@ -89,17 +101,29 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> None: def __init_get_num_warm_instances(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_num_warm_instances) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "x_random_header": - new_parameters.append(parameter.replace(default=fastapi.Header(default=None, alias="X-Random-Header"))) + new_parameters.append( + parameter.replace( + default=fastapi.Header(default=None, alias="X-Random-Header") + ) + ) else: new_parameters.append(parameter) - setattr(cls.get_num_warm_instances, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_num_warm_instances, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_num_warm_instances) - def wrapper(*args: typing.Any, **kwargs: typing.Any) -> typing.Dict[Language, int]: + def wrapper( + *args: typing.Any, **kwargs: typing.Any + ) -> typing.Dict[Language, int]: try: return cls.get_num_warm_instances(*args, **kwargs) except FernHTTPException as e: diff --git a/seed/fastapi/trace/resources/v_2/resources/problem/service/service.py b/seed/fastapi/trace/resources/v_2/resources/problem/service/service.py index ef5f8b95ebc..a6402d18864 100644 --- a/seed/fastapi/trace/resources/v_2/resources/problem/service/service.py +++ b/seed/fastapi/trace/resources/v_2/resources/problem/service/service.py @@ -1,18 +1,16 @@ # This file was auto-generated by Fern from our API Definition. -import abc -import functools -import inspect -import logging +from ......core.abstract_fern_service import AbstractFernService import typing - +from ..types.lightweight_problem_info_v_2 import LightweightProblemInfoV2 +import abc +from ..types.problem_info_v_2 import ProblemInfoV2 import fastapi - -from ......core.abstract_fern_service import AbstractFernService +import inspect from ......core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools from ......core.route_args import get_route_args -from ..types.lightweight_problem_info_v_2 import LightweightProblemInfoV2 -from ..types.problem_info_v_2 import ProblemInfoV2 class AbstractV2ProblemService(AbstractFernService): @@ -34,14 +32,18 @@ def get_lightweight_problems( ... @abc.abstractmethod - def get_problems(self, *, x_random_header: typing.Optional[str] = None) -> typing.Sequence[ProblemInfoV2]: + def get_problems( + self, *, x_random_header: typing.Optional[str] = None + ) -> typing.Sequence[ProblemInfoV2]: """ Returns latest versions of all problems """ ... @abc.abstractmethod - def get_latest_problem(self, *, problem_id: str, x_random_header: typing.Optional[str] = None) -> ProblemInfoV2: + def get_latest_problem( + self, *, problem_id: str, x_random_header: typing.Optional[str] = None + ) -> ProblemInfoV2: """ Returns latest version of a problem """ @@ -49,7 +51,11 @@ def get_latest_problem(self, *, problem_id: str, x_random_header: typing.Optiona @abc.abstractmethod def get_problem_version( - self, *, problem_id: str, problem_version: int, x_random_header: typing.Optional[str] = None + self, + *, + problem_id: str, + problem_version: int, + x_random_header: typing.Optional[str] = None, ) -> ProblemInfoV2: """ Returns requested version of a problem @@ -72,17 +78,29 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_get_lightweight_problems(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_lightweight_problems) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "x_random_header": - new_parameters.append(parameter.replace(default=fastapi.Header(default=None, alias="X-Random-Header"))) + new_parameters.append( + parameter.replace( + default=fastapi.Header(default=None, alias="X-Random-Header") + ) + ) else: new_parameters.append(parameter) - setattr(cls.get_lightweight_problems, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_lightweight_problems, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_lightweight_problems) - def wrapper(*args: typing.Any, **kwargs: typing.Any) -> typing.Sequence[LightweightProblemInfoV2]: + def wrapper( + *args: typing.Any, **kwargs: typing.Any + ) -> typing.Sequence[LightweightProblemInfoV2]: try: return cls.get_lightweight_problems(*args, **kwargs) except FernHTTPException as e: @@ -108,17 +126,29 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> typing.Sequence[Lightwei def __init_get_problems(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_problems) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "x_random_header": - new_parameters.append(parameter.replace(default=fastapi.Header(default=None, alias="X-Random-Header"))) + new_parameters.append( + parameter.replace( + default=fastapi.Header(default=None, alias="X-Random-Header") + ) + ) else: new_parameters.append(parameter) - setattr(cls.get_problems, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_problems, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_problems) - def wrapper(*args: typing.Any, **kwargs: typing.Any) -> typing.Sequence[ProblemInfoV2]: + def wrapper( + *args: typing.Any, **kwargs: typing.Any + ) -> typing.Sequence[ProblemInfoV2]: try: return cls.get_problems(*args, **kwargs) except FernHTTPException as e: @@ -144,16 +174,26 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> typing.Sequence[ProblemI def __init_get_latest_problem(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_latest_problem) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "problem_id": new_parameters.append(parameter.replace(default=fastapi.Path(...))) elif parameter_name == "x_random_header": - new_parameters.append(parameter.replace(default=fastapi.Header(default=None, alias="X-Random-Header"))) + new_parameters.append( + parameter.replace( + default=fastapi.Header(default=None, alias="X-Random-Header") + ) + ) else: new_parameters.append(parameter) - setattr(cls.get_latest_problem, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_latest_problem, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_latest_problem) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> ProblemInfoV2: @@ -182,7 +222,9 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> ProblemInfoV2: def __init_get_problem_version(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_problem_version) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "problem_id": @@ -190,10 +232,18 @@ def __init_get_problem_version(cls, router: fastapi.APIRouter) -> None: elif parameter_name == "problem_version": new_parameters.append(parameter.replace(default=fastapi.Path(...))) elif parameter_name == "x_random_header": - new_parameters.append(parameter.replace(default=fastapi.Header(default=None, alias="X-Random-Header"))) + new_parameters.append( + parameter.replace( + default=fastapi.Header(default=None, alias="X-Random-Header") + ) + ) else: new_parameters.append(parameter) - setattr(cls.get_problem_version, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_problem_version, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_problem_version) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> ProblemInfoV2: diff --git a/seed/fastapi/trace/resources/v_2/resources/problem/types/__init__.py b/seed/fastapi/trace/resources/v_2/resources/problem/types/__init__.py index 618e6aa9c52..f86d943b7a1 100644 --- a/seed/fastapi/trace/resources/v_2/resources/problem/types/__init__.py +++ b/seed/fastapi/trace/resources/v_2/resources/problem/types/__init__.py @@ -10,7 +10,9 @@ from .file_info_v_2 import FileInfoV2 from .files import Files from .function_implementation import FunctionImplementation -from .function_implementation_for_multiple_languages import FunctionImplementationForMultipleLanguages +from .function_implementation_for_multiple_languages import ( + FunctionImplementationForMultipleLanguages, +) from .function_signature import FunctionSignature from .generated_files import GeneratedFiles from .get_basic_solution_file_request import GetBasicSolutionFileRequest @@ -18,7 +20,9 @@ from .get_function_signature_request import GetFunctionSignatureRequest from .get_function_signature_response import GetFunctionSignatureResponse from .get_generated_test_case_file_request import GetGeneratedTestCaseFileRequest -from .get_generated_test_case_template_file_request import GetGeneratedTestCaseTemplateFileRequest +from .get_generated_test_case_template_file_request import ( + GetGeneratedTestCaseTemplateFileRequest, +) from .lightweight_problem_info_v_2 import LightweightProblemInfoV2 from .non_void_function_definition import NonVoidFunctionDefinition from .non_void_function_signature import NonVoidFunctionSignature @@ -30,17 +34,25 @@ from .test_case_id import TestCaseId from .test_case_implementation import TestCaseImplementation from .test_case_implementation_description import TestCaseImplementationDescription -from .test_case_implementation_description_board import TestCaseImplementationDescriptionBoard +from .test_case_implementation_description_board import ( + TestCaseImplementationDescriptionBoard, +) from .test_case_implementation_reference import TestCaseImplementationReference from .test_case_metadata import TestCaseMetadata from .test_case_template import TestCaseTemplate from .test_case_template_id import TestCaseTemplateId from .test_case_v_2 import TestCaseV2 -from .test_case_with_actual_result_implementation import TestCaseWithActualResultImplementation +from .test_case_with_actual_result_implementation import ( + TestCaseWithActualResultImplementation, +) from .void_function_definition import VoidFunctionDefinition -from .void_function_definition_that_takes_actual_result import VoidFunctionDefinitionThatTakesActualResult +from .void_function_definition_that_takes_actual_result import ( + VoidFunctionDefinitionThatTakesActualResult, +) from .void_function_signature import VoidFunctionSignature -from .void_function_signature_that_takes_actual_result import VoidFunctionSignatureThatTakesActualResult +from .void_function_signature_that_takes_actual_result import ( + VoidFunctionSignatureThatTakesActualResult, +) __all__ = [ "AssertCorrectnessCheck", diff --git a/seed/fastapi/trace/resources/v_2/resources/problem/types/assert_correctness_check.py b/seed/fastapi/trace/resources/v_2/resources/problem/types/assert_correctness_check.py index 7ba9544b4ff..5b63af5126f 100644 --- a/seed/fastapi/trace/resources/v_2/resources/problem/types/assert_correctness_check.py +++ b/seed/fastapi/trace/resources/v_2/resources/problem/types/assert_correctness_check.py @@ -1,38 +1,51 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from .deep_equality_correctness_check import DeepEqualityCorrectnessCheck +from ......core.pydantic_utilities import IS_PYDANTIC_V2 +from .void_function_definition_that_takes_actual_result import ( + VoidFunctionDefinitionThatTakesActualResult, +) +from ......core.pydantic_utilities import UniversalRootModel import typing - -import pydantic import typing_extensions - -from ......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalRootModel, update_forward_refs -from .deep_equality_correctness_check import DeepEqualityCorrectnessCheck -from .void_function_definition_that_takes_actual_result import VoidFunctionDefinitionThatTakesActualResult +import pydantic +from ......core.pydantic_utilities import update_forward_refs T_Result = typing.TypeVar("T_Result") class _Factory: - def deep_equality(self, value: DeepEqualityCorrectnessCheck) -> AssertCorrectnessCheck: + def deep_equality( + self, value: DeepEqualityCorrectnessCheck + ) -> AssertCorrectnessCheck: if IS_PYDANTIC_V2: return AssertCorrectnessCheck( - root=_AssertCorrectnessCheck.DeepEquality(**value.dict(exclude_unset=True), type="deepEquality") + root=_AssertCorrectnessCheck.DeepEquality( + **value.dict(exclude_unset=True), type="deepEquality" + ) ) else: return AssertCorrectnessCheck( - __root__=_AssertCorrectnessCheck.DeepEquality(**value.dict(exclude_unset=True), type="deepEquality") + __root__=_AssertCorrectnessCheck.DeepEquality( + **value.dict(exclude_unset=True), type="deepEquality" + ) ) - def custom(self, value: VoidFunctionDefinitionThatTakesActualResult) -> AssertCorrectnessCheck: + def custom( + self, value: VoidFunctionDefinitionThatTakesActualResult + ) -> AssertCorrectnessCheck: if IS_PYDANTIC_V2: return AssertCorrectnessCheck( - root=_AssertCorrectnessCheck.Custom(**value.dict(exclude_unset=True), type="custom") + root=_AssertCorrectnessCheck.Custom( + **value.dict(exclude_unset=True), type="custom" + ) ) else: return AssertCorrectnessCheck( - __root__=_AssertCorrectnessCheck.Custom(**value.dict(exclude_unset=True), type="custom") + __root__=_AssertCorrectnessCheck.Custom( + **value.dict(exclude_unset=True), type="custom" + ) ) @@ -41,35 +54,52 @@ class AssertCorrectnessCheck(UniversalRootModel): if IS_PYDANTIC_V2: root: typing_extensions.Annotated[ - typing.Union[_AssertCorrectnessCheck.DeepEquality, _AssertCorrectnessCheck.Custom], + typing.Union[ + _AssertCorrectnessCheck.DeepEquality, _AssertCorrectnessCheck.Custom + ], pydantic.Field(discriminator="type"), ] - def get_as_union(self) -> typing.Union[_AssertCorrectnessCheck.DeepEquality, _AssertCorrectnessCheck.Custom]: + def get_as_union( + self, + ) -> typing.Union[ + _AssertCorrectnessCheck.DeepEquality, _AssertCorrectnessCheck.Custom + ]: return self.root - else: __root__: typing_extensions.Annotated[ - typing.Union[_AssertCorrectnessCheck.DeepEquality, _AssertCorrectnessCheck.Custom], + typing.Union[ + _AssertCorrectnessCheck.DeepEquality, _AssertCorrectnessCheck.Custom + ], pydantic.Field(discriminator="type"), ] - def get_as_union(self) -> typing.Union[_AssertCorrectnessCheck.DeepEquality, _AssertCorrectnessCheck.Custom]: + def get_as_union( + self, + ) -> typing.Union[ + _AssertCorrectnessCheck.DeepEquality, _AssertCorrectnessCheck.Custom + ]: return self.__root__ def visit( self, deep_equality: typing.Callable[[DeepEqualityCorrectnessCheck], T_Result], - custom: typing.Callable[[VoidFunctionDefinitionThatTakesActualResult], T_Result], + custom: typing.Callable[ + [VoidFunctionDefinitionThatTakesActualResult], T_Result + ], ) -> T_Result: unioned_value = self.get_as_union() if unioned_value.type == "deepEquality": return deep_equality( - DeepEqualityCorrectnessCheck(**unioned_value.dict(exclude_unset=True, exclude={"type"})) + DeepEqualityCorrectnessCheck( + **unioned_value.dict(exclude_unset=True, exclude={"type"}) + ) ) if unioned_value.type == "custom": return custom( - VoidFunctionDefinitionThatTakesActualResult(**unioned_value.dict(exclude_unset=True, exclude={"type"})) + VoidFunctionDefinitionThatTakesActualResult( + **unioned_value.dict(exclude_unset=True, exclude={"type"}) + ) ) diff --git a/seed/fastapi/trace/resources/v_2/resources/problem/types/basic_custom_files.py b/seed/fastapi/trace/resources/v_2/resources/problem/types/basic_custom_files.py index 28ed1846e0a..fd23f7c4b5b 100644 --- a/seed/fastapi/trace/resources/v_2/resources/problem/types/basic_custom_files.py +++ b/seed/fastapi/trace/resources/v_2/resources/problem/types/basic_custom_files.py @@ -1,24 +1,29 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ......core.pydantic_utilities import UniversalBaseModel import pydantic - -from ......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from .non_void_function_signature import NonVoidFunctionSignature +import typing from .....commons.types.language import Language -from .basic_test_case_template import BasicTestCaseTemplate from .files import Files -from .non_void_function_signature import NonVoidFunctionSignature +from .basic_test_case_template import BasicTestCaseTemplate +from ......core.pydantic_utilities import IS_PYDANTIC_V2 class BasicCustomFiles(UniversalBaseModel): method_name: str = pydantic.Field(alias="methodName") signature: NonVoidFunctionSignature - additional_files: typing.Dict[Language, Files] = pydantic.Field(alias="additionalFiles") - basic_test_case_template: BasicTestCaseTemplate = pydantic.Field(alias="basicTestCaseTemplate") + additional_files: typing.Dict[Language, Files] = pydantic.Field( + alias="additionalFiles" + ) + basic_test_case_template: BasicTestCaseTemplate = pydantic.Field( + alias="basicTestCaseTemplate" + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/v_2/resources/problem/types/basic_test_case_template.py b/seed/fastapi/trace/resources/v_2/resources/problem/types/basic_test_case_template.py index 96dc879f6c4..2a783b9b2b8 100644 --- a/seed/fastapi/trace/resources/v_2/resources/problem/types/basic_test_case_template.py +++ b/seed/fastapi/trace/resources/v_2/resources/problem/types/basic_test_case_template.py @@ -1,23 +1,26 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ......core.pydantic_utilities import UniversalBaseModel +from .test_case_template_id import TestCaseTemplateId import pydantic - -from ......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .parameter_id import ParameterId from .test_case_implementation_description import TestCaseImplementationDescription -from .test_case_template_id import TestCaseTemplateId +from .parameter_id import ParameterId +from ......core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class BasicTestCaseTemplate(UniversalBaseModel): template_id: TestCaseTemplateId = pydantic.Field(alias="templateId") name: str description: TestCaseImplementationDescription - expected_value_parameter_id: ParameterId = pydantic.Field(alias="expectedValueParameterId") + expected_value_parameter_id: ParameterId = pydantic.Field( + alias="expectedValueParameterId" + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/v_2/resources/problem/types/create_problem_request_v_2.py b/seed/fastapi/trace/resources/v_2/resources/problem/types/create_problem_request_v_2.py index dcbba46935b..9db2dd7188e 100644 --- a/seed/fastapi/trace/resources/v_2/resources/problem/types/create_problem_request_v_2.py +++ b/seed/fastapi/trace/resources/v_2/resources/problem/types/create_problem_request_v_2.py @@ -1,28 +1,33 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ......core.pydantic_utilities import UniversalBaseModel import pydantic - -from ......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .....commons.types.language import Language from .....problem.types.problem_description import ProblemDescription from .custom_files import CustomFiles +import typing from .test_case_template import TestCaseTemplate from .test_case_v_2 import TestCaseV2 +from .....commons.types.language import Language +from ......core.pydantic_utilities import IS_PYDANTIC_V2 class CreateProblemRequestV2(UniversalBaseModel): problem_name: str = pydantic.Field(alias="problemName") problem_description: ProblemDescription = pydantic.Field(alias="problemDescription") custom_files: CustomFiles = pydantic.Field(alias="customFiles") - custom_test_case_templates: typing.List[TestCaseTemplate] = pydantic.Field(alias="customTestCaseTemplates") + custom_test_case_templates: typing.List[TestCaseTemplate] = pydantic.Field( + alias="customTestCaseTemplates" + ) testcases: typing.List[TestCaseV2] - supported_languages: typing.Set[Language] = pydantic.Field(alias="supportedLanguages") + supported_languages: typing.Set[Language] = pydantic.Field( + alias="supportedLanguages" + ) is_public: bool = pydantic.Field(alias="isPublic") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/v_2/resources/problem/types/custom_files.py b/seed/fastapi/trace/resources/v_2/resources/problem/types/custom_files.py index 36763eb62fe..7b1710becec 100644 --- a/seed/fastapi/trace/resources/v_2/resources/problem/types/custom_files.py +++ b/seed/fastapi/trace/resources/v_2/resources/problem/types/custom_files.py @@ -1,16 +1,16 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from .basic_custom_files import BasicCustomFiles +from ......core.pydantic_utilities import IS_PYDANTIC_V2 import typing - -import pydantic -import typing_extensions - -from ......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel, UniversalRootModel, update_forward_refs from .....commons.types.language import Language -from .basic_custom_files import BasicCustomFiles from .files import Files +from ......core.pydantic_utilities import UniversalRootModel +import typing_extensions +import pydantic +from ......core.pydantic_utilities import UniversalBaseModel +from ......core.pydantic_utilities import update_forward_refs T_Result = typing.TypeVar("T_Result") @@ -18,9 +18,15 @@ class _Factory: def basic(self, value: BasicCustomFiles) -> CustomFiles: if IS_PYDANTIC_V2: - return CustomFiles(root=_CustomFiles.Basic(**value.dict(exclude_unset=True), type="basic")) + return CustomFiles( + root=_CustomFiles.Basic(**value.dict(exclude_unset=True), type="basic") + ) else: - return CustomFiles(__root__=_CustomFiles.Basic(**value.dict(exclude_unset=True), type="basic")) + return CustomFiles( + __root__=_CustomFiles.Basic( + **value.dict(exclude_unset=True), type="basic" + ) + ) def custom(self, value: typing.Dict[Language, Files]) -> CustomFiles: if IS_PYDANTIC_V2: @@ -34,15 +40,16 @@ class CustomFiles(UniversalRootModel): if IS_PYDANTIC_V2: root: typing_extensions.Annotated[ - typing.Union[_CustomFiles.Basic, _CustomFiles.Custom], pydantic.Field(discriminator="type") + typing.Union[_CustomFiles.Basic, _CustomFiles.Custom], + pydantic.Field(discriminator="type"), ] def get_as_union(self) -> typing.Union[_CustomFiles.Basic, _CustomFiles.Custom]: return self.root - else: __root__: typing_extensions.Annotated[ - typing.Union[_CustomFiles.Basic, _CustomFiles.Custom], pydantic.Field(discriminator="type") + typing.Union[_CustomFiles.Basic, _CustomFiles.Custom], + pydantic.Field(discriminator="type"), ] def get_as_union(self) -> typing.Union[_CustomFiles.Basic, _CustomFiles.Custom]: @@ -55,7 +62,11 @@ def visit( ) -> T_Result: unioned_value = self.get_as_union() if unioned_value.type == "basic": - return basic(BasicCustomFiles(**unioned_value.dict(exclude_unset=True, exclude={"type"}))) + return basic( + BasicCustomFiles( + **unioned_value.dict(exclude_unset=True, exclude={"type"}) + ) + ) if unioned_value.type == "custom": return custom(unioned_value.value) diff --git a/seed/fastapi/trace/resources/v_2/resources/problem/types/deep_equality_correctness_check.py b/seed/fastapi/trace/resources/v_2/resources/problem/types/deep_equality_correctness_check.py index 28aa7f44719..3319d82b41f 100644 --- a/seed/fastapi/trace/resources/v_2/resources/problem/types/deep_equality_correctness_check.py +++ b/seed/fastapi/trace/resources/v_2/resources/problem/types/deep_equality_correctness_check.py @@ -1,18 +1,21 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ......core.pydantic_utilities import UniversalBaseModel from .parameter_id import ParameterId +import pydantic +from ......core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class DeepEqualityCorrectnessCheck(UniversalBaseModel): - expected_value_parameter_id: ParameterId = pydantic.Field(alias="expectedValueParameterId") + expected_value_parameter_id: ParameterId = pydantic.Field( + alias="expectedValueParameterId" + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/v_2/resources/problem/types/default_provided_file.py b/seed/fastapi/trace/resources/v_2/resources/problem/types/default_provided_file.py index 8df27ac6d43..83b6c4de9e4 100644 --- a/seed/fastapi/trace/resources/v_2/resources/problem/types/default_provided_file.py +++ b/seed/fastapi/trace/resources/v_2/resources/problem/types/default_provided_file.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. +from ......core.pydantic_utilities import UniversalBaseModel +from .file_info_v_2 import FileInfoV2 import typing - -import pydantic - -from ......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .....commons.types.variable_type import VariableType -from .file_info_v_2 import FileInfoV2 +import pydantic +from ......core.pydantic_utilities import IS_PYDANTIC_V2 class DefaultProvidedFile(UniversalBaseModel): @@ -14,7 +13,9 @@ class DefaultProvidedFile(UniversalBaseModel): related_types: typing.List[VariableType] = pydantic.Field(alias="relatedTypes") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/v_2/resources/problem/types/file_info_v_2.py b/seed/fastapi/trace/resources/v_2/resources/problem/types/file_info_v_2.py index d1bce8ce84d..118d8514f34 100644 --- a/seed/fastapi/trace/resources/v_2/resources/problem/types/file_info_v_2.py +++ b/seed/fastapi/trace/resources/v_2/resources/problem/types/file_info_v_2.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from ......core.pydantic_utilities import UniversalBaseModel +from ......core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class FileInfoV2(UniversalBaseModel): filename: str @@ -14,7 +13,9 @@ class FileInfoV2(UniversalBaseModel): editable: bool if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/v_2/resources/problem/types/files.py b/seed/fastapi/trace/resources/v_2/resources/problem/types/files.py index 66dc9c13ee8..a319d9cc409 100644 --- a/seed/fastapi/trace/resources/v_2/resources/problem/types/files.py +++ b/seed/fastapi/trace/resources/v_2/resources/problem/types/files.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from ......core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .file_info_v_2 import FileInfoV2 +from ......core.pydantic_utilities import IS_PYDANTIC_V2 +import pydantic class Files(UniversalBaseModel): files: typing.List[FileInfoV2] if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/v_2/resources/problem/types/function_implementation.py b/seed/fastapi/trace/resources/v_2/resources/problem/types/function_implementation.py index b2520e16f84..ad9b3cf1148 100644 --- a/seed/fastapi/trace/resources/v_2/resources/problem/types/function_implementation.py +++ b/seed/fastapi/trace/resources/v_2/resources/problem/types/function_implementation.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from ......core.pydantic_utilities import UniversalBaseModel import typing - +from ......core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class FunctionImplementation(UniversalBaseModel): impl: str imports: typing.Optional[str] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/v_2/resources/problem/types/function_implementation_for_multiple_languages.py b/seed/fastapi/trace/resources/v_2/resources/problem/types/function_implementation_for_multiple_languages.py index ab9c5f4bbe9..885dad83d2c 100644 --- a/seed/fastapi/trace/resources/v_2/resources/problem/types/function_implementation_for_multiple_languages.py +++ b/seed/fastapi/trace/resources/v_2/resources/problem/types/function_implementation_for_multiple_languages.py @@ -1,19 +1,22 @@ # This file was auto-generated by Fern from our API Definition. +from ......core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .....commons.types.language import Language from .function_implementation import FunctionImplementation +import pydantic +from ......core.pydantic_utilities import IS_PYDANTIC_V2 class FunctionImplementationForMultipleLanguages(UniversalBaseModel): - code_by_language: typing.Dict[Language, FunctionImplementation] = pydantic.Field(alias="codeByLanguage") + code_by_language: typing.Dict[Language, FunctionImplementation] = pydantic.Field( + alias="codeByLanguage" + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/v_2/resources/problem/types/function_signature.py b/seed/fastapi/trace/resources/v_2/resources/problem/types/function_signature.py index 9a8baf6717f..cbc817f03cd 100644 --- a/seed/fastapi/trace/resources/v_2/resources/problem/types/function_signature.py +++ b/seed/fastapi/trace/resources/v_2/resources/problem/types/function_signature.py @@ -1,16 +1,17 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from .void_function_signature import VoidFunctionSignature +from ......core.pydantic_utilities import IS_PYDANTIC_V2 +from .non_void_function_signature import NonVoidFunctionSignature +from .void_function_signature_that_takes_actual_result import ( + VoidFunctionSignatureThatTakesActualResult, +) +from ......core.pydantic_utilities import UniversalRootModel import typing - -import pydantic import typing_extensions - -from ......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalRootModel, update_forward_refs -from .non_void_function_signature import NonVoidFunctionSignature -from .void_function_signature import VoidFunctionSignature -from .void_function_signature_that_takes_actual_result import VoidFunctionSignatureThatTakesActualResult +import pydantic +from ......core.pydantic_utilities import update_forward_refs T_Result = typing.TypeVar("T_Result") @@ -18,19 +19,35 @@ class _Factory: def void(self, value: VoidFunctionSignature) -> FunctionSignature: if IS_PYDANTIC_V2: - return FunctionSignature(root=_FunctionSignature.Void(**value.dict(exclude_unset=True), type="void")) + return FunctionSignature( + root=_FunctionSignature.Void( + **value.dict(exclude_unset=True), type="void" + ) + ) else: - return FunctionSignature(__root__=_FunctionSignature.Void(**value.dict(exclude_unset=True), type="void")) + return FunctionSignature( + __root__=_FunctionSignature.Void( + **value.dict(exclude_unset=True), type="void" + ) + ) def non_void(self, value: NonVoidFunctionSignature) -> FunctionSignature: if IS_PYDANTIC_V2: - return FunctionSignature(root=_FunctionSignature.NonVoid(**value.dict(exclude_unset=True), type="nonVoid")) + return FunctionSignature( + root=_FunctionSignature.NonVoid( + **value.dict(exclude_unset=True), type="nonVoid" + ) + ) else: return FunctionSignature( - __root__=_FunctionSignature.NonVoid(**value.dict(exclude_unset=True), type="nonVoid") + __root__=_FunctionSignature.NonVoid( + **value.dict(exclude_unset=True), type="nonVoid" + ) ) - def void_that_takes_actual_result(self, value: VoidFunctionSignatureThatTakesActualResult) -> FunctionSignature: + def void_that_takes_actual_result( + self, value: VoidFunctionSignatureThatTakesActualResult + ) -> FunctionSignature: if IS_PYDANTIC_V2: return FunctionSignature( root=_FunctionSignature.VoidThatTakesActualResult( @@ -51,7 +68,9 @@ class FunctionSignature(UniversalRootModel): if IS_PYDANTIC_V2: root: typing_extensions.Annotated[ typing.Union[ - _FunctionSignature.Void, _FunctionSignature.NonVoid, _FunctionSignature.VoidThatTakesActualResult + _FunctionSignature.Void, + _FunctionSignature.NonVoid, + _FunctionSignature.VoidThatTakesActualResult, ], pydantic.Field(discriminator="type"), ] @@ -59,14 +78,17 @@ class FunctionSignature(UniversalRootModel): def get_as_union( self, ) -> typing.Union[ - _FunctionSignature.Void, _FunctionSignature.NonVoid, _FunctionSignature.VoidThatTakesActualResult + _FunctionSignature.Void, + _FunctionSignature.NonVoid, + _FunctionSignature.VoidThatTakesActualResult, ]: return self.root - else: __root__: typing_extensions.Annotated[ typing.Union[ - _FunctionSignature.Void, _FunctionSignature.NonVoid, _FunctionSignature.VoidThatTakesActualResult + _FunctionSignature.Void, + _FunctionSignature.NonVoid, + _FunctionSignature.VoidThatTakesActualResult, ], pydantic.Field(discriminator="type"), ] @@ -74,7 +96,9 @@ def get_as_union( def get_as_union( self, ) -> typing.Union[ - _FunctionSignature.Void, _FunctionSignature.NonVoid, _FunctionSignature.VoidThatTakesActualResult + _FunctionSignature.Void, + _FunctionSignature.NonVoid, + _FunctionSignature.VoidThatTakesActualResult, ]: return self.__root__ @@ -82,16 +106,28 @@ def visit( self, void: typing.Callable[[VoidFunctionSignature], T_Result], non_void: typing.Callable[[NonVoidFunctionSignature], T_Result], - void_that_takes_actual_result: typing.Callable[[VoidFunctionSignatureThatTakesActualResult], T_Result], + void_that_takes_actual_result: typing.Callable[ + [VoidFunctionSignatureThatTakesActualResult], T_Result + ], ) -> T_Result: unioned_value = self.get_as_union() if unioned_value.type == "void": - return void(VoidFunctionSignature(**unioned_value.dict(exclude_unset=True, exclude={"type"}))) + return void( + VoidFunctionSignature( + **unioned_value.dict(exclude_unset=True, exclude={"type"}) + ) + ) if unioned_value.type == "nonVoid": - return non_void(NonVoidFunctionSignature(**unioned_value.dict(exclude_unset=True, exclude={"type"}))) + return non_void( + NonVoidFunctionSignature( + **unioned_value.dict(exclude_unset=True, exclude={"type"}) + ) + ) if unioned_value.type == "voidThatTakesActualResult": return void_that_takes_actual_result( - VoidFunctionSignatureThatTakesActualResult(**unioned_value.dict(exclude_unset=True, exclude={"type"})) + VoidFunctionSignatureThatTakesActualResult( + **unioned_value.dict(exclude_unset=True, exclude={"type"}) + ) ) diff --git a/seed/fastapi/trace/resources/v_2/resources/problem/types/generated_files.py b/seed/fastapi/trace/resources/v_2/resources/problem/types/generated_files.py index 30c0ea0bfef..0a3d40c56ef 100644 --- a/seed/fastapi/trace/resources/v_2/resources/problem/types/generated_files.py +++ b/seed/fastapi/trace/resources/v_2/resources/problem/types/generated_files.py @@ -1,21 +1,26 @@ # This file was auto-generated by Fern from our API Definition. +from ......core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .....commons.types.language import Language from .files import Files +import pydantic +from ......core.pydantic_utilities import IS_PYDANTIC_V2 class GeneratedFiles(UniversalBaseModel): - generated_test_case_files: typing.Dict[Language, Files] = pydantic.Field(alias="generatedTestCaseFiles") - generated_template_files: typing.Dict[Language, Files] = pydantic.Field(alias="generatedTemplateFiles") + generated_test_case_files: typing.Dict[Language, Files] = pydantic.Field( + alias="generatedTestCaseFiles" + ) + generated_template_files: typing.Dict[Language, Files] = pydantic.Field( + alias="generatedTemplateFiles" + ) other: typing.Dict[Language, Files] if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/v_2/resources/problem/types/get_basic_solution_file_request.py b/seed/fastapi/trace/resources/v_2/resources/problem/types/get_basic_solution_file_request.py index 7d3af6be915..0308d669e4e 100644 --- a/seed/fastapi/trace/resources/v_2/resources/problem/types/get_basic_solution_file_request.py +++ b/seed/fastapi/trace/resources/v_2/resources/problem/types/get_basic_solution_file_request.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ......core.pydantic_utilities import UniversalBaseModel import pydantic - -from ......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .non_void_function_signature import NonVoidFunctionSignature +from ......core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class GetBasicSolutionFileRequest(UniversalBaseModel): @@ -13,7 +12,9 @@ class GetBasicSolutionFileRequest(UniversalBaseModel): signature: NonVoidFunctionSignature if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/v_2/resources/problem/types/get_basic_solution_file_response.py b/seed/fastapi/trace/resources/v_2/resources/problem/types/get_basic_solution_file_response.py index 638d8416678..01a867c570a 100644 --- a/seed/fastapi/trace/resources/v_2/resources/problem/types/get_basic_solution_file_response.py +++ b/seed/fastapi/trace/resources/v_2/resources/problem/types/get_basic_solution_file_response.py @@ -1,19 +1,22 @@ # This file was auto-generated by Fern from our API Definition. +from ......core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .....commons.types.language import Language from .file_info_v_2 import FileInfoV2 +import pydantic +from ......core.pydantic_utilities import IS_PYDANTIC_V2 class GetBasicSolutionFileResponse(UniversalBaseModel): - solution_file_by_language: typing.Dict[Language, FileInfoV2] = pydantic.Field(alias="solutionFileByLanguage") + solution_file_by_language: typing.Dict[Language, FileInfoV2] = pydantic.Field( + alias="solutionFileByLanguage" + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/v_2/resources/problem/types/get_function_signature_request.py b/seed/fastapi/trace/resources/v_2/resources/problem/types/get_function_signature_request.py index 23a8fbe870c..9a53e9ab953 100644 --- a/seed/fastapi/trace/resources/v_2/resources/problem/types/get_function_signature_request.py +++ b/seed/fastapi/trace/resources/v_2/resources/problem/types/get_function_signature_request.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ......core.pydantic_utilities import UniversalBaseModel from .function_signature import FunctionSignature +import pydantic +from ......core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class GetFunctionSignatureRequest(UniversalBaseModel): function_signature: FunctionSignature = pydantic.Field(alias="functionSignature") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/v_2/resources/problem/types/get_function_signature_response.py b/seed/fastapi/trace/resources/v_2/resources/problem/types/get_function_signature_response.py index 5c4233ade34..7189e0a985f 100644 --- a/seed/fastapi/trace/resources/v_2/resources/problem/types/get_function_signature_response.py +++ b/seed/fastapi/trace/resources/v_2/resources/problem/types/get_function_signature_response.py @@ -1,18 +1,21 @@ # This file was auto-generated by Fern from our API Definition. +from ......core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .....commons.types.language import Language +import pydantic +from ......core.pydantic_utilities import IS_PYDANTIC_V2 class GetFunctionSignatureResponse(UniversalBaseModel): - function_by_language: typing.Dict[Language, str] = pydantic.Field(alias="functionByLanguage") + function_by_language: typing.Dict[Language, str] = pydantic.Field( + alias="functionByLanguage" + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/v_2/resources/problem/types/get_generated_test_case_file_request.py b/seed/fastapi/trace/resources/v_2/resources/problem/types/get_generated_test_case_file_request.py index 1cb853571a1..0b78e0dbfa4 100644 --- a/seed/fastapi/trace/resources/v_2/resources/problem/types/get_generated_test_case_file_request.py +++ b/seed/fastapi/trace/resources/v_2/resources/problem/types/get_generated_test_case_file_request.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. +from ......core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .test_case_template import TestCaseTemplate from .test_case_v_2 import TestCaseV2 +import pydantic +from ......core.pydantic_utilities import IS_PYDANTIC_V2 class GetGeneratedTestCaseFileRequest(UniversalBaseModel): @@ -14,7 +13,9 @@ class GetGeneratedTestCaseFileRequest(UniversalBaseModel): test_case: TestCaseV2 = pydantic.Field(alias="testCase") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/v_2/resources/problem/types/get_generated_test_case_template_file_request.py b/seed/fastapi/trace/resources/v_2/resources/problem/types/get_generated_test_case_template_file_request.py index 31f7014ec98..44d1c146008 100644 --- a/seed/fastapi/trace/resources/v_2/resources/problem/types/get_generated_test_case_template_file_request.py +++ b/seed/fastapi/trace/resources/v_2/resources/problem/types/get_generated_test_case_template_file_request.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from ......core.pydantic_utilities import UniversalBaseModel +from .test_case_template import TestCaseTemplate +from ......core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .test_case_template import TestCaseTemplate - class GetGeneratedTestCaseTemplateFileRequest(UniversalBaseModel): template: TestCaseTemplate if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/v_2/resources/problem/types/lightweight_problem_info_v_2.py b/seed/fastapi/trace/resources/v_2/resources/problem/types/lightweight_problem_info_v_2.py index c8c03ec4f24..5c701608aa7 100644 --- a/seed/fastapi/trace/resources/v_2/resources/problem/types/lightweight_problem_info_v_2.py +++ b/seed/fastapi/trace/resources/v_2/resources/problem/types/lightweight_problem_info_v_2.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ......core.pydantic_utilities import UniversalBaseModel from .....commons.types.problem_id import ProblemId +import pydantic +import typing from .....commons.types.variable_type import VariableType +from ......core.pydantic_utilities import IS_PYDANTIC_V2 class LightweightProblemInfoV2(UniversalBaseModel): @@ -16,7 +15,9 @@ class LightweightProblemInfoV2(UniversalBaseModel): variable_types: typing.List[VariableType] = pydantic.Field(alias="variableTypes") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/v_2/resources/problem/types/non_void_function_definition.py b/seed/fastapi/trace/resources/v_2/resources/problem/types/non_void_function_definition.py index 78165906d5c..2f19db30c83 100644 --- a/seed/fastapi/trace/resources/v_2/resources/problem/types/non_void_function_definition.py +++ b/seed/fastapi/trace/resources/v_2/resources/problem/types/non_void_function_definition.py @@ -1,20 +1,23 @@ # This file was auto-generated by Fern from our API Definition. +from ......core.pydantic_utilities import UniversalBaseModel +from .non_void_function_signature import NonVoidFunctionSignature +from .function_implementation_for_multiple_languages import ( + FunctionImplementationForMultipleLanguages, +) +from ......core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .function_implementation_for_multiple_languages import FunctionImplementationForMultipleLanguages -from .non_void_function_signature import NonVoidFunctionSignature - class NonVoidFunctionDefinition(UniversalBaseModel): signature: NonVoidFunctionSignature code: FunctionImplementationForMultipleLanguages if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/v_2/resources/problem/types/non_void_function_signature.py b/seed/fastapi/trace/resources/v_2/resources/problem/types/non_void_function_signature.py index 6741004c9a3..8e95c57e598 100644 --- a/seed/fastapi/trace/resources/v_2/resources/problem/types/non_void_function_signature.py +++ b/seed/fastapi/trace/resources/v_2/resources/problem/types/non_void_function_signature.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. +from ......core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .....commons.types.variable_type import VariableType from .parameter import Parameter +from .....commons.types.variable_type import VariableType +import pydantic +from ......core.pydantic_utilities import IS_PYDANTIC_V2 class NonVoidFunctionSignature(UniversalBaseModel): @@ -14,7 +13,9 @@ class NonVoidFunctionSignature(UniversalBaseModel): return_type: VariableType = pydantic.Field(alias="returnType") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/v_2/resources/problem/types/parameter.py b/seed/fastapi/trace/resources/v_2/resources/problem/types/parameter.py index 6ebed9f8494..534245b9caa 100644 --- a/seed/fastapi/trace/resources/v_2/resources/problem/types/parameter.py +++ b/seed/fastapi/trace/resources/v_2/resources/problem/types/parameter.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ......core.pydantic_utilities import UniversalBaseModel +from .parameter_id import ParameterId import pydantic - -from ......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .....commons.types.variable_type import VariableType -from .parameter_id import ParameterId +from ......core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class Parameter(UniversalBaseModel): @@ -15,7 +14,9 @@ class Parameter(UniversalBaseModel): variable_type: VariableType = pydantic.Field(alias="variableType") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/v_2/resources/problem/types/problem_info_v_2.py b/seed/fastapi/trace/resources/v_2/resources/problem/types/problem_info_v_2.py index c895cef0b99..494f4c1737e 100644 --- a/seed/fastapi/trace/resources/v_2/resources/problem/types/problem_info_v_2.py +++ b/seed/fastapi/trace/resources/v_2/resources/problem/types/problem_info_v_2.py @@ -1,17 +1,16 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .....commons.types.language import Language +from ......core.pydantic_utilities import UniversalBaseModel from .....commons.types.problem_id import ProblemId +import pydantic from .....problem.types.problem_description import ProblemDescription +import typing +from .....commons.types.language import Language from .custom_files import CustomFiles from .generated_files import GeneratedFiles from .test_case_template import TestCaseTemplate from .test_case_v_2 import TestCaseV2 +from ......core.pydantic_utilities import IS_PYDANTIC_V2 class ProblemInfoV2(UniversalBaseModel): @@ -19,15 +18,21 @@ class ProblemInfoV2(UniversalBaseModel): problem_description: ProblemDescription = pydantic.Field(alias="problemDescription") problem_name: str = pydantic.Field(alias="problemName") problem_version: int = pydantic.Field(alias="problemVersion") - supported_languages: typing.Set[Language] = pydantic.Field(alias="supportedLanguages") + supported_languages: typing.Set[Language] = pydantic.Field( + alias="supportedLanguages" + ) custom_files: CustomFiles = pydantic.Field(alias="customFiles") generated_files: GeneratedFiles = pydantic.Field(alias="generatedFiles") - custom_test_case_templates: typing.List[TestCaseTemplate] = pydantic.Field(alias="customTestCaseTemplates") + custom_test_case_templates: typing.List[TestCaseTemplate] = pydantic.Field( + alias="customTestCaseTemplates" + ) testcases: typing.List[TestCaseV2] is_public: bool = pydantic.Field(alias="isPublic") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/v_2/resources/problem/types/test_case_expects.py b/seed/fastapi/trace/resources/v_2/resources/problem/types/test_case_expects.py index 4d2ed29e0fe..b0f3b5f56bf 100644 --- a/seed/fastapi/trace/resources/v_2/resources/problem/types/test_case_expects.py +++ b/seed/fastapi/trace/resources/v_2/resources/problem/types/test_case_expects.py @@ -1,17 +1,20 @@ # This file was auto-generated by Fern from our API Definition. +from ......core.pydantic_utilities import UniversalBaseModel import typing - import pydantic - -from ......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ......core.pydantic_utilities import IS_PYDANTIC_V2 class TestCaseExpects(UniversalBaseModel): - expected_stdout: typing.Optional[str] = pydantic.Field(alias="expectedStdout", default=None) + expected_stdout: typing.Optional[str] = pydantic.Field( + alias="expectedStdout", default=None + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/v_2/resources/problem/types/test_case_function.py b/seed/fastapi/trace/resources/v_2/resources/problem/types/test_case_function.py index 1727b67befc..78328cb522d 100644 --- a/seed/fastapi/trace/resources/v_2/resources/problem/types/test_case_function.py +++ b/seed/fastapi/trace/resources/v_2/resources/problem/types/test_case_function.py @@ -1,35 +1,50 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from .test_case_with_actual_result_implementation import ( + TestCaseWithActualResultImplementation, +) +from ......core.pydantic_utilities import IS_PYDANTIC_V2 +from .void_function_definition import VoidFunctionDefinition +from ......core.pydantic_utilities import UniversalRootModel import typing - -import pydantic import typing_extensions - -from ......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalRootModel, update_forward_refs -from .test_case_with_actual_result_implementation import TestCaseWithActualResultImplementation -from .void_function_definition import VoidFunctionDefinition +import pydantic +from ......core.pydantic_utilities import update_forward_refs T_Result = typing.TypeVar("T_Result") class _Factory: - def with_actual_result(self, value: TestCaseWithActualResultImplementation) -> TestCaseFunction: + def with_actual_result( + self, value: TestCaseWithActualResultImplementation + ) -> TestCaseFunction: if IS_PYDANTIC_V2: return TestCaseFunction( - root=_TestCaseFunction.WithActualResult(**value.dict(exclude_unset=True), type="withActualResult") + root=_TestCaseFunction.WithActualResult( + **value.dict(exclude_unset=True), type="withActualResult" + ) ) else: return TestCaseFunction( - __root__=_TestCaseFunction.WithActualResult(**value.dict(exclude_unset=True), type="withActualResult") + __root__=_TestCaseFunction.WithActualResult( + **value.dict(exclude_unset=True), type="withActualResult" + ) ) def custom(self, value: VoidFunctionDefinition) -> TestCaseFunction: if IS_PYDANTIC_V2: - return TestCaseFunction(root=_TestCaseFunction.Custom(**value.dict(exclude_unset=True), type="custom")) + return TestCaseFunction( + root=_TestCaseFunction.Custom( + **value.dict(exclude_unset=True), type="custom" + ) + ) else: - return TestCaseFunction(__root__=_TestCaseFunction.Custom(**value.dict(exclude_unset=True), type="custom")) + return TestCaseFunction( + __root__=_TestCaseFunction.Custom( + **value.dict(exclude_unset=True), type="custom" + ) + ) class TestCaseFunction(UniversalRootModel): @@ -41,30 +56,41 @@ class TestCaseFunction(UniversalRootModel): pydantic.Field(discriminator="type"), ] - def get_as_union(self) -> typing.Union[_TestCaseFunction.WithActualResult, _TestCaseFunction.Custom]: + def get_as_union( + self, + ) -> typing.Union[_TestCaseFunction.WithActualResult, _TestCaseFunction.Custom]: return self.root - else: __root__: typing_extensions.Annotated[ typing.Union[_TestCaseFunction.WithActualResult, _TestCaseFunction.Custom], pydantic.Field(discriminator="type"), ] - def get_as_union(self) -> typing.Union[_TestCaseFunction.WithActualResult, _TestCaseFunction.Custom]: + def get_as_union( + self, + ) -> typing.Union[_TestCaseFunction.WithActualResult, _TestCaseFunction.Custom]: return self.__root__ def visit( self, - with_actual_result: typing.Callable[[TestCaseWithActualResultImplementation], T_Result], + with_actual_result: typing.Callable[ + [TestCaseWithActualResultImplementation], T_Result + ], custom: typing.Callable[[VoidFunctionDefinition], T_Result], ) -> T_Result: unioned_value = self.get_as_union() if unioned_value.type == "withActualResult": return with_actual_result( - TestCaseWithActualResultImplementation(**unioned_value.dict(exclude_unset=True, exclude={"type"})) + TestCaseWithActualResultImplementation( + **unioned_value.dict(exclude_unset=True, exclude={"type"}) + ) ) if unioned_value.type == "custom": - return custom(VoidFunctionDefinition(**unioned_value.dict(exclude_unset=True, exclude={"type"}))) + return custom( + VoidFunctionDefinition( + **unioned_value.dict(exclude_unset=True, exclude={"type"}) + ) + ) class _TestCaseFunction: diff --git a/seed/fastapi/trace/resources/v_2/resources/problem/types/test_case_implementation.py b/seed/fastapi/trace/resources/v_2/resources/problem/types/test_case_implementation.py index 83007f0e9ab..2da44d2595a 100644 --- a/seed/fastapi/trace/resources/v_2/resources/problem/types/test_case_implementation.py +++ b/seed/fastapi/trace/resources/v_2/resources/problem/types/test_case_implementation.py @@ -1,20 +1,21 @@ # This file was auto-generated by Fern from our API Definition. +from ......core.pydantic_utilities import UniversalBaseModel +from .test_case_implementation_description import TestCaseImplementationDescription +from .test_case_function import TestCaseFunction +from ......core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .test_case_function import TestCaseFunction -from .test_case_implementation_description import TestCaseImplementationDescription - class TestCaseImplementation(UniversalBaseModel): description: TestCaseImplementationDescription function: TestCaseFunction if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/v_2/resources/problem/types/test_case_implementation_description.py b/seed/fastapi/trace/resources/v_2/resources/problem/types/test_case_implementation_description.py index 80e3640b91f..c9f25a11e54 100644 --- a/seed/fastapi/trace/resources/v_2/resources/problem/types/test_case_implementation_description.py +++ b/seed/fastapi/trace/resources/v_2/resources/problem/types/test_case_implementation_description.py @@ -1,18 +1,21 @@ # This file was auto-generated by Fern from our API Definition. +from ......core.pydantic_utilities import UniversalBaseModel import typing - +from .test_case_implementation_description_board import ( + TestCaseImplementationDescriptionBoard, +) +from ......core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .test_case_implementation_description_board import TestCaseImplementationDescriptionBoard - class TestCaseImplementationDescription(UniversalBaseModel): boards: typing.List[TestCaseImplementationDescriptionBoard] if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/v_2/resources/problem/types/test_case_implementation_description_board.py b/seed/fastapi/trace/resources/v_2/resources/problem/types/test_case_implementation_description_board.py index 5b9629eaea1..7b3027d5712 100644 --- a/seed/fastapi/trace/resources/v_2/resources/problem/types/test_case_implementation_description_board.py +++ b/seed/fastapi/trace/resources/v_2/resources/problem/types/test_case_implementation_description_board.py @@ -1,14 +1,14 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ......core.pydantic_utilities import IS_PYDANTIC_V2 +from .parameter_id import ParameterId +from ......core.pydantic_utilities import UniversalRootModel import typing - -import pydantic import typing_extensions - -from ......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel, UniversalRootModel, update_forward_refs -from .parameter_id import ParameterId +import pydantic +from ......core.pydantic_utilities import UniversalBaseModel +from ......core.pydantic_utilities import update_forward_refs T_Result = typing.TypeVar("T_Result") @@ -17,21 +17,29 @@ class _Factory: def html(self, value: str) -> TestCaseImplementationDescriptionBoard: if IS_PYDANTIC_V2: return TestCaseImplementationDescriptionBoard( - root=_TestCaseImplementationDescriptionBoard.Html(type="html", value=value) + root=_TestCaseImplementationDescriptionBoard.Html( + type="html", value=value + ) ) else: return TestCaseImplementationDescriptionBoard( - __root__=_TestCaseImplementationDescriptionBoard.Html(type="html", value=value) + __root__=_TestCaseImplementationDescriptionBoard.Html( + type="html", value=value + ) ) def param_id(self, value: ParameterId) -> TestCaseImplementationDescriptionBoard: if IS_PYDANTIC_V2: return TestCaseImplementationDescriptionBoard( - root=_TestCaseImplementationDescriptionBoard.ParamId(type="paramId", value=value) + root=_TestCaseImplementationDescriptionBoard.ParamId( + type="paramId", value=value + ) ) else: return TestCaseImplementationDescriptionBoard( - __root__=_TestCaseImplementationDescriptionBoard.ParamId(type="paramId", value=value) + __root__=_TestCaseImplementationDescriptionBoard.ParamId( + type="paramId", value=value + ) ) @@ -40,32 +48,41 @@ class TestCaseImplementationDescriptionBoard(UniversalRootModel): if IS_PYDANTIC_V2: root: typing_extensions.Annotated[ - typing.Union[_TestCaseImplementationDescriptionBoard.Html, _TestCaseImplementationDescriptionBoard.ParamId], + typing.Union[ + _TestCaseImplementationDescriptionBoard.Html, + _TestCaseImplementationDescriptionBoard.ParamId, + ], pydantic.Field(discriminator="type"), ] def get_as_union( self, ) -> typing.Union[ - _TestCaseImplementationDescriptionBoard.Html, _TestCaseImplementationDescriptionBoard.ParamId + _TestCaseImplementationDescriptionBoard.Html, + _TestCaseImplementationDescriptionBoard.ParamId, ]: return self.root - else: __root__: typing_extensions.Annotated[ - typing.Union[_TestCaseImplementationDescriptionBoard.Html, _TestCaseImplementationDescriptionBoard.ParamId], + typing.Union[ + _TestCaseImplementationDescriptionBoard.Html, + _TestCaseImplementationDescriptionBoard.ParamId, + ], pydantic.Field(discriminator="type"), ] def get_as_union( self, ) -> typing.Union[ - _TestCaseImplementationDescriptionBoard.Html, _TestCaseImplementationDescriptionBoard.ParamId + _TestCaseImplementationDescriptionBoard.Html, + _TestCaseImplementationDescriptionBoard.ParamId, ]: return self.__root__ def visit( - self, html: typing.Callable[[str], T_Result], param_id: typing.Callable[[ParameterId], T_Result] + self, + html: typing.Callable[[str], T_Result], + param_id: typing.Callable[[ParameterId], T_Result], ) -> T_Result: unioned_value = self.get_as_union() if unioned_value.type == "html": diff --git a/seed/fastapi/trace/resources/v_2/resources/problem/types/test_case_implementation_reference.py b/seed/fastapi/trace/resources/v_2/resources/problem/types/test_case_implementation_reference.py index 7c6170397f0..e278184b4ce 100644 --- a/seed/fastapi/trace/resources/v_2/resources/problem/types/test_case_implementation_reference.py +++ b/seed/fastapi/trace/resources/v_2/resources/problem/types/test_case_implementation_reference.py @@ -1,15 +1,15 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from .test_case_template_id import TestCaseTemplateId +from ......core.pydantic_utilities import IS_PYDANTIC_V2 +from .test_case_implementation import TestCaseImplementation +from ......core.pydantic_utilities import UniversalRootModel import typing - -import pydantic import typing_extensions - -from ......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel, UniversalRootModel, update_forward_refs -from .test_case_implementation import TestCaseImplementation -from .test_case_template_id import TestCaseTemplateId +import pydantic +from ......core.pydantic_utilities import UniversalBaseModel +from ......core.pydantic_utilities import update_forward_refs T_Result = typing.TypeVar("T_Result") @@ -18,14 +18,20 @@ class _Factory: def template_id(self, value: TestCaseTemplateId) -> TestCaseImplementationReference: if IS_PYDANTIC_V2: return TestCaseImplementationReference( - root=_TestCaseImplementationReference.TemplateId(type="templateId", value=value) + root=_TestCaseImplementationReference.TemplateId( + type="templateId", value=value + ) ) else: return TestCaseImplementationReference( - __root__=_TestCaseImplementationReference.TemplateId(type="templateId", value=value) + __root__=_TestCaseImplementationReference.TemplateId( + type="templateId", value=value + ) ) - def implementation(self, value: TestCaseImplementation) -> TestCaseImplementationReference: + def implementation( + self, value: TestCaseImplementation + ) -> TestCaseImplementationReference: if IS_PYDANTIC_V2: return TestCaseImplementationReference( root=_TestCaseImplementationReference.Implementation( @@ -45,24 +51,35 @@ class TestCaseImplementationReference(UniversalRootModel): if IS_PYDANTIC_V2: root: typing_extensions.Annotated[ - typing.Union[_TestCaseImplementationReference.TemplateId, _TestCaseImplementationReference.Implementation], + typing.Union[ + _TestCaseImplementationReference.TemplateId, + _TestCaseImplementationReference.Implementation, + ], pydantic.Field(discriminator="type"), ] def get_as_union( self, - ) -> typing.Union[_TestCaseImplementationReference.TemplateId, _TestCaseImplementationReference.Implementation]: + ) -> typing.Union[ + _TestCaseImplementationReference.TemplateId, + _TestCaseImplementationReference.Implementation, + ]: return self.root - else: __root__: typing_extensions.Annotated[ - typing.Union[_TestCaseImplementationReference.TemplateId, _TestCaseImplementationReference.Implementation], + typing.Union[ + _TestCaseImplementationReference.TemplateId, + _TestCaseImplementationReference.Implementation, + ], pydantic.Field(discriminator="type"), ] def get_as_union( self, - ) -> typing.Union[_TestCaseImplementationReference.TemplateId, _TestCaseImplementationReference.Implementation]: + ) -> typing.Union[ + _TestCaseImplementationReference.TemplateId, + _TestCaseImplementationReference.Implementation, + ]: return self.__root__ def visit( @@ -74,7 +91,11 @@ def visit( if unioned_value.type == "templateId": return template_id(unioned_value.value) if unioned_value.type == "implementation": - return implementation(TestCaseImplementation(**unioned_value.dict(exclude_unset=True, exclude={"type"}))) + return implementation( + TestCaseImplementation( + **unioned_value.dict(exclude_unset=True, exclude={"type"}) + ) + ) class _TestCaseImplementationReference: diff --git a/seed/fastapi/trace/resources/v_2/resources/problem/types/test_case_metadata.py b/seed/fastapi/trace/resources/v_2/resources/problem/types/test_case_metadata.py index 50b70ca9433..a4fb6d2a6d1 100644 --- a/seed/fastapi/trace/resources/v_2/resources/problem/types/test_case_metadata.py +++ b/seed/fastapi/trace/resources/v_2/resources/problem/types/test_case_metadata.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. +from ......core.pydantic_utilities import UniversalBaseModel +from .test_case_id import TestCaseId +from ......core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .test_case_id import TestCaseId - class TestCaseMetadata(UniversalBaseModel): id: TestCaseId @@ -14,7 +13,9 @@ class TestCaseMetadata(UniversalBaseModel): hidden: bool if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/v_2/resources/problem/types/test_case_template.py b/seed/fastapi/trace/resources/v_2/resources/problem/types/test_case_template.py index 13a1fb13b9f..bf42dd6ed4c 100644 --- a/seed/fastapi/trace/resources/v_2/resources/problem/types/test_case_template.py +++ b/seed/fastapi/trace/resources/v_2/resources/problem/types/test_case_template.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ......core.pydantic_utilities import UniversalBaseModel +from .test_case_template_id import TestCaseTemplateId import pydantic - -from ......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .test_case_implementation import TestCaseImplementation -from .test_case_template_id import TestCaseTemplateId +from ......core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class TestCaseTemplate(UniversalBaseModel): @@ -15,7 +14,9 @@ class TestCaseTemplate(UniversalBaseModel): implementation: TestCaseImplementation if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/v_2/resources/problem/types/test_case_v_2.py b/seed/fastapi/trace/resources/v_2/resources/problem/types/test_case_v_2.py index 8ce3407aefd..1e844da70a7 100644 --- a/seed/fastapi/trace/resources/v_2/resources/problem/types/test_case_v_2.py +++ b/seed/fastapi/trace/resources/v_2/resources/problem/types/test_case_v_2.py @@ -1,15 +1,14 @@ # This file was auto-generated by Fern from our API Definition. +from ......core.pydantic_utilities import UniversalBaseModel +from .test_case_metadata import TestCaseMetadata +from .test_case_implementation_reference import TestCaseImplementationReference import typing - -import pydantic - -from ......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .....commons.types.variable_value import VariableValue from .parameter_id import ParameterId +from .....commons.types.variable_value import VariableValue from .test_case_expects import TestCaseExpects -from .test_case_implementation_reference import TestCaseImplementationReference -from .test_case_metadata import TestCaseMetadata +from ......core.pydantic_utilities import IS_PYDANTIC_V2 +import pydantic class TestCaseV2(UniversalBaseModel): @@ -19,7 +18,9 @@ class TestCaseV2(UniversalBaseModel): expects: typing.Optional[TestCaseExpects] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/v_2/resources/problem/types/test_case_with_actual_result_implementation.py b/seed/fastapi/trace/resources/v_2/resources/problem/types/test_case_with_actual_result_implementation.py index 8da1341dd4d..6d30b256f2c 100644 --- a/seed/fastapi/trace/resources/v_2/resources/problem/types/test_case_with_actual_result_implementation.py +++ b/seed/fastapi/trace/resources/v_2/resources/problem/types/test_case_with_actual_result_implementation.py @@ -1,20 +1,25 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ......core.pydantic_utilities import UniversalBaseModel +from .non_void_function_definition import NonVoidFunctionDefinition import pydantic - -from ......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .assert_correctness_check import AssertCorrectnessCheck -from .non_void_function_definition import NonVoidFunctionDefinition +from ......core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class TestCaseWithActualResultImplementation(UniversalBaseModel): - get_actual_result: NonVoidFunctionDefinition = pydantic.Field(alias="getActualResult") - assert_correctness_check: AssertCorrectnessCheck = pydantic.Field(alias="assertCorrectnessCheck") + get_actual_result: NonVoidFunctionDefinition = pydantic.Field( + alias="getActualResult" + ) + assert_correctness_check: AssertCorrectnessCheck = pydantic.Field( + alias="assertCorrectnessCheck" + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/v_2/resources/problem/types/void_function_definition.py b/seed/fastapi/trace/resources/v_2/resources/problem/types/void_function_definition.py index 6b6b4fea7d9..f850d60ab3d 100644 --- a/seed/fastapi/trace/resources/v_2/resources/problem/types/void_function_definition.py +++ b/seed/fastapi/trace/resources/v_2/resources/problem/types/void_function_definition.py @@ -1,12 +1,13 @@ # This file was auto-generated by Fern from our API Definition. +from ......core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .function_implementation_for_multiple_languages import FunctionImplementationForMultipleLanguages from .parameter import Parameter +from .function_implementation_for_multiple_languages import ( + FunctionImplementationForMultipleLanguages, +) +from ......core.pydantic_utilities import IS_PYDANTIC_V2 +import pydantic class VoidFunctionDefinition(UniversalBaseModel): @@ -14,7 +15,9 @@ class VoidFunctionDefinition(UniversalBaseModel): code: FunctionImplementationForMultipleLanguages if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/v_2/resources/problem/types/void_function_definition_that_takes_actual_result.py b/seed/fastapi/trace/resources/v_2/resources/problem/types/void_function_definition_that_takes_actual_result.py index 700c796fc79..93d799d0a12 100644 --- a/seed/fastapi/trace/resources/v_2/resources/problem/types/void_function_definition_that_takes_actual_result.py +++ b/seed/fastapi/trace/resources/v_2/resources/problem/types/void_function_definition_that_takes_actual_result.py @@ -1,12 +1,13 @@ # This file was auto-generated by Fern from our API Definition. +from ......core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .function_implementation_for_multiple_languages import FunctionImplementationForMultipleLanguages from .parameter import Parameter +import pydantic +from .function_implementation_for_multiple_languages import ( + FunctionImplementationForMultipleLanguages, +) +from ......core.pydantic_utilities import IS_PYDANTIC_V2 class VoidFunctionDefinitionThatTakesActualResult(UniversalBaseModel): @@ -14,11 +15,15 @@ class VoidFunctionDefinitionThatTakesActualResult(UniversalBaseModel): The generated signature will include an additional param, actualResult """ - additional_parameters: typing.List[Parameter] = pydantic.Field(alias="additionalParameters") + additional_parameters: typing.List[Parameter] = pydantic.Field( + alias="additionalParameters" + ) code: FunctionImplementationForMultipleLanguages if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/v_2/resources/problem/types/void_function_signature.py b/seed/fastapi/trace/resources/v_2/resources/problem/types/void_function_signature.py index 62c69a5ddab..456fbd54f56 100644 --- a/seed/fastapi/trace/resources/v_2/resources/problem/types/void_function_signature.py +++ b/seed/fastapi/trace/resources/v_2/resources/problem/types/void_function_signature.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from ......core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .parameter import Parameter +from ......core.pydantic_utilities import IS_PYDANTIC_V2 +import pydantic class VoidFunctionSignature(UniversalBaseModel): parameters: typing.List[Parameter] if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/v_2/resources/problem/types/void_function_signature_that_takes_actual_result.py b/seed/fastapi/trace/resources/v_2/resources/problem/types/void_function_signature_that_takes_actual_result.py index 8ba3eb68003..a660d7c40f8 100644 --- a/seed/fastapi/trace/resources/v_2/resources/problem/types/void_function_signature_that_takes_actual_result.py +++ b/seed/fastapi/trace/resources/v_2/resources/problem/types/void_function_signature_that_takes_actual_result.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. +from ......core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .....commons.types.variable_type import VariableType from .parameter import Parameter +from .....commons.types.variable_type import VariableType +import pydantic +from ......core.pydantic_utilities import IS_PYDANTIC_V2 class VoidFunctionSignatureThatTakesActualResult(UniversalBaseModel): @@ -14,7 +13,9 @@ class VoidFunctionSignatureThatTakesActualResult(UniversalBaseModel): actual_result_type: VariableType = pydantic.Field(alias="actualResultType") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/service/service.py b/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/service/service.py index 96e626d6380..a163d88052a 100644 --- a/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/service/service.py +++ b/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/service/service.py @@ -1,18 +1,16 @@ # This file was auto-generated by Fern from our API Definition. -import abc -import functools -import inspect -import logging +from ........core.abstract_fern_service import AbstractFernService import typing - +from ..types.lightweight_problem_info_v_2 import LightweightProblemInfoV2 +import abc +from ..types.problem_info_v_2 import ProblemInfoV2 import fastapi - -from ........core.abstract_fern_service import AbstractFernService +import inspect from ........core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools from ........core.route_args import get_route_args -from ..types.lightweight_problem_info_v_2 import LightweightProblemInfoV2 -from ..types.problem_info_v_2 import ProblemInfoV2 class AbstractV2V3ProblemService(AbstractFernService): @@ -34,14 +32,18 @@ def get_lightweight_problems( ... @abc.abstractmethod - def get_problems(self, *, x_random_header: typing.Optional[str] = None) -> typing.Sequence[ProblemInfoV2]: + def get_problems( + self, *, x_random_header: typing.Optional[str] = None + ) -> typing.Sequence[ProblemInfoV2]: """ Returns latest versions of all problems """ ... @abc.abstractmethod - def get_latest_problem(self, *, problem_id: str, x_random_header: typing.Optional[str] = None) -> ProblemInfoV2: + def get_latest_problem( + self, *, problem_id: str, x_random_header: typing.Optional[str] = None + ) -> ProblemInfoV2: """ Returns latest version of a problem """ @@ -49,7 +51,11 @@ def get_latest_problem(self, *, problem_id: str, x_random_header: typing.Optiona @abc.abstractmethod def get_problem_version( - self, *, problem_id: str, problem_version: int, x_random_header: typing.Optional[str] = None + self, + *, + problem_id: str, + problem_version: int, + x_random_header: typing.Optional[str] = None, ) -> ProblemInfoV2: """ Returns requested version of a problem @@ -72,17 +78,29 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_get_lightweight_problems(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_lightweight_problems) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "x_random_header": - new_parameters.append(parameter.replace(default=fastapi.Header(default=None, alias="X-Random-Header"))) + new_parameters.append( + parameter.replace( + default=fastapi.Header(default=None, alias="X-Random-Header") + ) + ) else: new_parameters.append(parameter) - setattr(cls.get_lightweight_problems, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_lightweight_problems, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_lightweight_problems) - def wrapper(*args: typing.Any, **kwargs: typing.Any) -> typing.Sequence[LightweightProblemInfoV2]: + def wrapper( + *args: typing.Any, **kwargs: typing.Any + ) -> typing.Sequence[LightweightProblemInfoV2]: try: return cls.get_lightweight_problems(*args, **kwargs) except FernHTTPException as e: @@ -101,24 +119,38 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> typing.Sequence[Lightwei path="/problems-v2/lightweight-problem-info", response_model=typing.Sequence[LightweightProblemInfoV2], description=AbstractV2V3ProblemService.get_lightweight_problems.__doc__, - **get_route_args(cls.get_lightweight_problems, default_tag="v_2.v_3.problem"), + **get_route_args( + cls.get_lightweight_problems, default_tag="v_2.v_3.problem" + ), )(wrapper) @classmethod def __init_get_problems(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_problems) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "x_random_header": - new_parameters.append(parameter.replace(default=fastapi.Header(default=None, alias="X-Random-Header"))) + new_parameters.append( + parameter.replace( + default=fastapi.Header(default=None, alias="X-Random-Header") + ) + ) else: new_parameters.append(parameter) - setattr(cls.get_problems, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_problems, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_problems) - def wrapper(*args: typing.Any, **kwargs: typing.Any) -> typing.Sequence[ProblemInfoV2]: + def wrapper( + *args: typing.Any, **kwargs: typing.Any + ) -> typing.Sequence[ProblemInfoV2]: try: return cls.get_problems(*args, **kwargs) except FernHTTPException as e: @@ -144,16 +176,26 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> typing.Sequence[ProblemI def __init_get_latest_problem(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_latest_problem) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "problem_id": new_parameters.append(parameter.replace(default=fastapi.Path(...))) elif parameter_name == "x_random_header": - new_parameters.append(parameter.replace(default=fastapi.Header(default=None, alias="X-Random-Header"))) + new_parameters.append( + parameter.replace( + default=fastapi.Header(default=None, alias="X-Random-Header") + ) + ) else: new_parameters.append(parameter) - setattr(cls.get_latest_problem, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_latest_problem, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_latest_problem) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> ProblemInfoV2: @@ -182,7 +224,9 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> ProblemInfoV2: def __init_get_problem_version(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_problem_version) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "problem_id": @@ -190,10 +234,18 @@ def __init_get_problem_version(cls, router: fastapi.APIRouter) -> None: elif parameter_name == "problem_version": new_parameters.append(parameter.replace(default=fastapi.Path(...))) elif parameter_name == "x_random_header": - new_parameters.append(parameter.replace(default=fastapi.Header(default=None, alias="X-Random-Header"))) + new_parameters.append( + parameter.replace( + default=fastapi.Header(default=None, alias="X-Random-Header") + ) + ) else: new_parameters.append(parameter) - setattr(cls.get_problem_version, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_problem_version, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_problem_version) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> ProblemInfoV2: diff --git a/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/__init__.py b/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/__init__.py index 618e6aa9c52..f86d943b7a1 100644 --- a/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/__init__.py +++ b/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/__init__.py @@ -10,7 +10,9 @@ from .file_info_v_2 import FileInfoV2 from .files import Files from .function_implementation import FunctionImplementation -from .function_implementation_for_multiple_languages import FunctionImplementationForMultipleLanguages +from .function_implementation_for_multiple_languages import ( + FunctionImplementationForMultipleLanguages, +) from .function_signature import FunctionSignature from .generated_files import GeneratedFiles from .get_basic_solution_file_request import GetBasicSolutionFileRequest @@ -18,7 +20,9 @@ from .get_function_signature_request import GetFunctionSignatureRequest from .get_function_signature_response import GetFunctionSignatureResponse from .get_generated_test_case_file_request import GetGeneratedTestCaseFileRequest -from .get_generated_test_case_template_file_request import GetGeneratedTestCaseTemplateFileRequest +from .get_generated_test_case_template_file_request import ( + GetGeneratedTestCaseTemplateFileRequest, +) from .lightweight_problem_info_v_2 import LightweightProblemInfoV2 from .non_void_function_definition import NonVoidFunctionDefinition from .non_void_function_signature import NonVoidFunctionSignature @@ -30,17 +34,25 @@ from .test_case_id import TestCaseId from .test_case_implementation import TestCaseImplementation from .test_case_implementation_description import TestCaseImplementationDescription -from .test_case_implementation_description_board import TestCaseImplementationDescriptionBoard +from .test_case_implementation_description_board import ( + TestCaseImplementationDescriptionBoard, +) from .test_case_implementation_reference import TestCaseImplementationReference from .test_case_metadata import TestCaseMetadata from .test_case_template import TestCaseTemplate from .test_case_template_id import TestCaseTemplateId from .test_case_v_2 import TestCaseV2 -from .test_case_with_actual_result_implementation import TestCaseWithActualResultImplementation +from .test_case_with_actual_result_implementation import ( + TestCaseWithActualResultImplementation, +) from .void_function_definition import VoidFunctionDefinition -from .void_function_definition_that_takes_actual_result import VoidFunctionDefinitionThatTakesActualResult +from .void_function_definition_that_takes_actual_result import ( + VoidFunctionDefinitionThatTakesActualResult, +) from .void_function_signature import VoidFunctionSignature -from .void_function_signature_that_takes_actual_result import VoidFunctionSignatureThatTakesActualResult +from .void_function_signature_that_takes_actual_result import ( + VoidFunctionSignatureThatTakesActualResult, +) __all__ = [ "AssertCorrectnessCheck", diff --git a/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/assert_correctness_check.py b/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/assert_correctness_check.py index fa62b079367..071ea3d0d1e 100644 --- a/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/assert_correctness_check.py +++ b/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/assert_correctness_check.py @@ -1,38 +1,51 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from .deep_equality_correctness_check import DeepEqualityCorrectnessCheck +from ........core.pydantic_utilities import IS_PYDANTIC_V2 +from .void_function_definition_that_takes_actual_result import ( + VoidFunctionDefinitionThatTakesActualResult, +) +from ........core.pydantic_utilities import UniversalRootModel import typing - -import pydantic import typing_extensions - -from ........core.pydantic_utilities import IS_PYDANTIC_V2, UniversalRootModel, update_forward_refs -from .deep_equality_correctness_check import DeepEqualityCorrectnessCheck -from .void_function_definition_that_takes_actual_result import VoidFunctionDefinitionThatTakesActualResult +import pydantic +from ........core.pydantic_utilities import update_forward_refs T_Result = typing.TypeVar("T_Result") class _Factory: - def deep_equality(self, value: DeepEqualityCorrectnessCheck) -> AssertCorrectnessCheck: + def deep_equality( + self, value: DeepEqualityCorrectnessCheck + ) -> AssertCorrectnessCheck: if IS_PYDANTIC_V2: return AssertCorrectnessCheck( - root=_AssertCorrectnessCheck.DeepEquality(**value.dict(exclude_unset=True), type="deepEquality") + root=_AssertCorrectnessCheck.DeepEquality( + **value.dict(exclude_unset=True), type="deepEquality" + ) ) else: return AssertCorrectnessCheck( - __root__=_AssertCorrectnessCheck.DeepEquality(**value.dict(exclude_unset=True), type="deepEquality") + __root__=_AssertCorrectnessCheck.DeepEquality( + **value.dict(exclude_unset=True), type="deepEquality" + ) ) - def custom(self, value: VoidFunctionDefinitionThatTakesActualResult) -> AssertCorrectnessCheck: + def custom( + self, value: VoidFunctionDefinitionThatTakesActualResult + ) -> AssertCorrectnessCheck: if IS_PYDANTIC_V2: return AssertCorrectnessCheck( - root=_AssertCorrectnessCheck.Custom(**value.dict(exclude_unset=True), type="custom") + root=_AssertCorrectnessCheck.Custom( + **value.dict(exclude_unset=True), type="custom" + ) ) else: return AssertCorrectnessCheck( - __root__=_AssertCorrectnessCheck.Custom(**value.dict(exclude_unset=True), type="custom") + __root__=_AssertCorrectnessCheck.Custom( + **value.dict(exclude_unset=True), type="custom" + ) ) @@ -41,35 +54,52 @@ class AssertCorrectnessCheck(UniversalRootModel): if IS_PYDANTIC_V2: root: typing_extensions.Annotated[ - typing.Union[_AssertCorrectnessCheck.DeepEquality, _AssertCorrectnessCheck.Custom], + typing.Union[ + _AssertCorrectnessCheck.DeepEquality, _AssertCorrectnessCheck.Custom + ], pydantic.Field(discriminator="type"), ] - def get_as_union(self) -> typing.Union[_AssertCorrectnessCheck.DeepEquality, _AssertCorrectnessCheck.Custom]: + def get_as_union( + self, + ) -> typing.Union[ + _AssertCorrectnessCheck.DeepEquality, _AssertCorrectnessCheck.Custom + ]: return self.root - else: __root__: typing_extensions.Annotated[ - typing.Union[_AssertCorrectnessCheck.DeepEquality, _AssertCorrectnessCheck.Custom], + typing.Union[ + _AssertCorrectnessCheck.DeepEquality, _AssertCorrectnessCheck.Custom + ], pydantic.Field(discriminator="type"), ] - def get_as_union(self) -> typing.Union[_AssertCorrectnessCheck.DeepEquality, _AssertCorrectnessCheck.Custom]: + def get_as_union( + self, + ) -> typing.Union[ + _AssertCorrectnessCheck.DeepEquality, _AssertCorrectnessCheck.Custom + ]: return self.__root__ def visit( self, deep_equality: typing.Callable[[DeepEqualityCorrectnessCheck], T_Result], - custom: typing.Callable[[VoidFunctionDefinitionThatTakesActualResult], T_Result], + custom: typing.Callable[ + [VoidFunctionDefinitionThatTakesActualResult], T_Result + ], ) -> T_Result: unioned_value = self.get_as_union() if unioned_value.type == "deepEquality": return deep_equality( - DeepEqualityCorrectnessCheck(**unioned_value.dict(exclude_unset=True, exclude={"type"})) + DeepEqualityCorrectnessCheck( + **unioned_value.dict(exclude_unset=True, exclude={"type"}) + ) ) if unioned_value.type == "custom": return custom( - VoidFunctionDefinitionThatTakesActualResult(**unioned_value.dict(exclude_unset=True, exclude={"type"})) + VoidFunctionDefinitionThatTakesActualResult( + **unioned_value.dict(exclude_unset=True, exclude={"type"}) + ) ) diff --git a/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/basic_custom_files.py b/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/basic_custom_files.py index 6d5d1758e41..4844862caec 100644 --- a/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/basic_custom_files.py +++ b/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/basic_custom_files.py @@ -1,24 +1,29 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ........core.pydantic_utilities import UniversalBaseModel import pydantic - -from ........core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from .non_void_function_signature import NonVoidFunctionSignature +import typing from .......commons.types.language import Language -from .basic_test_case_template import BasicTestCaseTemplate from .files import Files -from .non_void_function_signature import NonVoidFunctionSignature +from .basic_test_case_template import BasicTestCaseTemplate +from ........core.pydantic_utilities import IS_PYDANTIC_V2 class BasicCustomFiles(UniversalBaseModel): method_name: str = pydantic.Field(alias="methodName") signature: NonVoidFunctionSignature - additional_files: typing.Dict[Language, Files] = pydantic.Field(alias="additionalFiles") - basic_test_case_template: BasicTestCaseTemplate = pydantic.Field(alias="basicTestCaseTemplate") + additional_files: typing.Dict[Language, Files] = pydantic.Field( + alias="additionalFiles" + ) + basic_test_case_template: BasicTestCaseTemplate = pydantic.Field( + alias="basicTestCaseTemplate" + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/basic_test_case_template.py b/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/basic_test_case_template.py index 22afc7ea391..36f73a447fa 100644 --- a/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/basic_test_case_template.py +++ b/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/basic_test_case_template.py @@ -1,23 +1,26 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ........core.pydantic_utilities import UniversalBaseModel +from .test_case_template_id import TestCaseTemplateId import pydantic - -from ........core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .parameter_id import ParameterId from .test_case_implementation_description import TestCaseImplementationDescription -from .test_case_template_id import TestCaseTemplateId +from .parameter_id import ParameterId +from ........core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class BasicTestCaseTemplate(UniversalBaseModel): template_id: TestCaseTemplateId = pydantic.Field(alias="templateId") name: str description: TestCaseImplementationDescription - expected_value_parameter_id: ParameterId = pydantic.Field(alias="expectedValueParameterId") + expected_value_parameter_id: ParameterId = pydantic.Field( + alias="expectedValueParameterId" + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/create_problem_request_v_2.py b/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/create_problem_request_v_2.py index 1830a7dc94a..0ded64207c6 100644 --- a/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/create_problem_request_v_2.py +++ b/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/create_problem_request_v_2.py @@ -1,28 +1,33 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ........core.pydantic_utilities import UniversalBaseModel import pydantic - -from ........core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .......commons.types.language import Language from .......problem.types.problem_description import ProblemDescription from .custom_files import CustomFiles +import typing from .test_case_template import TestCaseTemplate from .test_case_v_2 import TestCaseV2 +from .......commons.types.language import Language +from ........core.pydantic_utilities import IS_PYDANTIC_V2 class CreateProblemRequestV2(UniversalBaseModel): problem_name: str = pydantic.Field(alias="problemName") problem_description: ProblemDescription = pydantic.Field(alias="problemDescription") custom_files: CustomFiles = pydantic.Field(alias="customFiles") - custom_test_case_templates: typing.List[TestCaseTemplate] = pydantic.Field(alias="customTestCaseTemplates") + custom_test_case_templates: typing.List[TestCaseTemplate] = pydantic.Field( + alias="customTestCaseTemplates" + ) testcases: typing.List[TestCaseV2] - supported_languages: typing.Set[Language] = pydantic.Field(alias="supportedLanguages") + supported_languages: typing.Set[Language] = pydantic.Field( + alias="supportedLanguages" + ) is_public: bool = pydantic.Field(alias="isPublic") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/custom_files.py b/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/custom_files.py index 4cc36f426d7..7e59cc6a099 100644 --- a/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/custom_files.py +++ b/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/custom_files.py @@ -1,16 +1,16 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from .basic_custom_files import BasicCustomFiles +from ........core.pydantic_utilities import IS_PYDANTIC_V2 import typing - -import pydantic -import typing_extensions - -from ........core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel, UniversalRootModel, update_forward_refs from .......commons.types.language import Language -from .basic_custom_files import BasicCustomFiles from .files import Files +from ........core.pydantic_utilities import UniversalRootModel +import typing_extensions +import pydantic +from ........core.pydantic_utilities import UniversalBaseModel +from ........core.pydantic_utilities import update_forward_refs T_Result = typing.TypeVar("T_Result") @@ -18,9 +18,15 @@ class _Factory: def basic(self, value: BasicCustomFiles) -> CustomFiles: if IS_PYDANTIC_V2: - return CustomFiles(root=_CustomFiles.Basic(**value.dict(exclude_unset=True), type="basic")) + return CustomFiles( + root=_CustomFiles.Basic(**value.dict(exclude_unset=True), type="basic") + ) else: - return CustomFiles(__root__=_CustomFiles.Basic(**value.dict(exclude_unset=True), type="basic")) + return CustomFiles( + __root__=_CustomFiles.Basic( + **value.dict(exclude_unset=True), type="basic" + ) + ) def custom(self, value: typing.Dict[Language, Files]) -> CustomFiles: if IS_PYDANTIC_V2: @@ -34,15 +40,16 @@ class CustomFiles(UniversalRootModel): if IS_PYDANTIC_V2: root: typing_extensions.Annotated[ - typing.Union[_CustomFiles.Basic, _CustomFiles.Custom], pydantic.Field(discriminator="type") + typing.Union[_CustomFiles.Basic, _CustomFiles.Custom], + pydantic.Field(discriminator="type"), ] def get_as_union(self) -> typing.Union[_CustomFiles.Basic, _CustomFiles.Custom]: return self.root - else: __root__: typing_extensions.Annotated[ - typing.Union[_CustomFiles.Basic, _CustomFiles.Custom], pydantic.Field(discriminator="type") + typing.Union[_CustomFiles.Basic, _CustomFiles.Custom], + pydantic.Field(discriminator="type"), ] def get_as_union(self) -> typing.Union[_CustomFiles.Basic, _CustomFiles.Custom]: @@ -55,7 +62,11 @@ def visit( ) -> T_Result: unioned_value = self.get_as_union() if unioned_value.type == "basic": - return basic(BasicCustomFiles(**unioned_value.dict(exclude_unset=True, exclude={"type"}))) + return basic( + BasicCustomFiles( + **unioned_value.dict(exclude_unset=True, exclude={"type"}) + ) + ) if unioned_value.type == "custom": return custom(unioned_value.value) diff --git a/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/deep_equality_correctness_check.py b/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/deep_equality_correctness_check.py index 4839eb923a2..8e1638af76c 100644 --- a/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/deep_equality_correctness_check.py +++ b/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/deep_equality_correctness_check.py @@ -1,18 +1,21 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ........core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ........core.pydantic_utilities import UniversalBaseModel from .parameter_id import ParameterId +import pydantic +from ........core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class DeepEqualityCorrectnessCheck(UniversalBaseModel): - expected_value_parameter_id: ParameterId = pydantic.Field(alias="expectedValueParameterId") + expected_value_parameter_id: ParameterId = pydantic.Field( + alias="expectedValueParameterId" + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/default_provided_file.py b/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/default_provided_file.py index 99bb98ee5a8..4e726accf1d 100644 --- a/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/default_provided_file.py +++ b/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/default_provided_file.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. +from ........core.pydantic_utilities import UniversalBaseModel +from .file_info_v_2 import FileInfoV2 import typing - -import pydantic - -from ........core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .......commons.types.variable_type import VariableType -from .file_info_v_2 import FileInfoV2 +import pydantic +from ........core.pydantic_utilities import IS_PYDANTIC_V2 class DefaultProvidedFile(UniversalBaseModel): @@ -14,7 +13,9 @@ class DefaultProvidedFile(UniversalBaseModel): related_types: typing.List[VariableType] = pydantic.Field(alias="relatedTypes") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/file_info_v_2.py b/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/file_info_v_2.py index 4b135851bd8..869c4c4c605 100644 --- a/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/file_info_v_2.py +++ b/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/file_info_v_2.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from ........core.pydantic_utilities import UniversalBaseModel +from ........core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ........core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class FileInfoV2(UniversalBaseModel): filename: str @@ -14,7 +13,9 @@ class FileInfoV2(UniversalBaseModel): editable: bool if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/files.py b/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/files.py index 826bd3846d6..028bbbc2357 100644 --- a/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/files.py +++ b/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/files.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from ........core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ........core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .file_info_v_2 import FileInfoV2 +from ........core.pydantic_utilities import IS_PYDANTIC_V2 +import pydantic class Files(UniversalBaseModel): files: typing.List[FileInfoV2] if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/function_implementation.py b/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/function_implementation.py index 588d1281067..d533f5d2082 100644 --- a/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/function_implementation.py +++ b/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/function_implementation.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from ........core.pydantic_utilities import UniversalBaseModel import typing - +from ........core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ........core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class FunctionImplementation(UniversalBaseModel): impl: str imports: typing.Optional[str] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/function_implementation_for_multiple_languages.py b/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/function_implementation_for_multiple_languages.py index 0507e75826f..9842dca6c32 100644 --- a/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/function_implementation_for_multiple_languages.py +++ b/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/function_implementation_for_multiple_languages.py @@ -1,19 +1,22 @@ # This file was auto-generated by Fern from our API Definition. +from ........core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ........core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .......commons.types.language import Language from .function_implementation import FunctionImplementation +import pydantic +from ........core.pydantic_utilities import IS_PYDANTIC_V2 class FunctionImplementationForMultipleLanguages(UniversalBaseModel): - code_by_language: typing.Dict[Language, FunctionImplementation] = pydantic.Field(alias="codeByLanguage") + code_by_language: typing.Dict[Language, FunctionImplementation] = pydantic.Field( + alias="codeByLanguage" + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/function_signature.py b/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/function_signature.py index caedf48655a..c999653dcfd 100644 --- a/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/function_signature.py +++ b/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/function_signature.py @@ -1,16 +1,17 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from .void_function_signature import VoidFunctionSignature +from ........core.pydantic_utilities import IS_PYDANTIC_V2 +from .non_void_function_signature import NonVoidFunctionSignature +from .void_function_signature_that_takes_actual_result import ( + VoidFunctionSignatureThatTakesActualResult, +) +from ........core.pydantic_utilities import UniversalRootModel import typing - -import pydantic import typing_extensions - -from ........core.pydantic_utilities import IS_PYDANTIC_V2, UniversalRootModel, update_forward_refs -from .non_void_function_signature import NonVoidFunctionSignature -from .void_function_signature import VoidFunctionSignature -from .void_function_signature_that_takes_actual_result import VoidFunctionSignatureThatTakesActualResult +import pydantic +from ........core.pydantic_utilities import update_forward_refs T_Result = typing.TypeVar("T_Result") @@ -18,19 +19,35 @@ class _Factory: def void(self, value: VoidFunctionSignature) -> FunctionSignature: if IS_PYDANTIC_V2: - return FunctionSignature(root=_FunctionSignature.Void(**value.dict(exclude_unset=True), type="void")) + return FunctionSignature( + root=_FunctionSignature.Void( + **value.dict(exclude_unset=True), type="void" + ) + ) else: - return FunctionSignature(__root__=_FunctionSignature.Void(**value.dict(exclude_unset=True), type="void")) + return FunctionSignature( + __root__=_FunctionSignature.Void( + **value.dict(exclude_unset=True), type="void" + ) + ) def non_void(self, value: NonVoidFunctionSignature) -> FunctionSignature: if IS_PYDANTIC_V2: - return FunctionSignature(root=_FunctionSignature.NonVoid(**value.dict(exclude_unset=True), type="nonVoid")) + return FunctionSignature( + root=_FunctionSignature.NonVoid( + **value.dict(exclude_unset=True), type="nonVoid" + ) + ) else: return FunctionSignature( - __root__=_FunctionSignature.NonVoid(**value.dict(exclude_unset=True), type="nonVoid") + __root__=_FunctionSignature.NonVoid( + **value.dict(exclude_unset=True), type="nonVoid" + ) ) - def void_that_takes_actual_result(self, value: VoidFunctionSignatureThatTakesActualResult) -> FunctionSignature: + def void_that_takes_actual_result( + self, value: VoidFunctionSignatureThatTakesActualResult + ) -> FunctionSignature: if IS_PYDANTIC_V2: return FunctionSignature( root=_FunctionSignature.VoidThatTakesActualResult( @@ -51,7 +68,9 @@ class FunctionSignature(UniversalRootModel): if IS_PYDANTIC_V2: root: typing_extensions.Annotated[ typing.Union[ - _FunctionSignature.Void, _FunctionSignature.NonVoid, _FunctionSignature.VoidThatTakesActualResult + _FunctionSignature.Void, + _FunctionSignature.NonVoid, + _FunctionSignature.VoidThatTakesActualResult, ], pydantic.Field(discriminator="type"), ] @@ -59,14 +78,17 @@ class FunctionSignature(UniversalRootModel): def get_as_union( self, ) -> typing.Union[ - _FunctionSignature.Void, _FunctionSignature.NonVoid, _FunctionSignature.VoidThatTakesActualResult + _FunctionSignature.Void, + _FunctionSignature.NonVoid, + _FunctionSignature.VoidThatTakesActualResult, ]: return self.root - else: __root__: typing_extensions.Annotated[ typing.Union[ - _FunctionSignature.Void, _FunctionSignature.NonVoid, _FunctionSignature.VoidThatTakesActualResult + _FunctionSignature.Void, + _FunctionSignature.NonVoid, + _FunctionSignature.VoidThatTakesActualResult, ], pydantic.Field(discriminator="type"), ] @@ -74,7 +96,9 @@ def get_as_union( def get_as_union( self, ) -> typing.Union[ - _FunctionSignature.Void, _FunctionSignature.NonVoid, _FunctionSignature.VoidThatTakesActualResult + _FunctionSignature.Void, + _FunctionSignature.NonVoid, + _FunctionSignature.VoidThatTakesActualResult, ]: return self.__root__ @@ -82,16 +106,28 @@ def visit( self, void: typing.Callable[[VoidFunctionSignature], T_Result], non_void: typing.Callable[[NonVoidFunctionSignature], T_Result], - void_that_takes_actual_result: typing.Callable[[VoidFunctionSignatureThatTakesActualResult], T_Result], + void_that_takes_actual_result: typing.Callable[ + [VoidFunctionSignatureThatTakesActualResult], T_Result + ], ) -> T_Result: unioned_value = self.get_as_union() if unioned_value.type == "void": - return void(VoidFunctionSignature(**unioned_value.dict(exclude_unset=True, exclude={"type"}))) + return void( + VoidFunctionSignature( + **unioned_value.dict(exclude_unset=True, exclude={"type"}) + ) + ) if unioned_value.type == "nonVoid": - return non_void(NonVoidFunctionSignature(**unioned_value.dict(exclude_unset=True, exclude={"type"}))) + return non_void( + NonVoidFunctionSignature( + **unioned_value.dict(exclude_unset=True, exclude={"type"}) + ) + ) if unioned_value.type == "voidThatTakesActualResult": return void_that_takes_actual_result( - VoidFunctionSignatureThatTakesActualResult(**unioned_value.dict(exclude_unset=True, exclude={"type"})) + VoidFunctionSignatureThatTakesActualResult( + **unioned_value.dict(exclude_unset=True, exclude={"type"}) + ) ) diff --git a/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/generated_files.py b/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/generated_files.py index 820cacbacc4..216e59a012a 100644 --- a/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/generated_files.py +++ b/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/generated_files.py @@ -1,21 +1,26 @@ # This file was auto-generated by Fern from our API Definition. +from ........core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ........core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .......commons.types.language import Language from .files import Files +import pydantic +from ........core.pydantic_utilities import IS_PYDANTIC_V2 class GeneratedFiles(UniversalBaseModel): - generated_test_case_files: typing.Dict[Language, Files] = pydantic.Field(alias="generatedTestCaseFiles") - generated_template_files: typing.Dict[Language, Files] = pydantic.Field(alias="generatedTemplateFiles") + generated_test_case_files: typing.Dict[Language, Files] = pydantic.Field( + alias="generatedTestCaseFiles" + ) + generated_template_files: typing.Dict[Language, Files] = pydantic.Field( + alias="generatedTemplateFiles" + ) other: typing.Dict[Language, Files] if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/get_basic_solution_file_request.py b/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/get_basic_solution_file_request.py index 7cbc893ca91..2a4006c4822 100644 --- a/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/get_basic_solution_file_request.py +++ b/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/get_basic_solution_file_request.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ........core.pydantic_utilities import UniversalBaseModel import pydantic - -from ........core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .non_void_function_signature import NonVoidFunctionSignature +from ........core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class GetBasicSolutionFileRequest(UniversalBaseModel): @@ -13,7 +12,9 @@ class GetBasicSolutionFileRequest(UniversalBaseModel): signature: NonVoidFunctionSignature if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/get_basic_solution_file_response.py b/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/get_basic_solution_file_response.py index a0129c0f7c6..37639efb303 100644 --- a/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/get_basic_solution_file_response.py +++ b/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/get_basic_solution_file_response.py @@ -1,19 +1,22 @@ # This file was auto-generated by Fern from our API Definition. +from ........core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ........core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .......commons.types.language import Language from .file_info_v_2 import FileInfoV2 +import pydantic +from ........core.pydantic_utilities import IS_PYDANTIC_V2 class GetBasicSolutionFileResponse(UniversalBaseModel): - solution_file_by_language: typing.Dict[Language, FileInfoV2] = pydantic.Field(alias="solutionFileByLanguage") + solution_file_by_language: typing.Dict[Language, FileInfoV2] = pydantic.Field( + alias="solutionFileByLanguage" + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/get_function_signature_request.py b/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/get_function_signature_request.py index aa3698f4b6e..9bd433684f1 100644 --- a/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/get_function_signature_request.py +++ b/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/get_function_signature_request.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ........core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ........core.pydantic_utilities import UniversalBaseModel from .function_signature import FunctionSignature +import pydantic +from ........core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class GetFunctionSignatureRequest(UniversalBaseModel): function_signature: FunctionSignature = pydantic.Field(alias="functionSignature") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/get_function_signature_response.py b/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/get_function_signature_response.py index 5c8f792ff1a..0f5022d3c7d 100644 --- a/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/get_function_signature_response.py +++ b/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/get_function_signature_response.py @@ -1,18 +1,21 @@ # This file was auto-generated by Fern from our API Definition. +from ........core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ........core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .......commons.types.language import Language +import pydantic +from ........core.pydantic_utilities import IS_PYDANTIC_V2 class GetFunctionSignatureResponse(UniversalBaseModel): - function_by_language: typing.Dict[Language, str] = pydantic.Field(alias="functionByLanguage") + function_by_language: typing.Dict[Language, str] = pydantic.Field( + alias="functionByLanguage" + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/get_generated_test_case_file_request.py b/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/get_generated_test_case_file_request.py index e952b0d3b1a..4f46a10b534 100644 --- a/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/get_generated_test_case_file_request.py +++ b/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/get_generated_test_case_file_request.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. +from ........core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ........core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .test_case_template import TestCaseTemplate from .test_case_v_2 import TestCaseV2 +import pydantic +from ........core.pydantic_utilities import IS_PYDANTIC_V2 class GetGeneratedTestCaseFileRequest(UniversalBaseModel): @@ -14,7 +13,9 @@ class GetGeneratedTestCaseFileRequest(UniversalBaseModel): test_case: TestCaseV2 = pydantic.Field(alias="testCase") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/get_generated_test_case_template_file_request.py b/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/get_generated_test_case_template_file_request.py index a751795ff03..3d7e86073fb 100644 --- a/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/get_generated_test_case_template_file_request.py +++ b/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/get_generated_test_case_template_file_request.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from ........core.pydantic_utilities import UniversalBaseModel +from .test_case_template import TestCaseTemplate +from ........core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ........core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .test_case_template import TestCaseTemplate - class GetGeneratedTestCaseTemplateFileRequest(UniversalBaseModel): template: TestCaseTemplate if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/lightweight_problem_info_v_2.py b/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/lightweight_problem_info_v_2.py index 4cc37ab66e5..15b5ad99df0 100644 --- a/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/lightweight_problem_info_v_2.py +++ b/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/lightweight_problem_info_v_2.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ........core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ........core.pydantic_utilities import UniversalBaseModel from .......commons.types.problem_id import ProblemId +import pydantic +import typing from .......commons.types.variable_type import VariableType +from ........core.pydantic_utilities import IS_PYDANTIC_V2 class LightweightProblemInfoV2(UniversalBaseModel): @@ -16,7 +15,9 @@ class LightweightProblemInfoV2(UniversalBaseModel): variable_types: typing.List[VariableType] = pydantic.Field(alias="variableTypes") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/non_void_function_definition.py b/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/non_void_function_definition.py index 5b733e8eac0..d24d309733f 100644 --- a/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/non_void_function_definition.py +++ b/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/non_void_function_definition.py @@ -1,20 +1,23 @@ # This file was auto-generated by Fern from our API Definition. +from ........core.pydantic_utilities import UniversalBaseModel +from .non_void_function_signature import NonVoidFunctionSignature +from .function_implementation_for_multiple_languages import ( + FunctionImplementationForMultipleLanguages, +) +from ........core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ........core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .function_implementation_for_multiple_languages import FunctionImplementationForMultipleLanguages -from .non_void_function_signature import NonVoidFunctionSignature - class NonVoidFunctionDefinition(UniversalBaseModel): signature: NonVoidFunctionSignature code: FunctionImplementationForMultipleLanguages if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/non_void_function_signature.py b/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/non_void_function_signature.py index 178c47fddfa..621cca67ab1 100644 --- a/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/non_void_function_signature.py +++ b/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/non_void_function_signature.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. +from ........core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ........core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .......commons.types.variable_type import VariableType from .parameter import Parameter +from .......commons.types.variable_type import VariableType +import pydantic +from ........core.pydantic_utilities import IS_PYDANTIC_V2 class NonVoidFunctionSignature(UniversalBaseModel): @@ -14,7 +13,9 @@ class NonVoidFunctionSignature(UniversalBaseModel): return_type: VariableType = pydantic.Field(alias="returnType") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/parameter.py b/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/parameter.py index 7674619504e..1e2d82aaf76 100644 --- a/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/parameter.py +++ b/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/parameter.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ........core.pydantic_utilities import UniversalBaseModel +from .parameter_id import ParameterId import pydantic - -from ........core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .......commons.types.variable_type import VariableType -from .parameter_id import ParameterId +from ........core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class Parameter(UniversalBaseModel): @@ -15,7 +14,9 @@ class Parameter(UniversalBaseModel): variable_type: VariableType = pydantic.Field(alias="variableType") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/problem_info_v_2.py b/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/problem_info_v_2.py index 439e065f46d..b530fdc070c 100644 --- a/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/problem_info_v_2.py +++ b/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/problem_info_v_2.py @@ -1,17 +1,16 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ........core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .......commons.types.language import Language +from ........core.pydantic_utilities import UniversalBaseModel from .......commons.types.problem_id import ProblemId +import pydantic from .......problem.types.problem_description import ProblemDescription +import typing +from .......commons.types.language import Language from .custom_files import CustomFiles from .generated_files import GeneratedFiles from .test_case_template import TestCaseTemplate from .test_case_v_2 import TestCaseV2 +from ........core.pydantic_utilities import IS_PYDANTIC_V2 class ProblemInfoV2(UniversalBaseModel): @@ -19,15 +18,21 @@ class ProblemInfoV2(UniversalBaseModel): problem_description: ProblemDescription = pydantic.Field(alias="problemDescription") problem_name: str = pydantic.Field(alias="problemName") problem_version: int = pydantic.Field(alias="problemVersion") - supported_languages: typing.Set[Language] = pydantic.Field(alias="supportedLanguages") + supported_languages: typing.Set[Language] = pydantic.Field( + alias="supportedLanguages" + ) custom_files: CustomFiles = pydantic.Field(alias="customFiles") generated_files: GeneratedFiles = pydantic.Field(alias="generatedFiles") - custom_test_case_templates: typing.List[TestCaseTemplate] = pydantic.Field(alias="customTestCaseTemplates") + custom_test_case_templates: typing.List[TestCaseTemplate] = pydantic.Field( + alias="customTestCaseTemplates" + ) testcases: typing.List[TestCaseV2] is_public: bool = pydantic.Field(alias="isPublic") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/test_case_expects.py b/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/test_case_expects.py index e4100d0d5d3..48d2c26149c 100644 --- a/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/test_case_expects.py +++ b/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/test_case_expects.py @@ -1,17 +1,20 @@ # This file was auto-generated by Fern from our API Definition. +from ........core.pydantic_utilities import UniversalBaseModel import typing - import pydantic - -from ........core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ........core.pydantic_utilities import IS_PYDANTIC_V2 class TestCaseExpects(UniversalBaseModel): - expected_stdout: typing.Optional[str] = pydantic.Field(alias="expectedStdout", default=None) + expected_stdout: typing.Optional[str] = pydantic.Field( + alias="expectedStdout", default=None + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/test_case_function.py b/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/test_case_function.py index 16fe9553ae6..f17f949ac33 100644 --- a/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/test_case_function.py +++ b/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/test_case_function.py @@ -1,35 +1,50 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from .test_case_with_actual_result_implementation import ( + TestCaseWithActualResultImplementation, +) +from ........core.pydantic_utilities import IS_PYDANTIC_V2 +from .void_function_definition import VoidFunctionDefinition +from ........core.pydantic_utilities import UniversalRootModel import typing - -import pydantic import typing_extensions - -from ........core.pydantic_utilities import IS_PYDANTIC_V2, UniversalRootModel, update_forward_refs -from .test_case_with_actual_result_implementation import TestCaseWithActualResultImplementation -from .void_function_definition import VoidFunctionDefinition +import pydantic +from ........core.pydantic_utilities import update_forward_refs T_Result = typing.TypeVar("T_Result") class _Factory: - def with_actual_result(self, value: TestCaseWithActualResultImplementation) -> TestCaseFunction: + def with_actual_result( + self, value: TestCaseWithActualResultImplementation + ) -> TestCaseFunction: if IS_PYDANTIC_V2: return TestCaseFunction( - root=_TestCaseFunction.WithActualResult(**value.dict(exclude_unset=True), type="withActualResult") + root=_TestCaseFunction.WithActualResult( + **value.dict(exclude_unset=True), type="withActualResult" + ) ) else: return TestCaseFunction( - __root__=_TestCaseFunction.WithActualResult(**value.dict(exclude_unset=True), type="withActualResult") + __root__=_TestCaseFunction.WithActualResult( + **value.dict(exclude_unset=True), type="withActualResult" + ) ) def custom(self, value: VoidFunctionDefinition) -> TestCaseFunction: if IS_PYDANTIC_V2: - return TestCaseFunction(root=_TestCaseFunction.Custom(**value.dict(exclude_unset=True), type="custom")) + return TestCaseFunction( + root=_TestCaseFunction.Custom( + **value.dict(exclude_unset=True), type="custom" + ) + ) else: - return TestCaseFunction(__root__=_TestCaseFunction.Custom(**value.dict(exclude_unset=True), type="custom")) + return TestCaseFunction( + __root__=_TestCaseFunction.Custom( + **value.dict(exclude_unset=True), type="custom" + ) + ) class TestCaseFunction(UniversalRootModel): @@ -41,30 +56,41 @@ class TestCaseFunction(UniversalRootModel): pydantic.Field(discriminator="type"), ] - def get_as_union(self) -> typing.Union[_TestCaseFunction.WithActualResult, _TestCaseFunction.Custom]: + def get_as_union( + self, + ) -> typing.Union[_TestCaseFunction.WithActualResult, _TestCaseFunction.Custom]: return self.root - else: __root__: typing_extensions.Annotated[ typing.Union[_TestCaseFunction.WithActualResult, _TestCaseFunction.Custom], pydantic.Field(discriminator="type"), ] - def get_as_union(self) -> typing.Union[_TestCaseFunction.WithActualResult, _TestCaseFunction.Custom]: + def get_as_union( + self, + ) -> typing.Union[_TestCaseFunction.WithActualResult, _TestCaseFunction.Custom]: return self.__root__ def visit( self, - with_actual_result: typing.Callable[[TestCaseWithActualResultImplementation], T_Result], + with_actual_result: typing.Callable[ + [TestCaseWithActualResultImplementation], T_Result + ], custom: typing.Callable[[VoidFunctionDefinition], T_Result], ) -> T_Result: unioned_value = self.get_as_union() if unioned_value.type == "withActualResult": return with_actual_result( - TestCaseWithActualResultImplementation(**unioned_value.dict(exclude_unset=True, exclude={"type"})) + TestCaseWithActualResultImplementation( + **unioned_value.dict(exclude_unset=True, exclude={"type"}) + ) ) if unioned_value.type == "custom": - return custom(VoidFunctionDefinition(**unioned_value.dict(exclude_unset=True, exclude={"type"}))) + return custom( + VoidFunctionDefinition( + **unioned_value.dict(exclude_unset=True, exclude={"type"}) + ) + ) class _TestCaseFunction: diff --git a/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/test_case_implementation.py b/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/test_case_implementation.py index 6921858dd9d..3189960cda1 100644 --- a/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/test_case_implementation.py +++ b/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/test_case_implementation.py @@ -1,20 +1,21 @@ # This file was auto-generated by Fern from our API Definition. +from ........core.pydantic_utilities import UniversalBaseModel +from .test_case_implementation_description import TestCaseImplementationDescription +from .test_case_function import TestCaseFunction +from ........core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ........core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .test_case_function import TestCaseFunction -from .test_case_implementation_description import TestCaseImplementationDescription - class TestCaseImplementation(UniversalBaseModel): description: TestCaseImplementationDescription function: TestCaseFunction if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/test_case_implementation_description.py b/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/test_case_implementation_description.py index 0ff38aeb16b..dc3b825f0db 100644 --- a/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/test_case_implementation_description.py +++ b/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/test_case_implementation_description.py @@ -1,18 +1,21 @@ # This file was auto-generated by Fern from our API Definition. +from ........core.pydantic_utilities import UniversalBaseModel import typing - +from .test_case_implementation_description_board import ( + TestCaseImplementationDescriptionBoard, +) +from ........core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ........core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .test_case_implementation_description_board import TestCaseImplementationDescriptionBoard - class TestCaseImplementationDescription(UniversalBaseModel): boards: typing.List[TestCaseImplementationDescriptionBoard] if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/test_case_implementation_description_board.py b/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/test_case_implementation_description_board.py index 16029b2eef5..07805b24b11 100644 --- a/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/test_case_implementation_description_board.py +++ b/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/test_case_implementation_description_board.py @@ -1,14 +1,14 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ........core.pydantic_utilities import IS_PYDANTIC_V2 +from .parameter_id import ParameterId +from ........core.pydantic_utilities import UniversalRootModel import typing - -import pydantic import typing_extensions - -from ........core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel, UniversalRootModel, update_forward_refs -from .parameter_id import ParameterId +import pydantic +from ........core.pydantic_utilities import UniversalBaseModel +from ........core.pydantic_utilities import update_forward_refs T_Result = typing.TypeVar("T_Result") @@ -17,21 +17,29 @@ class _Factory: def html(self, value: str) -> TestCaseImplementationDescriptionBoard: if IS_PYDANTIC_V2: return TestCaseImplementationDescriptionBoard( - root=_TestCaseImplementationDescriptionBoard.Html(type="html", value=value) + root=_TestCaseImplementationDescriptionBoard.Html( + type="html", value=value + ) ) else: return TestCaseImplementationDescriptionBoard( - __root__=_TestCaseImplementationDescriptionBoard.Html(type="html", value=value) + __root__=_TestCaseImplementationDescriptionBoard.Html( + type="html", value=value + ) ) def param_id(self, value: ParameterId) -> TestCaseImplementationDescriptionBoard: if IS_PYDANTIC_V2: return TestCaseImplementationDescriptionBoard( - root=_TestCaseImplementationDescriptionBoard.ParamId(type="paramId", value=value) + root=_TestCaseImplementationDescriptionBoard.ParamId( + type="paramId", value=value + ) ) else: return TestCaseImplementationDescriptionBoard( - __root__=_TestCaseImplementationDescriptionBoard.ParamId(type="paramId", value=value) + __root__=_TestCaseImplementationDescriptionBoard.ParamId( + type="paramId", value=value + ) ) @@ -40,32 +48,41 @@ class TestCaseImplementationDescriptionBoard(UniversalRootModel): if IS_PYDANTIC_V2: root: typing_extensions.Annotated[ - typing.Union[_TestCaseImplementationDescriptionBoard.Html, _TestCaseImplementationDescriptionBoard.ParamId], + typing.Union[ + _TestCaseImplementationDescriptionBoard.Html, + _TestCaseImplementationDescriptionBoard.ParamId, + ], pydantic.Field(discriminator="type"), ] def get_as_union( self, ) -> typing.Union[ - _TestCaseImplementationDescriptionBoard.Html, _TestCaseImplementationDescriptionBoard.ParamId + _TestCaseImplementationDescriptionBoard.Html, + _TestCaseImplementationDescriptionBoard.ParamId, ]: return self.root - else: __root__: typing_extensions.Annotated[ - typing.Union[_TestCaseImplementationDescriptionBoard.Html, _TestCaseImplementationDescriptionBoard.ParamId], + typing.Union[ + _TestCaseImplementationDescriptionBoard.Html, + _TestCaseImplementationDescriptionBoard.ParamId, + ], pydantic.Field(discriminator="type"), ] def get_as_union( self, ) -> typing.Union[ - _TestCaseImplementationDescriptionBoard.Html, _TestCaseImplementationDescriptionBoard.ParamId + _TestCaseImplementationDescriptionBoard.Html, + _TestCaseImplementationDescriptionBoard.ParamId, ]: return self.__root__ def visit( - self, html: typing.Callable[[str], T_Result], param_id: typing.Callable[[ParameterId], T_Result] + self, + html: typing.Callable[[str], T_Result], + param_id: typing.Callable[[ParameterId], T_Result], ) -> T_Result: unioned_value = self.get_as_union() if unioned_value.type == "html": diff --git a/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/test_case_implementation_reference.py b/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/test_case_implementation_reference.py index 37b35514c25..98571da4e67 100644 --- a/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/test_case_implementation_reference.py +++ b/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/test_case_implementation_reference.py @@ -1,15 +1,15 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from .test_case_template_id import TestCaseTemplateId +from ........core.pydantic_utilities import IS_PYDANTIC_V2 +from .test_case_implementation import TestCaseImplementation +from ........core.pydantic_utilities import UniversalRootModel import typing - -import pydantic import typing_extensions - -from ........core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel, UniversalRootModel, update_forward_refs -from .test_case_implementation import TestCaseImplementation -from .test_case_template_id import TestCaseTemplateId +import pydantic +from ........core.pydantic_utilities import UniversalBaseModel +from ........core.pydantic_utilities import update_forward_refs T_Result = typing.TypeVar("T_Result") @@ -18,14 +18,20 @@ class _Factory: def template_id(self, value: TestCaseTemplateId) -> TestCaseImplementationReference: if IS_PYDANTIC_V2: return TestCaseImplementationReference( - root=_TestCaseImplementationReference.TemplateId(type="templateId", value=value) + root=_TestCaseImplementationReference.TemplateId( + type="templateId", value=value + ) ) else: return TestCaseImplementationReference( - __root__=_TestCaseImplementationReference.TemplateId(type="templateId", value=value) + __root__=_TestCaseImplementationReference.TemplateId( + type="templateId", value=value + ) ) - def implementation(self, value: TestCaseImplementation) -> TestCaseImplementationReference: + def implementation( + self, value: TestCaseImplementation + ) -> TestCaseImplementationReference: if IS_PYDANTIC_V2: return TestCaseImplementationReference( root=_TestCaseImplementationReference.Implementation( @@ -45,24 +51,35 @@ class TestCaseImplementationReference(UniversalRootModel): if IS_PYDANTIC_V2: root: typing_extensions.Annotated[ - typing.Union[_TestCaseImplementationReference.TemplateId, _TestCaseImplementationReference.Implementation], + typing.Union[ + _TestCaseImplementationReference.TemplateId, + _TestCaseImplementationReference.Implementation, + ], pydantic.Field(discriminator="type"), ] def get_as_union( self, - ) -> typing.Union[_TestCaseImplementationReference.TemplateId, _TestCaseImplementationReference.Implementation]: + ) -> typing.Union[ + _TestCaseImplementationReference.TemplateId, + _TestCaseImplementationReference.Implementation, + ]: return self.root - else: __root__: typing_extensions.Annotated[ - typing.Union[_TestCaseImplementationReference.TemplateId, _TestCaseImplementationReference.Implementation], + typing.Union[ + _TestCaseImplementationReference.TemplateId, + _TestCaseImplementationReference.Implementation, + ], pydantic.Field(discriminator="type"), ] def get_as_union( self, - ) -> typing.Union[_TestCaseImplementationReference.TemplateId, _TestCaseImplementationReference.Implementation]: + ) -> typing.Union[ + _TestCaseImplementationReference.TemplateId, + _TestCaseImplementationReference.Implementation, + ]: return self.__root__ def visit( @@ -74,7 +91,11 @@ def visit( if unioned_value.type == "templateId": return template_id(unioned_value.value) if unioned_value.type == "implementation": - return implementation(TestCaseImplementation(**unioned_value.dict(exclude_unset=True, exclude={"type"}))) + return implementation( + TestCaseImplementation( + **unioned_value.dict(exclude_unset=True, exclude={"type"}) + ) + ) class _TestCaseImplementationReference: diff --git a/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/test_case_metadata.py b/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/test_case_metadata.py index bc3946f1833..1e92d3e64a1 100644 --- a/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/test_case_metadata.py +++ b/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/test_case_metadata.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. +from ........core.pydantic_utilities import UniversalBaseModel +from .test_case_id import TestCaseId +from ........core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ........core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .test_case_id import TestCaseId - class TestCaseMetadata(UniversalBaseModel): id: TestCaseId @@ -14,7 +13,9 @@ class TestCaseMetadata(UniversalBaseModel): hidden: bool if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/test_case_template.py b/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/test_case_template.py index 8be522e54c1..ea0a1c8d1a0 100644 --- a/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/test_case_template.py +++ b/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/test_case_template.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ........core.pydantic_utilities import UniversalBaseModel +from .test_case_template_id import TestCaseTemplateId import pydantic - -from ........core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .test_case_implementation import TestCaseImplementation -from .test_case_template_id import TestCaseTemplateId +from ........core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class TestCaseTemplate(UniversalBaseModel): @@ -15,7 +14,9 @@ class TestCaseTemplate(UniversalBaseModel): implementation: TestCaseImplementation if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/test_case_v_2.py b/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/test_case_v_2.py index 62274462e9a..0f06e2266ba 100644 --- a/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/test_case_v_2.py +++ b/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/test_case_v_2.py @@ -1,15 +1,14 @@ # This file was auto-generated by Fern from our API Definition. +from ........core.pydantic_utilities import UniversalBaseModel +from .test_case_metadata import TestCaseMetadata +from .test_case_implementation_reference import TestCaseImplementationReference import typing - -import pydantic - -from ........core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .......commons.types.variable_value import VariableValue from .parameter_id import ParameterId +from .......commons.types.variable_value import VariableValue from .test_case_expects import TestCaseExpects -from .test_case_implementation_reference import TestCaseImplementationReference -from .test_case_metadata import TestCaseMetadata +from ........core.pydantic_utilities import IS_PYDANTIC_V2 +import pydantic class TestCaseV2(UniversalBaseModel): @@ -19,7 +18,9 @@ class TestCaseV2(UniversalBaseModel): expects: typing.Optional[TestCaseExpects] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/test_case_with_actual_result_implementation.py b/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/test_case_with_actual_result_implementation.py index 98954d71d5b..184b98a13fa 100644 --- a/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/test_case_with_actual_result_implementation.py +++ b/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/test_case_with_actual_result_implementation.py @@ -1,20 +1,25 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ........core.pydantic_utilities import UniversalBaseModel +from .non_void_function_definition import NonVoidFunctionDefinition import pydantic - -from ........core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .assert_correctness_check import AssertCorrectnessCheck -from .non_void_function_definition import NonVoidFunctionDefinition +from ........core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class TestCaseWithActualResultImplementation(UniversalBaseModel): - get_actual_result: NonVoidFunctionDefinition = pydantic.Field(alias="getActualResult") - assert_correctness_check: AssertCorrectnessCheck = pydantic.Field(alias="assertCorrectnessCheck") + get_actual_result: NonVoidFunctionDefinition = pydantic.Field( + alias="getActualResult" + ) + assert_correctness_check: AssertCorrectnessCheck = pydantic.Field( + alias="assertCorrectnessCheck" + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/void_function_definition.py b/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/void_function_definition.py index b666eb1bf55..9d72b78f49c 100644 --- a/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/void_function_definition.py +++ b/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/void_function_definition.py @@ -1,12 +1,13 @@ # This file was auto-generated by Fern from our API Definition. +from ........core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ........core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .function_implementation_for_multiple_languages import FunctionImplementationForMultipleLanguages from .parameter import Parameter +from .function_implementation_for_multiple_languages import ( + FunctionImplementationForMultipleLanguages, +) +from ........core.pydantic_utilities import IS_PYDANTIC_V2 +import pydantic class VoidFunctionDefinition(UniversalBaseModel): @@ -14,7 +15,9 @@ class VoidFunctionDefinition(UniversalBaseModel): code: FunctionImplementationForMultipleLanguages if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/void_function_definition_that_takes_actual_result.py b/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/void_function_definition_that_takes_actual_result.py index b0dcd218b86..a37d4ae146e 100644 --- a/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/void_function_definition_that_takes_actual_result.py +++ b/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/void_function_definition_that_takes_actual_result.py @@ -1,12 +1,13 @@ # This file was auto-generated by Fern from our API Definition. +from ........core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ........core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .function_implementation_for_multiple_languages import FunctionImplementationForMultipleLanguages from .parameter import Parameter +import pydantic +from .function_implementation_for_multiple_languages import ( + FunctionImplementationForMultipleLanguages, +) +from ........core.pydantic_utilities import IS_PYDANTIC_V2 class VoidFunctionDefinitionThatTakesActualResult(UniversalBaseModel): @@ -14,11 +15,15 @@ class VoidFunctionDefinitionThatTakesActualResult(UniversalBaseModel): The generated signature will include an additional param, actualResult """ - additional_parameters: typing.List[Parameter] = pydantic.Field(alias="additionalParameters") + additional_parameters: typing.List[Parameter] = pydantic.Field( + alias="additionalParameters" + ) code: FunctionImplementationForMultipleLanguages if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/void_function_signature.py b/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/void_function_signature.py index 247aa531420..1e28b0d76a1 100644 --- a/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/void_function_signature.py +++ b/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/void_function_signature.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from ........core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ........core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .parameter import Parameter +from ........core.pydantic_utilities import IS_PYDANTIC_V2 +import pydantic class VoidFunctionSignature(UniversalBaseModel): parameters: typing.List[Parameter] if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/void_function_signature_that_takes_actual_result.py b/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/void_function_signature_that_takes_actual_result.py index 5f766fd374d..bcb8d4e74bc 100644 --- a/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/void_function_signature_that_takes_actual_result.py +++ b/seed/fastapi/trace/resources/v_2/resources/v_3/resources/problem/types/void_function_signature_that_takes_actual_result.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. +from ........core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ........core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .......commons.types.variable_type import VariableType from .parameter import Parameter +from .......commons.types.variable_type import VariableType +import pydantic +from ........core.pydantic_utilities import IS_PYDANTIC_V2 class VoidFunctionSignatureThatTakesActualResult(UniversalBaseModel): @@ -14,7 +13,9 @@ class VoidFunctionSignatureThatTakesActualResult(UniversalBaseModel): actual_result_type: VariableType = pydantic.Field(alias="actualResultType") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/trace/resources/v_2/service/service.py b/seed/fastapi/trace/resources/v_2/service/service.py index 8d2e2e52979..aafe8ccfa20 100644 --- a/seed/fastapi/trace/resources/v_2/service/service.py +++ b/seed/fastapi/trace/resources/v_2/service/service.py @@ -1,16 +1,14 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.abstract_fern_service import AbstractFernService +import typing import abc -import functools +import fastapi import inspect +from ....core.exceptions.fern_http_exception import FernHTTPException import logging -import typing - -import fastapi +import functools import starlette - -from ....core.abstract_fern_service import AbstractFernService -from ....core.exceptions.fern_http_exception import FernHTTPException from ....core.route_args import get_route_args @@ -24,8 +22,7 @@ class AbstractV2Service(AbstractFernService): """ @abc.abstractmethod - def test(self, *, x_random_header: typing.Optional[str] = None) -> None: - ... + def test(self, *, x_random_header: typing.Optional[str] = None) -> None: ... """ Below are internal methods used by Fern to register your implementation. @@ -40,14 +37,24 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_test(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.test) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "x_random_header": - new_parameters.append(parameter.replace(default=fastapi.Header(default=None, alias="X-Random-Header"))) + new_parameters.append( + parameter.replace( + default=fastapi.Header(default=None, alias="X-Random-Header") + ) + ) else: new_parameters.append(parameter) - setattr(cls.test, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.test, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.test) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> None: diff --git a/seed/fastapi/trace/security.py b/seed/fastapi/trace/security.py index bab014441e1..4ccabc21106 100644 --- a/seed/fastapi/trace/security.py +++ b/seed/fastapi/trace/security.py @@ -1,8 +1,8 @@ # This file was auto-generated by Fern from our API Definition. +from .core.security.bearer import BearerToken import fastapi - -from .core.security.bearer import BearerToken, HTTPBearer +from .core.security.bearer import HTTPBearer ApiAuth = BearerToken diff --git a/seed/fastapi/undiscriminated-unions/core/abstract_fern_service.py b/seed/fastapi/undiscriminated-unions/core/abstract_fern_service.py index da7c8dc49c4..9966b4876da 100644 --- a/seed/fastapi/undiscriminated-unions/core/abstract_fern_service.py +++ b/seed/fastapi/undiscriminated-unions/core/abstract_fern_service.py @@ -7,5 +7,4 @@ class AbstractFernService(abc.ABC): @classmethod - def _init_fern(cls, router: fastapi.APIRouter) -> None: - ... + def _init_fern(cls, router: fastapi.APIRouter) -> None: ... diff --git a/seed/fastapi/undiscriminated-unions/core/datetime_utils.py b/seed/fastapi/undiscriminated-unions/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/fastapi/undiscriminated-unions/core/datetime_utils.py +++ b/seed/fastapi/undiscriminated-unions/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/fastapi/undiscriminated-unions/core/exceptions/__init__.py b/seed/fastapi/undiscriminated-unions/core/exceptions/__init__.py index 297d6e06f5f..dae4b8980c1 100644 --- a/seed/fastapi/undiscriminated-unions/core/exceptions/__init__.py +++ b/seed/fastapi/undiscriminated-unions/core/exceptions/__init__.py @@ -1,7 +1,11 @@ # This file was auto-generated by Fern from our API Definition. from .fern_http_exception import FernHTTPException -from .handlers import default_exception_handler, fern_http_exception_handler, http_exception_handler +from .handlers import ( + default_exception_handler, + fern_http_exception_handler, + http_exception_handler, +) from .unauthorized import UnauthorizedException __all__ = [ diff --git a/seed/fastapi/undiscriminated-unions/core/exceptions/fern_http_exception.py b/seed/fastapi/undiscriminated-unions/core/exceptions/fern_http_exception.py index bdf03862487..81610359a7f 100644 --- a/seed/fastapi/undiscriminated-unions/core/exceptions/fern_http_exception.py +++ b/seed/fastapi/undiscriminated-unions/core/exceptions/fern_http_exception.py @@ -1,14 +1,16 @@ # This file was auto-generated by Fern from our API Definition. import abc -import typing - import fastapi +import typing class FernHTTPException(abc.ABC, fastapi.HTTPException): def __init__( - self, status_code: int, name: typing.Optional[str] = None, content: typing.Optional[typing.Any] = None + self, + status_code: int, + name: typing.Optional[str] = None, + content: typing.Optional[typing.Any] = None, ): super().__init__(status_code=status_code) self.name = name @@ -17,4 +19,6 @@ def __init__( def to_json_response(self) -> fastapi.responses.JSONResponse: content = fastapi.encoders.jsonable_encoder(self.content, exclude_none=True) - return fastapi.responses.JSONResponse(content=content, status_code=self.status_code) + return fastapi.responses.JSONResponse( + content=content, status_code=self.status_code + ) diff --git a/seed/fastapi/undiscriminated-unions/core/exceptions/handlers.py b/seed/fastapi/undiscriminated-unions/core/exceptions/handlers.py index 6d8c4155c5a..ae1c2741f06 100644 --- a/seed/fastapi/undiscriminated-unions/core/exceptions/handlers.py +++ b/seed/fastapi/undiscriminated-unions/core/exceptions/handlers.py @@ -2,32 +2,49 @@ import logging -import fastapi import starlette import starlette.exceptions +import fastapi + from .fern_http_exception import FernHTTPException def fern_http_exception_handler( - request: fastapi.requests.Request, exc: FernHTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: FernHTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) return exc.to_json_response() def http_exception_handler( - request: fastapi.requests.Request, exc: starlette.exceptions.HTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: starlette.exceptions.HTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=exc.status_code, content=exc.detail).to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=exc.status_code, content=exc.detail + ).to_json_response() def default_exception_handler( - request: fastapi.requests.Request, exc: Exception, skip_log: bool = False + request: fastapi.requests.Request, + exc: Exception, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=500, content="Internal Server Error").to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=500, content="Internal Server Error" + ).to_json_response() diff --git a/seed/fastapi/undiscriminated-unions/core/pydantic_utilities.py b/seed/fastapi/undiscriminated-unions/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/fastapi/undiscriminated-unions/core/pydantic_utilities.py +++ b/seed/fastapi/undiscriminated-unions/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/fastapi/undiscriminated-unions/core/route_args.py b/seed/fastapi/undiscriminated-unions/core/route_args.py index 4228e2fe05d..bd940bf4ddd 100644 --- a/seed/fastapi/undiscriminated-unions/core/route_args.py +++ b/seed/fastapi/undiscriminated-unions/core/route_args.py @@ -20,9 +20,15 @@ class RouteArgs(typing_extensions.TypedDict): DEFAULT_ROUTE_ARGS = RouteArgs(openapi_extra=None, tags=None, include_in_schema=True) -def get_route_args(endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str) -> RouteArgs: - unwrapped = inspect.unwrap(endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY))) - route_args = typing.cast(RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS)) +def get_route_args( + endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str +) -> RouteArgs: + unwrapped = inspect.unwrap( + endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY)) + ) + route_args = typing.cast( + RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS) + ) if route_args["tags"] is None: return RouteArgs( openapi_extra=route_args["openapi_extra"], @@ -56,7 +62,11 @@ def decorator(endpoint_function: T) -> T: setattr( endpoint_function, FERN_CONFIG_KEY, - RouteArgs(openapi_extra=openapi_extra, tags=tags, include_in_schema=include_in_schema), + RouteArgs( + openapi_extra=openapi_extra, + tags=tags, + include_in_schema=include_in_schema, + ), ) return endpoint_function diff --git a/seed/fastapi/undiscriminated-unions/register.py b/seed/fastapi/undiscriminated-unions/register.py index 489967bf003..95088b3c80e 100644 --- a/seed/fastapi/undiscriminated-unions/register.py +++ b/seed/fastapi/undiscriminated-unions/register.py @@ -1,31 +1,33 @@ # This file was auto-generated by Fern from our API Definition. -import glob -import importlib -import os -import types -import typing - import fastapi -import starlette.exceptions +from .resources.union.service.service import AbstractUnionService +import typing from fastapi import params - -from .core.abstract_fern_service import AbstractFernService -from .core.exceptions import default_exception_handler, fern_http_exception_handler, http_exception_handler from .core.exceptions.fern_http_exception import FernHTTPException -from .resources.union.service.service import AbstractUnionService +from .core.exceptions import fern_http_exception_handler +import starlette.exceptions +from .core.exceptions import http_exception_handler +from .core.exceptions import default_exception_handler +from .core.abstract_fern_service import AbstractFernService +import types +import os +import glob +import importlib def register( _app: fastapi.FastAPI, *, union: AbstractUnionService, - dependencies: typing.Optional[typing.Sequence[params.Depends]] = None + dependencies: typing.Optional[typing.Sequence[params.Depends]] = None, ) -> None: _app.include_router(__register_service(union), dependencies=dependencies) _app.add_exception_handler(FernHTTPException, fern_http_exception_handler) # type: ignore - _app.add_exception_handler(starlette.exceptions.HTTPException, http_exception_handler) # type: ignore + _app.add_exception_handler( + starlette.exceptions.HTTPException, http_exception_handler + ) # type: ignore _app.add_exception_handler(Exception, default_exception_handler) # type: ignore @@ -37,7 +39,9 @@ def __register_service(service: AbstractFernService) -> fastapi.APIRouter: def register_validators(module: types.ModuleType) -> None: validators_directory: str = os.path.dirname(module.__file__) # type: ignore - for path in glob.glob(os.path.join(validators_directory, "**/*.py"), recursive=True): + for path in glob.glob( + os.path.join(validators_directory, "**/*.py"), recursive=True + ): if os.path.isfile(path): relative_path = os.path.relpath(path, start=validators_directory) module_path = ".".join([module.__name__] + relative_path[:-3].split("/")) diff --git a/seed/fastapi/undiscriminated-unions/resources/union/service/service.py b/seed/fastapi/undiscriminated-unions/resources/union/service/service.py index 0d9cdf1b754..42b96a7c7ed 100644 --- a/seed/fastapi/undiscriminated-unions/resources/union/service/service.py +++ b/seed/fastapi/undiscriminated-unions/resources/union/service/service.py @@ -1,18 +1,16 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.abstract_fern_service import AbstractFernService +from ..types.my_union import MyUnion import abc -import functools +from ..types.metadata import Metadata +import fastapi import inspect -import logging import typing - -import fastapi - -from ....core.abstract_fern_service import AbstractFernService from ....core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools from ....core.route_args import get_route_args -from ..types.metadata import Metadata -from ..types.my_union import MyUnion class AbstractUnionService(AbstractFernService): @@ -25,12 +23,10 @@ class AbstractUnionService(AbstractFernService): """ @abc.abstractmethod - def get(self, *, body: MyUnion) -> MyUnion: - ... + def get(self, *, body: MyUnion) -> MyUnion: ... @abc.abstractmethod - def get_metadata(self) -> Metadata: - ... + def get_metadata(self) -> Metadata: ... """ Below are internal methods used by Fern to register your implementation. @@ -46,14 +42,20 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_get(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) else: new_parameters.append(parameter) - setattr(cls.get, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> MyUnion: @@ -82,12 +84,18 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> MyUnion: def __init_get_metadata(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_metadata) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) else: new_parameters.append(parameter) - setattr(cls.get_metadata, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_metadata, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_metadata) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> Metadata: diff --git a/seed/fastapi/undiscriminated-unions/resources/union/types/key.py b/seed/fastapi/undiscriminated-unions/resources/union/types/key.py index 3c379619874..c143ecf00b2 100644 --- a/seed/fastapi/undiscriminated-unions/resources/union/types/key.py +++ b/seed/fastapi/undiscriminated-unions/resources/union/types/key.py @@ -1,7 +1,6 @@ # This file was auto-generated by Fern from our API Definition. import typing - from .key_type import KeyType Key = typing.Union[KeyType, typing.Literal["default"]] diff --git a/seed/fastapi/undiscriminated-unions/resources/union/types/key_type.py b/seed/fastapi/undiscriminated-unions/resources/union/types/key_type.py index 00733e5c035..4a6de166ef9 100644 --- a/seed/fastapi/undiscriminated-unions/resources/union/types/key_type.py +++ b/seed/fastapi/undiscriminated-unions/resources/union/types/key_type.py @@ -10,7 +10,9 @@ class KeyType(str, enum.Enum): NAME = "name" VALUE = "value" - def visit(self, name: typing.Callable[[], T_Result], value: typing.Callable[[], T_Result]) -> T_Result: + def visit( + self, name: typing.Callable[[], T_Result], value: typing.Callable[[], T_Result] + ) -> T_Result: if self is KeyType.NAME: return name() if self is KeyType.VALUE: diff --git a/seed/fastapi/undiscriminated-unions/resources/union/types/metadata.py b/seed/fastapi/undiscriminated-unions/resources/union/types/metadata.py index 793bb560d84..f279ed30260 100644 --- a/seed/fastapi/undiscriminated-unions/resources/union/types/metadata.py +++ b/seed/fastapi/undiscriminated-unions/resources/union/types/metadata.py @@ -1,7 +1,6 @@ # This file was auto-generated by Fern from our API Definition. import typing - from .key import Key """ diff --git a/seed/fastapi/undiscriminated-unions/resources/union/types/my_union.py b/seed/fastapi/undiscriminated-unions/resources/union/types/my_union.py index 6b8c3dae2f4..9a8a6426908 100644 --- a/seed/fastapi/undiscriminated-unions/resources/union/types/my_union.py +++ b/seed/fastapi/undiscriminated-unions/resources/union/types/my_union.py @@ -2,4 +2,11 @@ import typing -MyUnion = typing.Union[str, typing.List[str], int, typing.List[int], typing.List[typing.List[int]], typing.Set[str]] +MyUnion = typing.Union[ + str, + typing.List[str], + int, + typing.List[int], + typing.List[typing.List[int]], + typing.Set[str], +] diff --git a/seed/fastapi/unions/core/abstract_fern_service.py b/seed/fastapi/unions/core/abstract_fern_service.py index da7c8dc49c4..9966b4876da 100644 --- a/seed/fastapi/unions/core/abstract_fern_service.py +++ b/seed/fastapi/unions/core/abstract_fern_service.py @@ -7,5 +7,4 @@ class AbstractFernService(abc.ABC): @classmethod - def _init_fern(cls, router: fastapi.APIRouter) -> None: - ... + def _init_fern(cls, router: fastapi.APIRouter) -> None: ... diff --git a/seed/fastapi/unions/core/datetime_utils.py b/seed/fastapi/unions/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/fastapi/unions/core/datetime_utils.py +++ b/seed/fastapi/unions/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/fastapi/unions/core/exceptions/__init__.py b/seed/fastapi/unions/core/exceptions/__init__.py index 297d6e06f5f..dae4b8980c1 100644 --- a/seed/fastapi/unions/core/exceptions/__init__.py +++ b/seed/fastapi/unions/core/exceptions/__init__.py @@ -1,7 +1,11 @@ # This file was auto-generated by Fern from our API Definition. from .fern_http_exception import FernHTTPException -from .handlers import default_exception_handler, fern_http_exception_handler, http_exception_handler +from .handlers import ( + default_exception_handler, + fern_http_exception_handler, + http_exception_handler, +) from .unauthorized import UnauthorizedException __all__ = [ diff --git a/seed/fastapi/unions/core/exceptions/fern_http_exception.py b/seed/fastapi/unions/core/exceptions/fern_http_exception.py index bdf03862487..81610359a7f 100644 --- a/seed/fastapi/unions/core/exceptions/fern_http_exception.py +++ b/seed/fastapi/unions/core/exceptions/fern_http_exception.py @@ -1,14 +1,16 @@ # This file was auto-generated by Fern from our API Definition. import abc -import typing - import fastapi +import typing class FernHTTPException(abc.ABC, fastapi.HTTPException): def __init__( - self, status_code: int, name: typing.Optional[str] = None, content: typing.Optional[typing.Any] = None + self, + status_code: int, + name: typing.Optional[str] = None, + content: typing.Optional[typing.Any] = None, ): super().__init__(status_code=status_code) self.name = name @@ -17,4 +19,6 @@ def __init__( def to_json_response(self) -> fastapi.responses.JSONResponse: content = fastapi.encoders.jsonable_encoder(self.content, exclude_none=True) - return fastapi.responses.JSONResponse(content=content, status_code=self.status_code) + return fastapi.responses.JSONResponse( + content=content, status_code=self.status_code + ) diff --git a/seed/fastapi/unions/core/exceptions/handlers.py b/seed/fastapi/unions/core/exceptions/handlers.py index 6d8c4155c5a..ae1c2741f06 100644 --- a/seed/fastapi/unions/core/exceptions/handlers.py +++ b/seed/fastapi/unions/core/exceptions/handlers.py @@ -2,32 +2,49 @@ import logging -import fastapi import starlette import starlette.exceptions +import fastapi + from .fern_http_exception import FernHTTPException def fern_http_exception_handler( - request: fastapi.requests.Request, exc: FernHTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: FernHTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) return exc.to_json_response() def http_exception_handler( - request: fastapi.requests.Request, exc: starlette.exceptions.HTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: starlette.exceptions.HTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=exc.status_code, content=exc.detail).to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=exc.status_code, content=exc.detail + ).to_json_response() def default_exception_handler( - request: fastapi.requests.Request, exc: Exception, skip_log: bool = False + request: fastapi.requests.Request, + exc: Exception, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=500, content="Internal Server Error").to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=500, content="Internal Server Error" + ).to_json_response() diff --git a/seed/fastapi/unions/core/pydantic_utilities.py b/seed/fastapi/unions/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/fastapi/unions/core/pydantic_utilities.py +++ b/seed/fastapi/unions/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/fastapi/unions/core/route_args.py b/seed/fastapi/unions/core/route_args.py index 4228e2fe05d..bd940bf4ddd 100644 --- a/seed/fastapi/unions/core/route_args.py +++ b/seed/fastapi/unions/core/route_args.py @@ -20,9 +20,15 @@ class RouteArgs(typing_extensions.TypedDict): DEFAULT_ROUTE_ARGS = RouteArgs(openapi_extra=None, tags=None, include_in_schema=True) -def get_route_args(endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str) -> RouteArgs: - unwrapped = inspect.unwrap(endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY))) - route_args = typing.cast(RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS)) +def get_route_args( + endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str +) -> RouteArgs: + unwrapped = inspect.unwrap( + endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY)) + ) + route_args = typing.cast( + RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS) + ) if route_args["tags"] is None: return RouteArgs( openapi_extra=route_args["openapi_extra"], @@ -56,7 +62,11 @@ def decorator(endpoint_function: T) -> T: setattr( endpoint_function, FERN_CONFIG_KEY, - RouteArgs(openapi_extra=openapi_extra, tags=tags, include_in_schema=include_in_schema), + RouteArgs( + openapi_extra=openapi_extra, + tags=tags, + include_in_schema=include_in_schema, + ), ) return endpoint_function diff --git a/seed/fastapi/unions/register.py b/seed/fastapi/unions/register.py index 489967bf003..95088b3c80e 100644 --- a/seed/fastapi/unions/register.py +++ b/seed/fastapi/unions/register.py @@ -1,31 +1,33 @@ # This file was auto-generated by Fern from our API Definition. -import glob -import importlib -import os -import types -import typing - import fastapi -import starlette.exceptions +from .resources.union.service.service import AbstractUnionService +import typing from fastapi import params - -from .core.abstract_fern_service import AbstractFernService -from .core.exceptions import default_exception_handler, fern_http_exception_handler, http_exception_handler from .core.exceptions.fern_http_exception import FernHTTPException -from .resources.union.service.service import AbstractUnionService +from .core.exceptions import fern_http_exception_handler +import starlette.exceptions +from .core.exceptions import http_exception_handler +from .core.exceptions import default_exception_handler +from .core.abstract_fern_service import AbstractFernService +import types +import os +import glob +import importlib def register( _app: fastapi.FastAPI, *, union: AbstractUnionService, - dependencies: typing.Optional[typing.Sequence[params.Depends]] = None + dependencies: typing.Optional[typing.Sequence[params.Depends]] = None, ) -> None: _app.include_router(__register_service(union), dependencies=dependencies) _app.add_exception_handler(FernHTTPException, fern_http_exception_handler) # type: ignore - _app.add_exception_handler(starlette.exceptions.HTTPException, http_exception_handler) # type: ignore + _app.add_exception_handler( + starlette.exceptions.HTTPException, http_exception_handler + ) # type: ignore _app.add_exception_handler(Exception, default_exception_handler) # type: ignore @@ -37,7 +39,9 @@ def __register_service(service: AbstractFernService) -> fastapi.APIRouter: def register_validators(module: types.ModuleType) -> None: validators_directory: str = os.path.dirname(module.__file__) # type: ignore - for path in glob.glob(os.path.join(validators_directory, "**/*.py"), recursive=True): + for path in glob.glob( + os.path.join(validators_directory, "**/*.py"), recursive=True + ): if os.path.isfile(path): relative_path = os.path.relpath(path, start=validators_directory) module_path = ".".join([module.__name__] + relative_path[:-3].split("/")) diff --git a/seed/fastapi/unions/resources/types/types/bar.py b/seed/fastapi/unions/resources/types/types/bar.py index c2e73f56d3c..ae5717ea2c0 100644 --- a/seed/fastapi/unions/resources/types/types/bar.py +++ b/seed/fastapi/unions/resources/types/types/bar.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class Bar(UniversalBaseModel): name: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/unions/resources/types/types/foo.py b/seed/fastapi/unions/resources/types/types/foo.py index 719ef36be5b..4fbb1185af3 100644 --- a/seed/fastapi/unions/resources/types/types/foo.py +++ b/seed/fastapi/unions/resources/types/types/foo.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class Foo(UniversalBaseModel): name: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/unions/resources/types/types/union.py b/seed/fastapi/unions/resources/types/types/union.py index 77d6aafdb28..5be6316733c 100644 --- a/seed/fastapi/unions/resources/types/types/union.py +++ b/seed/fastapi/unions/resources/types/types/union.py @@ -1,15 +1,15 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from .foo import Foo as resources_types_types_foo_Foo +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +from .bar import Bar as resources_types_types_bar_Bar +from ....core.pydantic_utilities import UniversalRootModel import typing - -import pydantic import typing_extensions - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel, UniversalRootModel, update_forward_refs -from .bar import Bar as resources_types_types_bar_Bar -from .foo import Foo as resources_types_types_foo_Foo +import pydantic +from ....core.pydantic_utilities import UniversalBaseModel +from ....core.pydantic_utilities import update_forward_refs T_Result = typing.TypeVar("T_Result") @@ -36,11 +36,12 @@ class Union(UniversalRootModel): factory: typing.ClassVar[_Factory] = _Factory() if IS_PYDANTIC_V2: - root: typing_extensions.Annotated[typing.Union[_Union.Foo, _Union.Bar], pydantic.Field(discriminator="type")] + root: typing_extensions.Annotated[ + typing.Union[_Union.Foo, _Union.Bar], pydantic.Field(discriminator="type") + ] def get_as_union(self) -> typing.Union[_Union.Foo, _Union.Bar]: return self.root - else: __root__: typing_extensions.Annotated[ typing.Union[_Union.Foo, _Union.Bar], pydantic.Field(discriminator="type") diff --git a/seed/fastapi/unions/resources/types/types/union_with_base_properties.py b/seed/fastapi/unions/resources/types/types/union_with_base_properties.py index e09ba6e4e00..fa4f58a8e98 100644 --- a/seed/fastapi/unions/resources/types/types/union_with_base_properties.py +++ b/seed/fastapi/unions/resources/types/types/union_with_base_properties.py @@ -1,14 +1,14 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +from .foo import Foo as resources_types_types_foo_Foo +from ....core.pydantic_utilities import UniversalRootModel import typing - -import pydantic import typing_extensions - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel, UniversalRootModel, update_forward_refs -from .foo import Foo as resources_types_types_foo_Foo +import pydantic +from ....core.pydantic_utilities import UniversalBaseModel +from ....core.pydantic_utilities import update_forward_refs T_Result = typing.TypeVar("T_Result") @@ -16,24 +16,36 @@ class _Factory: def integer(self, value: int) -> UnionWithBaseProperties: if IS_PYDANTIC_V2: - return UnionWithBaseProperties(root=_UnionWithBaseProperties.Integer(type="integer", value=value)) + return UnionWithBaseProperties( + root=_UnionWithBaseProperties.Integer(type="integer", value=value) + ) else: - return UnionWithBaseProperties(__root__=_UnionWithBaseProperties.Integer(type="integer", value=value)) + return UnionWithBaseProperties( + __root__=_UnionWithBaseProperties.Integer(type="integer", value=value) + ) def string(self, value: str) -> UnionWithBaseProperties: if IS_PYDANTIC_V2: - return UnionWithBaseProperties(root=_UnionWithBaseProperties.String(type="string", value=value)) + return UnionWithBaseProperties( + root=_UnionWithBaseProperties.String(type="string", value=value) + ) else: - return UnionWithBaseProperties(__root__=_UnionWithBaseProperties.String(type="string", value=value)) + return UnionWithBaseProperties( + __root__=_UnionWithBaseProperties.String(type="string", value=value) + ) def foo(self, value: resources_types_types_foo_Foo) -> UnionWithBaseProperties: if IS_PYDANTIC_V2: return UnionWithBaseProperties( - root=_UnionWithBaseProperties.Foo(**value.dict(exclude_unset=True), type="foo") + root=_UnionWithBaseProperties.Foo( + **value.dict(exclude_unset=True), type="foo" + ) ) else: return UnionWithBaseProperties( - __root__=_UnionWithBaseProperties.Foo(**value.dict(exclude_unset=True), type="foo") + __root__=_UnionWithBaseProperties.Foo( + **value.dict(exclude_unset=True), type="foo" + ) ) @@ -43,7 +55,9 @@ class UnionWithBaseProperties(UniversalRootModel): if IS_PYDANTIC_V2: root: typing_extensions.Annotated[ typing.Union[ - _UnionWithBaseProperties.Integer, _UnionWithBaseProperties.String, _UnionWithBaseProperties.Foo + _UnionWithBaseProperties.Integer, + _UnionWithBaseProperties.String, + _UnionWithBaseProperties.Foo, ], pydantic.Field(discriminator="type"), ] @@ -51,14 +65,17 @@ class UnionWithBaseProperties(UniversalRootModel): def get_as_union( self, ) -> typing.Union[ - _UnionWithBaseProperties.Integer, _UnionWithBaseProperties.String, _UnionWithBaseProperties.Foo + _UnionWithBaseProperties.Integer, + _UnionWithBaseProperties.String, + _UnionWithBaseProperties.Foo, ]: return self.root - else: __root__: typing_extensions.Annotated[ typing.Union[ - _UnionWithBaseProperties.Integer, _UnionWithBaseProperties.String, _UnionWithBaseProperties.Foo + _UnionWithBaseProperties.Integer, + _UnionWithBaseProperties.String, + _UnionWithBaseProperties.Foo, ], pydantic.Field(discriminator="type"), ] @@ -66,7 +83,9 @@ def get_as_union( def get_as_union( self, ) -> typing.Union[ - _UnionWithBaseProperties.Integer, _UnionWithBaseProperties.String, _UnionWithBaseProperties.Foo + _UnionWithBaseProperties.Integer, + _UnionWithBaseProperties.String, + _UnionWithBaseProperties.Foo, ]: return self.__root__ @@ -82,7 +101,11 @@ def visit( if unioned_value.type == "string": return string(unioned_value.value) if unioned_value.type == "foo": - return foo(resources_types_types_foo_Foo(**unioned_value.dict(exclude_unset=True, exclude={"type"}))) + return foo( + resources_types_types_foo_Foo( + **unioned_value.dict(exclude_unset=True, exclude={"type"}) + ) + ) class _UnionWithBaseProperties: diff --git a/seed/fastapi/unions/resources/types/types/union_with_discriminant.py b/seed/fastapi/unions/resources/types/types/union_with_discriminant.py index d96b2281fa3..03c9d3d6891 100644 --- a/seed/fastapi/unions/resources/types/types/union_with_discriminant.py +++ b/seed/fastapi/unions/resources/types/types/union_with_discriminant.py @@ -1,15 +1,15 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from .foo import Foo as resources_types_types_foo_Foo +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +from .bar import Bar as resources_types_types_bar_Bar +from ....core.pydantic_utilities import UniversalRootModel import typing - -import pydantic import typing_extensions - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel, UniversalRootModel, update_forward_refs -from .bar import Bar as resources_types_types_bar_Bar -from .foo import Foo as resources_types_types_foo_Foo +import pydantic +from ....core.pydantic_utilities import UniversalBaseModel +from ....core.pydantic_utilities import update_forward_refs T_Result = typing.TypeVar("T_Result") @@ -17,15 +17,23 @@ class _Factory: def foo(self, value: resources_types_types_foo_Foo) -> UnionWithDiscriminant: if IS_PYDANTIC_V2: - return UnionWithDiscriminant(root=_UnionWithDiscriminant.Foo(type="foo", foo=value)) + return UnionWithDiscriminant( + root=_UnionWithDiscriminant.Foo(type="foo", foo=value) + ) else: - return UnionWithDiscriminant(__root__=_UnionWithDiscriminant.Foo(type="foo", foo=value)) + return UnionWithDiscriminant( + __root__=_UnionWithDiscriminant.Foo(type="foo", foo=value) + ) def bar(self, value: resources_types_types_bar_Bar) -> UnionWithDiscriminant: if IS_PYDANTIC_V2: - return UnionWithDiscriminant(root=_UnionWithDiscriminant.Bar(type="bar", bar=value)) + return UnionWithDiscriminant( + root=_UnionWithDiscriminant.Bar(type="bar", bar=value) + ) else: - return UnionWithDiscriminant(__root__=_UnionWithDiscriminant.Bar(type="bar", bar=value)) + return UnionWithDiscriminant( + __root__=_UnionWithDiscriminant.Bar(type="bar", bar=value) + ) class UnionWithDiscriminant(UniversalRootModel): @@ -33,18 +41,23 @@ class UnionWithDiscriminant(UniversalRootModel): if IS_PYDANTIC_V2: root: typing_extensions.Annotated[ - typing.Union[_UnionWithDiscriminant.Foo, _UnionWithDiscriminant.Bar], pydantic.Field(discriminator="type") + typing.Union[_UnionWithDiscriminant.Foo, _UnionWithDiscriminant.Bar], + pydantic.Field(discriminator="type"), ] - def get_as_union(self) -> typing.Union[_UnionWithDiscriminant.Foo, _UnionWithDiscriminant.Bar]: + def get_as_union( + self, + ) -> typing.Union[_UnionWithDiscriminant.Foo, _UnionWithDiscriminant.Bar]: return self.root - else: __root__: typing_extensions.Annotated[ - typing.Union[_UnionWithDiscriminant.Foo, _UnionWithDiscriminant.Bar], pydantic.Field(discriminator="type") + typing.Union[_UnionWithDiscriminant.Foo, _UnionWithDiscriminant.Bar], + pydantic.Field(discriminator="type"), ] - def get_as_union(self) -> typing.Union[_UnionWithDiscriminant.Foo, _UnionWithDiscriminant.Bar]: + def get_as_union( + self, + ) -> typing.Union[_UnionWithDiscriminant.Foo, _UnionWithDiscriminant.Bar]: return self.__root__ def visit( diff --git a/seed/fastapi/unions/resources/types/types/union_with_literal.py b/seed/fastapi/unions/resources/types/types/union_with_literal.py index 03468335a3d..3ea83ade881 100644 --- a/seed/fastapi/unions/resources/types/types/union_with_literal.py +++ b/seed/fastapi/unions/resources/types/types/union_with_literal.py @@ -1,10 +1,11 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - import typing - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel, UniversalRootModel, update_forward_refs +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +from ....core.pydantic_utilities import UniversalRootModel +from ....core.pydantic_utilities import UniversalBaseModel +from ....core.pydantic_utilities import update_forward_refs T_Result = typing.TypeVar("T_Result") @@ -12,9 +13,13 @@ class _Factory: def fern(self, value: typing.Literal["fern"]) -> UnionWithLiteral: if IS_PYDANTIC_V2: - return UnionWithLiteral(root=_UnionWithLiteral.Fern(type="fern", value=value)) + return UnionWithLiteral( + root=_UnionWithLiteral.Fern(type="fern", value=value) + ) else: - return UnionWithLiteral(__root__=_UnionWithLiteral.Fern(type="fern", value=value)) + return UnionWithLiteral( + __root__=_UnionWithLiteral.Fern(type="fern", value=value) + ) class UnionWithLiteral(UniversalRootModel): @@ -25,14 +30,15 @@ class UnionWithLiteral(UniversalRootModel): def get_as_union(self) -> typing.Union[_UnionWithLiteral.Fern]: return self.root - else: __root__: typing.Union[_UnionWithLiteral.Fern] def get_as_union(self) -> typing.Union[_UnionWithLiteral.Fern]: return self.__root__ - def visit(self, fern: typing.Callable[[typing.Literal["fern"]], T_Result]) -> T_Result: + def visit( + self, fern: typing.Callable[[typing.Literal["fern"]], T_Result] + ) -> T_Result: unioned_value = self.get_as_union() if unioned_value.type == "fern": return fern(unioned_value.value) diff --git a/seed/fastapi/unions/resources/types/types/union_with_optional_time.py b/seed/fastapi/unions/resources/types/types/union_with_optional_time.py index 8a4c7b33376..2ae8f9c3b92 100644 --- a/seed/fastapi/unions/resources/types/types/union_with_optional_time.py +++ b/seed/fastapi/unions/resources/types/types/union_with_optional_time.py @@ -1,14 +1,14 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - -import datetime as dt import typing - -import pydantic +import datetime as dt +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +from ....core.pydantic_utilities import UniversalRootModel import typing_extensions - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel, UniversalRootModel, update_forward_refs +import pydantic +from ....core.pydantic_utilities import UniversalBaseModel +from ....core.pydantic_utilities import update_forward_refs T_Result = typing.TypeVar("T_Result") @@ -16,15 +16,23 @@ class _Factory: def date(self, value: typing.Optional[dt.date]) -> UnionWithOptionalTime: if IS_PYDANTIC_V2: - return UnionWithOptionalTime(root=_UnionWithOptionalTime.Date(type="date", value=value)) + return UnionWithOptionalTime( + root=_UnionWithOptionalTime.Date(type="date", value=value) + ) else: - return UnionWithOptionalTime(__root__=_UnionWithOptionalTime.Date(type="date", value=value)) + return UnionWithOptionalTime( + __root__=_UnionWithOptionalTime.Date(type="date", value=value) + ) def dateimte(self, value: typing.Optional[dt.datetime]) -> UnionWithOptionalTime: if IS_PYDANTIC_V2: - return UnionWithOptionalTime(root=_UnionWithOptionalTime.Dateimte(type="dateimte", value=value)) + return UnionWithOptionalTime( + root=_UnionWithOptionalTime.Dateimte(type="dateimte", value=value) + ) else: - return UnionWithOptionalTime(__root__=_UnionWithOptionalTime.Dateimte(type="dateimte", value=value)) + return UnionWithOptionalTime( + __root__=_UnionWithOptionalTime.Dateimte(type="dateimte", value=value) + ) class UnionWithOptionalTime(UniversalRootModel): @@ -36,16 +44,19 @@ class UnionWithOptionalTime(UniversalRootModel): pydantic.Field(discriminator="type"), ] - def get_as_union(self) -> typing.Union[_UnionWithOptionalTime.Date, _UnionWithOptionalTime.Dateimte]: + def get_as_union( + self, + ) -> typing.Union[_UnionWithOptionalTime.Date, _UnionWithOptionalTime.Dateimte]: return self.root - else: __root__: typing_extensions.Annotated[ typing.Union[_UnionWithOptionalTime.Date, _UnionWithOptionalTime.Dateimte], pydantic.Field(discriminator="type"), ] - def get_as_union(self) -> typing.Union[_UnionWithOptionalTime.Date, _UnionWithOptionalTime.Dateimte]: + def get_as_union( + self, + ) -> typing.Union[_UnionWithOptionalTime.Date, _UnionWithOptionalTime.Dateimte]: return self.__root__ def visit( diff --git a/seed/fastapi/unions/resources/types/types/union_with_primitive.py b/seed/fastapi/unions/resources/types/types/union_with_primitive.py index 11f55d93e7d..08843ac8036 100644 --- a/seed/fastapi/unions/resources/types/types/union_with_primitive.py +++ b/seed/fastapi/unions/resources/types/types/union_with_primitive.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +from ....core.pydantic_utilities import UniversalRootModel import typing - -import pydantic import typing_extensions - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel, UniversalRootModel, update_forward_refs +import pydantic +from ....core.pydantic_utilities import UniversalBaseModel +from ....core.pydantic_utilities import update_forward_refs T_Result = typing.TypeVar("T_Result") @@ -15,15 +15,23 @@ class _Factory: def integer(self, value: int) -> UnionWithPrimitive: if IS_PYDANTIC_V2: - return UnionWithPrimitive(root=_UnionWithPrimitive.Integer(type="integer", value=value)) + return UnionWithPrimitive( + root=_UnionWithPrimitive.Integer(type="integer", value=value) + ) else: - return UnionWithPrimitive(__root__=_UnionWithPrimitive.Integer(type="integer", value=value)) + return UnionWithPrimitive( + __root__=_UnionWithPrimitive.Integer(type="integer", value=value) + ) def string(self, value: str) -> UnionWithPrimitive: if IS_PYDANTIC_V2: - return UnionWithPrimitive(root=_UnionWithPrimitive.String(type="string", value=value)) + return UnionWithPrimitive( + root=_UnionWithPrimitive.String(type="string", value=value) + ) else: - return UnionWithPrimitive(__root__=_UnionWithPrimitive.String(type="string", value=value)) + return UnionWithPrimitive( + __root__=_UnionWithPrimitive.String(type="string", value=value) + ) class UnionWithPrimitive(UniversalRootModel): @@ -31,21 +39,30 @@ class UnionWithPrimitive(UniversalRootModel): if IS_PYDANTIC_V2: root: typing_extensions.Annotated[ - typing.Union[_UnionWithPrimitive.Integer, _UnionWithPrimitive.String], pydantic.Field(discriminator="type") + typing.Union[_UnionWithPrimitive.Integer, _UnionWithPrimitive.String], + pydantic.Field(discriminator="type"), ] - def get_as_union(self) -> typing.Union[_UnionWithPrimitive.Integer, _UnionWithPrimitive.String]: + def get_as_union( + self, + ) -> typing.Union[_UnionWithPrimitive.Integer, _UnionWithPrimitive.String]: return self.root - else: __root__: typing_extensions.Annotated[ - typing.Union[_UnionWithPrimitive.Integer, _UnionWithPrimitive.String], pydantic.Field(discriminator="type") + typing.Union[_UnionWithPrimitive.Integer, _UnionWithPrimitive.String], + pydantic.Field(discriminator="type"), ] - def get_as_union(self) -> typing.Union[_UnionWithPrimitive.Integer, _UnionWithPrimitive.String]: + def get_as_union( + self, + ) -> typing.Union[_UnionWithPrimitive.Integer, _UnionWithPrimitive.String]: return self.__root__ - def visit(self, integer: typing.Callable[[int], T_Result], string: typing.Callable[[str], T_Result]) -> T_Result: + def visit( + self, + integer: typing.Callable[[int], T_Result], + string: typing.Callable[[str], T_Result], + ) -> T_Result: unioned_value = self.get_as_union() if unioned_value.type == "integer": return integer(unioned_value.value) diff --git a/seed/fastapi/unions/resources/types/types/union_with_single_element.py b/seed/fastapi/unions/resources/types/types/union_with_single_element.py index f2a50151178..a27deef0a75 100644 --- a/seed/fastapi/unions/resources/types/types/union_with_single_element.py +++ b/seed/fastapi/unions/resources/types/types/union_with_single_element.py @@ -1,11 +1,11 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - -import typing - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalRootModel, update_forward_refs from .foo import Foo as resources_types_types_foo_Foo +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +from ....core.pydantic_utilities import UniversalRootModel +import typing +from ....core.pydantic_utilities import update_forward_refs T_Result = typing.TypeVar("T_Result") @@ -14,11 +14,15 @@ class _Factory: def foo(self, value: resources_types_types_foo_Foo) -> UnionWithSingleElement: if IS_PYDANTIC_V2: return UnionWithSingleElement( - root=_UnionWithSingleElement.Foo(**value.dict(exclude_unset=True), type="foo") + root=_UnionWithSingleElement.Foo( + **value.dict(exclude_unset=True), type="foo" + ) ) else: return UnionWithSingleElement( - __root__=_UnionWithSingleElement.Foo(**value.dict(exclude_unset=True), type="foo") + __root__=_UnionWithSingleElement.Foo( + **value.dict(exclude_unset=True), type="foo" + ) ) @@ -30,17 +34,22 @@ class UnionWithSingleElement(UniversalRootModel): def get_as_union(self) -> typing.Union[_UnionWithSingleElement.Foo]: return self.root - else: __root__: typing.Union[_UnionWithSingleElement.Foo] def get_as_union(self) -> typing.Union[_UnionWithSingleElement.Foo]: return self.__root__ - def visit(self, foo: typing.Callable[[resources_types_types_foo_Foo], T_Result]) -> T_Result: + def visit( + self, foo: typing.Callable[[resources_types_types_foo_Foo], T_Result] + ) -> T_Result: unioned_value = self.get_as_union() if unioned_value.type == "foo": - return foo(resources_types_types_foo_Foo(**unioned_value.dict(exclude_unset=True, exclude={"type"}))) + return foo( + resources_types_types_foo_Foo( + **unioned_value.dict(exclude_unset=True, exclude={"type"}) + ) + ) class _UnionWithSingleElement: diff --git a/seed/fastapi/unions/resources/types/types/union_with_time.py b/seed/fastapi/unions/resources/types/types/union_with_time.py index 41872f220ee..4baf24cd82a 100644 --- a/seed/fastapi/unions/resources/types/types/union_with_time.py +++ b/seed/fastapi/unions/resources/types/types/union_with_time.py @@ -1,14 +1,14 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import datetime as dt +from ....core.pydantic_utilities import UniversalRootModel import typing - -import pydantic import typing_extensions - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel, UniversalRootModel, update_forward_refs +import pydantic +from ....core.pydantic_utilities import UniversalBaseModel +from ....core.pydantic_utilities import update_forward_refs T_Result = typing.TypeVar("T_Result") @@ -18,7 +18,9 @@ def value(self, value: int) -> UnionWithTime: if IS_PYDANTIC_V2: return UnionWithTime(root=_UnionWithTime.Value(type="value", value=value)) else: - return UnionWithTime(__root__=_UnionWithTime.Value(type="value", value=value)) + return UnionWithTime( + __root__=_UnionWithTime.Value(type="value", value=value) + ) def date(self, value: dt.date) -> UnionWithTime: if IS_PYDANTIC_V2: @@ -28,9 +30,13 @@ def date(self, value: dt.date) -> UnionWithTime: def datetime(self, value: dt.datetime) -> UnionWithTime: if IS_PYDANTIC_V2: - return UnionWithTime(root=_UnionWithTime.Datetime(type="datetime", value=value)) + return UnionWithTime( + root=_UnionWithTime.Datetime(type="datetime", value=value) + ) else: - return UnionWithTime(__root__=_UnionWithTime.Datetime(type="datetime", value=value)) + return UnionWithTime( + __root__=_UnionWithTime.Datetime(type="datetime", value=value) + ) class UnionWithTime(UniversalRootModel): @@ -38,20 +44,31 @@ class UnionWithTime(UniversalRootModel): if IS_PYDANTIC_V2: root: typing_extensions.Annotated[ - typing.Union[_UnionWithTime.Value, _UnionWithTime.Date, _UnionWithTime.Datetime], + typing.Union[ + _UnionWithTime.Value, _UnionWithTime.Date, _UnionWithTime.Datetime + ], pydantic.Field(discriminator="type"), ] - def get_as_union(self) -> typing.Union[_UnionWithTime.Value, _UnionWithTime.Date, _UnionWithTime.Datetime]: + def get_as_union( + self, + ) -> typing.Union[ + _UnionWithTime.Value, _UnionWithTime.Date, _UnionWithTime.Datetime + ]: return self.root - else: __root__: typing_extensions.Annotated[ - typing.Union[_UnionWithTime.Value, _UnionWithTime.Date, _UnionWithTime.Datetime], + typing.Union[ + _UnionWithTime.Value, _UnionWithTime.Date, _UnionWithTime.Datetime + ], pydantic.Field(discriminator="type"), ] - def get_as_union(self) -> typing.Union[_UnionWithTime.Value, _UnionWithTime.Date, _UnionWithTime.Datetime]: + def get_as_union( + self, + ) -> typing.Union[ + _UnionWithTime.Value, _UnionWithTime.Date, _UnionWithTime.Datetime + ]: return self.__root__ def visit( diff --git a/seed/fastapi/unions/resources/types/types/union_with_unknown.py b/seed/fastapi/unions/resources/types/types/union_with_unknown.py index dc9ee8c621e..780a8c2161c 100644 --- a/seed/fastapi/unions/resources/types/types/union_with_unknown.py +++ b/seed/fastapi/unions/resources/types/types/union_with_unknown.py @@ -1,14 +1,14 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from .foo import Foo as resources_types_types_foo_Foo +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +from ....core.pydantic_utilities import UniversalRootModel import typing - -import pydantic import typing_extensions - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel, UniversalRootModel, update_forward_refs -from .foo import Foo as resources_types_types_foo_Foo +import pydantic +from ....core.pydantic_utilities import UniversalBaseModel +from ....core.pydantic_utilities import update_forward_refs T_Result = typing.TypeVar("T_Result") @@ -16,9 +16,15 @@ class _Factory: def foo(self, value: resources_types_types_foo_Foo) -> UnionWithUnknown: if IS_PYDANTIC_V2: - return UnionWithUnknown(root=_UnionWithUnknown.Foo(**value.dict(exclude_unset=True), type="foo")) + return UnionWithUnknown( + root=_UnionWithUnknown.Foo(**value.dict(exclude_unset=True), type="foo") + ) else: - return UnionWithUnknown(__root__=_UnionWithUnknown.Foo(**value.dict(exclude_unset=True), type="foo")) + return UnionWithUnknown( + __root__=_UnionWithUnknown.Foo( + **value.dict(exclude_unset=True), type="foo" + ) + ) def unknown(self) -> UnionWithUnknown: if IS_PYDANTIC_V2: @@ -32,26 +38,37 @@ class UnionWithUnknown(UniversalRootModel): if IS_PYDANTIC_V2: root: typing_extensions.Annotated[ - typing.Union[_UnionWithUnknown.Foo, _UnionWithUnknown.Unknown], pydantic.Field(discriminator="type") + typing.Union[_UnionWithUnknown.Foo, _UnionWithUnknown.Unknown], + pydantic.Field(discriminator="type"), ] - def get_as_union(self) -> typing.Union[_UnionWithUnknown.Foo, _UnionWithUnknown.Unknown]: + def get_as_union( + self, + ) -> typing.Union[_UnionWithUnknown.Foo, _UnionWithUnknown.Unknown]: return self.root - else: __root__: typing_extensions.Annotated[ - typing.Union[_UnionWithUnknown.Foo, _UnionWithUnknown.Unknown], pydantic.Field(discriminator="type") + typing.Union[_UnionWithUnknown.Foo, _UnionWithUnknown.Unknown], + pydantic.Field(discriminator="type"), ] - def get_as_union(self) -> typing.Union[_UnionWithUnknown.Foo, _UnionWithUnknown.Unknown]: + def get_as_union( + self, + ) -> typing.Union[_UnionWithUnknown.Foo, _UnionWithUnknown.Unknown]: return self.__root__ def visit( - self, foo: typing.Callable[[resources_types_types_foo_Foo], T_Result], unknown: typing.Callable[[], T_Result] + self, + foo: typing.Callable[[resources_types_types_foo_Foo], T_Result], + unknown: typing.Callable[[], T_Result], ) -> T_Result: unioned_value = self.get_as_union() if unioned_value.type == "foo": - return foo(resources_types_types_foo_Foo(**unioned_value.dict(exclude_unset=True, exclude={"type"}))) + return foo( + resources_types_types_foo_Foo( + **unioned_value.dict(exclude_unset=True, exclude={"type"}) + ) + ) if unioned_value.type == "unknown": return unknown() diff --git a/seed/fastapi/unions/resources/types/types/union_without_key.py b/seed/fastapi/unions/resources/types/types/union_without_key.py index e728455a547..94209b7c55a 100644 --- a/seed/fastapi/unions/resources/types/types/union_without_key.py +++ b/seed/fastapi/unions/resources/types/types/union_without_key.py @@ -1,15 +1,14 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from .foo import Foo as resources_types_types_foo_Foo +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +from .bar import Bar as resources_types_types_bar_Bar +from ....core.pydantic_utilities import UniversalRootModel import typing - -import pydantic import typing_extensions - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalRootModel, update_forward_refs -from .bar import Bar as resources_types_types_bar_Bar -from .foo import Foo as resources_types_types_foo_Foo +import pydantic +from ....core.pydantic_utilities import update_forward_refs T_Result = typing.TypeVar("T_Result") @@ -17,15 +16,27 @@ class _Factory: def foo(self, value: resources_types_types_foo_Foo) -> UnionWithoutKey: if IS_PYDANTIC_V2: - return UnionWithoutKey(root=_UnionWithoutKey.Foo(**value.dict(exclude_unset=True), type="foo")) + return UnionWithoutKey( + root=_UnionWithoutKey.Foo(**value.dict(exclude_unset=True), type="foo") + ) else: - return UnionWithoutKey(__root__=_UnionWithoutKey.Foo(**value.dict(exclude_unset=True), type="foo")) + return UnionWithoutKey( + __root__=_UnionWithoutKey.Foo( + **value.dict(exclude_unset=True), type="foo" + ) + ) def bar(self, value: resources_types_types_bar_Bar) -> UnionWithoutKey: if IS_PYDANTIC_V2: - return UnionWithoutKey(root=_UnionWithoutKey.Bar(**value.dict(exclude_unset=True), type="bar")) + return UnionWithoutKey( + root=_UnionWithoutKey.Bar(**value.dict(exclude_unset=True), type="bar") + ) else: - return UnionWithoutKey(__root__=_UnionWithoutKey.Bar(**value.dict(exclude_unset=True), type="bar")) + return UnionWithoutKey( + __root__=_UnionWithoutKey.Bar( + **value.dict(exclude_unset=True), type="bar" + ) + ) class UnionWithoutKey(UniversalRootModel): @@ -33,18 +44,23 @@ class UnionWithoutKey(UniversalRootModel): if IS_PYDANTIC_V2: root: typing_extensions.Annotated[ - typing.Union[_UnionWithoutKey.Foo, _UnionWithoutKey.Bar], pydantic.Field(discriminator="type") + typing.Union[_UnionWithoutKey.Foo, _UnionWithoutKey.Bar], + pydantic.Field(discriminator="type"), ] - def get_as_union(self) -> typing.Union[_UnionWithoutKey.Foo, _UnionWithoutKey.Bar]: + def get_as_union( + self, + ) -> typing.Union[_UnionWithoutKey.Foo, _UnionWithoutKey.Bar]: return self.root - else: __root__: typing_extensions.Annotated[ - typing.Union[_UnionWithoutKey.Foo, _UnionWithoutKey.Bar], pydantic.Field(discriminator="type") + typing.Union[_UnionWithoutKey.Foo, _UnionWithoutKey.Bar], + pydantic.Field(discriminator="type"), ] - def get_as_union(self) -> typing.Union[_UnionWithoutKey.Foo, _UnionWithoutKey.Bar]: + def get_as_union( + self, + ) -> typing.Union[_UnionWithoutKey.Foo, _UnionWithoutKey.Bar]: return self.__root__ def visit( @@ -54,9 +70,17 @@ def visit( ) -> T_Result: unioned_value = self.get_as_union() if unioned_value.type == "foo": - return foo(resources_types_types_foo_Foo(**unioned_value.dict(exclude_unset=True, exclude={"type"}))) + return foo( + resources_types_types_foo_Foo( + **unioned_value.dict(exclude_unset=True, exclude={"type"}) + ) + ) if unioned_value.type == "bar": - return bar(resources_types_types_bar_Bar(**unioned_value.dict(exclude_unset=True, exclude={"type"}))) + return bar( + resources_types_types_bar_Bar( + **unioned_value.dict(exclude_unset=True, exclude={"type"}) + ) + ) class _UnionWithoutKey: diff --git a/seed/fastapi/unions/resources/union/service/service.py b/seed/fastapi/unions/resources/union/service/service.py index 61e9880a7dd..2d6713da570 100644 --- a/seed/fastapi/unions/resources/union/service/service.py +++ b/seed/fastapi/unions/resources/union/service/service.py @@ -1,17 +1,15 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.abstract_fern_service import AbstractFernService +from ..types.shape import Shape import abc -import functools +import fastapi import inspect -import logging import typing - -import fastapi - -from ....core.abstract_fern_service import AbstractFernService from ....core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools from ....core.route_args import get_route_args -from ..types.shape import Shape class AbstractUnionService(AbstractFernService): @@ -24,12 +22,10 @@ class AbstractUnionService(AbstractFernService): """ @abc.abstractmethod - def get(self, *, id: str) -> Shape: - ... + def get(self, *, id: str) -> Shape: ... @abc.abstractmethod - def update(self, *, body: Shape) -> bool: - ... + def update(self, *, body: Shape) -> bool: ... """ Below are internal methods used by Fern to register your implementation. @@ -45,14 +41,20 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_get(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "id": new_parameters.append(parameter.replace(default=fastapi.Path(...))) else: new_parameters.append(parameter) - setattr(cls.get, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> Shape: @@ -81,14 +83,20 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> Shape: def __init_update(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.update) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) else: new_parameters.append(parameter) - setattr(cls.update, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.update, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.update) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> bool: diff --git a/seed/fastapi/unions/resources/union/types/circle.py b/seed/fastapi/unions/resources/union/types/circle.py index b9618172b5f..83ff96c670f 100644 --- a/seed/fastapi/unions/resources/union/types/circle.py +++ b/seed/fastapi/unions/resources/union/types/circle.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class Circle(UniversalBaseModel): radius: float if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/unions/resources/union/types/get_shape_request.py b/seed/fastapi/unions/resources/union/types/get_shape_request.py index 5d17d2acda6..e75c2638af0 100644 --- a/seed/fastapi/unions/resources/union/types/get_shape_request.py +++ b/seed/fastapi/unions/resources/union/types/get_shape_request.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class GetShapeRequest(UniversalBaseModel): id: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/unions/resources/union/types/shape.py b/seed/fastapi/unions/resources/union/types/shape.py index b0d5c389503..03f43cb2a8e 100644 --- a/seed/fastapi/unions/resources/union/types/shape.py +++ b/seed/fastapi/unions/resources/union/types/shape.py @@ -1,15 +1,14 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - -import typing - -import pydantic -import typing_extensions - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalRootModel, update_forward_refs from .circle import Circle as resources_union_types_circle_Circle +from ....core.pydantic_utilities import IS_PYDANTIC_V2 from .square import Square as resources_union_types_square_Square +from ....core.pydantic_utilities import UniversalRootModel +import typing +import typing_extensions +import pydantic +from ....core.pydantic_utilities import update_forward_refs T_Result = typing.TypeVar("T_Result") @@ -17,15 +16,23 @@ class _Factory: def circle(self, value: resources_union_types_circle_Circle) -> Shape: if IS_PYDANTIC_V2: - return Shape(root=_Shape.Circle(**value.dict(exclude_unset=True), type="circle")) + return Shape( + root=_Shape.Circle(**value.dict(exclude_unset=True), type="circle") + ) else: - return Shape(__root__=_Shape.Circle(**value.dict(exclude_unset=True), type="circle")) + return Shape( + __root__=_Shape.Circle(**value.dict(exclude_unset=True), type="circle") + ) def square(self, value: resources_union_types_square_Square) -> Shape: if IS_PYDANTIC_V2: - return Shape(root=_Shape.Square(**value.dict(exclude_unset=True), type="square")) + return Shape( + root=_Shape.Square(**value.dict(exclude_unset=True), type="square") + ) else: - return Shape(__root__=_Shape.Square(**value.dict(exclude_unset=True), type="square")) + return Shape( + __root__=_Shape.Square(**value.dict(exclude_unset=True), type="square") + ) class Shape(UniversalRootModel): @@ -33,15 +40,16 @@ class Shape(UniversalRootModel): if IS_PYDANTIC_V2: root: typing_extensions.Annotated[ - typing.Union[_Shape.Circle, _Shape.Square], pydantic.Field(discriminator="type") + typing.Union[_Shape.Circle, _Shape.Square], + pydantic.Field(discriminator="type"), ] def get_as_union(self) -> typing.Union[_Shape.Circle, _Shape.Square]: return self.root - else: __root__: typing_extensions.Annotated[ - typing.Union[_Shape.Circle, _Shape.Square], pydantic.Field(discriminator="type") + typing.Union[_Shape.Circle, _Shape.Square], + pydantic.Field(discriminator="type"), ] def get_as_union(self) -> typing.Union[_Shape.Circle, _Shape.Square]: @@ -55,11 +63,15 @@ def visit( unioned_value = self.get_as_union() if unioned_value.type == "circle": return circle( - resources_union_types_circle_Circle(**unioned_value.dict(exclude_unset=True, exclude={"type"})) + resources_union_types_circle_Circle( + **unioned_value.dict(exclude_unset=True, exclude={"type"}) + ) ) if unioned_value.type == "square": return square( - resources_union_types_square_Square(**unioned_value.dict(exclude_unset=True, exclude={"type"})) + resources_union_types_square_Square( + **unioned_value.dict(exclude_unset=True, exclude={"type"}) + ) ) diff --git a/seed/fastapi/unions/resources/union/types/square.py b/seed/fastapi/unions/resources/union/types/square.py index d6233f8afb9..c0d868eead5 100644 --- a/seed/fastapi/unions/resources/union/types/square.py +++ b/seed/fastapi/unions/resources/union/types/square.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class Square(UniversalBaseModel): length: float if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/unknown/core/abstract_fern_service.py b/seed/fastapi/unknown/core/abstract_fern_service.py index da7c8dc49c4..9966b4876da 100644 --- a/seed/fastapi/unknown/core/abstract_fern_service.py +++ b/seed/fastapi/unknown/core/abstract_fern_service.py @@ -7,5 +7,4 @@ class AbstractFernService(abc.ABC): @classmethod - def _init_fern(cls, router: fastapi.APIRouter) -> None: - ... + def _init_fern(cls, router: fastapi.APIRouter) -> None: ... diff --git a/seed/fastapi/unknown/core/datetime_utils.py b/seed/fastapi/unknown/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/fastapi/unknown/core/datetime_utils.py +++ b/seed/fastapi/unknown/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/fastapi/unknown/core/exceptions/__init__.py b/seed/fastapi/unknown/core/exceptions/__init__.py index 297d6e06f5f..dae4b8980c1 100644 --- a/seed/fastapi/unknown/core/exceptions/__init__.py +++ b/seed/fastapi/unknown/core/exceptions/__init__.py @@ -1,7 +1,11 @@ # This file was auto-generated by Fern from our API Definition. from .fern_http_exception import FernHTTPException -from .handlers import default_exception_handler, fern_http_exception_handler, http_exception_handler +from .handlers import ( + default_exception_handler, + fern_http_exception_handler, + http_exception_handler, +) from .unauthorized import UnauthorizedException __all__ = [ diff --git a/seed/fastapi/unknown/core/exceptions/fern_http_exception.py b/seed/fastapi/unknown/core/exceptions/fern_http_exception.py index bdf03862487..81610359a7f 100644 --- a/seed/fastapi/unknown/core/exceptions/fern_http_exception.py +++ b/seed/fastapi/unknown/core/exceptions/fern_http_exception.py @@ -1,14 +1,16 @@ # This file was auto-generated by Fern from our API Definition. import abc -import typing - import fastapi +import typing class FernHTTPException(abc.ABC, fastapi.HTTPException): def __init__( - self, status_code: int, name: typing.Optional[str] = None, content: typing.Optional[typing.Any] = None + self, + status_code: int, + name: typing.Optional[str] = None, + content: typing.Optional[typing.Any] = None, ): super().__init__(status_code=status_code) self.name = name @@ -17,4 +19,6 @@ def __init__( def to_json_response(self) -> fastapi.responses.JSONResponse: content = fastapi.encoders.jsonable_encoder(self.content, exclude_none=True) - return fastapi.responses.JSONResponse(content=content, status_code=self.status_code) + return fastapi.responses.JSONResponse( + content=content, status_code=self.status_code + ) diff --git a/seed/fastapi/unknown/core/exceptions/handlers.py b/seed/fastapi/unknown/core/exceptions/handlers.py index 6d8c4155c5a..ae1c2741f06 100644 --- a/seed/fastapi/unknown/core/exceptions/handlers.py +++ b/seed/fastapi/unknown/core/exceptions/handlers.py @@ -2,32 +2,49 @@ import logging -import fastapi import starlette import starlette.exceptions +import fastapi + from .fern_http_exception import FernHTTPException def fern_http_exception_handler( - request: fastapi.requests.Request, exc: FernHTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: FernHTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) return exc.to_json_response() def http_exception_handler( - request: fastapi.requests.Request, exc: starlette.exceptions.HTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: starlette.exceptions.HTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=exc.status_code, content=exc.detail).to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=exc.status_code, content=exc.detail + ).to_json_response() def default_exception_handler( - request: fastapi.requests.Request, exc: Exception, skip_log: bool = False + request: fastapi.requests.Request, + exc: Exception, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=500, content="Internal Server Error").to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=500, content="Internal Server Error" + ).to_json_response() diff --git a/seed/fastapi/unknown/core/pydantic_utilities.py b/seed/fastapi/unknown/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/fastapi/unknown/core/pydantic_utilities.py +++ b/seed/fastapi/unknown/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/fastapi/unknown/core/route_args.py b/seed/fastapi/unknown/core/route_args.py index 4228e2fe05d..bd940bf4ddd 100644 --- a/seed/fastapi/unknown/core/route_args.py +++ b/seed/fastapi/unknown/core/route_args.py @@ -20,9 +20,15 @@ class RouteArgs(typing_extensions.TypedDict): DEFAULT_ROUTE_ARGS = RouteArgs(openapi_extra=None, tags=None, include_in_schema=True) -def get_route_args(endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str) -> RouteArgs: - unwrapped = inspect.unwrap(endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY))) - route_args = typing.cast(RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS)) +def get_route_args( + endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str +) -> RouteArgs: + unwrapped = inspect.unwrap( + endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY)) + ) + route_args = typing.cast( + RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS) + ) if route_args["tags"] is None: return RouteArgs( openapi_extra=route_args["openapi_extra"], @@ -56,7 +62,11 @@ def decorator(endpoint_function: T) -> T: setattr( endpoint_function, FERN_CONFIG_KEY, - RouteArgs(openapi_extra=openapi_extra, tags=tags, include_in_schema=include_in_schema), + RouteArgs( + openapi_extra=openapi_extra, + tags=tags, + include_in_schema=include_in_schema, + ), ) return endpoint_function diff --git a/seed/fastapi/unknown/register.py b/seed/fastapi/unknown/register.py index 919ebe5de4a..ab8047d058b 100644 --- a/seed/fastapi/unknown/register.py +++ b/seed/fastapi/unknown/register.py @@ -1,31 +1,33 @@ # This file was auto-generated by Fern from our API Definition. -import glob -import importlib -import os -import types -import typing - import fastapi -import starlette.exceptions +from .resources.unknown.service.service import AbstractUnknownService +import typing from fastapi import params - -from .core.abstract_fern_service import AbstractFernService -from .core.exceptions import default_exception_handler, fern_http_exception_handler, http_exception_handler from .core.exceptions.fern_http_exception import FernHTTPException -from .resources.unknown.service.service import AbstractUnknownService +from .core.exceptions import fern_http_exception_handler +import starlette.exceptions +from .core.exceptions import http_exception_handler +from .core.exceptions import default_exception_handler +from .core.abstract_fern_service import AbstractFernService +import types +import os +import glob +import importlib def register( _app: fastapi.FastAPI, *, unknown: AbstractUnknownService, - dependencies: typing.Optional[typing.Sequence[params.Depends]] = None + dependencies: typing.Optional[typing.Sequence[params.Depends]] = None, ) -> None: _app.include_router(__register_service(unknown), dependencies=dependencies) _app.add_exception_handler(FernHTTPException, fern_http_exception_handler) # type: ignore - _app.add_exception_handler(starlette.exceptions.HTTPException, http_exception_handler) # type: ignore + _app.add_exception_handler( + starlette.exceptions.HTTPException, http_exception_handler + ) # type: ignore _app.add_exception_handler(Exception, default_exception_handler) # type: ignore @@ -37,7 +39,9 @@ def __register_service(service: AbstractFernService) -> fastapi.APIRouter: def register_validators(module: types.ModuleType) -> None: validators_directory: str = os.path.dirname(module.__file__) # type: ignore - for path in glob.glob(os.path.join(validators_directory, "**/*.py"), recursive=True): + for path in glob.glob( + os.path.join(validators_directory, "**/*.py"), recursive=True + ): if os.path.isfile(path): relative_path = os.path.relpath(path, start=validators_directory) module_path = ".".join([module.__name__] + relative_path[:-3].split("/")) diff --git a/seed/fastapi/unknown/resources/unknown/service/service.py b/seed/fastapi/unknown/resources/unknown/service/service.py index 11fb66a09a9..1972457ffa7 100644 --- a/seed/fastapi/unknown/resources/unknown/service/service.py +++ b/seed/fastapi/unknown/resources/unknown/service/service.py @@ -1,15 +1,13 @@ # This file was auto-generated by Fern from our API Definition. -import abc -import functools -import inspect -import logging +from ....core.abstract_fern_service import AbstractFernService import typing - +import abc import fastapi - -from ....core.abstract_fern_service import AbstractFernService +import inspect from ....core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools from ....core.route_args import get_route_args @@ -23,8 +21,7 @@ class AbstractUnknownService(AbstractFernService): """ @abc.abstractmethod - def post(self, *, body: typing.Any) -> typing.Sequence[typing.Any]: - ... + def post(self, *, body: typing.Any) -> typing.Sequence[typing.Any]: ... """ Below are internal methods used by Fern to register your implementation. @@ -39,17 +36,25 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_post(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.post) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) else: new_parameters.append(parameter) - setattr(cls.post, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.post, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.post) - def wrapper(*args: typing.Any, **kwargs: typing.Any) -> typing.Sequence[typing.Any]: + def wrapper( + *args: typing.Any, **kwargs: typing.Any + ) -> typing.Sequence[typing.Any]: try: return cls.post(*args, **kwargs) except FernHTTPException as e: diff --git a/seed/fastapi/unknown/resources/unknown/types/my_object.py b/seed/fastapi/unknown/resources/unknown/types/my_object.py index ef700a3d48a..691fbd48240 100644 --- a/seed/fastapi/unknown/resources/unknown/types/my_object.py +++ b/seed/fastapi/unknown/resources/unknown/types/my_object.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class MyObject(UniversalBaseModel): unknown: typing.Any if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/validation/__init__.py b/seed/fastapi/validation/__init__.py index ac0213df7d5..aa779b474cf 100644 --- a/seed/fastapi/validation/__init__.py +++ b/seed/fastapi/validation/__init__.py @@ -3,4 +3,13 @@ from .service import CreateRequest from .types import Double, LargeInteger, Sentence, Shape, SmallInteger, Type, Word -__all__ = ["CreateRequest", "Double", "LargeInteger", "Sentence", "Shape", "SmallInteger", "Type", "Word"] +__all__ = [ + "CreateRequest", + "Double", + "LargeInteger", + "Sentence", + "Shape", + "SmallInteger", + "Type", + "Word", +] diff --git a/seed/fastapi/validation/core/abstract_fern_service.py b/seed/fastapi/validation/core/abstract_fern_service.py index da7c8dc49c4..9966b4876da 100644 --- a/seed/fastapi/validation/core/abstract_fern_service.py +++ b/seed/fastapi/validation/core/abstract_fern_service.py @@ -7,5 +7,4 @@ class AbstractFernService(abc.ABC): @classmethod - def _init_fern(cls, router: fastapi.APIRouter) -> None: - ... + def _init_fern(cls, router: fastapi.APIRouter) -> None: ... diff --git a/seed/fastapi/validation/core/datetime_utils.py b/seed/fastapi/validation/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/fastapi/validation/core/datetime_utils.py +++ b/seed/fastapi/validation/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/fastapi/validation/core/exceptions/__init__.py b/seed/fastapi/validation/core/exceptions/__init__.py index 297d6e06f5f..dae4b8980c1 100644 --- a/seed/fastapi/validation/core/exceptions/__init__.py +++ b/seed/fastapi/validation/core/exceptions/__init__.py @@ -1,7 +1,11 @@ # This file was auto-generated by Fern from our API Definition. from .fern_http_exception import FernHTTPException -from .handlers import default_exception_handler, fern_http_exception_handler, http_exception_handler +from .handlers import ( + default_exception_handler, + fern_http_exception_handler, + http_exception_handler, +) from .unauthorized import UnauthorizedException __all__ = [ diff --git a/seed/fastapi/validation/core/exceptions/fern_http_exception.py b/seed/fastapi/validation/core/exceptions/fern_http_exception.py index bdf03862487..81610359a7f 100644 --- a/seed/fastapi/validation/core/exceptions/fern_http_exception.py +++ b/seed/fastapi/validation/core/exceptions/fern_http_exception.py @@ -1,14 +1,16 @@ # This file was auto-generated by Fern from our API Definition. import abc -import typing - import fastapi +import typing class FernHTTPException(abc.ABC, fastapi.HTTPException): def __init__( - self, status_code: int, name: typing.Optional[str] = None, content: typing.Optional[typing.Any] = None + self, + status_code: int, + name: typing.Optional[str] = None, + content: typing.Optional[typing.Any] = None, ): super().__init__(status_code=status_code) self.name = name @@ -17,4 +19,6 @@ def __init__( def to_json_response(self) -> fastapi.responses.JSONResponse: content = fastapi.encoders.jsonable_encoder(self.content, exclude_none=True) - return fastapi.responses.JSONResponse(content=content, status_code=self.status_code) + return fastapi.responses.JSONResponse( + content=content, status_code=self.status_code + ) diff --git a/seed/fastapi/validation/core/exceptions/handlers.py b/seed/fastapi/validation/core/exceptions/handlers.py index 6d8c4155c5a..ae1c2741f06 100644 --- a/seed/fastapi/validation/core/exceptions/handlers.py +++ b/seed/fastapi/validation/core/exceptions/handlers.py @@ -2,32 +2,49 @@ import logging -import fastapi import starlette import starlette.exceptions +import fastapi + from .fern_http_exception import FernHTTPException def fern_http_exception_handler( - request: fastapi.requests.Request, exc: FernHTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: FernHTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) return exc.to_json_response() def http_exception_handler( - request: fastapi.requests.Request, exc: starlette.exceptions.HTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: starlette.exceptions.HTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=exc.status_code, content=exc.detail).to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=exc.status_code, content=exc.detail + ).to_json_response() def default_exception_handler( - request: fastapi.requests.Request, exc: Exception, skip_log: bool = False + request: fastapi.requests.Request, + exc: Exception, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=500, content="Internal Server Error").to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=500, content="Internal Server Error" + ).to_json_response() diff --git a/seed/fastapi/validation/core/pydantic_utilities.py b/seed/fastapi/validation/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/fastapi/validation/core/pydantic_utilities.py +++ b/seed/fastapi/validation/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/fastapi/validation/core/route_args.py b/seed/fastapi/validation/core/route_args.py index 4228e2fe05d..bd940bf4ddd 100644 --- a/seed/fastapi/validation/core/route_args.py +++ b/seed/fastapi/validation/core/route_args.py @@ -20,9 +20,15 @@ class RouteArgs(typing_extensions.TypedDict): DEFAULT_ROUTE_ARGS = RouteArgs(openapi_extra=None, tags=None, include_in_schema=True) -def get_route_args(endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str) -> RouteArgs: - unwrapped = inspect.unwrap(endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY))) - route_args = typing.cast(RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS)) +def get_route_args( + endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str +) -> RouteArgs: + unwrapped = inspect.unwrap( + endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY)) + ) + route_args = typing.cast( + RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS) + ) if route_args["tags"] is None: return RouteArgs( openapi_extra=route_args["openapi_extra"], @@ -56,7 +62,11 @@ def decorator(endpoint_function: T) -> T: setattr( endpoint_function, FERN_CONFIG_KEY, - RouteArgs(openapi_extra=openapi_extra, tags=tags, include_in_schema=include_in_schema), + RouteArgs( + openapi_extra=openapi_extra, + tags=tags, + include_in_schema=include_in_schema, + ), ) return endpoint_function diff --git a/seed/fastapi/validation/register.py b/seed/fastapi/validation/register.py index 3b90d0c034f..ce9f38fa412 100644 --- a/seed/fastapi/validation/register.py +++ b/seed/fastapi/validation/register.py @@ -1,31 +1,33 @@ # This file was auto-generated by Fern from our API Definition. -import glob -import importlib -import os -import types -import typing - import fastapi -import starlette.exceptions +from .service.service import AbstractRootService +import typing from fastapi import params - -from .core.abstract_fern_service import AbstractFernService -from .core.exceptions import default_exception_handler, fern_http_exception_handler, http_exception_handler from .core.exceptions.fern_http_exception import FernHTTPException -from .service.service import AbstractRootService +from .core.exceptions import fern_http_exception_handler +import starlette.exceptions +from .core.exceptions import http_exception_handler +from .core.exceptions import default_exception_handler +from .core.abstract_fern_service import AbstractFernService +import types +import os +import glob +import importlib def register( _app: fastapi.FastAPI, *, root: AbstractRootService, - dependencies: typing.Optional[typing.Sequence[params.Depends]] = None + dependencies: typing.Optional[typing.Sequence[params.Depends]] = None, ) -> None: _app.include_router(__register_service(root), dependencies=dependencies) _app.add_exception_handler(FernHTTPException, fern_http_exception_handler) # type: ignore - _app.add_exception_handler(starlette.exceptions.HTTPException, http_exception_handler) # type: ignore + _app.add_exception_handler( + starlette.exceptions.HTTPException, http_exception_handler + ) # type: ignore _app.add_exception_handler(Exception, default_exception_handler) # type: ignore @@ -37,7 +39,9 @@ def __register_service(service: AbstractFernService) -> fastapi.APIRouter: def register_validators(module: types.ModuleType) -> None: validators_directory: str = os.path.dirname(module.__file__) # type: ignore - for path in glob.glob(os.path.join(validators_directory, "**/*.py"), recursive=True): + for path in glob.glob( + os.path.join(validators_directory, "**/*.py"), recursive=True + ): if os.path.isfile(path): relative_path = os.path.relpath(path, start=validators_directory) module_path = ".".join([module.__name__] + relative_path[:-3].split("/")) diff --git a/seed/fastapi/validation/service/create_request.py b/seed/fastapi/validation/service/create_request.py index 3dc85259134..71f97103911 100644 --- a/seed/fastapi/validation/service/create_request.py +++ b/seed/fastapi/validation/service/create_request.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. +from ..core.pydantic_utilities import UniversalBaseModel +from ..types.shape import Shape +from ..core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from ..types.shape import Shape - class CreateRequest(UniversalBaseModel): decimal: float @@ -15,7 +14,9 @@ class CreateRequest(UniversalBaseModel): shape: Shape if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/validation/service/service.py b/seed/fastapi/validation/service/service.py index a56fd992254..22f793d22d3 100644 --- a/seed/fastapi/validation/service/service.py +++ b/seed/fastapi/validation/service/service.py @@ -1,18 +1,16 @@ # This file was auto-generated by Fern from our API Definition. +from ..core.abstract_fern_service import AbstractFernService +from .create_request import CreateRequest +from ..types.type import Type import abc -import functools +import fastapi import inspect -import logging import typing - -import fastapi - -from ..core.abstract_fern_service import AbstractFernService from ..core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools from ..core.route_args import get_route_args -from ..types.type import Type -from .create_request import CreateRequest class AbstractRootService(AbstractFernService): @@ -25,12 +23,10 @@ class AbstractRootService(AbstractFernService): """ @abc.abstractmethod - def create(self, *, body: CreateRequest) -> Type: - ... + def create(self, *, body: CreateRequest) -> Type: ... @abc.abstractmethod - def get(self, *, decimal: float, even: int, name: str) -> Type: - ... + def get(self, *, decimal: float, even: int, name: str) -> Type: ... """ Below are internal methods used by Fern to register your implementation. @@ -46,14 +42,20 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_create(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.create) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) else: new_parameters.append(parameter) - setattr(cls.create, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.create, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.create) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> Type: @@ -82,18 +84,30 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> Type: def __init_get(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "decimal": - new_parameters.append(parameter.replace(default=fastapi.Query(default=...))) + new_parameters.append( + parameter.replace(default=fastapi.Query(default=...)) + ) elif parameter_name == "even": - new_parameters.append(parameter.replace(default=fastapi.Query(default=...))) + new_parameters.append( + parameter.replace(default=fastapi.Query(default=...)) + ) elif parameter_name == "name": - new_parameters.append(parameter.replace(default=fastapi.Query(default=...))) + new_parameters.append( + parameter.replace(default=fastapi.Query(default=...)) + ) else: new_parameters.append(parameter) - setattr(cls.get, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> Type: diff --git a/seed/fastapi/validation/types/__init__.py b/seed/fastapi/validation/types/__init__.py index d30f52138d4..51957e8c8c5 100644 --- a/seed/fastapi/validation/types/__init__.py +++ b/seed/fastapi/validation/types/__init__.py @@ -8,4 +8,12 @@ from .type import Type from .word import Word -__all__ = ["Double", "LargeInteger", "Sentence", "Shape", "SmallInteger", "Type", "Word"] +__all__ = [ + "Double", + "LargeInteger", + "Sentence", + "Shape", + "SmallInteger", + "Type", + "Word", +] diff --git a/seed/fastapi/validation/types/type.py b/seed/fastapi/validation/types/type.py index 1b3d6944b73..faa91f5f925 100644 --- a/seed/fastapi/validation/types/type.py +++ b/seed/fastapi/validation/types/type.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. +from ..core.pydantic_utilities import UniversalBaseModel +from .shape import Shape +from ..core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .shape import Shape - class Type(UniversalBaseModel): """ @@ -30,7 +29,9 @@ class Type(UniversalBaseModel): shape: Shape if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/variables/core/abstract_fern_service.py b/seed/fastapi/variables/core/abstract_fern_service.py index da7c8dc49c4..9966b4876da 100644 --- a/seed/fastapi/variables/core/abstract_fern_service.py +++ b/seed/fastapi/variables/core/abstract_fern_service.py @@ -7,5 +7,4 @@ class AbstractFernService(abc.ABC): @classmethod - def _init_fern(cls, router: fastapi.APIRouter) -> None: - ... + def _init_fern(cls, router: fastapi.APIRouter) -> None: ... diff --git a/seed/fastapi/variables/core/datetime_utils.py b/seed/fastapi/variables/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/fastapi/variables/core/datetime_utils.py +++ b/seed/fastapi/variables/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/fastapi/variables/core/exceptions/__init__.py b/seed/fastapi/variables/core/exceptions/__init__.py index 297d6e06f5f..dae4b8980c1 100644 --- a/seed/fastapi/variables/core/exceptions/__init__.py +++ b/seed/fastapi/variables/core/exceptions/__init__.py @@ -1,7 +1,11 @@ # This file was auto-generated by Fern from our API Definition. from .fern_http_exception import FernHTTPException -from .handlers import default_exception_handler, fern_http_exception_handler, http_exception_handler +from .handlers import ( + default_exception_handler, + fern_http_exception_handler, + http_exception_handler, +) from .unauthorized import UnauthorizedException __all__ = [ diff --git a/seed/fastapi/variables/core/exceptions/fern_http_exception.py b/seed/fastapi/variables/core/exceptions/fern_http_exception.py index bdf03862487..81610359a7f 100644 --- a/seed/fastapi/variables/core/exceptions/fern_http_exception.py +++ b/seed/fastapi/variables/core/exceptions/fern_http_exception.py @@ -1,14 +1,16 @@ # This file was auto-generated by Fern from our API Definition. import abc -import typing - import fastapi +import typing class FernHTTPException(abc.ABC, fastapi.HTTPException): def __init__( - self, status_code: int, name: typing.Optional[str] = None, content: typing.Optional[typing.Any] = None + self, + status_code: int, + name: typing.Optional[str] = None, + content: typing.Optional[typing.Any] = None, ): super().__init__(status_code=status_code) self.name = name @@ -17,4 +19,6 @@ def __init__( def to_json_response(self) -> fastapi.responses.JSONResponse: content = fastapi.encoders.jsonable_encoder(self.content, exclude_none=True) - return fastapi.responses.JSONResponse(content=content, status_code=self.status_code) + return fastapi.responses.JSONResponse( + content=content, status_code=self.status_code + ) diff --git a/seed/fastapi/variables/core/exceptions/handlers.py b/seed/fastapi/variables/core/exceptions/handlers.py index 6d8c4155c5a..ae1c2741f06 100644 --- a/seed/fastapi/variables/core/exceptions/handlers.py +++ b/seed/fastapi/variables/core/exceptions/handlers.py @@ -2,32 +2,49 @@ import logging -import fastapi import starlette import starlette.exceptions +import fastapi + from .fern_http_exception import FernHTTPException def fern_http_exception_handler( - request: fastapi.requests.Request, exc: FernHTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: FernHTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) return exc.to_json_response() def http_exception_handler( - request: fastapi.requests.Request, exc: starlette.exceptions.HTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: starlette.exceptions.HTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=exc.status_code, content=exc.detail).to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=exc.status_code, content=exc.detail + ).to_json_response() def default_exception_handler( - request: fastapi.requests.Request, exc: Exception, skip_log: bool = False + request: fastapi.requests.Request, + exc: Exception, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=500, content="Internal Server Error").to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=500, content="Internal Server Error" + ).to_json_response() diff --git a/seed/fastapi/variables/core/pydantic_utilities.py b/seed/fastapi/variables/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/fastapi/variables/core/pydantic_utilities.py +++ b/seed/fastapi/variables/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/fastapi/variables/core/route_args.py b/seed/fastapi/variables/core/route_args.py index 4228e2fe05d..bd940bf4ddd 100644 --- a/seed/fastapi/variables/core/route_args.py +++ b/seed/fastapi/variables/core/route_args.py @@ -20,9 +20,15 @@ class RouteArgs(typing_extensions.TypedDict): DEFAULT_ROUTE_ARGS = RouteArgs(openapi_extra=None, tags=None, include_in_schema=True) -def get_route_args(endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str) -> RouteArgs: - unwrapped = inspect.unwrap(endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY))) - route_args = typing.cast(RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS)) +def get_route_args( + endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str +) -> RouteArgs: + unwrapped = inspect.unwrap( + endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY)) + ) + route_args = typing.cast( + RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS) + ) if route_args["tags"] is None: return RouteArgs( openapi_extra=route_args["openapi_extra"], @@ -56,7 +62,11 @@ def decorator(endpoint_function: T) -> T: setattr( endpoint_function, FERN_CONFIG_KEY, - RouteArgs(openapi_extra=openapi_extra, tags=tags, include_in_schema=include_in_schema), + RouteArgs( + openapi_extra=openapi_extra, + tags=tags, + include_in_schema=include_in_schema, + ), ) return endpoint_function diff --git a/seed/fastapi/variables/register.py b/seed/fastapi/variables/register.py index ebdfdf9318d..1d60bbe4d5d 100644 --- a/seed/fastapi/variables/register.py +++ b/seed/fastapi/variables/register.py @@ -1,31 +1,33 @@ # This file was auto-generated by Fern from our API Definition. -import glob -import importlib -import os -import types -import typing - import fastapi -import starlette.exceptions +from .resources.service.service.service import AbstractServiceService +import typing from fastapi import params - -from .core.abstract_fern_service import AbstractFernService -from .core.exceptions import default_exception_handler, fern_http_exception_handler, http_exception_handler from .core.exceptions.fern_http_exception import FernHTTPException -from .resources.service.service.service import AbstractServiceService +from .core.exceptions import fern_http_exception_handler +import starlette.exceptions +from .core.exceptions import http_exception_handler +from .core.exceptions import default_exception_handler +from .core.abstract_fern_service import AbstractFernService +import types +import os +import glob +import importlib def register( _app: fastapi.FastAPI, *, service: AbstractServiceService, - dependencies: typing.Optional[typing.Sequence[params.Depends]] = None + dependencies: typing.Optional[typing.Sequence[params.Depends]] = None, ) -> None: _app.include_router(__register_service(service), dependencies=dependencies) _app.add_exception_handler(FernHTTPException, fern_http_exception_handler) # type: ignore - _app.add_exception_handler(starlette.exceptions.HTTPException, http_exception_handler) # type: ignore + _app.add_exception_handler( + starlette.exceptions.HTTPException, http_exception_handler + ) # type: ignore _app.add_exception_handler(Exception, default_exception_handler) # type: ignore @@ -37,7 +39,9 @@ def __register_service(service: AbstractFernService) -> fastapi.APIRouter: def register_validators(module: types.ModuleType) -> None: validators_directory: str = os.path.dirname(module.__file__) # type: ignore - for path in glob.glob(os.path.join(validators_directory, "**/*.py"), recursive=True): + for path in glob.glob( + os.path.join(validators_directory, "**/*.py"), recursive=True + ): if os.path.isfile(path): relative_path = os.path.relpath(path, start=validators_directory) module_path = ".".join([module.__name__] + relative_path[:-3].split("/")) diff --git a/seed/fastapi/variables/resources/service/service/service.py b/seed/fastapi/variables/resources/service/service/service.py index 1c946f41277..460467f1aca 100644 --- a/seed/fastapi/variables/resources/service/service/service.py +++ b/seed/fastapi/variables/resources/service/service/service.py @@ -1,16 +1,14 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.abstract_fern_service import AbstractFernService import abc -import functools +import fastapi import inspect -import logging import typing - -import fastapi -import starlette - -from ....core.abstract_fern_service import AbstractFernService from ....core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools +import starlette from ....core.route_args import get_route_args @@ -24,8 +22,7 @@ class AbstractServiceService(AbstractFernService): """ @abc.abstractmethod - def post(self, *, endpoint_param: str) -> None: - ... + def post(self, *, endpoint_param: str) -> None: ... """ Below are internal methods used by Fern to register your implementation. @@ -40,14 +37,20 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_post(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.post) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "endpoint_param": new_parameters.append(parameter.replace(default=fastapi.Path(...))) else: new_parameters.append(parameter) - setattr(cls.post, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.post, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.post) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> None: diff --git a/seed/fastapi/version-no-default/core/abstract_fern_service.py b/seed/fastapi/version-no-default/core/abstract_fern_service.py index da7c8dc49c4..9966b4876da 100644 --- a/seed/fastapi/version-no-default/core/abstract_fern_service.py +++ b/seed/fastapi/version-no-default/core/abstract_fern_service.py @@ -7,5 +7,4 @@ class AbstractFernService(abc.ABC): @classmethod - def _init_fern(cls, router: fastapi.APIRouter) -> None: - ... + def _init_fern(cls, router: fastapi.APIRouter) -> None: ... diff --git a/seed/fastapi/version-no-default/core/datetime_utils.py b/seed/fastapi/version-no-default/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/fastapi/version-no-default/core/datetime_utils.py +++ b/seed/fastapi/version-no-default/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/fastapi/version-no-default/core/exceptions/__init__.py b/seed/fastapi/version-no-default/core/exceptions/__init__.py index 297d6e06f5f..dae4b8980c1 100644 --- a/seed/fastapi/version-no-default/core/exceptions/__init__.py +++ b/seed/fastapi/version-no-default/core/exceptions/__init__.py @@ -1,7 +1,11 @@ # This file was auto-generated by Fern from our API Definition. from .fern_http_exception import FernHTTPException -from .handlers import default_exception_handler, fern_http_exception_handler, http_exception_handler +from .handlers import ( + default_exception_handler, + fern_http_exception_handler, + http_exception_handler, +) from .unauthorized import UnauthorizedException __all__ = [ diff --git a/seed/fastapi/version-no-default/core/exceptions/fern_http_exception.py b/seed/fastapi/version-no-default/core/exceptions/fern_http_exception.py index bdf03862487..81610359a7f 100644 --- a/seed/fastapi/version-no-default/core/exceptions/fern_http_exception.py +++ b/seed/fastapi/version-no-default/core/exceptions/fern_http_exception.py @@ -1,14 +1,16 @@ # This file was auto-generated by Fern from our API Definition. import abc -import typing - import fastapi +import typing class FernHTTPException(abc.ABC, fastapi.HTTPException): def __init__( - self, status_code: int, name: typing.Optional[str] = None, content: typing.Optional[typing.Any] = None + self, + status_code: int, + name: typing.Optional[str] = None, + content: typing.Optional[typing.Any] = None, ): super().__init__(status_code=status_code) self.name = name @@ -17,4 +19,6 @@ def __init__( def to_json_response(self) -> fastapi.responses.JSONResponse: content = fastapi.encoders.jsonable_encoder(self.content, exclude_none=True) - return fastapi.responses.JSONResponse(content=content, status_code=self.status_code) + return fastapi.responses.JSONResponse( + content=content, status_code=self.status_code + ) diff --git a/seed/fastapi/version-no-default/core/exceptions/handlers.py b/seed/fastapi/version-no-default/core/exceptions/handlers.py index 6d8c4155c5a..ae1c2741f06 100644 --- a/seed/fastapi/version-no-default/core/exceptions/handlers.py +++ b/seed/fastapi/version-no-default/core/exceptions/handlers.py @@ -2,32 +2,49 @@ import logging -import fastapi import starlette import starlette.exceptions +import fastapi + from .fern_http_exception import FernHTTPException def fern_http_exception_handler( - request: fastapi.requests.Request, exc: FernHTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: FernHTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) return exc.to_json_response() def http_exception_handler( - request: fastapi.requests.Request, exc: starlette.exceptions.HTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: starlette.exceptions.HTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=exc.status_code, content=exc.detail).to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=exc.status_code, content=exc.detail + ).to_json_response() def default_exception_handler( - request: fastapi.requests.Request, exc: Exception, skip_log: bool = False + request: fastapi.requests.Request, + exc: Exception, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=500, content="Internal Server Error").to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=500, content="Internal Server Error" + ).to_json_response() diff --git a/seed/fastapi/version-no-default/core/pydantic_utilities.py b/seed/fastapi/version-no-default/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/fastapi/version-no-default/core/pydantic_utilities.py +++ b/seed/fastapi/version-no-default/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/fastapi/version-no-default/core/route_args.py b/seed/fastapi/version-no-default/core/route_args.py index 4228e2fe05d..bd940bf4ddd 100644 --- a/seed/fastapi/version-no-default/core/route_args.py +++ b/seed/fastapi/version-no-default/core/route_args.py @@ -20,9 +20,15 @@ class RouteArgs(typing_extensions.TypedDict): DEFAULT_ROUTE_ARGS = RouteArgs(openapi_extra=None, tags=None, include_in_schema=True) -def get_route_args(endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str) -> RouteArgs: - unwrapped = inspect.unwrap(endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY))) - route_args = typing.cast(RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS)) +def get_route_args( + endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str +) -> RouteArgs: + unwrapped = inspect.unwrap( + endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY)) + ) + route_args = typing.cast( + RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS) + ) if route_args["tags"] is None: return RouteArgs( openapi_extra=route_args["openapi_extra"], @@ -56,7 +62,11 @@ def decorator(endpoint_function: T) -> T: setattr( endpoint_function, FERN_CONFIG_KEY, - RouteArgs(openapi_extra=openapi_extra, tags=tags, include_in_schema=include_in_schema), + RouteArgs( + openapi_extra=openapi_extra, + tags=tags, + include_in_schema=include_in_schema, + ), ) return endpoint_function diff --git a/seed/fastapi/version-no-default/register.py b/seed/fastapi/version-no-default/register.py index cad83228e21..f0b801ec079 100644 --- a/seed/fastapi/version-no-default/register.py +++ b/seed/fastapi/version-no-default/register.py @@ -1,31 +1,33 @@ # This file was auto-generated by Fern from our API Definition. -import glob -import importlib -import os -import types -import typing - import fastapi -import starlette.exceptions +from .resources.user.service.service import AbstractUserService +import typing from fastapi import params - -from .core.abstract_fern_service import AbstractFernService -from .core.exceptions import default_exception_handler, fern_http_exception_handler, http_exception_handler from .core.exceptions.fern_http_exception import FernHTTPException -from .resources.user.service.service import AbstractUserService +from .core.exceptions import fern_http_exception_handler +import starlette.exceptions +from .core.exceptions import http_exception_handler +from .core.exceptions import default_exception_handler +from .core.abstract_fern_service import AbstractFernService +import types +import os +import glob +import importlib def register( _app: fastapi.FastAPI, *, user: AbstractUserService, - dependencies: typing.Optional[typing.Sequence[params.Depends]] = None + dependencies: typing.Optional[typing.Sequence[params.Depends]] = None, ) -> None: _app.include_router(__register_service(user), dependencies=dependencies) _app.add_exception_handler(FernHTTPException, fern_http_exception_handler) # type: ignore - _app.add_exception_handler(starlette.exceptions.HTTPException, http_exception_handler) # type: ignore + _app.add_exception_handler( + starlette.exceptions.HTTPException, http_exception_handler + ) # type: ignore _app.add_exception_handler(Exception, default_exception_handler) # type: ignore @@ -37,7 +39,9 @@ def __register_service(service: AbstractFernService) -> fastapi.APIRouter: def register_validators(module: types.ModuleType) -> None: validators_directory: str = os.path.dirname(module.__file__) # type: ignore - for path in glob.glob(os.path.join(validators_directory, "**/*.py"), recursive=True): + for path in glob.glob( + os.path.join(validators_directory, "**/*.py"), recursive=True + ): if os.path.isfile(path): relative_path = os.path.relpath(path, start=validators_directory) module_path = ".".join([module.__name__] + relative_path[:-3].split("/")) diff --git a/seed/fastapi/version-no-default/resources/user/service/service.py b/seed/fastapi/version-no-default/resources/user/service/service.py index 5db188dff63..134dfa4c926 100644 --- a/seed/fastapi/version-no-default/resources/user/service/service.py +++ b/seed/fastapi/version-no-default/resources/user/service/service.py @@ -1,17 +1,15 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.abstract_fern_service import AbstractFernService +from ..types.user import User import abc -import functools +import fastapi import inspect -import logging import typing - -import fastapi - -from ....core.abstract_fern_service import AbstractFernService from ....core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools from ....core.route_args import get_route_args -from ..types.user import User class AbstractUserService(AbstractFernService): @@ -24,8 +22,7 @@ class AbstractUserService(AbstractFernService): """ @abc.abstractmethod - def get_user(self, *, user_id: str) -> User: - ... + def get_user(self, *, user_id: str) -> User: ... """ Below are internal methods used by Fern to register your implementation. @@ -40,14 +37,20 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_get_user(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_user) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "user_id": new_parameters.append(parameter.replace(default=fastapi.Path(...))) else: new_parameters.append(parameter) - setattr(cls.get_user, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_user, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_user) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> User: diff --git a/seed/fastapi/version-no-default/resources/user/types/user.py b/seed/fastapi/version-no-default/resources/user/types/user.py index b2801510612..b641d5b7ff9 100644 --- a/seed/fastapi/version-no-default/resources/user/types/user.py +++ b/seed/fastapi/version-no-default/resources/user/types/user.py @@ -1,19 +1,20 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel +from .user_id import UserId +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .user_id import UserId - class User(UniversalBaseModel): id: UserId name: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/version/core/abstract_fern_service.py b/seed/fastapi/version/core/abstract_fern_service.py index da7c8dc49c4..9966b4876da 100644 --- a/seed/fastapi/version/core/abstract_fern_service.py +++ b/seed/fastapi/version/core/abstract_fern_service.py @@ -7,5 +7,4 @@ class AbstractFernService(abc.ABC): @classmethod - def _init_fern(cls, router: fastapi.APIRouter) -> None: - ... + def _init_fern(cls, router: fastapi.APIRouter) -> None: ... diff --git a/seed/fastapi/version/core/datetime_utils.py b/seed/fastapi/version/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/fastapi/version/core/datetime_utils.py +++ b/seed/fastapi/version/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/fastapi/version/core/exceptions/__init__.py b/seed/fastapi/version/core/exceptions/__init__.py index 297d6e06f5f..dae4b8980c1 100644 --- a/seed/fastapi/version/core/exceptions/__init__.py +++ b/seed/fastapi/version/core/exceptions/__init__.py @@ -1,7 +1,11 @@ # This file was auto-generated by Fern from our API Definition. from .fern_http_exception import FernHTTPException -from .handlers import default_exception_handler, fern_http_exception_handler, http_exception_handler +from .handlers import ( + default_exception_handler, + fern_http_exception_handler, + http_exception_handler, +) from .unauthorized import UnauthorizedException __all__ = [ diff --git a/seed/fastapi/version/core/exceptions/fern_http_exception.py b/seed/fastapi/version/core/exceptions/fern_http_exception.py index bdf03862487..81610359a7f 100644 --- a/seed/fastapi/version/core/exceptions/fern_http_exception.py +++ b/seed/fastapi/version/core/exceptions/fern_http_exception.py @@ -1,14 +1,16 @@ # This file was auto-generated by Fern from our API Definition. import abc -import typing - import fastapi +import typing class FernHTTPException(abc.ABC, fastapi.HTTPException): def __init__( - self, status_code: int, name: typing.Optional[str] = None, content: typing.Optional[typing.Any] = None + self, + status_code: int, + name: typing.Optional[str] = None, + content: typing.Optional[typing.Any] = None, ): super().__init__(status_code=status_code) self.name = name @@ -17,4 +19,6 @@ def __init__( def to_json_response(self) -> fastapi.responses.JSONResponse: content = fastapi.encoders.jsonable_encoder(self.content, exclude_none=True) - return fastapi.responses.JSONResponse(content=content, status_code=self.status_code) + return fastapi.responses.JSONResponse( + content=content, status_code=self.status_code + ) diff --git a/seed/fastapi/version/core/exceptions/handlers.py b/seed/fastapi/version/core/exceptions/handlers.py index 6d8c4155c5a..ae1c2741f06 100644 --- a/seed/fastapi/version/core/exceptions/handlers.py +++ b/seed/fastapi/version/core/exceptions/handlers.py @@ -2,32 +2,49 @@ import logging -import fastapi import starlette import starlette.exceptions +import fastapi + from .fern_http_exception import FernHTTPException def fern_http_exception_handler( - request: fastapi.requests.Request, exc: FernHTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: FernHTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) return exc.to_json_response() def http_exception_handler( - request: fastapi.requests.Request, exc: starlette.exceptions.HTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: starlette.exceptions.HTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=exc.status_code, content=exc.detail).to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=exc.status_code, content=exc.detail + ).to_json_response() def default_exception_handler( - request: fastapi.requests.Request, exc: Exception, skip_log: bool = False + request: fastapi.requests.Request, + exc: Exception, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=500, content="Internal Server Error").to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=500, content="Internal Server Error" + ).to_json_response() diff --git a/seed/fastapi/version/core/pydantic_utilities.py b/seed/fastapi/version/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/fastapi/version/core/pydantic_utilities.py +++ b/seed/fastapi/version/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/fastapi/version/core/route_args.py b/seed/fastapi/version/core/route_args.py index 4228e2fe05d..bd940bf4ddd 100644 --- a/seed/fastapi/version/core/route_args.py +++ b/seed/fastapi/version/core/route_args.py @@ -20,9 +20,15 @@ class RouteArgs(typing_extensions.TypedDict): DEFAULT_ROUTE_ARGS = RouteArgs(openapi_extra=None, tags=None, include_in_schema=True) -def get_route_args(endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str) -> RouteArgs: - unwrapped = inspect.unwrap(endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY))) - route_args = typing.cast(RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS)) +def get_route_args( + endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str +) -> RouteArgs: + unwrapped = inspect.unwrap( + endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY)) + ) + route_args = typing.cast( + RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS) + ) if route_args["tags"] is None: return RouteArgs( openapi_extra=route_args["openapi_extra"], @@ -56,7 +62,11 @@ def decorator(endpoint_function: T) -> T: setattr( endpoint_function, FERN_CONFIG_KEY, - RouteArgs(openapi_extra=openapi_extra, tags=tags, include_in_schema=include_in_schema), + RouteArgs( + openapi_extra=openapi_extra, + tags=tags, + include_in_schema=include_in_schema, + ), ) return endpoint_function diff --git a/seed/fastapi/version/register.py b/seed/fastapi/version/register.py index cad83228e21..f0b801ec079 100644 --- a/seed/fastapi/version/register.py +++ b/seed/fastapi/version/register.py @@ -1,31 +1,33 @@ # This file was auto-generated by Fern from our API Definition. -import glob -import importlib -import os -import types -import typing - import fastapi -import starlette.exceptions +from .resources.user.service.service import AbstractUserService +import typing from fastapi import params - -from .core.abstract_fern_service import AbstractFernService -from .core.exceptions import default_exception_handler, fern_http_exception_handler, http_exception_handler from .core.exceptions.fern_http_exception import FernHTTPException -from .resources.user.service.service import AbstractUserService +from .core.exceptions import fern_http_exception_handler +import starlette.exceptions +from .core.exceptions import http_exception_handler +from .core.exceptions import default_exception_handler +from .core.abstract_fern_service import AbstractFernService +import types +import os +import glob +import importlib def register( _app: fastapi.FastAPI, *, user: AbstractUserService, - dependencies: typing.Optional[typing.Sequence[params.Depends]] = None + dependencies: typing.Optional[typing.Sequence[params.Depends]] = None, ) -> None: _app.include_router(__register_service(user), dependencies=dependencies) _app.add_exception_handler(FernHTTPException, fern_http_exception_handler) # type: ignore - _app.add_exception_handler(starlette.exceptions.HTTPException, http_exception_handler) # type: ignore + _app.add_exception_handler( + starlette.exceptions.HTTPException, http_exception_handler + ) # type: ignore _app.add_exception_handler(Exception, default_exception_handler) # type: ignore @@ -37,7 +39,9 @@ def __register_service(service: AbstractFernService) -> fastapi.APIRouter: def register_validators(module: types.ModuleType) -> None: validators_directory: str = os.path.dirname(module.__file__) # type: ignore - for path in glob.glob(os.path.join(validators_directory, "**/*.py"), recursive=True): + for path in glob.glob( + os.path.join(validators_directory, "**/*.py"), recursive=True + ): if os.path.isfile(path): relative_path = os.path.relpath(path, start=validators_directory) module_path = ".".join([module.__name__] + relative_path[:-3].split("/")) diff --git a/seed/fastapi/version/resources/user/service/service.py b/seed/fastapi/version/resources/user/service/service.py index 5db188dff63..134dfa4c926 100644 --- a/seed/fastapi/version/resources/user/service/service.py +++ b/seed/fastapi/version/resources/user/service/service.py @@ -1,17 +1,15 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.abstract_fern_service import AbstractFernService +from ..types.user import User import abc -import functools +import fastapi import inspect -import logging import typing - -import fastapi - -from ....core.abstract_fern_service import AbstractFernService from ....core.exceptions.fern_http_exception import FernHTTPException +import logging +import functools from ....core.route_args import get_route_args -from ..types.user import User class AbstractUserService(AbstractFernService): @@ -24,8 +22,7 @@ class AbstractUserService(AbstractFernService): """ @abc.abstractmethod - def get_user(self, *, user_id: str) -> User: - ... + def get_user(self, *, user_id: str) -> User: ... """ Below are internal methods used by Fern to register your implementation. @@ -40,14 +37,20 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_get_user(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.get_user) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "user_id": new_parameters.append(parameter.replace(default=fastapi.Path(...))) else: new_parameters.append(parameter) - setattr(cls.get_user, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.get_user, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.get_user) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> User: diff --git a/seed/fastapi/version/resources/user/types/user.py b/seed/fastapi/version/resources/user/types/user.py index b2801510612..b641d5b7ff9 100644 --- a/seed/fastapi/version/resources/user/types/user.py +++ b/seed/fastapi/version/resources/user/types/user.py @@ -1,19 +1,20 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel +from .user_id import UserId +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .user_id import UserId - class User(UniversalBaseModel): id: UserId name: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="forbid") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="forbid" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/fastapi/websocket/core/abstract_fern_service.py b/seed/fastapi/websocket/core/abstract_fern_service.py index da7c8dc49c4..9966b4876da 100644 --- a/seed/fastapi/websocket/core/abstract_fern_service.py +++ b/seed/fastapi/websocket/core/abstract_fern_service.py @@ -7,5 +7,4 @@ class AbstractFernService(abc.ABC): @classmethod - def _init_fern(cls, router: fastapi.APIRouter) -> None: - ... + def _init_fern(cls, router: fastapi.APIRouter) -> None: ... diff --git a/seed/fastapi/websocket/core/datetime_utils.py b/seed/fastapi/websocket/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/fastapi/websocket/core/datetime_utils.py +++ b/seed/fastapi/websocket/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/fastapi/websocket/core/exceptions/__init__.py b/seed/fastapi/websocket/core/exceptions/__init__.py index 297d6e06f5f..dae4b8980c1 100644 --- a/seed/fastapi/websocket/core/exceptions/__init__.py +++ b/seed/fastapi/websocket/core/exceptions/__init__.py @@ -1,7 +1,11 @@ # This file was auto-generated by Fern from our API Definition. from .fern_http_exception import FernHTTPException -from .handlers import default_exception_handler, fern_http_exception_handler, http_exception_handler +from .handlers import ( + default_exception_handler, + fern_http_exception_handler, + http_exception_handler, +) from .unauthorized import UnauthorizedException __all__ = [ diff --git a/seed/fastapi/websocket/core/exceptions/fern_http_exception.py b/seed/fastapi/websocket/core/exceptions/fern_http_exception.py index bdf03862487..81610359a7f 100644 --- a/seed/fastapi/websocket/core/exceptions/fern_http_exception.py +++ b/seed/fastapi/websocket/core/exceptions/fern_http_exception.py @@ -1,14 +1,16 @@ # This file was auto-generated by Fern from our API Definition. import abc -import typing - import fastapi +import typing class FernHTTPException(abc.ABC, fastapi.HTTPException): def __init__( - self, status_code: int, name: typing.Optional[str] = None, content: typing.Optional[typing.Any] = None + self, + status_code: int, + name: typing.Optional[str] = None, + content: typing.Optional[typing.Any] = None, ): super().__init__(status_code=status_code) self.name = name @@ -17,4 +19,6 @@ def __init__( def to_json_response(self) -> fastapi.responses.JSONResponse: content = fastapi.encoders.jsonable_encoder(self.content, exclude_none=True) - return fastapi.responses.JSONResponse(content=content, status_code=self.status_code) + return fastapi.responses.JSONResponse( + content=content, status_code=self.status_code + ) diff --git a/seed/fastapi/websocket/core/exceptions/handlers.py b/seed/fastapi/websocket/core/exceptions/handlers.py index 6d8c4155c5a..ae1c2741f06 100644 --- a/seed/fastapi/websocket/core/exceptions/handlers.py +++ b/seed/fastapi/websocket/core/exceptions/handlers.py @@ -2,32 +2,49 @@ import logging -import fastapi import starlette import starlette.exceptions +import fastapi + from .fern_http_exception import FernHTTPException def fern_http_exception_handler( - request: fastapi.requests.Request, exc: FernHTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: FernHTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) return exc.to_json_response() def http_exception_handler( - request: fastapi.requests.Request, exc: starlette.exceptions.HTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: starlette.exceptions.HTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=exc.status_code, content=exc.detail).to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=exc.status_code, content=exc.detail + ).to_json_response() def default_exception_handler( - request: fastapi.requests.Request, exc: Exception, skip_log: bool = False + request: fastapi.requests.Request, + exc: Exception, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=500, content="Internal Server Error").to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=500, content="Internal Server Error" + ).to_json_response() diff --git a/seed/fastapi/websocket/core/pydantic_utilities.py b/seed/fastapi/websocket/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/fastapi/websocket/core/pydantic_utilities.py +++ b/seed/fastapi/websocket/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/fastapi/websocket/core/route_args.py b/seed/fastapi/websocket/core/route_args.py index 4228e2fe05d..bd940bf4ddd 100644 --- a/seed/fastapi/websocket/core/route_args.py +++ b/seed/fastapi/websocket/core/route_args.py @@ -20,9 +20,15 @@ class RouteArgs(typing_extensions.TypedDict): DEFAULT_ROUTE_ARGS = RouteArgs(openapi_extra=None, tags=None, include_in_schema=True) -def get_route_args(endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str) -> RouteArgs: - unwrapped = inspect.unwrap(endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY))) - route_args = typing.cast(RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS)) +def get_route_args( + endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str +) -> RouteArgs: + unwrapped = inspect.unwrap( + endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY)) + ) + route_args = typing.cast( + RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS) + ) if route_args["tags"] is None: return RouteArgs( openapi_extra=route_args["openapi_extra"], @@ -56,7 +62,11 @@ def decorator(endpoint_function: T) -> T: setattr( endpoint_function, FERN_CONFIG_KEY, - RouteArgs(openapi_extra=openapi_extra, tags=tags, include_in_schema=include_in_schema), + RouteArgs( + openapi_extra=openapi_extra, + tags=tags, + include_in_schema=include_in_schema, + ), ) return endpoint_function diff --git a/seed/fastapi/websocket/register.py b/seed/fastapi/websocket/register.py index 6f6e6707f03..a536c0ce4e4 100644 --- a/seed/fastapi/websocket/register.py +++ b/seed/fastapi/websocket/register.py @@ -1,23 +1,29 @@ # This file was auto-generated by Fern from our API Definition. -import glob -import importlib -import os -import types -import typing - import fastapi -import starlette.exceptions +import typing from fastapi import params - -from .core.abstract_fern_service import AbstractFernService -from .core.exceptions import default_exception_handler, fern_http_exception_handler, http_exception_handler from .core.exceptions.fern_http_exception import FernHTTPException +from .core.exceptions import fern_http_exception_handler +import starlette.exceptions +from .core.exceptions import http_exception_handler +from .core.exceptions import default_exception_handler +from .core.abstract_fern_service import AbstractFernService +import types +import os +import glob +import importlib -def register(_app: fastapi.FastAPI, *, dependencies: typing.Optional[typing.Sequence[params.Depends]] = None) -> None: +def register( + _app: fastapi.FastAPI, + *, + dependencies: typing.Optional[typing.Sequence[params.Depends]] = None, +) -> None: _app.add_exception_handler(FernHTTPException, fern_http_exception_handler) # type: ignore - _app.add_exception_handler(starlette.exceptions.HTTPException, http_exception_handler) # type: ignore + _app.add_exception_handler( + starlette.exceptions.HTTPException, http_exception_handler + ) # type: ignore _app.add_exception_handler(Exception, default_exception_handler) # type: ignore @@ -29,7 +35,9 @@ def __register_service(service: AbstractFernService) -> fastapi.APIRouter: def register_validators(module: types.ModuleType) -> None: validators_directory: str = os.path.dirname(module.__file__) # type: ignore - for path in glob.glob(os.path.join(validators_directory, "**/*.py"), recursive=True): + for path in glob.glob( + os.path.join(validators_directory, "**/*.py"), recursive=True + ): if os.path.isfile(path): relative_path = os.path.relpath(path, start=validators_directory) module_path = ".".join([module.__name__] + relative_path[:-3].split("/")) diff --git a/seed/pydantic/alias-extends/pyproject.toml b/seed/pydantic/alias-extends/pyproject.toml index d96d0a80473..d00e5e60466 100644 --- a/seed/pydantic/alias-extends/pyproject.toml +++ b/seed/pydantic/alias-extends/pyproject.toml @@ -41,6 +41,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/pydantic/alias-extends/src/seed/alias_extends/child.py b/seed/pydantic/alias-extends/src/seed/alias_extends/child.py index 206a0153cdc..b16beca9ef7 100644 --- a/seed/pydantic/alias-extends/src/seed/alias_extends/child.py +++ b/seed/pydantic/alias-extends/src/seed/alias_extends/child.py @@ -1,12 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from .parent import Parent +from .core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from .core.pydantic_utilities import IS_PYDANTIC_V2 -from .parent import Parent - class Child(Parent): """ @@ -23,7 +21,9 @@ class Child(Parent): child: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/alias-extends/src/seed/alias_extends/core/datetime_utils.py b/seed/pydantic/alias-extends/src/seed/alias_extends/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/pydantic/alias-extends/src/seed/alias_extends/core/datetime_utils.py +++ b/seed/pydantic/alias-extends/src/seed/alias_extends/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/pydantic/alias-extends/src/seed/alias_extends/core/pydantic_utilities.py b/seed/pydantic/alias-extends/src/seed/alias_extends/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/pydantic/alias-extends/src/seed/alias_extends/core/pydantic_utilities.py +++ b/seed/pydantic/alias-extends/src/seed/alias_extends/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/pydantic/alias-extends/src/seed/alias_extends/core/serialization.py b/seed/pydantic/alias-extends/src/seed/alias_extends/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/pydantic/alias-extends/src/seed/alias_extends/core/serialization.py +++ b/seed/pydantic/alias-extends/src/seed/alias_extends/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/pydantic/alias-extends/src/seed/alias_extends/parent.py b/seed/pydantic/alias-extends/src/seed/alias_extends/parent.py index aa1a43d6886..ab34d1d09b5 100644 --- a/seed/pydantic/alias-extends/src/seed/alias_extends/parent.py +++ b/seed/pydantic/alias-extends/src/seed/alias_extends/parent.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from .core.pydantic_utilities import UniversalBaseModel +from .core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from .core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class Parent(UniversalBaseModel): """ @@ -21,7 +20,9 @@ class Parent(UniversalBaseModel): parent: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/alias-extends/tests/custom/test_client.py b/seed/pydantic/alias-extends/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/pydantic/alias-extends/tests/custom/test_client.py +++ b/seed/pydantic/alias-extends/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/pydantic/alias/pyproject.toml b/seed/pydantic/alias/pyproject.toml index 1e105b93ce0..37809d2b3c5 100644 --- a/seed/pydantic/alias/pyproject.toml +++ b/seed/pydantic/alias/pyproject.toml @@ -41,6 +41,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/pydantic/alias/src/seed/alias/core/datetime_utils.py b/seed/pydantic/alias/src/seed/alias/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/pydantic/alias/src/seed/alias/core/datetime_utils.py +++ b/seed/pydantic/alias/src/seed/alias/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/pydantic/alias/src/seed/alias/core/pydantic_utilities.py b/seed/pydantic/alias/src/seed/alias/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/pydantic/alias/src/seed/alias/core/pydantic_utilities.py +++ b/seed/pydantic/alias/src/seed/alias/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/pydantic/alias/src/seed/alias/core/serialization.py b/seed/pydantic/alias/src/seed/alias/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/pydantic/alias/src/seed/alias/core/serialization.py +++ b/seed/pydantic/alias/src/seed/alias/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/pydantic/alias/src/seed/alias/type.py b/seed/pydantic/alias/src/seed/alias/type.py index 24f0ee8d475..960a3f2ac9e 100644 --- a/seed/pydantic/alias/src/seed/alias/type.py +++ b/seed/pydantic/alias/src/seed/alias/type.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. +from .core.pydantic_utilities import UniversalBaseModel +from .type_id import TypeId +from .core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from .core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .type_id import TypeId - class Type(UniversalBaseModel): """ @@ -26,7 +25,9 @@ class Type(UniversalBaseModel): name: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/alias/src/seed/alias/type_id.py b/seed/pydantic/alias/src/seed/alias/type_id.py index 5cd53c920d5..c5f3b3bb32e 100644 --- a/seed/pydantic/alias/src/seed/alias/type_id.py +++ b/seed/pydantic/alias/src/seed/alias/type_id.py @@ -3,4 +3,5 @@ """ "type-kaljhv87" """ + TypeId = str diff --git a/seed/pydantic/alias/tests/custom/test_client.py b/seed/pydantic/alias/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/pydantic/alias/tests/custom/test_client.py +++ b/seed/pydantic/alias/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/pydantic/api-wide-base-path/pyproject.toml b/seed/pydantic/api-wide-base-path/pyproject.toml index dfec711b317..dd4d55e5cf1 100644 --- a/seed/pydantic/api-wide-base-path/pyproject.toml +++ b/seed/pydantic/api-wide-base-path/pyproject.toml @@ -40,6 +40,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/pydantic/api-wide-base-path/src/seed/api_wide_base_path/core/datetime_utils.py b/seed/pydantic/api-wide-base-path/src/seed/api_wide_base_path/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/pydantic/api-wide-base-path/src/seed/api_wide_base_path/core/datetime_utils.py +++ b/seed/pydantic/api-wide-base-path/src/seed/api_wide_base_path/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/pydantic/api-wide-base-path/src/seed/api_wide_base_path/core/pydantic_utilities.py b/seed/pydantic/api-wide-base-path/src/seed/api_wide_base_path/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/pydantic/api-wide-base-path/src/seed/api_wide_base_path/core/pydantic_utilities.py +++ b/seed/pydantic/api-wide-base-path/src/seed/api_wide_base_path/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/pydantic/api-wide-base-path/src/seed/api_wide_base_path/core/serialization.py b/seed/pydantic/api-wide-base-path/src/seed/api_wide_base_path/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/pydantic/api-wide-base-path/src/seed/api_wide_base_path/core/serialization.py +++ b/seed/pydantic/api-wide-base-path/src/seed/api_wide_base_path/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/pydantic/api-wide-base-path/tests/custom/test_client.py b/seed/pydantic/api-wide-base-path/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/pydantic/api-wide-base-path/tests/custom/test_client.py +++ b/seed/pydantic/api-wide-base-path/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/pydantic/audiences/pyproject.toml b/seed/pydantic/audiences/pyproject.toml index 2957c8da5ee..04103097b20 100644 --- a/seed/pydantic/audiences/pyproject.toml +++ b/seed/pydantic/audiences/pyproject.toml @@ -41,6 +41,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/pydantic/audiences/src/seed/audiences/__init__.py b/seed/pydantic/audiences/src/seed/audiences/__init__.py index a974933681f..d0f97890c3b 100644 --- a/seed/pydantic/audiences/src/seed/audiences/__init__.py +++ b/seed/pydantic/audiences/src/seed/audiences/__init__.py @@ -1,6 +1,16 @@ # This file was auto-generated by Fern from our API Definition. -from .resources import FilteredType, Imported, ImportingType, OptionalString, commons, folder_a, folder_b, folder_c, foo +from .resources import ( + FilteredType, + Imported, + ImportingType, + OptionalString, + commons, + folder_a, + folder_b, + folder_c, + foo, +) __all__ = [ "FilteredType", diff --git a/seed/pydantic/audiences/src/seed/audiences/core/datetime_utils.py b/seed/pydantic/audiences/src/seed/audiences/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/pydantic/audiences/src/seed/audiences/core/datetime_utils.py +++ b/seed/pydantic/audiences/src/seed/audiences/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/pydantic/audiences/src/seed/audiences/core/pydantic_utilities.py b/seed/pydantic/audiences/src/seed/audiences/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/pydantic/audiences/src/seed/audiences/core/pydantic_utilities.py +++ b/seed/pydantic/audiences/src/seed/audiences/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/pydantic/audiences/src/seed/audiences/core/serialization.py b/seed/pydantic/audiences/src/seed/audiences/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/pydantic/audiences/src/seed/audiences/core/serialization.py +++ b/seed/pydantic/audiences/src/seed/audiences/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/pydantic/audiences/src/seed/audiences/resources/folder_a/resources/service/response.py b/seed/pydantic/audiences/src/seed/audiences/resources/folder_a/resources/service/response.py index 4f47ffc9b0c..220399a364f 100644 --- a/seed/pydantic/audiences/src/seed/audiences/resources/folder_a/resources/service/response.py +++ b/seed/pydantic/audiences/src/seed/audiences/resources/folder_a/resources/service/response.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from .....core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from .....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from ....folder_b.resources.common.foo import Foo +from .....core.pydantic_utilities import IS_PYDANTIC_V2 +import pydantic class Response(UniversalBaseModel): foo: typing.Optional[Foo] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/audiences/src/seed/audiences/resources/folder_b/resources/common/foo.py b/seed/pydantic/audiences/src/seed/audiences/resources/folder_b/resources/common/foo.py index b8b3d501caa..2c9df338b83 100644 --- a/seed/pydantic/audiences/src/seed/audiences/resources/folder_b/resources/common/foo.py +++ b/seed/pydantic/audiences/src/seed/audiences/resources/folder_b/resources/common/foo.py @@ -1,18 +1,21 @@ # This file was auto-generated by Fern from our API Definition. +from .....core.pydantic_utilities import UniversalBaseModel import typing - +from ....folder_c.resources.common.foo import ( + Foo as resources_folder_c_resources_common_foo_Foo, +) +from .....core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from .....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from ....folder_c.resources.common.foo import Foo as resources_folder_c_resources_common_foo_Foo - class Foo(UniversalBaseModel): foo: typing.Optional[resources_folder_c_resources_common_foo_Foo] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/audiences/src/seed/audiences/resources/folder_c/resources/common/foo.py b/seed/pydantic/audiences/src/seed/audiences/resources/folder_c/resources/common/foo.py index fd0473f1bb8..4feb888543c 100644 --- a/seed/pydantic/audiences/src/seed/audiences/resources/folder_c/resources/common/foo.py +++ b/seed/pydantic/audiences/src/seed/audiences/resources/folder_c/resources/common/foo.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. -import typing +from .....core.pydantic_utilities import UniversalBaseModel import uuid - +from .....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing import pydantic -from .....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class Foo(UniversalBaseModel): bar_property: uuid.UUID if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/audiences/src/seed/audiences/resources/foo/filtered_type.py b/seed/pydantic/audiences/src/seed/audiences/resources/foo/filtered_type.py index a1349051677..756d98670be 100644 --- a/seed/pydantic/audiences/src/seed/audiences/resources/foo/filtered_type.py +++ b/seed/pydantic/audiences/src/seed/audiences/resources/foo/filtered_type.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel import typing - +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class FilteredType(UniversalBaseModel): public_property: typing.Optional[str] = None private_property: int if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/audiences/src/seed/audiences/resources/foo/importing_type.py b/seed/pydantic/audiences/src/seed/audiences/resources/foo/importing_type.py index f68ea3a098e..c23eda7fe2b 100644 --- a/seed/pydantic/audiences/src/seed/audiences/resources/foo/importing_type.py +++ b/seed/pydantic/audiences/src/seed/audiences/resources/foo/importing_type.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ..commons.imported import Imported +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from ..commons.imported import Imported - class ImportingType(UniversalBaseModel): imported: Imported if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/audiences/tests/custom/test_client.py b/seed/pydantic/audiences/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/pydantic/audiences/tests/custom/test_client.py +++ b/seed/pydantic/audiences/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/pydantic/auth-environment-variables/pyproject.toml b/seed/pydantic/auth-environment-variables/pyproject.toml index 3f0b0a86071..8c28f693229 100644 --- a/seed/pydantic/auth-environment-variables/pyproject.toml +++ b/seed/pydantic/auth-environment-variables/pyproject.toml @@ -40,6 +40,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/pydantic/auth-environment-variables/src/seed/auth_environment_variables/core/datetime_utils.py b/seed/pydantic/auth-environment-variables/src/seed/auth_environment_variables/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/pydantic/auth-environment-variables/src/seed/auth_environment_variables/core/datetime_utils.py +++ b/seed/pydantic/auth-environment-variables/src/seed/auth_environment_variables/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/pydantic/auth-environment-variables/src/seed/auth_environment_variables/core/pydantic_utilities.py b/seed/pydantic/auth-environment-variables/src/seed/auth_environment_variables/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/pydantic/auth-environment-variables/src/seed/auth_environment_variables/core/pydantic_utilities.py +++ b/seed/pydantic/auth-environment-variables/src/seed/auth_environment_variables/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/pydantic/auth-environment-variables/src/seed/auth_environment_variables/core/serialization.py b/seed/pydantic/auth-environment-variables/src/seed/auth_environment_variables/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/pydantic/auth-environment-variables/src/seed/auth_environment_variables/core/serialization.py +++ b/seed/pydantic/auth-environment-variables/src/seed/auth_environment_variables/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/pydantic/auth-environment-variables/tests/custom/test_client.py b/seed/pydantic/auth-environment-variables/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/pydantic/auth-environment-variables/tests/custom/test_client.py +++ b/seed/pydantic/auth-environment-variables/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/pydantic/basic-auth-environment-variables/pyproject.toml b/seed/pydantic/basic-auth-environment-variables/pyproject.toml index ffd5a7bc845..3e2133f958a 100644 --- a/seed/pydantic/basic-auth-environment-variables/pyproject.toml +++ b/seed/pydantic/basic-auth-environment-variables/pyproject.toml @@ -41,6 +41,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/pydantic/basic-auth-environment-variables/src/seed/basic_auth_environment_variables/core/datetime_utils.py b/seed/pydantic/basic-auth-environment-variables/src/seed/basic_auth_environment_variables/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/pydantic/basic-auth-environment-variables/src/seed/basic_auth_environment_variables/core/datetime_utils.py +++ b/seed/pydantic/basic-auth-environment-variables/src/seed/basic_auth_environment_variables/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/pydantic/basic-auth-environment-variables/src/seed/basic_auth_environment_variables/core/pydantic_utilities.py b/seed/pydantic/basic-auth-environment-variables/src/seed/basic_auth_environment_variables/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/pydantic/basic-auth-environment-variables/src/seed/basic_auth_environment_variables/core/pydantic_utilities.py +++ b/seed/pydantic/basic-auth-environment-variables/src/seed/basic_auth_environment_variables/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/pydantic/basic-auth-environment-variables/src/seed/basic_auth_environment_variables/core/serialization.py b/seed/pydantic/basic-auth-environment-variables/src/seed/basic_auth_environment_variables/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/pydantic/basic-auth-environment-variables/src/seed/basic_auth_environment_variables/core/serialization.py +++ b/seed/pydantic/basic-auth-environment-variables/src/seed/basic_auth_environment_variables/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/pydantic/basic-auth-environment-variables/src/seed/basic_auth_environment_variables/resources/errors/unauthorized_request_error_body.py b/seed/pydantic/basic-auth-environment-variables/src/seed/basic_auth_environment_variables/resources/errors/unauthorized_request_error_body.py index adfe2d56bf0..9dbfe2b0c1f 100644 --- a/seed/pydantic/basic-auth-environment-variables/src/seed/basic_auth_environment_variables/resources/errors/unauthorized_request_error_body.py +++ b/seed/pydantic/basic-auth-environment-variables/src/seed/basic_auth_environment_variables/resources/errors/unauthorized_request_error_body.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class UnauthorizedRequestErrorBody(UniversalBaseModel): message: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/basic-auth-environment-variables/tests/custom/test_client.py b/seed/pydantic/basic-auth-environment-variables/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/pydantic/basic-auth-environment-variables/tests/custom/test_client.py +++ b/seed/pydantic/basic-auth-environment-variables/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/pydantic/basic-auth/pyproject.toml b/seed/pydantic/basic-auth/pyproject.toml index b60a11e12bd..abe3d3a1fb6 100644 --- a/seed/pydantic/basic-auth/pyproject.toml +++ b/seed/pydantic/basic-auth/pyproject.toml @@ -41,6 +41,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/pydantic/basic-auth/src/seed/basic_auth/core/datetime_utils.py b/seed/pydantic/basic-auth/src/seed/basic_auth/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/pydantic/basic-auth/src/seed/basic_auth/core/datetime_utils.py +++ b/seed/pydantic/basic-auth/src/seed/basic_auth/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/pydantic/basic-auth/src/seed/basic_auth/core/pydantic_utilities.py b/seed/pydantic/basic-auth/src/seed/basic_auth/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/pydantic/basic-auth/src/seed/basic_auth/core/pydantic_utilities.py +++ b/seed/pydantic/basic-auth/src/seed/basic_auth/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/pydantic/basic-auth/src/seed/basic_auth/core/serialization.py b/seed/pydantic/basic-auth/src/seed/basic_auth/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/pydantic/basic-auth/src/seed/basic_auth/core/serialization.py +++ b/seed/pydantic/basic-auth/src/seed/basic_auth/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/pydantic/basic-auth/src/seed/basic_auth/resources/errors/unauthorized_request_error_body.py b/seed/pydantic/basic-auth/src/seed/basic_auth/resources/errors/unauthorized_request_error_body.py index adfe2d56bf0..9dbfe2b0c1f 100644 --- a/seed/pydantic/basic-auth/src/seed/basic_auth/resources/errors/unauthorized_request_error_body.py +++ b/seed/pydantic/basic-auth/src/seed/basic_auth/resources/errors/unauthorized_request_error_body.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class UnauthorizedRequestErrorBody(UniversalBaseModel): message: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/basic-auth/tests/custom/test_client.py b/seed/pydantic/basic-auth/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/pydantic/basic-auth/tests/custom/test_client.py +++ b/seed/pydantic/basic-auth/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/pydantic/bearer-token-environment-variable/pyproject.toml b/seed/pydantic/bearer-token-environment-variable/pyproject.toml index 47a9fc2aec4..7bf4b3589be 100644 --- a/seed/pydantic/bearer-token-environment-variable/pyproject.toml +++ b/seed/pydantic/bearer-token-environment-variable/pyproject.toml @@ -40,6 +40,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/pydantic/bearer-token-environment-variable/src/seed/bearer_token_environment_variable/core/datetime_utils.py b/seed/pydantic/bearer-token-environment-variable/src/seed/bearer_token_environment_variable/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/pydantic/bearer-token-environment-variable/src/seed/bearer_token_environment_variable/core/datetime_utils.py +++ b/seed/pydantic/bearer-token-environment-variable/src/seed/bearer_token_environment_variable/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/pydantic/bearer-token-environment-variable/src/seed/bearer_token_environment_variable/core/pydantic_utilities.py b/seed/pydantic/bearer-token-environment-variable/src/seed/bearer_token_environment_variable/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/pydantic/bearer-token-environment-variable/src/seed/bearer_token_environment_variable/core/pydantic_utilities.py +++ b/seed/pydantic/bearer-token-environment-variable/src/seed/bearer_token_environment_variable/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/pydantic/bearer-token-environment-variable/src/seed/bearer_token_environment_variable/core/serialization.py b/seed/pydantic/bearer-token-environment-variable/src/seed/bearer_token_environment_variable/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/pydantic/bearer-token-environment-variable/src/seed/bearer_token_environment_variable/core/serialization.py +++ b/seed/pydantic/bearer-token-environment-variable/src/seed/bearer_token_environment_variable/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/pydantic/bearer-token-environment-variable/tests/custom/test_client.py b/seed/pydantic/bearer-token-environment-variable/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/pydantic/bearer-token-environment-variable/tests/custom/test_client.py +++ b/seed/pydantic/bearer-token-environment-variable/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/pydantic/bytes/pyproject.toml b/seed/pydantic/bytes/pyproject.toml index eb3426e25e6..cf210c7cd3e 100644 --- a/seed/pydantic/bytes/pyproject.toml +++ b/seed/pydantic/bytes/pyproject.toml @@ -40,6 +40,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/pydantic/bytes/src/seed/bytes/core/datetime_utils.py b/seed/pydantic/bytes/src/seed/bytes/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/pydantic/bytes/src/seed/bytes/core/datetime_utils.py +++ b/seed/pydantic/bytes/src/seed/bytes/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/pydantic/bytes/src/seed/bytes/core/pydantic_utilities.py b/seed/pydantic/bytes/src/seed/bytes/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/pydantic/bytes/src/seed/bytes/core/pydantic_utilities.py +++ b/seed/pydantic/bytes/src/seed/bytes/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/pydantic/bytes/src/seed/bytes/core/serialization.py b/seed/pydantic/bytes/src/seed/bytes/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/pydantic/bytes/src/seed/bytes/core/serialization.py +++ b/seed/pydantic/bytes/src/seed/bytes/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/pydantic/bytes/tests/custom/test_client.py b/seed/pydantic/bytes/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/pydantic/bytes/tests/custom/test_client.py +++ b/seed/pydantic/bytes/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/pydantic/circular-references-advanced/pyproject.toml b/seed/pydantic/circular-references-advanced/pyproject.toml index 497855e73c7..49b02fde520 100644 --- a/seed/pydantic/circular-references-advanced/pyproject.toml +++ b/seed/pydantic/circular-references-advanced/pyproject.toml @@ -41,6 +41,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/pydantic/circular-references-advanced/src/seed/api/core/datetime_utils.py b/seed/pydantic/circular-references-advanced/src/seed/api/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/pydantic/circular-references-advanced/src/seed/api/core/datetime_utils.py +++ b/seed/pydantic/circular-references-advanced/src/seed/api/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/pydantic/circular-references-advanced/src/seed/api/core/pydantic_utilities.py b/seed/pydantic/circular-references-advanced/src/seed/api/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/pydantic/circular-references-advanced/src/seed/api/core/pydantic_utilities.py +++ b/seed/pydantic/circular-references-advanced/src/seed/api/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/pydantic/circular-references-advanced/src/seed/api/core/serialization.py b/seed/pydantic/circular-references-advanced/src/seed/api/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/pydantic/circular-references-advanced/src/seed/api/core/serialization.py +++ b/seed/pydantic/circular-references-advanced/src/seed/api/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/pydantic/circular-references-advanced/src/seed/api/importing_a.py b/seed/pydantic/circular-references-advanced/src/seed/api/importing_a.py index f31f5390330..c0a8dd06886 100644 --- a/seed/pydantic/circular-references-advanced/src/seed/api/importing_a.py +++ b/seed/pydantic/circular-references-advanced/src/seed/api/importing_a.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from .core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from .core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .resources.a.a import A +from .core.pydantic_utilities import IS_PYDANTIC_V2 +import pydantic class ImportingA(UniversalBaseModel): a: typing.Optional[A] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/circular-references-advanced/src/seed/api/resources/a/a.py b/seed/pydantic/circular-references-advanced/src/seed/api/resources/a/a.py index 6d95ac4af77..e8dce0461f4 100644 --- a/seed/pydantic/circular-references-advanced/src/seed/api/resources/a/a.py +++ b/seed/pydantic/circular-references-advanced/src/seed/api/resources/a/a.py @@ -1,16 +1,16 @@ # This file was auto-generated by Fern from our API Definition. +from ...root_type import RootType +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2 -from ...root_type import RootType - class A(RootType): if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/circular-references-advanced/src/seed/api/resources/ast/__init__.py b/seed/pydantic/circular-references-advanced/src/seed/api/resources/ast/__init__.py index 036ab4a59d4..a884e3ead85 100644 --- a/seed/pydantic/circular-references-advanced/src/seed/api/resources/ast/__init__.py +++ b/seed/pydantic/circular-references-advanced/src/seed/api/resources/ast/__init__.py @@ -1,8 +1,17 @@ # This file was auto-generated by Fern from our API Definition. -from .container_value import ContainerValue, ContainerValue_List, ContainerValue_Optional +from .container_value import ( + ContainerValue, + ContainerValue_List, + ContainerValue_Optional, +) from .field_name import FieldName -from .field_value import FieldValue, FieldValue_ContainerValue, FieldValue_ObjectValue, FieldValue_PrimitiveValue +from .field_value import ( + FieldValue, + FieldValue_ContainerValue, + FieldValue_ObjectValue, + FieldValue_PrimitiveValue, +) from .object_field_value import ObjectFieldValue from .object_value import ObjectValue from .primitive_value import PrimitiveValue diff --git a/seed/pydantic/circular-references-advanced/src/seed/api/resources/ast/container_value.py b/seed/pydantic/circular-references-advanced/src/seed/api/resources/ast/container_value.py index 02918ccb82a..570ab64071e 100644 --- a/seed/pydantic/circular-references-advanced/src/seed/api/resources/ast/container_value.py +++ b/seed/pydantic/circular-references-advanced/src/seed/api/resources/ast/container_value.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ...core.pydantic_utilities import UniversalBaseModel import typing - -from ...core.pydantic_utilities import UniversalBaseModel, update_forward_refs from .object_value import ObjectValue from .primitive_value import PrimitiveValue +from ...core.pydantic_utilities import update_forward_refs class ContainerValue_List(UniversalBaseModel): diff --git a/seed/pydantic/circular-references-advanced/src/seed/api/resources/ast/field_value.py b/seed/pydantic/circular-references-advanced/src/seed/api/resources/ast/field_value.py index 68a6c4306e0..2ccee5607d1 100644 --- a/seed/pydantic/circular-references-advanced/src/seed/api/resources/ast/field_value.py +++ b/seed/pydantic/circular-references-advanced/src/seed/api/resources/ast/field_value.py @@ -1,13 +1,12 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ...core.pydantic_utilities import UniversalBaseModel +from .primitive_value import PrimitiveValue import typing - +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel, update_forward_refs -from .primitive_value import PrimitiveValue +from ...core.pydantic_utilities import update_forward_refs class FieldValue_PrimitiveValue(UniversalBaseModel): @@ -19,7 +18,9 @@ class FieldValue_ObjectValue(UniversalBaseModel): type: typing.Literal["object_value"] = "object_value" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -31,7 +32,9 @@ class FieldValue_ContainerValue(UniversalBaseModel): type: typing.Literal["container_value"] = "container_value" -FieldValue = typing.Union[FieldValue_PrimitiveValue, FieldValue_ObjectValue, FieldValue_ContainerValue] +FieldValue = typing.Union[ + FieldValue_PrimitiveValue, FieldValue_ObjectValue, FieldValue_ContainerValue +] from .container_value import ContainerValue # noqa: E402 update_forward_refs(FieldValue_ContainerValue, ContainerValue=ContainerValue) diff --git a/seed/pydantic/circular-references-advanced/src/seed/api/resources/ast/object_field_value.py b/seed/pydantic/circular-references-advanced/src/seed/api/resources/ast/object_field_value.py index 156fc220010..4f0eb280711 100644 --- a/seed/pydantic/circular-references-advanced/src/seed/api/resources/ast/object_field_value.py +++ b/seed/pydantic/circular-references-advanced/src/seed/api/resources/ast/object_field_value.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ...core.pydantic_utilities import UniversalBaseModel from .field_name import FieldName from .field_value import FieldValue +from ...core.pydantic_utilities import IS_PYDANTIC_V2 +import typing +import pydantic class ObjectFieldValue(UniversalBaseModel): @@ -18,7 +17,9 @@ class ObjectFieldValue(UniversalBaseModel): value: FieldValue if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/circular-references-advanced/src/seed/api/resources/ast/object_value.py b/seed/pydantic/circular-references-advanced/src/seed/api/resources/ast/object_value.py index 5142289a93d..0c561ad2b97 100644 --- a/seed/pydantic/circular-references-advanced/src/seed/api/resources/ast/object_value.py +++ b/seed/pydantic/circular-references-advanced/src/seed/api/resources/ast/object_value.py @@ -1,15 +1,16 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class ObjectValue(UniversalBaseModel): if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/circular-references-advanced/src/seed/api/root_type.py b/seed/pydantic/circular-references-advanced/src/seed/api/root_type.py index d3a75bef55e..21f7bc0f818 100644 --- a/seed/pydantic/circular-references-advanced/src/seed/api/root_type.py +++ b/seed/pydantic/circular-references-advanced/src/seed/api/root_type.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from .core.pydantic_utilities import UniversalBaseModel +from .core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from .core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class RootType(UniversalBaseModel): s: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/circular-references-advanced/tests/custom/test_client.py b/seed/pydantic/circular-references-advanced/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/pydantic/circular-references-advanced/tests/custom/test_client.py +++ b/seed/pydantic/circular-references-advanced/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/pydantic/circular-references/pyproject.toml b/seed/pydantic/circular-references/pyproject.toml index fa666fb47fc..95e02720560 100644 --- a/seed/pydantic/circular-references/pyproject.toml +++ b/seed/pydantic/circular-references/pyproject.toml @@ -41,6 +41,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/pydantic/circular-references/src/seed/api/core/datetime_utils.py b/seed/pydantic/circular-references/src/seed/api/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/pydantic/circular-references/src/seed/api/core/datetime_utils.py +++ b/seed/pydantic/circular-references/src/seed/api/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/pydantic/circular-references/src/seed/api/core/pydantic_utilities.py b/seed/pydantic/circular-references/src/seed/api/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/pydantic/circular-references/src/seed/api/core/pydantic_utilities.py +++ b/seed/pydantic/circular-references/src/seed/api/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/pydantic/circular-references/src/seed/api/core/serialization.py b/seed/pydantic/circular-references/src/seed/api/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/pydantic/circular-references/src/seed/api/core/serialization.py +++ b/seed/pydantic/circular-references/src/seed/api/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/pydantic/circular-references/src/seed/api/importing_a.py b/seed/pydantic/circular-references/src/seed/api/importing_a.py index f31f5390330..c0a8dd06886 100644 --- a/seed/pydantic/circular-references/src/seed/api/importing_a.py +++ b/seed/pydantic/circular-references/src/seed/api/importing_a.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from .core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from .core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .resources.a.a import A +from .core.pydantic_utilities import IS_PYDANTIC_V2 +import pydantic class ImportingA(UniversalBaseModel): a: typing.Optional[A] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/circular-references/src/seed/api/resources/a/a.py b/seed/pydantic/circular-references/src/seed/api/resources/a/a.py index 6d95ac4af77..e8dce0461f4 100644 --- a/seed/pydantic/circular-references/src/seed/api/resources/a/a.py +++ b/seed/pydantic/circular-references/src/seed/api/resources/a/a.py @@ -1,16 +1,16 @@ # This file was auto-generated by Fern from our API Definition. +from ...root_type import RootType +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2 -from ...root_type import RootType - class A(RootType): if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/circular-references/src/seed/api/resources/ast/__init__.py b/seed/pydantic/circular-references/src/seed/api/resources/ast/__init__.py index a820a4eea37..10dd40bdd5b 100644 --- a/seed/pydantic/circular-references/src/seed/api/resources/ast/__init__.py +++ b/seed/pydantic/circular-references/src/seed/api/resources/ast/__init__.py @@ -1,7 +1,16 @@ # This file was auto-generated by Fern from our API Definition. -from .container_value import ContainerValue, ContainerValue_List, ContainerValue_Optional -from .field_value import FieldValue, FieldValue_ContainerValue, FieldValue_ObjectValue, FieldValue_PrimitiveValue +from .container_value import ( + ContainerValue, + ContainerValue_List, + ContainerValue_Optional, +) +from .field_value import ( + FieldValue, + FieldValue_ContainerValue, + FieldValue_ObjectValue, + FieldValue_PrimitiveValue, +) from .object_value import ObjectValue from .primitive_value import PrimitiveValue diff --git a/seed/pydantic/circular-references/src/seed/api/resources/ast/container_value.py b/seed/pydantic/circular-references/src/seed/api/resources/ast/container_value.py index 02918ccb82a..570ab64071e 100644 --- a/seed/pydantic/circular-references/src/seed/api/resources/ast/container_value.py +++ b/seed/pydantic/circular-references/src/seed/api/resources/ast/container_value.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ...core.pydantic_utilities import UniversalBaseModel import typing - -from ...core.pydantic_utilities import UniversalBaseModel, update_forward_refs from .object_value import ObjectValue from .primitive_value import PrimitiveValue +from ...core.pydantic_utilities import update_forward_refs class ContainerValue_List(UniversalBaseModel): diff --git a/seed/pydantic/circular-references/src/seed/api/resources/ast/field_value.py b/seed/pydantic/circular-references/src/seed/api/resources/ast/field_value.py index 68a6c4306e0..2ccee5607d1 100644 --- a/seed/pydantic/circular-references/src/seed/api/resources/ast/field_value.py +++ b/seed/pydantic/circular-references/src/seed/api/resources/ast/field_value.py @@ -1,13 +1,12 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ...core.pydantic_utilities import UniversalBaseModel +from .primitive_value import PrimitiveValue import typing - +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel, update_forward_refs -from .primitive_value import PrimitiveValue +from ...core.pydantic_utilities import update_forward_refs class FieldValue_PrimitiveValue(UniversalBaseModel): @@ -19,7 +18,9 @@ class FieldValue_ObjectValue(UniversalBaseModel): type: typing.Literal["object_value"] = "object_value" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -31,7 +32,9 @@ class FieldValue_ContainerValue(UniversalBaseModel): type: typing.Literal["container_value"] = "container_value" -FieldValue = typing.Union[FieldValue_PrimitiveValue, FieldValue_ObjectValue, FieldValue_ContainerValue] +FieldValue = typing.Union[ + FieldValue_PrimitiveValue, FieldValue_ObjectValue, FieldValue_ContainerValue +] from .container_value import ContainerValue # noqa: E402 update_forward_refs(FieldValue_ContainerValue, ContainerValue=ContainerValue) diff --git a/seed/pydantic/circular-references/src/seed/api/resources/ast/object_value.py b/seed/pydantic/circular-references/src/seed/api/resources/ast/object_value.py index 5142289a93d..0c561ad2b97 100644 --- a/seed/pydantic/circular-references/src/seed/api/resources/ast/object_value.py +++ b/seed/pydantic/circular-references/src/seed/api/resources/ast/object_value.py @@ -1,15 +1,16 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class ObjectValue(UniversalBaseModel): if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/circular-references/src/seed/api/root_type.py b/seed/pydantic/circular-references/src/seed/api/root_type.py index d3a75bef55e..21f7bc0f818 100644 --- a/seed/pydantic/circular-references/src/seed/api/root_type.py +++ b/seed/pydantic/circular-references/src/seed/api/root_type.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from .core.pydantic_utilities import UniversalBaseModel +from .core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from .core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class RootType(UniversalBaseModel): s: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/circular-references/tests/custom/test_client.py b/seed/pydantic/circular-references/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/pydantic/circular-references/tests/custom/test_client.py +++ b/seed/pydantic/circular-references/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/pydantic/code-samples/pyproject.toml b/seed/pydantic/code-samples/pyproject.toml index 93267aa1021..6a0b36aa31c 100644 --- a/seed/pydantic/code-samples/pyproject.toml +++ b/seed/pydantic/code-samples/pyproject.toml @@ -41,6 +41,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/pydantic/code-samples/src/seed/code_samples/core/datetime_utils.py b/seed/pydantic/code-samples/src/seed/code_samples/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/pydantic/code-samples/src/seed/code_samples/core/datetime_utils.py +++ b/seed/pydantic/code-samples/src/seed/code_samples/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/pydantic/code-samples/src/seed/code_samples/core/pydantic_utilities.py b/seed/pydantic/code-samples/src/seed/code_samples/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/pydantic/code-samples/src/seed/code_samples/core/pydantic_utilities.py +++ b/seed/pydantic/code-samples/src/seed/code_samples/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/pydantic/code-samples/src/seed/code_samples/core/serialization.py b/seed/pydantic/code-samples/src/seed/code_samples/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/pydantic/code-samples/src/seed/code_samples/core/serialization.py +++ b/seed/pydantic/code-samples/src/seed/code_samples/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/pydantic/code-samples/src/seed/code_samples/resources/service/my_response.py b/seed/pydantic/code-samples/src/seed/code_samples/resources/service/my_response.py index 3569519c269..2efc27a867b 100644 --- a/seed/pydantic/code-samples/src/seed/code_samples/resources/service/my_response.py +++ b/seed/pydantic/code-samples/src/seed/code_samples/resources/service/my_response.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel import typing - +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class MyResponse(UniversalBaseModel): id: str name: typing.Optional[str] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/code-samples/tests/custom/test_client.py b/seed/pydantic/code-samples/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/pydantic/code-samples/tests/custom/test_client.py +++ b/seed/pydantic/code-samples/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/pydantic/custom-auth/pyproject.toml b/seed/pydantic/custom-auth/pyproject.toml index 984cc4e21da..c5537b925da 100644 --- a/seed/pydantic/custom-auth/pyproject.toml +++ b/seed/pydantic/custom-auth/pyproject.toml @@ -41,6 +41,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/pydantic/custom-auth/src/seed/custom_auth/core/datetime_utils.py b/seed/pydantic/custom-auth/src/seed/custom_auth/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/pydantic/custom-auth/src/seed/custom_auth/core/datetime_utils.py +++ b/seed/pydantic/custom-auth/src/seed/custom_auth/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/pydantic/custom-auth/src/seed/custom_auth/core/pydantic_utilities.py b/seed/pydantic/custom-auth/src/seed/custom_auth/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/pydantic/custom-auth/src/seed/custom_auth/core/pydantic_utilities.py +++ b/seed/pydantic/custom-auth/src/seed/custom_auth/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/pydantic/custom-auth/src/seed/custom_auth/core/serialization.py b/seed/pydantic/custom-auth/src/seed/custom_auth/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/pydantic/custom-auth/src/seed/custom_auth/core/serialization.py +++ b/seed/pydantic/custom-auth/src/seed/custom_auth/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/pydantic/custom-auth/src/seed/custom_auth/resources/errors/unauthorized_request_error_body.py b/seed/pydantic/custom-auth/src/seed/custom_auth/resources/errors/unauthorized_request_error_body.py index adfe2d56bf0..9dbfe2b0c1f 100644 --- a/seed/pydantic/custom-auth/src/seed/custom_auth/resources/errors/unauthorized_request_error_body.py +++ b/seed/pydantic/custom-auth/src/seed/custom_auth/resources/errors/unauthorized_request_error_body.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class UnauthorizedRequestErrorBody(UniversalBaseModel): message: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/custom-auth/tests/custom/test_client.py b/seed/pydantic/custom-auth/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/pydantic/custom-auth/tests/custom/test_client.py +++ b/seed/pydantic/custom-auth/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/pydantic/enum-query-params/src/seed/api/core/datetime_utils.py b/seed/pydantic/enum-query-params/src/seed/api/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/pydantic/enum-query-params/src/seed/api/core/datetime_utils.py +++ b/seed/pydantic/enum-query-params/src/seed/api/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/pydantic/enum-query-params/tests/test_client.py b/seed/pydantic/enum-query-params/tests/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/pydantic/enum-query-params/tests/test_client.py +++ b/seed/pydantic/enum-query-params/tests/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/pydantic/enum/pyproject.toml b/seed/pydantic/enum/pyproject.toml index c55662a418f..b86d5b4e2e5 100644 --- a/seed/pydantic/enum/pyproject.toml +++ b/seed/pydantic/enum/pyproject.toml @@ -40,6 +40,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/pydantic/enum/src/seed/enum/color_or_operand.py b/seed/pydantic/enum/src/seed/enum/color_or_operand.py index 5de8179707c..1bbec1032b1 100644 --- a/seed/pydantic/enum/src/seed/enum/color_or_operand.py +++ b/seed/pydantic/enum/src/seed/enum/color_or_operand.py @@ -1,7 +1,6 @@ # This file was auto-generated by Fern from our API Definition. import typing - from .color import Color from .operand import Operand diff --git a/seed/pydantic/enum/src/seed/enum/core/datetime_utils.py b/seed/pydantic/enum/src/seed/enum/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/pydantic/enum/src/seed/enum/core/datetime_utils.py +++ b/seed/pydantic/enum/src/seed/enum/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/pydantic/enum/src/seed/enum/core/pydantic_utilities.py b/seed/pydantic/enum/src/seed/enum/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/pydantic/enum/src/seed/enum/core/pydantic_utilities.py +++ b/seed/pydantic/enum/src/seed/enum/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/pydantic/enum/src/seed/enum/core/serialization.py b/seed/pydantic/enum/src/seed/enum/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/pydantic/enum/src/seed/enum/core/serialization.py +++ b/seed/pydantic/enum/src/seed/enum/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/pydantic/enum/tests/custom/test_client.py b/seed/pydantic/enum/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/pydantic/enum/tests/custom/test_client.py +++ b/seed/pydantic/enum/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/pydantic/error-property/pyproject.toml b/seed/pydantic/error-property/pyproject.toml index 2c74bb16d6b..47b18bb68ca 100644 --- a/seed/pydantic/error-property/pyproject.toml +++ b/seed/pydantic/error-property/pyproject.toml @@ -41,6 +41,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/pydantic/error-property/src/seed/error_property/core/datetime_utils.py b/seed/pydantic/error-property/src/seed/error_property/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/pydantic/error-property/src/seed/error_property/core/datetime_utils.py +++ b/seed/pydantic/error-property/src/seed/error_property/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/pydantic/error-property/src/seed/error_property/core/pydantic_utilities.py b/seed/pydantic/error-property/src/seed/error_property/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/pydantic/error-property/src/seed/error_property/core/pydantic_utilities.py +++ b/seed/pydantic/error-property/src/seed/error_property/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/pydantic/error-property/src/seed/error_property/core/serialization.py b/seed/pydantic/error-property/src/seed/error_property/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/pydantic/error-property/src/seed/error_property/core/serialization.py +++ b/seed/pydantic/error-property/src/seed/error_property/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/pydantic/error-property/src/seed/error_property/resources/errors/property_based_error_test_body.py b/seed/pydantic/error-property/src/seed/error_property/resources/errors/property_based_error_test_body.py index db67fcc7f50..05cc298063e 100644 --- a/seed/pydantic/error-property/src/seed/error_property/resources/errors/property_based_error_test_body.py +++ b/seed/pydantic/error-property/src/seed/error_property/resources/errors/property_based_error_test_body.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class PropertyBasedErrorTestBody(UniversalBaseModel): message: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/error-property/tests/custom/test_client.py b/seed/pydantic/error-property/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/pydantic/error-property/tests/custom/test_client.py +++ b/seed/pydantic/error-property/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/pydantic/examples/pyproject.toml b/seed/pydantic/examples/pyproject.toml index 49304543482..99b4485f980 100644 --- a/seed/pydantic/examples/pyproject.toml +++ b/seed/pydantic/examples/pyproject.toml @@ -41,6 +41,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/pydantic/examples/src/seed/examples/core/datetime_utils.py b/seed/pydantic/examples/src/seed/examples/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/pydantic/examples/src/seed/examples/core/datetime_utils.py +++ b/seed/pydantic/examples/src/seed/examples/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/pydantic/examples/src/seed/examples/core/pydantic_utilities.py b/seed/pydantic/examples/src/seed/examples/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/pydantic/examples/src/seed/examples/core/pydantic_utilities.py +++ b/seed/pydantic/examples/src/seed/examples/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/pydantic/examples/src/seed/examples/core/serialization.py b/seed/pydantic/examples/src/seed/examples/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/pydantic/examples/src/seed/examples/core/serialization.py +++ b/seed/pydantic/examples/src/seed/examples/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/pydantic/examples/src/seed/examples/identifier.py b/seed/pydantic/examples/src/seed/examples/identifier.py index 137cf65a18a..1ddd6c4c7a2 100644 --- a/seed/pydantic/examples/src/seed/examples/identifier.py +++ b/seed/pydantic/examples/src/seed/examples/identifier.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. +from .core.pydantic_utilities import UniversalBaseModel +from .type import Type +from .core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from .core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .type import Type - class Identifier(UniversalBaseModel): type: Type @@ -14,7 +13,9 @@ class Identifier(UniversalBaseModel): label: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/examples/src/seed/examples/resources/commons/resources/__init__.py b/seed/pydantic/examples/src/seed/examples/resources/commons/resources/__init__.py index 18f8242ba3b..1bdaa4d10af 100644 --- a/seed/pydantic/examples/src/seed/examples/resources/commons/resources/__init__.py +++ b/seed/pydantic/examples/src/seed/examples/resources/commons/resources/__init__.py @@ -1,7 +1,16 @@ # This file was auto-generated by Fern from our API Definition. from . import types -from .types import Data, Data_Base64, Data_String, EventInfo, EventInfo_Metadata, EventInfo_Tag, Metadata, Tag +from .types import ( + Data, + Data_Base64, + Data_String, + EventInfo, + EventInfo_Metadata, + EventInfo_Tag, + Metadata, + Tag, +) __all__ = [ "Data", diff --git a/seed/pydantic/examples/src/seed/examples/resources/commons/resources/types/__init__.py b/seed/pydantic/examples/src/seed/examples/resources/commons/resources/types/__init__.py index a73f9e83b6c..9c78512dba5 100644 --- a/seed/pydantic/examples/src/seed/examples/resources/commons/resources/types/__init__.py +++ b/seed/pydantic/examples/src/seed/examples/resources/commons/resources/types/__init__.py @@ -5,4 +5,13 @@ from .metadata import Metadata from .tag import Tag -__all__ = ["Data", "Data_Base64", "Data_String", "EventInfo", "EventInfo_Metadata", "EventInfo_Tag", "Metadata", "Tag"] +__all__ = [ + "Data", + "Data_Base64", + "Data_String", + "EventInfo", + "EventInfo_Metadata", + "EventInfo_Tag", + "Metadata", + "Tag", +] diff --git a/seed/pydantic/examples/src/seed/examples/resources/commons/resources/types/data.py b/seed/pydantic/examples/src/seed/examples/resources/commons/resources/types/data.py index 852ee906ee9..274e012f9c2 100644 --- a/seed/pydantic/examples/src/seed/examples/resources/commons/resources/types/data.py +++ b/seed/pydantic/examples/src/seed/examples/resources/commons/resources/types/data.py @@ -1,10 +1,8 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - -import typing - from .....core.pydantic_utilities import UniversalBaseModel +import typing class Data_String(UniversalBaseModel): diff --git a/seed/pydantic/examples/src/seed/examples/resources/commons/resources/types/event_info.py b/seed/pydantic/examples/src/seed/examples/resources/commons/resources/types/event_info.py index b1210fd45ad..5512b7ba3b5 100644 --- a/seed/pydantic/examples/src/seed/examples/resources/commons/resources/types/event_info.py +++ b/seed/pydantic/examples/src/seed/examples/resources/commons/resources/types/event_info.py @@ -1,12 +1,10 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from .....core.pydantic_utilities import UniversalBaseModel import typing - import pydantic - -from .....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from .....core.pydantic_utilities import IS_PYDANTIC_V2 from .tag import Tag @@ -29,7 +27,9 @@ class EventInfo_Metadata(UniversalBaseModel): json_string: typing.Optional[str] = pydantic.Field(alias="jsonString", default=None) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/examples/src/seed/examples/resources/commons/resources/types/metadata.py b/seed/pydantic/examples/src/seed/examples/resources/commons/resources/types/metadata.py index 4fe630acbde..ddebf111d7e 100644 --- a/seed/pydantic/examples/src/seed/examples/resources/commons/resources/types/metadata.py +++ b/seed/pydantic/examples/src/seed/examples/resources/commons/resources/types/metadata.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. +from .....core.pydantic_utilities import UniversalBaseModel import typing - import pydantic - -from .....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from .....core.pydantic_utilities import IS_PYDANTIC_V2 class Metadata(UniversalBaseModel): @@ -25,7 +24,9 @@ class Metadata(UniversalBaseModel): json_string: typing.Optional[str] = pydantic.Field(alias="jsonString", default=None) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/examples/src/seed/examples/resources/commons/resources/types/tag.py b/seed/pydantic/examples/src/seed/examples/resources/commons/resources/types/tag.py index ae576888232..ad97a39db4c 100644 --- a/seed/pydantic/examples/src/seed/examples/resources/commons/resources/types/tag.py +++ b/seed/pydantic/examples/src/seed/examples/resources/commons/resources/types/tag.py @@ -3,4 +3,5 @@ """ "tag-wf9as23d" """ + Tag = str diff --git a/seed/pydantic/examples/src/seed/examples/resources/file/resources/service/filename.py b/seed/pydantic/examples/src/seed/examples/resources/file/resources/service/filename.py index add91706b10..2531edee925 100644 --- a/seed/pydantic/examples/src/seed/examples/resources/file/resources/service/filename.py +++ b/seed/pydantic/examples/src/seed/examples/resources/file/resources/service/filename.py @@ -3,4 +3,5 @@ """ "file.txt" """ + Filename = str diff --git a/seed/pydantic/examples/src/seed/examples/resources/types/actor.py b/seed/pydantic/examples/src/seed/examples/resources/types/actor.py index bb689e0bffe..5740e98fc90 100644 --- a/seed/pydantic/examples/src/seed/examples/resources/types/actor.py +++ b/seed/pydantic/examples/src/seed/examples/resources/types/actor.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class Actor(UniversalBaseModel): name: str id: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/examples/src/seed/examples/resources/types/actress.py b/seed/pydantic/examples/src/seed/examples/resources/types/actress.py index 5b5a46baa54..28d726e1d38 100644 --- a/seed/pydantic/examples/src/seed/examples/resources/types/actress.py +++ b/seed/pydantic/examples/src/seed/examples/resources/types/actress.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class Actress(UniversalBaseModel): """ @@ -23,7 +22,9 @@ class Actress(UniversalBaseModel): id: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/examples/src/seed/examples/resources/types/cast_member.py b/seed/pydantic/examples/src/seed/examples/resources/types/cast_member.py index d73c89864e1..8be1a0b0a2a 100644 --- a/seed/pydantic/examples/src/seed/examples/resources/types/cast_member.py +++ b/seed/pydantic/examples/src/seed/examples/resources/types/cast_member.py @@ -1,7 +1,6 @@ # This file was auto-generated by Fern from our API Definition. import typing - from .actor import Actor from .actress import Actress from .stunt_double import StuntDouble diff --git a/seed/pydantic/examples/src/seed/examples/resources/types/directory.py b/seed/pydantic/examples/src/seed/examples/resources/types/directory.py index f2d4306c566..100782f780d 100644 --- a/seed/pydantic/examples/src/seed/examples/resources/types/directory.py +++ b/seed/pydantic/examples/src/seed/examples/resources/types/directory.py @@ -1,13 +1,12 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ...core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel, update_forward_refs from .file import File +from ...core.pydantic_utilities import IS_PYDANTIC_V2 +import pydantic +from ...core.pydantic_utilities import update_forward_refs class Directory(UniversalBaseModel): @@ -43,7 +42,9 @@ class Directory(UniversalBaseModel): directories: typing.Optional[typing.List[Directory]] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/examples/src/seed/examples/resources/types/entity.py b/seed/pydantic/examples/src/seed/examples/resources/types/entity.py index 9f7a44e9426..b484a293892 100644 --- a/seed/pydantic/examples/src/seed/examples/resources/types/entity.py +++ b/seed/pydantic/examples/src/seed/examples/resources/types/entity.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ...type import Type +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from ...type import Type - class Entity(UniversalBaseModel): """ @@ -24,7 +23,9 @@ class Entity(UniversalBaseModel): name: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/examples/src/seed/examples/resources/types/exception.py b/seed/pydantic/examples/src/seed/examples/resources/types/exception.py index 652f672924c..246262fe823 100644 --- a/seed/pydantic/examples/src/seed/examples/resources/types/exception.py +++ b/seed/pydantic/examples/src/seed/examples/resources/types/exception.py @@ -1,12 +1,10 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ...core.pydantic_utilities import UniversalBaseModel import typing - import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 class Exception_Generic(UniversalBaseModel): @@ -28,7 +26,9 @@ class Exception_Generic(UniversalBaseModel): exception_stacktrace: str = pydantic.Field(alias="exceptionStacktrace") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -51,7 +51,9 @@ class Exception_Timeout(UniversalBaseModel): type: typing.Literal["timeout"] = "timeout" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/examples/src/seed/examples/resources/types/exception_info.py b/seed/pydantic/examples/src/seed/examples/resources/types/exception_info.py index f46ac71bade..899d6c8e430 100644 --- a/seed/pydantic/examples/src/seed/examples/resources/types/exception_info.py +++ b/seed/pydantic/examples/src/seed/examples/resources/types/exception_info.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ...core.pydantic_utilities import UniversalBaseModel import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class ExceptionInfo(UniversalBaseModel): @@ -25,7 +24,9 @@ class ExceptionInfo(UniversalBaseModel): exception_stacktrace: str = pydantic.Field(alias="exceptionStacktrace") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/examples/src/seed/examples/resources/types/extended_movie.py b/seed/pydantic/examples/src/seed/examples/resources/types/extended_movie.py index 001575c18df..daecf88f45b 100644 --- a/seed/pydantic/examples/src/seed/examples/resources/types/extended_movie.py +++ b/seed/pydantic/examples/src/seed/examples/resources/types/extended_movie.py @@ -1,11 +1,9 @@ # This file was auto-generated by Fern from our API Definition. +from .movie import Movie import typing - -import pydantic - from ...core.pydantic_utilities import IS_PYDANTIC_V2 -from .movie import Movie +import pydantic class ExtendedMovie(Movie): @@ -32,7 +30,9 @@ class ExtendedMovie(Movie): cast: typing.List[str] if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/examples/src/seed/examples/resources/types/file.py b/seed/pydantic/examples/src/seed/examples/resources/types/file.py index ad943db303a..27fe0fed029 100644 --- a/seed/pydantic/examples/src/seed/examples/resources/types/file.py +++ b/seed/pydantic/examples/src/seed/examples/resources/types/file.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class File(UniversalBaseModel): """ @@ -23,7 +22,9 @@ class File(UniversalBaseModel): contents: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/examples/src/seed/examples/resources/types/metadata.py b/seed/pydantic/examples/src/seed/examples/resources/types/metadata.py index 4329d0fafbc..a9d684fba00 100644 --- a/seed/pydantic/examples/src/seed/examples/resources/types/metadata.py +++ b/seed/pydantic/examples/src/seed/examples/resources/types/metadata.py @@ -1,13 +1,11 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ...core.pydantic_utilities import UniversalBaseModel import typing - +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class Base(UniversalBaseModel): """ @@ -22,7 +20,9 @@ class Base(UniversalBaseModel): tags: typing.Set[str] if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/examples/src/seed/examples/resources/types/migration.py b/seed/pydantic/examples/src/seed/examples/resources/types/migration.py index 64766ca7180..6483ce78070 100644 --- a/seed/pydantic/examples/src/seed/examples/resources/types/migration.py +++ b/seed/pydantic/examples/src/seed/examples/resources/types/migration.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from .migration_status import MigrationStatus +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .migration_status import MigrationStatus - class Migration(UniversalBaseModel): """ @@ -24,7 +23,9 @@ class Migration(UniversalBaseModel): status: MigrationStatus if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/examples/src/seed/examples/resources/types/migration_status.py b/seed/pydantic/examples/src/seed/examples/resources/types/migration_status.py index c5a2e76b4af..e14e67e1b5a 100644 --- a/seed/pydantic/examples/src/seed/examples/resources/types/migration_status.py +++ b/seed/pydantic/examples/src/seed/examples/resources/types/migration_status.py @@ -2,4 +2,6 @@ import typing -MigrationStatus = typing.Union[typing.Literal["RUNNING", "FAILED", "FINISHED"], typing.Any] +MigrationStatus = typing.Union[ + typing.Literal["RUNNING", "FAILED", "FINISHED"], typing.Any +] diff --git a/seed/pydantic/examples/src/seed/examples/resources/types/moment.py b/seed/pydantic/examples/src/seed/examples/resources/types/moment.py index 3aec578e4b9..37a004b5837 100644 --- a/seed/pydantic/examples/src/seed/examples/resources/types/moment.py +++ b/seed/pydantic/examples/src/seed/examples/resources/types/moment.py @@ -1,13 +1,12 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +import uuid import datetime as dt +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing -import uuid - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class Moment(UniversalBaseModel): """ @@ -36,7 +35,9 @@ class Moment(UniversalBaseModel): datetime: dt.datetime if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/examples/src/seed/examples/resources/types/movie.py b/seed/pydantic/examples/src/seed/examples/resources/types/movie.py index d59a51cf20e..5fc405ff837 100644 --- a/seed/pydantic/examples/src/seed/examples/resources/types/movie.py +++ b/seed/pydantic/examples/src/seed/examples/resources/types/movie.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from .movie_id import MovieId import typing - import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from ..commons.resources.types.tag import Tag -from .movie_id import MovieId +from ...core.pydantic_utilities import IS_PYDANTIC_V2 class Movie(UniversalBaseModel): @@ -45,7 +44,9 @@ class Movie(UniversalBaseModel): metadata: typing.Dict[str, typing.Any] if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/examples/src/seed/examples/resources/types/movie_id.py b/seed/pydantic/examples/src/seed/examples/resources/types/movie_id.py index 86f7a4f4651..86945f3b676 100644 --- a/seed/pydantic/examples/src/seed/examples/resources/types/movie_id.py +++ b/seed/pydantic/examples/src/seed/examples/resources/types/movie_id.py @@ -3,4 +3,5 @@ """ "movie-c06a4ad7" """ + MovieId = str diff --git a/seed/pydantic/examples/src/seed/examples/resources/types/node.py b/seed/pydantic/examples/src/seed/examples/resources/types/node.py index 50fbc6ddffc..9a335529560 100644 --- a/seed/pydantic/examples/src/seed/examples/resources/types/node.py +++ b/seed/pydantic/examples/src/seed/examples/resources/types/node.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ...core.pydantic_utilities import UniversalBaseModel import typing - +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel, update_forward_refs +from ...core.pydantic_utilities import update_forward_refs class Node(UniversalBaseModel): @@ -45,7 +44,9 @@ class Node(UniversalBaseModel): trees: typing.Optional[typing.List[Tree]] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/examples/src/seed/examples/resources/types/request.py b/seed/pydantic/examples/src/seed/examples/resources/types/request.py index 8d2ac9806be..e2cb99acce2 100644 --- a/seed/pydantic/examples/src/seed/examples/resources/types/request.py +++ b/seed/pydantic/examples/src/seed/examples/resources/types/request.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel import typing - +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class Request(UniversalBaseModel): """ @@ -21,7 +20,9 @@ class Request(UniversalBaseModel): request: typing.Any if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/examples/src/seed/examples/resources/types/response.py b/seed/pydantic/examples/src/seed/examples/resources/types/response.py index 4a09aaf3823..415d7727a53 100644 --- a/seed/pydantic/examples/src/seed/examples/resources/types/response.py +++ b/seed/pydantic/examples/src/seed/examples/resources/types/response.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from ...identifier import Identifier +from ...core.pydantic_utilities import IS_PYDANTIC_V2 +import pydantic class Response(UniversalBaseModel): @@ -36,7 +35,9 @@ class Response(UniversalBaseModel): identifiers: typing.List[Identifier] if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/examples/src/seed/examples/resources/types/response_type.py b/seed/pydantic/examples/src/seed/examples/resources/types/response_type.py index eb83a708faf..81e428853bd 100644 --- a/seed/pydantic/examples/src/seed/examples/resources/types/response_type.py +++ b/seed/pydantic/examples/src/seed/examples/resources/types/response_type.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ...type import Type +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from ...type import Type - class ResponseType(UniversalBaseModel): type: Type if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/examples/src/seed/examples/resources/types/stunt_double.py b/seed/pydantic/examples/src/seed/examples/resources/types/stunt_double.py index 4c2a2299ea9..fa7add9be60 100644 --- a/seed/pydantic/examples/src/seed/examples/resources/types/stunt_double.py +++ b/seed/pydantic/examples/src/seed/examples/resources/types/stunt_double.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ...core.pydantic_utilities import UniversalBaseModel import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class StuntDouble(UniversalBaseModel): @@ -12,7 +11,9 @@ class StuntDouble(UniversalBaseModel): actor_or_actress_id: str = pydantic.Field(alias="actorOrActressId") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/examples/src/seed/examples/resources/types/test.py b/seed/pydantic/examples/src/seed/examples/resources/types/test.py index ca8b8ecd950..8739ac82733 100644 --- a/seed/pydantic/examples/src/seed/examples/resources/types/test.py +++ b/seed/pydantic/examples/src/seed/examples/resources/types/test.py @@ -1,10 +1,8 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - -import typing - from ...core.pydantic_utilities import UniversalBaseModel +import typing class Test_And(UniversalBaseModel): diff --git a/seed/pydantic/examples/src/seed/examples/resources/types/tree.py b/seed/pydantic/examples/src/seed/examples/resources/types/tree.py index 64dc355d428..355872e628d 100644 --- a/seed/pydantic/examples/src/seed/examples/resources/types/tree.py +++ b/seed/pydantic/examples/src/seed/examples/resources/types/tree.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ...core.pydantic_utilities import UniversalBaseModel import typing - +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel, update_forward_refs +from ...core.pydantic_utilities import update_forward_refs class Tree(UniversalBaseModel): @@ -30,7 +29,9 @@ class Tree(UniversalBaseModel): nodes: typing.Optional[typing.List[Node]] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/examples/src/seed/examples/type.py b/seed/pydantic/examples/src/seed/examples/type.py index 09d1c916dfd..e77e5e18b15 100644 --- a/seed/pydantic/examples/src/seed/examples/type.py +++ b/seed/pydantic/examples/src/seed/examples/type.py @@ -1,7 +1,6 @@ # This file was auto-generated by Fern from our API Definition. import typing - from .basic_type import BasicType from .complex_type import ComplexType diff --git a/seed/pydantic/examples/tests/custom/test_client.py b/seed/pydantic/examples/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/pydantic/examples/tests/custom/test_client.py +++ b/seed/pydantic/examples/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/pydantic/exhaustive/pydantic-v1/pyproject.toml b/seed/pydantic/exhaustive/pydantic-v1/pyproject.toml index 7a84145071d..3cfa25e6666 100644 --- a/seed/pydantic/exhaustive/pydantic-v1/pyproject.toml +++ b/seed/pydantic/exhaustive/pydantic-v1/pyproject.toml @@ -41,6 +41,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/pydantic/exhaustive/pydantic-v1/src/seed/exhaustive/core/datetime_utils.py b/seed/pydantic/exhaustive/pydantic-v1/src/seed/exhaustive/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/pydantic/exhaustive/pydantic-v1/src/seed/exhaustive/core/datetime_utils.py +++ b/seed/pydantic/exhaustive/pydantic-v1/src/seed/exhaustive/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/pydantic/exhaustive/pydantic-v1/src/seed/exhaustive/core/pydantic_utilities.py b/seed/pydantic/exhaustive/pydantic-v1/src/seed/exhaustive/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/pydantic/exhaustive/pydantic-v1/src/seed/exhaustive/core/pydantic_utilities.py +++ b/seed/pydantic/exhaustive/pydantic-v1/src/seed/exhaustive/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/pydantic/exhaustive/pydantic-v1/src/seed/exhaustive/core/serialization.py b/seed/pydantic/exhaustive/pydantic-v1/src/seed/exhaustive/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/pydantic/exhaustive/pydantic-v1/src/seed/exhaustive/core/serialization.py +++ b/seed/pydantic/exhaustive/pydantic-v1/src/seed/exhaustive/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/pydantic/exhaustive/pydantic-v1/src/seed/exhaustive/resources/general_errors/bad_object_request_info.py b/seed/pydantic/exhaustive/pydantic-v1/src/seed/exhaustive/resources/general_errors/bad_object_request_info.py index acb55f16b2f..dde0194de12 100644 --- a/seed/pydantic/exhaustive/pydantic-v1/src/seed/exhaustive/resources/general_errors/bad_object_request_info.py +++ b/seed/pydantic/exhaustive/pydantic-v1/src/seed/exhaustive/resources/general_errors/bad_object_request_info.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class BadObjectRequestInfo(UniversalBaseModel): message: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/exhaustive/pydantic-v1/src/seed/exhaustive/resources/types/resources/enum/weather_report.py b/seed/pydantic/exhaustive/pydantic-v1/src/seed/exhaustive/resources/types/resources/enum/weather_report.py index 2d54965dc22..84017ef161d 100644 --- a/seed/pydantic/exhaustive/pydantic-v1/src/seed/exhaustive/resources/types/resources/enum/weather_report.py +++ b/seed/pydantic/exhaustive/pydantic-v1/src/seed/exhaustive/resources/types/resources/enum/weather_report.py @@ -2,4 +2,6 @@ import typing -WeatherReport = typing.Union[typing.Literal["SUNNY", "CLOUDY", "RAINING", "SNOWING"], typing.Any] +WeatherReport = typing.Union[ + typing.Literal["SUNNY", "CLOUDY", "RAINING", "SNOWING"], typing.Any +] diff --git a/seed/pydantic/exhaustive/pydantic-v1/src/seed/exhaustive/resources/types/resources/object/double_optional.py b/seed/pydantic/exhaustive/pydantic-v1/src/seed/exhaustive/resources/types/resources/object/double_optional.py index 968523991ca..52340ced4a1 100644 --- a/seed/pydantic/exhaustive/pydantic-v1/src/seed/exhaustive/resources/types/resources/object/double_optional.py +++ b/seed/pydantic/exhaustive/pydantic-v1/src/seed/exhaustive/resources/types/resources/object/double_optional.py @@ -1,18 +1,21 @@ # This file was auto-generated by Fern from our API Definition. +from .....core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from .....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .optional_alias import OptionalAlias +import pydantic +from .....core.pydantic_utilities import IS_PYDANTIC_V2 class DoubleOptional(UniversalBaseModel): - optional_alias: typing.Optional[OptionalAlias] = pydantic.Field(alias="optionalAlias", default=None) + optional_alias: typing.Optional[OptionalAlias] = pydantic.Field( + alias="optionalAlias", default=None + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/exhaustive/pydantic-v1/src/seed/exhaustive/resources/types/resources/object/nested_object_with_optional_field.py b/seed/pydantic/exhaustive/pydantic-v1/src/seed/exhaustive/resources/types/resources/object/nested_object_with_optional_field.py index 3223eee122b..2139be2226e 100644 --- a/seed/pydantic/exhaustive/pydantic-v1/src/seed/exhaustive/resources/types/resources/object/nested_object_with_optional_field.py +++ b/seed/pydantic/exhaustive/pydantic-v1/src/seed/exhaustive/resources/types/resources/object/nested_object_with_optional_field.py @@ -1,19 +1,22 @@ # This file was auto-generated by Fern from our API Definition. +from .....core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from .....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .object_with_optional_field import ObjectWithOptionalField +import pydantic +from .....core.pydantic_utilities import IS_PYDANTIC_V2 class NestedObjectWithOptionalField(UniversalBaseModel): string: typing.Optional[str] = None - nested_object: typing.Optional[ObjectWithOptionalField] = pydantic.Field(alias="NestedObject", default=None) + nested_object: typing.Optional[ObjectWithOptionalField] = pydantic.Field( + alias="NestedObject", default=None + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/exhaustive/pydantic-v1/src/seed/exhaustive/resources/types/resources/object/nested_object_with_required_field.py b/seed/pydantic/exhaustive/pydantic-v1/src/seed/exhaustive/resources/types/resources/object/nested_object_with_required_field.py index 6d829532cd7..4204b1a0872 100644 --- a/seed/pydantic/exhaustive/pydantic-v1/src/seed/exhaustive/resources/types/resources/object/nested_object_with_required_field.py +++ b/seed/pydantic/exhaustive/pydantic-v1/src/seed/exhaustive/resources/types/resources/object/nested_object_with_required_field.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from .....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from .....core.pydantic_utilities import UniversalBaseModel from .object_with_optional_field import ObjectWithOptionalField +import pydantic +from .....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class NestedObjectWithRequiredField(UniversalBaseModel): @@ -13,7 +12,9 @@ class NestedObjectWithRequiredField(UniversalBaseModel): nested_object: ObjectWithOptionalField = pydantic.Field(alias="NestedObject") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/exhaustive/pydantic-v1/src/seed/exhaustive/resources/types/resources/object/object_with_map_of_map.py b/seed/pydantic/exhaustive/pydantic-v1/src/seed/exhaustive/resources/types/resources/object/object_with_map_of_map.py index fb3bff88d6f..04c83857064 100644 --- a/seed/pydantic/exhaustive/pydantic-v1/src/seed/exhaustive/resources/types/resources/object/object_with_map_of_map.py +++ b/seed/pydantic/exhaustive/pydantic-v1/src/seed/exhaustive/resources/types/resources/object/object_with_map_of_map.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from .....core.pydantic_utilities import UniversalBaseModel import typing - import pydantic - -from .....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from .....core.pydantic_utilities import IS_PYDANTIC_V2 class ObjectWithMapOfMap(UniversalBaseModel): map_: typing.Dict[str, typing.Dict[str, str]] = pydantic.Field(alias="map") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/exhaustive/pydantic-v1/src/seed/exhaustive/resources/types/resources/object/object_with_optional_field.py b/seed/pydantic/exhaustive/pydantic-v1/src/seed/exhaustive/resources/types/resources/object/object_with_optional_field.py index 6d55e1dc5a2..6cbc9f89900 100644 --- a/seed/pydantic/exhaustive/pydantic-v1/src/seed/exhaustive/resources/types/resources/object/object_with_optional_field.py +++ b/seed/pydantic/exhaustive/pydantic-v1/src/seed/exhaustive/resources/types/resources/object/object_with_optional_field.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. -import datetime as dt +from .....core.pydantic_utilities import UniversalBaseModel import typing -import uuid - import pydantic - -from .....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +import datetime as dt +import uuid +from .....core.pydantic_utilities import IS_PYDANTIC_V2 class ObjectWithOptionalField(UniversalBaseModel): @@ -23,13 +22,19 @@ class ObjectWithOptionalField(UniversalBaseModel): date: typing.Optional[dt.date] = None uuid_: typing.Optional[uuid.UUID] = pydantic.Field(alias="uuid", default=None) base_64: typing.Optional[str] = pydantic.Field(alias="base64", default=None) - list_: typing.Optional[typing.List[str]] = pydantic.Field(alias="list", default=None) + list_: typing.Optional[typing.List[str]] = pydantic.Field( + alias="list", default=None + ) set_: typing.Optional[typing.Set[str]] = pydantic.Field(alias="set", default=None) - map_: typing.Optional[typing.Dict[int, str]] = pydantic.Field(alias="map", default=None) + map_: typing.Optional[typing.Dict[int, str]] = pydantic.Field( + alias="map", default=None + ) bigint: typing.Optional[str] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/exhaustive/pydantic-v1/src/seed/exhaustive/resources/types/resources/object/object_with_required_field.py b/seed/pydantic/exhaustive/pydantic-v1/src/seed/exhaustive/resources/types/resources/object/object_with_required_field.py index d8222e96d55..40e6e7b2592 100644 --- a/seed/pydantic/exhaustive/pydantic-v1/src/seed/exhaustive/resources/types/resources/object/object_with_required_field.py +++ b/seed/pydantic/exhaustive/pydantic-v1/src/seed/exhaustive/resources/types/resources/object/object_with_required_field.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from .....core.pydantic_utilities import UniversalBaseModel +from .....core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from .....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class ObjectWithRequiredField(UniversalBaseModel): string: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/exhaustive/pydantic-v1/src/seed/exhaustive/resources/types/resources/union/animal.py b/seed/pydantic/exhaustive/pydantic-v1/src/seed/exhaustive/resources/types/resources/union/animal.py index ee6e412925e..77caa0ada05 100644 --- a/seed/pydantic/exhaustive/pydantic-v1/src/seed/exhaustive/resources/types/resources/union/animal.py +++ b/seed/pydantic/exhaustive/pydantic-v1/src/seed/exhaustive/resources/types/resources/union/animal.py @@ -1,12 +1,10 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from .....core.pydantic_utilities import UniversalBaseModel import typing - import pydantic - -from .....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from .....core.pydantic_utilities import IS_PYDANTIC_V2 class Animal_Dog(UniversalBaseModel): @@ -15,7 +13,9 @@ class Animal_Dog(UniversalBaseModel): likes_to_woof: bool = pydantic.Field(alias="likesToWoof") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -28,7 +28,9 @@ class Animal_Cat(UniversalBaseModel): likes_to_meow: bool = pydantic.Field(alias="likesToMeow") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/exhaustive/pydantic-v1/src/seed/exhaustive/resources/types/resources/union/cat.py b/seed/pydantic/exhaustive/pydantic-v1/src/seed/exhaustive/resources/types/resources/union/cat.py index f8caebe2547..0bd227c177a 100644 --- a/seed/pydantic/exhaustive/pydantic-v1/src/seed/exhaustive/resources/types/resources/union/cat.py +++ b/seed/pydantic/exhaustive/pydantic-v1/src/seed/exhaustive/resources/types/resources/union/cat.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from .....core.pydantic_utilities import UniversalBaseModel import pydantic - -from .....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from .....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class Cat(UniversalBaseModel): @@ -12,7 +11,9 @@ class Cat(UniversalBaseModel): likes_to_meow: bool = pydantic.Field(alias="likesToMeow") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/exhaustive/pydantic-v1/src/seed/exhaustive/resources/types/resources/union/dog.py b/seed/pydantic/exhaustive/pydantic-v1/src/seed/exhaustive/resources/types/resources/union/dog.py index 630b2bb8a3b..22e8bc35337 100644 --- a/seed/pydantic/exhaustive/pydantic-v1/src/seed/exhaustive/resources/types/resources/union/dog.py +++ b/seed/pydantic/exhaustive/pydantic-v1/src/seed/exhaustive/resources/types/resources/union/dog.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from .....core.pydantic_utilities import UniversalBaseModel import pydantic - -from .....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from .....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class Dog(UniversalBaseModel): @@ -12,7 +11,9 @@ class Dog(UniversalBaseModel): likes_to_woof: bool = pydantic.Field(alias="likesToWoof") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/exhaustive/pydantic-v1/tests/custom/test_client.py b/seed/pydantic/exhaustive/pydantic-v1/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/pydantic/exhaustive/pydantic-v1/tests/custom/test_client.py +++ b/seed/pydantic/exhaustive/pydantic-v1/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/pydantic/exhaustive/pydantic-v2/pyproject.toml b/seed/pydantic/exhaustive/pydantic-v2/pyproject.toml index 7a84145071d..3cfa25e6666 100644 --- a/seed/pydantic/exhaustive/pydantic-v2/pyproject.toml +++ b/seed/pydantic/exhaustive/pydantic-v2/pyproject.toml @@ -41,6 +41,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/pydantic/exhaustive/pydantic-v2/src/seed/exhaustive/core/datetime_utils.py b/seed/pydantic/exhaustive/pydantic-v2/src/seed/exhaustive/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/pydantic/exhaustive/pydantic-v2/src/seed/exhaustive/core/datetime_utils.py +++ b/seed/pydantic/exhaustive/pydantic-v2/src/seed/exhaustive/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/pydantic/exhaustive/pydantic-v2/src/seed/exhaustive/core/pydantic_utilities.py b/seed/pydantic/exhaustive/pydantic-v2/src/seed/exhaustive/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/pydantic/exhaustive/pydantic-v2/src/seed/exhaustive/core/pydantic_utilities.py +++ b/seed/pydantic/exhaustive/pydantic-v2/src/seed/exhaustive/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/pydantic/exhaustive/pydantic-v2/src/seed/exhaustive/core/serialization.py b/seed/pydantic/exhaustive/pydantic-v2/src/seed/exhaustive/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/pydantic/exhaustive/pydantic-v2/src/seed/exhaustive/core/serialization.py +++ b/seed/pydantic/exhaustive/pydantic-v2/src/seed/exhaustive/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/pydantic/exhaustive/pydantic-v2/src/seed/exhaustive/resources/general_errors/bad_object_request_info.py b/seed/pydantic/exhaustive/pydantic-v2/src/seed/exhaustive/resources/general_errors/bad_object_request_info.py index acb55f16b2f..dde0194de12 100644 --- a/seed/pydantic/exhaustive/pydantic-v2/src/seed/exhaustive/resources/general_errors/bad_object_request_info.py +++ b/seed/pydantic/exhaustive/pydantic-v2/src/seed/exhaustive/resources/general_errors/bad_object_request_info.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class BadObjectRequestInfo(UniversalBaseModel): message: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/exhaustive/pydantic-v2/src/seed/exhaustive/resources/types/resources/enum/weather_report.py b/seed/pydantic/exhaustive/pydantic-v2/src/seed/exhaustive/resources/types/resources/enum/weather_report.py index 2d54965dc22..84017ef161d 100644 --- a/seed/pydantic/exhaustive/pydantic-v2/src/seed/exhaustive/resources/types/resources/enum/weather_report.py +++ b/seed/pydantic/exhaustive/pydantic-v2/src/seed/exhaustive/resources/types/resources/enum/weather_report.py @@ -2,4 +2,6 @@ import typing -WeatherReport = typing.Union[typing.Literal["SUNNY", "CLOUDY", "RAINING", "SNOWING"], typing.Any] +WeatherReport = typing.Union[ + typing.Literal["SUNNY", "CLOUDY", "RAINING", "SNOWING"], typing.Any +] diff --git a/seed/pydantic/exhaustive/pydantic-v2/src/seed/exhaustive/resources/types/resources/object/double_optional.py b/seed/pydantic/exhaustive/pydantic-v2/src/seed/exhaustive/resources/types/resources/object/double_optional.py index 968523991ca..52340ced4a1 100644 --- a/seed/pydantic/exhaustive/pydantic-v2/src/seed/exhaustive/resources/types/resources/object/double_optional.py +++ b/seed/pydantic/exhaustive/pydantic-v2/src/seed/exhaustive/resources/types/resources/object/double_optional.py @@ -1,18 +1,21 @@ # This file was auto-generated by Fern from our API Definition. +from .....core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from .....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .optional_alias import OptionalAlias +import pydantic +from .....core.pydantic_utilities import IS_PYDANTIC_V2 class DoubleOptional(UniversalBaseModel): - optional_alias: typing.Optional[OptionalAlias] = pydantic.Field(alias="optionalAlias", default=None) + optional_alias: typing.Optional[OptionalAlias] = pydantic.Field( + alias="optionalAlias", default=None + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/exhaustive/pydantic-v2/src/seed/exhaustive/resources/types/resources/object/nested_object_with_optional_field.py b/seed/pydantic/exhaustive/pydantic-v2/src/seed/exhaustive/resources/types/resources/object/nested_object_with_optional_field.py index 3223eee122b..2139be2226e 100644 --- a/seed/pydantic/exhaustive/pydantic-v2/src/seed/exhaustive/resources/types/resources/object/nested_object_with_optional_field.py +++ b/seed/pydantic/exhaustive/pydantic-v2/src/seed/exhaustive/resources/types/resources/object/nested_object_with_optional_field.py @@ -1,19 +1,22 @@ # This file was auto-generated by Fern from our API Definition. +from .....core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from .....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .object_with_optional_field import ObjectWithOptionalField +import pydantic +from .....core.pydantic_utilities import IS_PYDANTIC_V2 class NestedObjectWithOptionalField(UniversalBaseModel): string: typing.Optional[str] = None - nested_object: typing.Optional[ObjectWithOptionalField] = pydantic.Field(alias="NestedObject", default=None) + nested_object: typing.Optional[ObjectWithOptionalField] = pydantic.Field( + alias="NestedObject", default=None + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/exhaustive/pydantic-v2/src/seed/exhaustive/resources/types/resources/object/nested_object_with_required_field.py b/seed/pydantic/exhaustive/pydantic-v2/src/seed/exhaustive/resources/types/resources/object/nested_object_with_required_field.py index 6d829532cd7..4204b1a0872 100644 --- a/seed/pydantic/exhaustive/pydantic-v2/src/seed/exhaustive/resources/types/resources/object/nested_object_with_required_field.py +++ b/seed/pydantic/exhaustive/pydantic-v2/src/seed/exhaustive/resources/types/resources/object/nested_object_with_required_field.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from .....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from .....core.pydantic_utilities import UniversalBaseModel from .object_with_optional_field import ObjectWithOptionalField +import pydantic +from .....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class NestedObjectWithRequiredField(UniversalBaseModel): @@ -13,7 +12,9 @@ class NestedObjectWithRequiredField(UniversalBaseModel): nested_object: ObjectWithOptionalField = pydantic.Field(alias="NestedObject") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/exhaustive/pydantic-v2/src/seed/exhaustive/resources/types/resources/object/object_with_map_of_map.py b/seed/pydantic/exhaustive/pydantic-v2/src/seed/exhaustive/resources/types/resources/object/object_with_map_of_map.py index fb3bff88d6f..04c83857064 100644 --- a/seed/pydantic/exhaustive/pydantic-v2/src/seed/exhaustive/resources/types/resources/object/object_with_map_of_map.py +++ b/seed/pydantic/exhaustive/pydantic-v2/src/seed/exhaustive/resources/types/resources/object/object_with_map_of_map.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from .....core.pydantic_utilities import UniversalBaseModel import typing - import pydantic - -from .....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from .....core.pydantic_utilities import IS_PYDANTIC_V2 class ObjectWithMapOfMap(UniversalBaseModel): map_: typing.Dict[str, typing.Dict[str, str]] = pydantic.Field(alias="map") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/exhaustive/pydantic-v2/src/seed/exhaustive/resources/types/resources/object/object_with_optional_field.py b/seed/pydantic/exhaustive/pydantic-v2/src/seed/exhaustive/resources/types/resources/object/object_with_optional_field.py index 6d55e1dc5a2..6cbc9f89900 100644 --- a/seed/pydantic/exhaustive/pydantic-v2/src/seed/exhaustive/resources/types/resources/object/object_with_optional_field.py +++ b/seed/pydantic/exhaustive/pydantic-v2/src/seed/exhaustive/resources/types/resources/object/object_with_optional_field.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. -import datetime as dt +from .....core.pydantic_utilities import UniversalBaseModel import typing -import uuid - import pydantic - -from .....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +import datetime as dt +import uuid +from .....core.pydantic_utilities import IS_PYDANTIC_V2 class ObjectWithOptionalField(UniversalBaseModel): @@ -23,13 +22,19 @@ class ObjectWithOptionalField(UniversalBaseModel): date: typing.Optional[dt.date] = None uuid_: typing.Optional[uuid.UUID] = pydantic.Field(alias="uuid", default=None) base_64: typing.Optional[str] = pydantic.Field(alias="base64", default=None) - list_: typing.Optional[typing.List[str]] = pydantic.Field(alias="list", default=None) + list_: typing.Optional[typing.List[str]] = pydantic.Field( + alias="list", default=None + ) set_: typing.Optional[typing.Set[str]] = pydantic.Field(alias="set", default=None) - map_: typing.Optional[typing.Dict[int, str]] = pydantic.Field(alias="map", default=None) + map_: typing.Optional[typing.Dict[int, str]] = pydantic.Field( + alias="map", default=None + ) bigint: typing.Optional[str] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/exhaustive/pydantic-v2/src/seed/exhaustive/resources/types/resources/object/object_with_required_field.py b/seed/pydantic/exhaustive/pydantic-v2/src/seed/exhaustive/resources/types/resources/object/object_with_required_field.py index d8222e96d55..40e6e7b2592 100644 --- a/seed/pydantic/exhaustive/pydantic-v2/src/seed/exhaustive/resources/types/resources/object/object_with_required_field.py +++ b/seed/pydantic/exhaustive/pydantic-v2/src/seed/exhaustive/resources/types/resources/object/object_with_required_field.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from .....core.pydantic_utilities import UniversalBaseModel +from .....core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from .....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class ObjectWithRequiredField(UniversalBaseModel): string: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/exhaustive/pydantic-v2/src/seed/exhaustive/resources/types/resources/union/animal.py b/seed/pydantic/exhaustive/pydantic-v2/src/seed/exhaustive/resources/types/resources/union/animal.py index ee6e412925e..77caa0ada05 100644 --- a/seed/pydantic/exhaustive/pydantic-v2/src/seed/exhaustive/resources/types/resources/union/animal.py +++ b/seed/pydantic/exhaustive/pydantic-v2/src/seed/exhaustive/resources/types/resources/union/animal.py @@ -1,12 +1,10 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from .....core.pydantic_utilities import UniversalBaseModel import typing - import pydantic - -from .....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from .....core.pydantic_utilities import IS_PYDANTIC_V2 class Animal_Dog(UniversalBaseModel): @@ -15,7 +13,9 @@ class Animal_Dog(UniversalBaseModel): likes_to_woof: bool = pydantic.Field(alias="likesToWoof") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -28,7 +28,9 @@ class Animal_Cat(UniversalBaseModel): likes_to_meow: bool = pydantic.Field(alias="likesToMeow") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/exhaustive/pydantic-v2/src/seed/exhaustive/resources/types/resources/union/cat.py b/seed/pydantic/exhaustive/pydantic-v2/src/seed/exhaustive/resources/types/resources/union/cat.py index f8caebe2547..0bd227c177a 100644 --- a/seed/pydantic/exhaustive/pydantic-v2/src/seed/exhaustive/resources/types/resources/union/cat.py +++ b/seed/pydantic/exhaustive/pydantic-v2/src/seed/exhaustive/resources/types/resources/union/cat.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from .....core.pydantic_utilities import UniversalBaseModel import pydantic - -from .....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from .....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class Cat(UniversalBaseModel): @@ -12,7 +11,9 @@ class Cat(UniversalBaseModel): likes_to_meow: bool = pydantic.Field(alias="likesToMeow") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/exhaustive/pydantic-v2/src/seed/exhaustive/resources/types/resources/union/dog.py b/seed/pydantic/exhaustive/pydantic-v2/src/seed/exhaustive/resources/types/resources/union/dog.py index 630b2bb8a3b..22e8bc35337 100644 --- a/seed/pydantic/exhaustive/pydantic-v2/src/seed/exhaustive/resources/types/resources/union/dog.py +++ b/seed/pydantic/exhaustive/pydantic-v2/src/seed/exhaustive/resources/types/resources/union/dog.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from .....core.pydantic_utilities import UniversalBaseModel import pydantic - -from .....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from .....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class Dog(UniversalBaseModel): @@ -12,7 +11,9 @@ class Dog(UniversalBaseModel): likes_to_woof: bool = pydantic.Field(alias="likesToWoof") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/exhaustive/pydantic-v2/tests/custom/test_client.py b/seed/pydantic/exhaustive/pydantic-v2/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/pydantic/exhaustive/pydantic-v2/tests/custom/test_client.py +++ b/seed/pydantic/exhaustive/pydantic-v2/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/pydantic/exhaustive/src/seed/exhaustive/core/datetime_utils.py b/seed/pydantic/exhaustive/src/seed/exhaustive/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/pydantic/exhaustive/src/seed/exhaustive/core/datetime_utils.py +++ b/seed/pydantic/exhaustive/src/seed/exhaustive/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/pydantic/exhaustive/src/seed/exhaustive/resources/general_errors/bad_object_request_info.py b/seed/pydantic/exhaustive/src/seed/exhaustive/resources/general_errors/bad_object_request_info.py index a865e9444bb..a5d7cc5087b 100644 --- a/seed/pydantic/exhaustive/src/seed/exhaustive/resources/general_errors/bad_object_request_info.py +++ b/seed/pydantic/exhaustive/src/seed/exhaustive/resources/general_errors/bad_object_request_info.py @@ -15,11 +15,19 @@ class BadObjectRequestInfo(pydantic.BaseModel): message: str def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/pydantic/exhaustive/src/seed/exhaustive/resources/types/resources/object/nested_object_with_optional_field.py b/seed/pydantic/exhaustive/src/seed/exhaustive/resources/types/resources/object/nested_object_with_optional_field.py index a7e46b9d843..29bdcc05428 100644 --- a/seed/pydantic/exhaustive/src/seed/exhaustive/resources/types/resources/object/nested_object_with_optional_field.py +++ b/seed/pydantic/exhaustive/src/seed/exhaustive/resources/types/resources/object/nested_object_with_optional_field.py @@ -14,14 +14,24 @@ class NestedObjectWithOptionalField(pydantic.BaseModel): string: typing.Optional[str] - nested_object: typing.Optional[ObjectWithOptionalField] = pydantic.Field(alias="NestedObject") + nested_object: typing.Optional[ObjectWithOptionalField] = pydantic.Field( + alias="NestedObject" + ) def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/pydantic/exhaustive/src/seed/exhaustive/resources/types/resources/object/nested_object_with_required_field.py b/seed/pydantic/exhaustive/src/seed/exhaustive/resources/types/resources/object/nested_object_with_required_field.py index 7e05249b484..d03eb1dc8c1 100644 --- a/seed/pydantic/exhaustive/src/seed/exhaustive/resources/types/resources/object/nested_object_with_required_field.py +++ b/seed/pydantic/exhaustive/src/seed/exhaustive/resources/types/resources/object/nested_object_with_required_field.py @@ -17,11 +17,19 @@ class NestedObjectWithRequiredField(pydantic.BaseModel): nested_object: ObjectWithOptionalField = pydantic.Field(alias="NestedObject") def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/pydantic/exhaustive/src/seed/exhaustive/resources/types/resources/object/object_with_optional_field.py b/seed/pydantic/exhaustive/src/seed/exhaustive/resources/types/resources/object/object_with_optional_field.py index 168b8292b3c..ed365c0e7ee 100644 --- a/seed/pydantic/exhaustive/src/seed/exhaustive/resources/types/resources/object/object_with_optional_field.py +++ b/seed/pydantic/exhaustive/src/seed/exhaustive/resources/types/resources/object/object_with_optional_field.py @@ -27,11 +27,19 @@ class ObjectWithOptionalField(pydantic.BaseModel): map: typing.Optional[typing.Dict[int, str]] def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/pydantic/exhaustive/src/seed/exhaustive/resources/types/resources/object/object_with_required_field.py b/seed/pydantic/exhaustive/src/seed/exhaustive/resources/types/resources/object/object_with_required_field.py index 044f6ff7931..af8432f26a3 100644 --- a/seed/pydantic/exhaustive/src/seed/exhaustive/resources/types/resources/object/object_with_required_field.py +++ b/seed/pydantic/exhaustive/src/seed/exhaustive/resources/types/resources/object/object_with_required_field.py @@ -15,11 +15,19 @@ class ObjectWithRequiredField(pydantic.BaseModel): string: str def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/pydantic/exhaustive/src/seed/exhaustive/resources/types/resources/union/cat.py b/seed/pydantic/exhaustive/src/seed/exhaustive/resources/types/resources/union/cat.py index 72df81e2963..caf722e1ee0 100644 --- a/seed/pydantic/exhaustive/src/seed/exhaustive/resources/types/resources/union/cat.py +++ b/seed/pydantic/exhaustive/src/seed/exhaustive/resources/types/resources/union/cat.py @@ -16,11 +16,19 @@ class Cat(pydantic.BaseModel): likes_to_meow: bool = pydantic.Field(alias="likesToMeow") def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/pydantic/exhaustive/src/seed/exhaustive/resources/types/resources/union/dog.py b/seed/pydantic/exhaustive/src/seed/exhaustive/resources/types/resources/union/dog.py index 0b6647eac2d..8fbcaca4261 100644 --- a/seed/pydantic/exhaustive/src/seed/exhaustive/resources/types/resources/union/dog.py +++ b/seed/pydantic/exhaustive/src/seed/exhaustive/resources/types/resources/union/dog.py @@ -16,11 +16,19 @@ class Dog(pydantic.BaseModel): likes_to_woof: bool = pydantic.Field(alias="likesToWoof") def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/pydantic/exhaustive/tests/test_client.py b/seed/pydantic/exhaustive/tests/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/pydantic/exhaustive/tests/test_client.py +++ b/seed/pydantic/exhaustive/tests/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/pydantic/extends/pyproject.toml b/seed/pydantic/extends/pyproject.toml index a57a8d60726..f694de6799a 100644 --- a/seed/pydantic/extends/pyproject.toml +++ b/seed/pydantic/extends/pyproject.toml @@ -41,6 +41,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/pydantic/extends/src/seed/extends/core/datetime_utils.py b/seed/pydantic/extends/src/seed/extends/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/pydantic/extends/src/seed/extends/core/datetime_utils.py +++ b/seed/pydantic/extends/src/seed/extends/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/pydantic/extends/src/seed/extends/core/pydantic_utilities.py b/seed/pydantic/extends/src/seed/extends/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/pydantic/extends/src/seed/extends/core/pydantic_utilities.py +++ b/seed/pydantic/extends/src/seed/extends/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/pydantic/extends/src/seed/extends/core/serialization.py b/seed/pydantic/extends/src/seed/extends/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/pydantic/extends/src/seed/extends/core/serialization.py +++ b/seed/pydantic/extends/src/seed/extends/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/pydantic/extends/src/seed/extends/docs.py b/seed/pydantic/extends/src/seed/extends/docs.py index afc62a096cb..6d33a3b0e6e 100644 --- a/seed/pydantic/extends/src/seed/extends/docs.py +++ b/seed/pydantic/extends/src/seed/extends/docs.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from .core.pydantic_utilities import UniversalBaseModel +from .core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from .core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class Docs(UniversalBaseModel): """ @@ -21,7 +20,9 @@ class Docs(UniversalBaseModel): docs: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/extends/src/seed/extends/example_type.py b/seed/pydantic/extends/src/seed/extends/example_type.py index 610c026ca48..fd7415318a1 100644 --- a/seed/pydantic/extends/src/seed/extends/example_type.py +++ b/seed/pydantic/extends/src/seed/extends/example_type.py @@ -1,12 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from .docs import Docs +from .core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from .core.pydantic_utilities import IS_PYDANTIC_V2 -from .docs import Docs - class ExampleType(Docs): """ @@ -23,7 +21,9 @@ class ExampleType(Docs): name: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/extends/src/seed/extends/json.py b/seed/pydantic/extends/src/seed/extends/json.py index 69c136403e0..162e36c2acb 100644 --- a/seed/pydantic/extends/src/seed/extends/json.py +++ b/seed/pydantic/extends/src/seed/extends/json.py @@ -1,12 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from .docs import Docs +from .core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from .core.pydantic_utilities import IS_PYDANTIC_V2 -from .docs import Docs - class Json(Docs): """ @@ -23,7 +21,9 @@ class Json(Docs): raw: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/extends/src/seed/extends/nested_type.py b/seed/pydantic/extends/src/seed/extends/nested_type.py index 6f9ed0624a2..3fa74985e59 100644 --- a/seed/pydantic/extends/src/seed/extends/nested_type.py +++ b/seed/pydantic/extends/src/seed/extends/nested_type.py @@ -1,12 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from .json import Json +from .core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from .core.pydantic_utilities import IS_PYDANTIC_V2 -from .json import Json - class NestedType(Json): """ @@ -24,7 +22,9 @@ class NestedType(Json): name: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/extends/tests/custom/test_client.py b/seed/pydantic/extends/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/pydantic/extends/tests/custom/test_client.py +++ b/seed/pydantic/extends/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/pydantic/extra-properties/pyproject.toml b/seed/pydantic/extra-properties/pyproject.toml index 2a913aa3849..43cfe3d5c56 100644 --- a/seed/pydantic/extra-properties/pyproject.toml +++ b/seed/pydantic/extra-properties/pyproject.toml @@ -41,6 +41,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/pydantic/extra-properties/src/seed/extra_properties/core/datetime_utils.py b/seed/pydantic/extra-properties/src/seed/extra_properties/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/pydantic/extra-properties/src/seed/extra_properties/core/datetime_utils.py +++ b/seed/pydantic/extra-properties/src/seed/extra_properties/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/pydantic/extra-properties/src/seed/extra_properties/core/pydantic_utilities.py b/seed/pydantic/extra-properties/src/seed/extra_properties/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/pydantic/extra-properties/src/seed/extra_properties/core/pydantic_utilities.py +++ b/seed/pydantic/extra-properties/src/seed/extra_properties/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/pydantic/extra-properties/src/seed/extra_properties/core/serialization.py b/seed/pydantic/extra-properties/src/seed/extra_properties/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/pydantic/extra-properties/src/seed/extra_properties/core/serialization.py +++ b/seed/pydantic/extra-properties/src/seed/extra_properties/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/pydantic/extra-properties/src/seed/extra_properties/failure.py b/seed/pydantic/extra-properties/src/seed/extra_properties/failure.py index cfb44b31469..74f47e5a01c 100644 --- a/seed/pydantic/extra-properties/src/seed/extra_properties/failure.py +++ b/seed/pydantic/extra-properties/src/seed/extra_properties/failure.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from .core.pydantic_utilities import UniversalBaseModel import typing - +from .core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from .core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class Failure(UniversalBaseModel): status: typing.Literal["failure"] = "failure" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/extra-properties/src/seed/extra_properties/resources/user/user.py b/seed/pydantic/extra-properties/src/seed/extra_properties/resources/user/user.py index 49d424884b2..0c7f30fb786 100644 --- a/seed/pydantic/extra-properties/src/seed/extra_properties/resources/user/user.py +++ b/seed/pydantic/extra-properties/src/seed/extra_properties/resources/user/user.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class User(UniversalBaseModel): name: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/extra-properties/tests/custom/test_client.py b/seed/pydantic/extra-properties/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/pydantic/extra-properties/tests/custom/test_client.py +++ b/seed/pydantic/extra-properties/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/pydantic/file-download/pyproject.toml b/seed/pydantic/file-download/pyproject.toml index 6ca051f2957..6b7976b124b 100644 --- a/seed/pydantic/file-download/pyproject.toml +++ b/seed/pydantic/file-download/pyproject.toml @@ -40,6 +40,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/pydantic/file-download/src/seed/file_download/core/datetime_utils.py b/seed/pydantic/file-download/src/seed/file_download/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/pydantic/file-download/src/seed/file_download/core/datetime_utils.py +++ b/seed/pydantic/file-download/src/seed/file_download/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/pydantic/file-download/src/seed/file_download/core/pydantic_utilities.py b/seed/pydantic/file-download/src/seed/file_download/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/pydantic/file-download/src/seed/file_download/core/pydantic_utilities.py +++ b/seed/pydantic/file-download/src/seed/file_download/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/pydantic/file-download/src/seed/file_download/core/serialization.py b/seed/pydantic/file-download/src/seed/file_download/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/pydantic/file-download/src/seed/file_download/core/serialization.py +++ b/seed/pydantic/file-download/src/seed/file_download/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/pydantic/file-download/tests/custom/test_client.py b/seed/pydantic/file-download/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/pydantic/file-download/tests/custom/test_client.py +++ b/seed/pydantic/file-download/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/pydantic/file-upload/pyproject.toml b/seed/pydantic/file-upload/pyproject.toml index 1e7cd0fa6d5..012751272c7 100644 --- a/seed/pydantic/file-upload/pyproject.toml +++ b/seed/pydantic/file-upload/pyproject.toml @@ -41,6 +41,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/pydantic/file-upload/src/seed/file_upload/core/datetime_utils.py b/seed/pydantic/file-upload/src/seed/file_upload/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/pydantic/file-upload/src/seed/file_upload/core/datetime_utils.py +++ b/seed/pydantic/file-upload/src/seed/file_upload/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/pydantic/file-upload/src/seed/file_upload/core/pydantic_utilities.py b/seed/pydantic/file-upload/src/seed/file_upload/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/pydantic/file-upload/src/seed/file_upload/core/pydantic_utilities.py +++ b/seed/pydantic/file-upload/src/seed/file_upload/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/pydantic/file-upload/src/seed/file_upload/core/serialization.py b/seed/pydantic/file-upload/src/seed/file_upload/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/pydantic/file-upload/src/seed/file_upload/core/serialization.py +++ b/seed/pydantic/file-upload/src/seed/file_upload/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/pydantic/file-upload/src/seed/file_upload/resources/service/my_object.py b/seed/pydantic/file-upload/src/seed/file_upload/resources/service/my_object.py index 21009321a4a..25e43a7dfd0 100644 --- a/seed/pydantic/file-upload/src/seed/file_upload/resources/service/my_object.py +++ b/seed/pydantic/file-upload/src/seed/file_upload/resources/service/my_object.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class MyObject(UniversalBaseModel): foo: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/file-upload/tests/custom/test_client.py b/seed/pydantic/file-upload/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/pydantic/file-upload/tests/custom/test_client.py +++ b/seed/pydantic/file-upload/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/pydantic/folders/pyproject.toml b/seed/pydantic/folders/pyproject.toml index c3010ea9af6..19d7bb28449 100644 --- a/seed/pydantic/folders/pyproject.toml +++ b/seed/pydantic/folders/pyproject.toml @@ -40,6 +40,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/pydantic/folders/src/seed/api/core/datetime_utils.py b/seed/pydantic/folders/src/seed/api/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/pydantic/folders/src/seed/api/core/datetime_utils.py +++ b/seed/pydantic/folders/src/seed/api/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/pydantic/folders/src/seed/api/core/pydantic_utilities.py b/seed/pydantic/folders/src/seed/api/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/pydantic/folders/src/seed/api/core/pydantic_utilities.py +++ b/seed/pydantic/folders/src/seed/api/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/pydantic/folders/src/seed/api/core/serialization.py b/seed/pydantic/folders/src/seed/api/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/pydantic/folders/src/seed/api/core/serialization.py +++ b/seed/pydantic/folders/src/seed/api/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/pydantic/folders/tests/custom/test_client.py b/seed/pydantic/folders/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/pydantic/folders/tests/custom/test_client.py +++ b/seed/pydantic/folders/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/pydantic/idempotency-headers/pyproject.toml b/seed/pydantic/idempotency-headers/pyproject.toml index 409eabec492..eaed24d692a 100644 --- a/seed/pydantic/idempotency-headers/pyproject.toml +++ b/seed/pydantic/idempotency-headers/pyproject.toml @@ -40,6 +40,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/pydantic/idempotency-headers/src/seed/idempotency_headers/core/datetime_utils.py b/seed/pydantic/idempotency-headers/src/seed/idempotency_headers/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/pydantic/idempotency-headers/src/seed/idempotency_headers/core/datetime_utils.py +++ b/seed/pydantic/idempotency-headers/src/seed/idempotency_headers/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/pydantic/idempotency-headers/src/seed/idempotency_headers/core/pydantic_utilities.py b/seed/pydantic/idempotency-headers/src/seed/idempotency_headers/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/pydantic/idempotency-headers/src/seed/idempotency_headers/core/pydantic_utilities.py +++ b/seed/pydantic/idempotency-headers/src/seed/idempotency_headers/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/pydantic/idempotency-headers/src/seed/idempotency_headers/core/serialization.py b/seed/pydantic/idempotency-headers/src/seed/idempotency_headers/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/pydantic/idempotency-headers/src/seed/idempotency_headers/core/serialization.py +++ b/seed/pydantic/idempotency-headers/src/seed/idempotency_headers/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/pydantic/idempotency-headers/tests/custom/test_client.py b/seed/pydantic/idempotency-headers/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/pydantic/idempotency-headers/tests/custom/test_client.py +++ b/seed/pydantic/idempotency-headers/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/pydantic/imdb/pyproject.toml b/seed/pydantic/imdb/pyproject.toml index cc0851972b4..960c981958d 100644 --- a/seed/pydantic/imdb/pyproject.toml +++ b/seed/pydantic/imdb/pyproject.toml @@ -41,6 +41,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/pydantic/imdb/src/seed/api/core/datetime_utils.py b/seed/pydantic/imdb/src/seed/api/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/pydantic/imdb/src/seed/api/core/datetime_utils.py +++ b/seed/pydantic/imdb/src/seed/api/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/pydantic/imdb/src/seed/api/core/pydantic_utilities.py b/seed/pydantic/imdb/src/seed/api/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/pydantic/imdb/src/seed/api/core/pydantic_utilities.py +++ b/seed/pydantic/imdb/src/seed/api/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/pydantic/imdb/src/seed/api/core/serialization.py b/seed/pydantic/imdb/src/seed/api/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/pydantic/imdb/src/seed/api/core/serialization.py +++ b/seed/pydantic/imdb/src/seed/api/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/pydantic/imdb/src/seed/api/resources/imdb/create_movie_request.py b/seed/pydantic/imdb/src/seed/api/resources/imdb/create_movie_request.py index eb5ffa0665b..aa479a145aa 100644 --- a/seed/pydantic/imdb/src/seed/api/resources/imdb/create_movie_request.py +++ b/seed/pydantic/imdb/src/seed/api/resources/imdb/create_movie_request.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class CreateMovieRequest(UniversalBaseModel): title: str rating: float if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/imdb/src/seed/api/resources/imdb/movie.py b/seed/pydantic/imdb/src/seed/api/resources/imdb/movie.py index ffe275edddb..f5da6ca212b 100644 --- a/seed/pydantic/imdb/src/seed/api/resources/imdb/movie.py +++ b/seed/pydantic/imdb/src/seed/api/resources/imdb/movie.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ...core.pydantic_utilities import UniversalBaseModel from .movie_id import MovieId +import pydantic +from ...core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class Movie(UniversalBaseModel): @@ -17,7 +16,9 @@ class Movie(UniversalBaseModel): """ if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/imdb/tests/custom/test_client.py b/seed/pydantic/imdb/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/pydantic/imdb/tests/custom/test_client.py +++ b/seed/pydantic/imdb/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/pydantic/literal/pyproject.toml b/seed/pydantic/literal/pyproject.toml index f56b0d64dab..3b24124fa63 100644 --- a/seed/pydantic/literal/pyproject.toml +++ b/seed/pydantic/literal/pyproject.toml @@ -41,6 +41,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/pydantic/literal/src/seed/literal/__init__.py b/seed/pydantic/literal/src/seed/literal/__init__.py index 7066e1cfe53..2310f46a994 100644 --- a/seed/pydantic/literal/src/seed/literal/__init__.py +++ b/seed/pydantic/literal/src/seed/literal/__init__.py @@ -3,4 +3,11 @@ from .resources import SendRequest, SomeAliasedLiteral, SomeLiteral, inlined, reference from .send_response import SendResponse -__all__ = ["SendRequest", "SendResponse", "SomeAliasedLiteral", "SomeLiteral", "inlined", "reference"] +__all__ = [ + "SendRequest", + "SendResponse", + "SomeAliasedLiteral", + "SomeLiteral", + "inlined", + "reference", +] diff --git a/seed/pydantic/literal/src/seed/literal/core/datetime_utils.py b/seed/pydantic/literal/src/seed/literal/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/pydantic/literal/src/seed/literal/core/datetime_utils.py +++ b/seed/pydantic/literal/src/seed/literal/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/pydantic/literal/src/seed/literal/core/pydantic_utilities.py b/seed/pydantic/literal/src/seed/literal/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/pydantic/literal/src/seed/literal/core/pydantic_utilities.py +++ b/seed/pydantic/literal/src/seed/literal/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/pydantic/literal/src/seed/literal/core/serialization.py b/seed/pydantic/literal/src/seed/literal/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/pydantic/literal/src/seed/literal/core/serialization.py +++ b/seed/pydantic/literal/src/seed/literal/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/pydantic/literal/src/seed/literal/resources/reference/send_request.py b/seed/pydantic/literal/src/seed/literal/resources/reference/send_request.py index 99b03c0c4fa..b3f528f7ea4 100644 --- a/seed/pydantic/literal/src/seed/literal/resources/reference/send_request.py +++ b/seed/pydantic/literal/src/seed/literal/resources/reference/send_request.py @@ -1,22 +1,27 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .some_literal import SomeLiteral +import pydantic +from ...core.pydantic_utilities import IS_PYDANTIC_V2 class SendRequest(UniversalBaseModel): - prompt: typing.Literal["You are a helpful assistant"] = "You are a helpful assistant" + prompt: typing.Literal["You are a helpful assistant"] = ( + "You are a helpful assistant" + ) query: str stream: typing.Literal[False] = False context: SomeLiteral = "You're super wise" - maybe_context: typing.Optional[SomeLiteral] = pydantic.Field(alias="maybeContext", default=None) + maybe_context: typing.Optional[SomeLiteral] = pydantic.Field( + alias="maybeContext", default=None + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/literal/src/seed/literal/send_response.py b/seed/pydantic/literal/src/seed/literal/send_response.py index d5b1b9fe799..0b313c49b2e 100644 --- a/seed/pydantic/literal/src/seed/literal/send_response.py +++ b/seed/pydantic/literal/src/seed/literal/send_response.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from .core.pydantic_utilities import UniversalBaseModel import typing - +from .core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from .core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class SendResponse(UniversalBaseModel): message: str @@ -13,7 +12,9 @@ class SendResponse(UniversalBaseModel): success: typing.Literal[True] = True if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/literal/tests/custom/test_client.py b/seed/pydantic/literal/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/pydantic/literal/tests/custom/test_client.py +++ b/seed/pydantic/literal/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/pydantic/mixed-case/pyproject.toml b/seed/pydantic/mixed-case/pyproject.toml index cf835702e71..fadb163ca26 100644 --- a/seed/pydantic/mixed-case/pyproject.toml +++ b/seed/pydantic/mixed-case/pyproject.toml @@ -41,6 +41,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/pydantic/mixed-case/src/seed/mixed_case/core/datetime_utils.py b/seed/pydantic/mixed-case/src/seed/mixed_case/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/pydantic/mixed-case/src/seed/mixed_case/core/datetime_utils.py +++ b/seed/pydantic/mixed-case/src/seed/mixed_case/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/pydantic/mixed-case/src/seed/mixed_case/core/pydantic_utilities.py b/seed/pydantic/mixed-case/src/seed/mixed_case/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/pydantic/mixed-case/src/seed/mixed_case/core/pydantic_utilities.py +++ b/seed/pydantic/mixed-case/src/seed/mixed_case/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/pydantic/mixed-case/src/seed/mixed_case/core/serialization.py b/seed/pydantic/mixed-case/src/seed/mixed_case/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/pydantic/mixed-case/src/seed/mixed_case/core/serialization.py +++ b/seed/pydantic/mixed-case/src/seed/mixed_case/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/pydantic/mixed-case/src/seed/mixed_case/resources/__init__.py b/seed/pydantic/mixed-case/src/seed/mixed_case/resources/__init__.py index eaa7b5de316..1ea3199afc8 100644 --- a/seed/pydantic/mixed-case/src/seed/mixed_case/resources/__init__.py +++ b/seed/pydantic/mixed-case/src/seed/mixed_case/resources/__init__.py @@ -1,7 +1,15 @@ # This file was auto-generated by Fern from our API Definition. from . import service -from .service import NestedUser, Organization, Resource, ResourceStatus, Resource_Organization, Resource_User, User +from .service import ( + NestedUser, + Organization, + Resource, + ResourceStatus, + Resource_Organization, + Resource_User, + User, +) __all__ = [ "NestedUser", diff --git a/seed/pydantic/mixed-case/src/seed/mixed_case/resources/service/__init__.py b/seed/pydantic/mixed-case/src/seed/mixed_case/resources/service/__init__.py index b6b435da5c1..c1d7d34969d 100644 --- a/seed/pydantic/mixed-case/src/seed/mixed_case/resources/service/__init__.py +++ b/seed/pydantic/mixed-case/src/seed/mixed_case/resources/service/__init__.py @@ -6,4 +6,12 @@ from .resource_status import ResourceStatus from .user import User -__all__ = ["NestedUser", "Organization", "Resource", "ResourceStatus", "Resource_Organization", "Resource_User", "User"] +__all__ = [ + "NestedUser", + "Organization", + "Resource", + "ResourceStatus", + "Resource_Organization", + "Resource_User", + "User", +] diff --git a/seed/pydantic/mixed-case/src/seed/mixed_case/resources/service/nested_user.py b/seed/pydantic/mixed-case/src/seed/mixed_case/resources/service/nested_user.py index 9a8947ffcc4..cd5ae27241d 100644 --- a/seed/pydantic/mixed-case/src/seed/mixed_case/resources/service/nested_user.py +++ b/seed/pydantic/mixed-case/src/seed/mixed_case/resources/service/nested_user.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ...core.pydantic_utilities import UniversalBaseModel import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .user import User +from ...core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class NestedUser(UniversalBaseModel): @@ -28,7 +27,9 @@ class NestedUser(UniversalBaseModel): nested_user: User = pydantic.Field(alias="NestedUser") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/mixed-case/src/seed/mixed_case/resources/service/organization.py b/seed/pydantic/mixed-case/src/seed/mixed_case/resources/service/organization.py index e8dd0dbef06..5a86ec3c216 100644 --- a/seed/pydantic/mixed-case/src/seed/mixed_case/resources/service/organization.py +++ b/seed/pydantic/mixed-case/src/seed/mixed_case/resources/service/organization.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class Organization(UniversalBaseModel): """ @@ -21,7 +20,9 @@ class Organization(UniversalBaseModel): name: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/mixed-case/src/seed/mixed_case/resources/service/resource.py b/seed/pydantic/mixed-case/src/seed/mixed_case/resources/service/resource.py index 4c87ba85350..55c25b52ed8 100644 --- a/seed/pydantic/mixed-case/src/seed/mixed_case/resources/service/resource.py +++ b/seed/pydantic/mixed-case/src/seed/mixed_case/resources/service/resource.py @@ -1,14 +1,12 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ...core.pydantic_utilities import UniversalBaseModel +from .resource_status import ResourceStatus +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .resource_status import ResourceStatus - class Base(UniversalBaseModel): """ @@ -26,7 +24,9 @@ class Base(UniversalBaseModel): status: ResourceStatus if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -52,7 +52,9 @@ class Resource_User(Base): extra_properties: typing.Dict[str, str] = pydantic.Field(alias="EXTRA_PROPERTIES") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -76,7 +78,9 @@ class Resource_Organization(Base): name: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/mixed-case/src/seed/mixed_case/resources/service/user.py b/seed/pydantic/mixed-case/src/seed/mixed_case/resources/service/user.py index f49e8837f5d..ba386445aad 100644 --- a/seed/pydantic/mixed-case/src/seed/mixed_case/resources/service/user.py +++ b/seed/pydantic/mixed-case/src/seed/mixed_case/resources/service/user.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ...core.pydantic_utilities import UniversalBaseModel import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +import typing +from ...core.pydantic_utilities import IS_PYDANTIC_V2 class User(UniversalBaseModel): @@ -25,7 +24,9 @@ class User(UniversalBaseModel): extra_properties: typing.Dict[str, str] = pydantic.Field(alias="EXTRA_PROPERTIES") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/mixed-case/tests/custom/test_client.py b/seed/pydantic/mixed-case/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/pydantic/mixed-case/tests/custom/test_client.py +++ b/seed/pydantic/mixed-case/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/pydantic/multi-line-docs/pyproject.toml b/seed/pydantic/multi-line-docs/pyproject.toml index 397248898a6..f23e9d7b047 100644 --- a/seed/pydantic/multi-line-docs/pyproject.toml +++ b/seed/pydantic/multi-line-docs/pyproject.toml @@ -41,6 +41,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/pydantic/multi-line-docs/src/seed/multi_line_docs/core/datetime_utils.py b/seed/pydantic/multi-line-docs/src/seed/multi_line_docs/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/pydantic/multi-line-docs/src/seed/multi_line_docs/core/datetime_utils.py +++ b/seed/pydantic/multi-line-docs/src/seed/multi_line_docs/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/pydantic/multi-line-docs/src/seed/multi_line_docs/core/pydantic_utilities.py b/seed/pydantic/multi-line-docs/src/seed/multi_line_docs/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/pydantic/multi-line-docs/src/seed/multi_line_docs/core/pydantic_utilities.py +++ b/seed/pydantic/multi-line-docs/src/seed/multi_line_docs/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/pydantic/multi-line-docs/src/seed/multi_line_docs/core/serialization.py b/seed/pydantic/multi-line-docs/src/seed/multi_line_docs/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/pydantic/multi-line-docs/src/seed/multi_line_docs/core/serialization.py +++ b/seed/pydantic/multi-line-docs/src/seed/multi_line_docs/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/pydantic/multi-line-docs/src/seed/multi_line_docs/resources/user/user.py b/seed/pydantic/multi-line-docs/src/seed/multi_line_docs/resources/user/user.py index 8ac271449a0..65432166512 100644 --- a/seed/pydantic/multi-line-docs/src/seed/multi_line_docs/resources/user/user.py +++ b/seed/pydantic/multi-line-docs/src/seed/multi_line_docs/resources/user/user.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ...core.pydantic_utilities import UniversalBaseModel import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +import typing +from ...core.pydantic_utilities import IS_PYDANTIC_V2 class User(UniversalBaseModel): @@ -31,7 +30,9 @@ class User(UniversalBaseModel): """ if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/multi-line-docs/tests/custom/test_client.py b/seed/pydantic/multi-line-docs/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/pydantic/multi-line-docs/tests/custom/test_client.py +++ b/seed/pydantic/multi-line-docs/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/pydantic/multi-url-environment-no-default/pyproject.toml b/seed/pydantic/multi-url-environment-no-default/pyproject.toml index 362479104c8..c4cfc390c72 100644 --- a/seed/pydantic/multi-url-environment-no-default/pyproject.toml +++ b/seed/pydantic/multi-url-environment-no-default/pyproject.toml @@ -40,6 +40,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/pydantic/multi-url-environment-no-default/src/seed/multi_url_environment_no_default/core/datetime_utils.py b/seed/pydantic/multi-url-environment-no-default/src/seed/multi_url_environment_no_default/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/pydantic/multi-url-environment-no-default/src/seed/multi_url_environment_no_default/core/datetime_utils.py +++ b/seed/pydantic/multi-url-environment-no-default/src/seed/multi_url_environment_no_default/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/pydantic/multi-url-environment-no-default/src/seed/multi_url_environment_no_default/core/pydantic_utilities.py b/seed/pydantic/multi-url-environment-no-default/src/seed/multi_url_environment_no_default/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/pydantic/multi-url-environment-no-default/src/seed/multi_url_environment_no_default/core/pydantic_utilities.py +++ b/seed/pydantic/multi-url-environment-no-default/src/seed/multi_url_environment_no_default/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/pydantic/multi-url-environment-no-default/src/seed/multi_url_environment_no_default/core/serialization.py b/seed/pydantic/multi-url-environment-no-default/src/seed/multi_url_environment_no_default/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/pydantic/multi-url-environment-no-default/src/seed/multi_url_environment_no_default/core/serialization.py +++ b/seed/pydantic/multi-url-environment-no-default/src/seed/multi_url_environment_no_default/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/pydantic/multi-url-environment-no-default/tests/custom/test_client.py b/seed/pydantic/multi-url-environment-no-default/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/pydantic/multi-url-environment-no-default/tests/custom/test_client.py +++ b/seed/pydantic/multi-url-environment-no-default/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/pydantic/multi-url-environment/pyproject.toml b/seed/pydantic/multi-url-environment/pyproject.toml index 713f8c5602d..460fa59c64c 100644 --- a/seed/pydantic/multi-url-environment/pyproject.toml +++ b/seed/pydantic/multi-url-environment/pyproject.toml @@ -40,6 +40,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/pydantic/multi-url-environment/src/seed/multi_url_environment/core/datetime_utils.py b/seed/pydantic/multi-url-environment/src/seed/multi_url_environment/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/pydantic/multi-url-environment/src/seed/multi_url_environment/core/datetime_utils.py +++ b/seed/pydantic/multi-url-environment/src/seed/multi_url_environment/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/pydantic/multi-url-environment/src/seed/multi_url_environment/core/pydantic_utilities.py b/seed/pydantic/multi-url-environment/src/seed/multi_url_environment/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/pydantic/multi-url-environment/src/seed/multi_url_environment/core/pydantic_utilities.py +++ b/seed/pydantic/multi-url-environment/src/seed/multi_url_environment/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/pydantic/multi-url-environment/src/seed/multi_url_environment/core/serialization.py b/seed/pydantic/multi-url-environment/src/seed/multi_url_environment/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/pydantic/multi-url-environment/src/seed/multi_url_environment/core/serialization.py +++ b/seed/pydantic/multi-url-environment/src/seed/multi_url_environment/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/pydantic/multi-url-environment/tests/custom/test_client.py b/seed/pydantic/multi-url-environment/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/pydantic/multi-url-environment/tests/custom/test_client.py +++ b/seed/pydantic/multi-url-environment/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/pydantic/no-environment/pyproject.toml b/seed/pydantic/no-environment/pyproject.toml index ef9cf1b7e0e..5dd8e78cb7b 100644 --- a/seed/pydantic/no-environment/pyproject.toml +++ b/seed/pydantic/no-environment/pyproject.toml @@ -40,6 +40,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/pydantic/no-environment/src/seed/no_environment/core/datetime_utils.py b/seed/pydantic/no-environment/src/seed/no_environment/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/pydantic/no-environment/src/seed/no_environment/core/datetime_utils.py +++ b/seed/pydantic/no-environment/src/seed/no_environment/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/pydantic/no-environment/src/seed/no_environment/core/pydantic_utilities.py b/seed/pydantic/no-environment/src/seed/no_environment/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/pydantic/no-environment/src/seed/no_environment/core/pydantic_utilities.py +++ b/seed/pydantic/no-environment/src/seed/no_environment/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/pydantic/no-environment/src/seed/no_environment/core/serialization.py b/seed/pydantic/no-environment/src/seed/no_environment/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/pydantic/no-environment/src/seed/no_environment/core/serialization.py +++ b/seed/pydantic/no-environment/src/seed/no_environment/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/pydantic/no-environment/tests/custom/test_client.py b/seed/pydantic/no-environment/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/pydantic/no-environment/tests/custom/test_client.py +++ b/seed/pydantic/no-environment/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/pydantic/oauth-client-credentials-default/pyproject.toml b/seed/pydantic/oauth-client-credentials-default/pyproject.toml index 44538e7b4aa..80b297cfd58 100644 --- a/seed/pydantic/oauth-client-credentials-default/pyproject.toml +++ b/seed/pydantic/oauth-client-credentials-default/pyproject.toml @@ -41,6 +41,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/pydantic/oauth-client-credentials-default/src/seed/oauth_client_credentials_default/core/datetime_utils.py b/seed/pydantic/oauth-client-credentials-default/src/seed/oauth_client_credentials_default/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/pydantic/oauth-client-credentials-default/src/seed/oauth_client_credentials_default/core/datetime_utils.py +++ b/seed/pydantic/oauth-client-credentials-default/src/seed/oauth_client_credentials_default/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/pydantic/oauth-client-credentials-default/src/seed/oauth_client_credentials_default/core/pydantic_utilities.py b/seed/pydantic/oauth-client-credentials-default/src/seed/oauth_client_credentials_default/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/pydantic/oauth-client-credentials-default/src/seed/oauth_client_credentials_default/core/pydantic_utilities.py +++ b/seed/pydantic/oauth-client-credentials-default/src/seed/oauth_client_credentials_default/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/pydantic/oauth-client-credentials-default/src/seed/oauth_client_credentials_default/core/serialization.py b/seed/pydantic/oauth-client-credentials-default/src/seed/oauth_client_credentials_default/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/pydantic/oauth-client-credentials-default/src/seed/oauth_client_credentials_default/core/serialization.py +++ b/seed/pydantic/oauth-client-credentials-default/src/seed/oauth_client_credentials_default/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/pydantic/oauth-client-credentials-default/src/seed/oauth_client_credentials_default/resources/auth/token_response.py b/seed/pydantic/oauth-client-credentials-default/src/seed/oauth_client_credentials_default/resources/auth/token_response.py index f7de87d10f1..840b85712a0 100644 --- a/seed/pydantic/oauth-client-credentials-default/src/seed/oauth_client_credentials_default/resources/auth/token_response.py +++ b/seed/pydantic/oauth-client-credentials-default/src/seed/oauth_client_credentials_default/resources/auth/token_response.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class TokenResponse(UniversalBaseModel): """ @@ -16,7 +15,9 @@ class TokenResponse(UniversalBaseModel): expires_in: int if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/oauth-client-credentials-default/tests/custom/test_client.py b/seed/pydantic/oauth-client-credentials-default/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/pydantic/oauth-client-credentials-default/tests/custom/test_client.py +++ b/seed/pydantic/oauth-client-credentials-default/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/pydantic/oauth-client-credentials-environment-variables/pyproject.toml b/seed/pydantic/oauth-client-credentials-environment-variables/pyproject.toml index 6965f94480a..ca8ff15f899 100644 --- a/seed/pydantic/oauth-client-credentials-environment-variables/pyproject.toml +++ b/seed/pydantic/oauth-client-credentials-environment-variables/pyproject.toml @@ -41,6 +41,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/pydantic/oauth-client-credentials-environment-variables/src/seed/oauth_client_credentials_environment_variables/core/datetime_utils.py b/seed/pydantic/oauth-client-credentials-environment-variables/src/seed/oauth_client_credentials_environment_variables/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/pydantic/oauth-client-credentials-environment-variables/src/seed/oauth_client_credentials_environment_variables/core/datetime_utils.py +++ b/seed/pydantic/oauth-client-credentials-environment-variables/src/seed/oauth_client_credentials_environment_variables/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/pydantic/oauth-client-credentials-environment-variables/src/seed/oauth_client_credentials_environment_variables/core/pydantic_utilities.py b/seed/pydantic/oauth-client-credentials-environment-variables/src/seed/oauth_client_credentials_environment_variables/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/pydantic/oauth-client-credentials-environment-variables/src/seed/oauth_client_credentials_environment_variables/core/pydantic_utilities.py +++ b/seed/pydantic/oauth-client-credentials-environment-variables/src/seed/oauth_client_credentials_environment_variables/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/pydantic/oauth-client-credentials-environment-variables/src/seed/oauth_client_credentials_environment_variables/core/serialization.py b/seed/pydantic/oauth-client-credentials-environment-variables/src/seed/oauth_client_credentials_environment_variables/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/pydantic/oauth-client-credentials-environment-variables/src/seed/oauth_client_credentials_environment_variables/core/serialization.py +++ b/seed/pydantic/oauth-client-credentials-environment-variables/src/seed/oauth_client_credentials_environment_variables/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/pydantic/oauth-client-credentials-environment-variables/src/seed/oauth_client_credentials_environment_variables/resources/auth/token_response.py b/seed/pydantic/oauth-client-credentials-environment-variables/src/seed/oauth_client_credentials_environment_variables/resources/auth/token_response.py index b262a8d62df..6176e622551 100644 --- a/seed/pydantic/oauth-client-credentials-environment-variables/src/seed/oauth_client_credentials_environment_variables/resources/auth/token_response.py +++ b/seed/pydantic/oauth-client-credentials-environment-variables/src/seed/oauth_client_credentials_environment_variables/resources/auth/token_response.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel import typing - +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class TokenResponse(UniversalBaseModel): """ @@ -17,7 +16,9 @@ class TokenResponse(UniversalBaseModel): refresh_token: typing.Optional[str] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/oauth-client-credentials-environment-variables/tests/custom/test_client.py b/seed/pydantic/oauth-client-credentials-environment-variables/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/pydantic/oauth-client-credentials-environment-variables/tests/custom/test_client.py +++ b/seed/pydantic/oauth-client-credentials-environment-variables/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/pydantic/oauth-client-credentials-nested-root/pyproject.toml b/seed/pydantic/oauth-client-credentials-nested-root/pyproject.toml index 05be769fa05..899a083b645 100644 --- a/seed/pydantic/oauth-client-credentials-nested-root/pyproject.toml +++ b/seed/pydantic/oauth-client-credentials-nested-root/pyproject.toml @@ -41,6 +41,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/pydantic/oauth-client-credentials-nested-root/src/seed/oauth_client_credentials/core/datetime_utils.py b/seed/pydantic/oauth-client-credentials-nested-root/src/seed/oauth_client_credentials/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/pydantic/oauth-client-credentials-nested-root/src/seed/oauth_client_credentials/core/datetime_utils.py +++ b/seed/pydantic/oauth-client-credentials-nested-root/src/seed/oauth_client_credentials/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/pydantic/oauth-client-credentials-nested-root/src/seed/oauth_client_credentials/core/pydantic_utilities.py b/seed/pydantic/oauth-client-credentials-nested-root/src/seed/oauth_client_credentials/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/pydantic/oauth-client-credentials-nested-root/src/seed/oauth_client_credentials/core/pydantic_utilities.py +++ b/seed/pydantic/oauth-client-credentials-nested-root/src/seed/oauth_client_credentials/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/pydantic/oauth-client-credentials-nested-root/src/seed/oauth_client_credentials/core/serialization.py b/seed/pydantic/oauth-client-credentials-nested-root/src/seed/oauth_client_credentials/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/pydantic/oauth-client-credentials-nested-root/src/seed/oauth_client_credentials/core/serialization.py +++ b/seed/pydantic/oauth-client-credentials-nested-root/src/seed/oauth_client_credentials/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/pydantic/oauth-client-credentials-nested-root/src/seed/oauth_client_credentials/resources/auth/token_response.py b/seed/pydantic/oauth-client-credentials-nested-root/src/seed/oauth_client_credentials/resources/auth/token_response.py index b262a8d62df..6176e622551 100644 --- a/seed/pydantic/oauth-client-credentials-nested-root/src/seed/oauth_client_credentials/resources/auth/token_response.py +++ b/seed/pydantic/oauth-client-credentials-nested-root/src/seed/oauth_client_credentials/resources/auth/token_response.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel import typing - +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class TokenResponse(UniversalBaseModel): """ @@ -17,7 +16,9 @@ class TokenResponse(UniversalBaseModel): refresh_token: typing.Optional[str] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/oauth-client-credentials-nested-root/tests/custom/test_client.py b/seed/pydantic/oauth-client-credentials-nested-root/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/pydantic/oauth-client-credentials-nested-root/tests/custom/test_client.py +++ b/seed/pydantic/oauth-client-credentials-nested-root/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/pydantic/oauth-client-credentials/pyproject.toml b/seed/pydantic/oauth-client-credentials/pyproject.toml index f3c7d85a627..b854322c9f8 100644 --- a/seed/pydantic/oauth-client-credentials/pyproject.toml +++ b/seed/pydantic/oauth-client-credentials/pyproject.toml @@ -41,6 +41,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/pydantic/oauth-client-credentials/src/seed/oauth_client_credentials/core/datetime_utils.py b/seed/pydantic/oauth-client-credentials/src/seed/oauth_client_credentials/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/pydantic/oauth-client-credentials/src/seed/oauth_client_credentials/core/datetime_utils.py +++ b/seed/pydantic/oauth-client-credentials/src/seed/oauth_client_credentials/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/pydantic/oauth-client-credentials/src/seed/oauth_client_credentials/core/pydantic_utilities.py b/seed/pydantic/oauth-client-credentials/src/seed/oauth_client_credentials/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/pydantic/oauth-client-credentials/src/seed/oauth_client_credentials/core/pydantic_utilities.py +++ b/seed/pydantic/oauth-client-credentials/src/seed/oauth_client_credentials/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/pydantic/oauth-client-credentials/src/seed/oauth_client_credentials/core/serialization.py b/seed/pydantic/oauth-client-credentials/src/seed/oauth_client_credentials/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/pydantic/oauth-client-credentials/src/seed/oauth_client_credentials/core/serialization.py +++ b/seed/pydantic/oauth-client-credentials/src/seed/oauth_client_credentials/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/pydantic/oauth-client-credentials/src/seed/oauth_client_credentials/resources/auth/token_response.py b/seed/pydantic/oauth-client-credentials/src/seed/oauth_client_credentials/resources/auth/token_response.py index b262a8d62df..6176e622551 100644 --- a/seed/pydantic/oauth-client-credentials/src/seed/oauth_client_credentials/resources/auth/token_response.py +++ b/seed/pydantic/oauth-client-credentials/src/seed/oauth_client_credentials/resources/auth/token_response.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel import typing - +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class TokenResponse(UniversalBaseModel): """ @@ -17,7 +16,9 @@ class TokenResponse(UniversalBaseModel): refresh_token: typing.Optional[str] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/oauth-client-credentials/tests/custom/test_client.py b/seed/pydantic/oauth-client-credentials/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/pydantic/oauth-client-credentials/tests/custom/test_client.py +++ b/seed/pydantic/oauth-client-credentials/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/pydantic/object/pyproject.toml b/seed/pydantic/object/pyproject.toml index aa879b7e435..3e7d11f68c3 100644 --- a/seed/pydantic/object/pyproject.toml +++ b/seed/pydantic/object/pyproject.toml @@ -41,6 +41,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/pydantic/object/src/seed/object/core/datetime_utils.py b/seed/pydantic/object/src/seed/object/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/pydantic/object/src/seed/object/core/datetime_utils.py +++ b/seed/pydantic/object/src/seed/object/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/pydantic/object/src/seed/object/core/pydantic_utilities.py b/seed/pydantic/object/src/seed/object/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/pydantic/object/src/seed/object/core/pydantic_utilities.py +++ b/seed/pydantic/object/src/seed/object/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/pydantic/object/src/seed/object/core/serialization.py b/seed/pydantic/object/src/seed/object/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/pydantic/object/src/seed/object/core/serialization.py +++ b/seed/pydantic/object/src/seed/object/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/pydantic/object/src/seed/object/name.py b/seed/pydantic/object/src/seed/object/name.py index 8fcaecb555b..ff5f2ed8223 100644 --- a/seed/pydantic/object/src/seed/object/name.py +++ b/seed/pydantic/object/src/seed/object/name.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from .core.pydantic_utilities import UniversalBaseModel +from .core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from .core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class Name(UniversalBaseModel): """ @@ -23,7 +22,9 @@ class Name(UniversalBaseModel): value: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/object/src/seed/object/type.py b/seed/pydantic/object/src/seed/object/type.py index 6f8dfcd0c1a..66ea4c597ac 100644 --- a/seed/pydantic/object/src/seed/object/type.py +++ b/seed/pydantic/object/src/seed/object/type.py @@ -1,13 +1,12 @@ # This file was auto-generated by Fern from our API Definition. +from .core.pydantic_utilities import UniversalBaseModel import datetime as dt -import typing import uuid - -import pydantic - -from .core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +import typing from .name import Name +from .core.pydantic_utilities import IS_PYDANTIC_V2 +import pydantic class Type(UniversalBaseModel): @@ -88,7 +87,9 @@ class Type(UniversalBaseModel): twentythree: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/object/tests/custom/test_client.py b/seed/pydantic/object/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/pydantic/object/tests/custom/test_client.py +++ b/seed/pydantic/object/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/pydantic/objects-with-imports/pyproject.toml b/seed/pydantic/objects-with-imports/pyproject.toml index c0e66184250..fee70a1a19a 100644 --- a/seed/pydantic/objects-with-imports/pyproject.toml +++ b/seed/pydantic/objects-with-imports/pyproject.toml @@ -41,6 +41,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/pydantic/objects-with-imports/src/seed/objects_with_imports/core/datetime_utils.py b/seed/pydantic/objects-with-imports/src/seed/objects_with_imports/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/pydantic/objects-with-imports/src/seed/objects_with_imports/core/datetime_utils.py +++ b/seed/pydantic/objects-with-imports/src/seed/objects_with_imports/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/pydantic/objects-with-imports/src/seed/objects_with_imports/core/pydantic_utilities.py b/seed/pydantic/objects-with-imports/src/seed/objects_with_imports/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/pydantic/objects-with-imports/src/seed/objects_with_imports/core/pydantic_utilities.py +++ b/seed/pydantic/objects-with-imports/src/seed/objects_with_imports/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/pydantic/objects-with-imports/src/seed/objects_with_imports/core/serialization.py b/seed/pydantic/objects-with-imports/src/seed/objects_with_imports/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/pydantic/objects-with-imports/src/seed/objects_with_imports/core/serialization.py +++ b/seed/pydantic/objects-with-imports/src/seed/objects_with_imports/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/pydantic/objects-with-imports/src/seed/objects_with_imports/node.py b/seed/pydantic/objects-with-imports/src/seed/objects_with_imports/node.py index bdd349bb252..ff19e964e0e 100644 --- a/seed/pydantic/objects-with-imports/src/seed/objects_with_imports/node.py +++ b/seed/pydantic/objects-with-imports/src/seed/objects_with_imports/node.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from .core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from .core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .resources.commons.resources.metadata.metadata import Metadata +from .core.pydantic_utilities import IS_PYDANTIC_V2 +import pydantic class Node(UniversalBaseModel): @@ -30,7 +29,9 @@ class Node(UniversalBaseModel): metadata: typing.Optional[Metadata] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/objects-with-imports/src/seed/objects_with_imports/resources/commons/resources/metadata/metadata.py b/seed/pydantic/objects-with-imports/src/seed/objects_with_imports/resources/commons/resources/metadata/metadata.py index fc38675be8f..cd5bf7521de 100644 --- a/seed/pydantic/objects-with-imports/src/seed/objects_with_imports/resources/commons/resources/metadata/metadata.py +++ b/seed/pydantic/objects-with-imports/src/seed/objects_with_imports/resources/commons/resources/metadata/metadata.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from .....core.pydantic_utilities import UniversalBaseModel import typing - +from .....core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from .....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class Metadata(UniversalBaseModel): """ @@ -23,7 +22,9 @@ class Metadata(UniversalBaseModel): data: typing.Optional[typing.Dict[str, str]] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/objects-with-imports/src/seed/objects_with_imports/resources/file/file.py b/seed/pydantic/objects-with-imports/src/seed/objects_with_imports/resources/file/file.py index cce647a9ea1..aaa3743b9d4 100644 --- a/seed/pydantic/objects-with-imports/src/seed/objects_with_imports/resources/file/file.py +++ b/seed/pydantic/objects-with-imports/src/seed/objects_with_imports/resources/file/file.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from .file_info import FileInfo +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .file_info import FileInfo - class File(UniversalBaseModel): """ @@ -26,7 +25,9 @@ class File(UniversalBaseModel): info: FileInfo if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/objects-with-imports/src/seed/objects_with_imports/resources/file/resources/directory/directory.py b/seed/pydantic/objects-with-imports/src/seed/objects_with_imports/resources/file/resources/directory/directory.py index fa516bcede7..4c6819a8af3 100644 --- a/seed/pydantic/objects-with-imports/src/seed/objects_with_imports/resources/file/resources/directory/directory.py +++ b/seed/pydantic/objects-with-imports/src/seed/objects_with_imports/resources/file/resources/directory/directory.py @@ -1,13 +1,12 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from .....core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from .....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel, update_forward_refs from ...file import File +from .....core.pydantic_utilities import IS_PYDANTIC_V2 +import pydantic +from .....core.pydantic_utilities import update_forward_refs class Directory(UniversalBaseModel): @@ -46,7 +45,9 @@ class Directory(UniversalBaseModel): directories: typing.Optional[typing.List[Directory]] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/objects-with-imports/src/seed/objects_with_imports/tree.py b/seed/pydantic/objects-with-imports/src/seed/objects_with_imports/tree.py index 50902bb3ef3..2f1bae8eaea 100644 --- a/seed/pydantic/objects-with-imports/src/seed/objects_with_imports/tree.py +++ b/seed/pydantic/objects-with-imports/src/seed/objects_with_imports/tree.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from .core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from .core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .node import Node +from .core.pydantic_utilities import IS_PYDANTIC_V2 +import pydantic class Tree(UniversalBaseModel): @@ -40,7 +39,9 @@ class Tree(UniversalBaseModel): nodes: typing.Optional[typing.List[Node]] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/objects-with-imports/tests/custom/test_client.py b/seed/pydantic/objects-with-imports/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/pydantic/objects-with-imports/tests/custom/test_client.py +++ b/seed/pydantic/objects-with-imports/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/pydantic/optional/pyproject.toml b/seed/pydantic/optional/pyproject.toml index 3068c52115f..0a507f7edd5 100644 --- a/seed/pydantic/optional/pyproject.toml +++ b/seed/pydantic/optional/pyproject.toml @@ -40,6 +40,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/pydantic/optional/src/seed/objects_with_imports/core/datetime_utils.py b/seed/pydantic/optional/src/seed/objects_with_imports/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/pydantic/optional/src/seed/objects_with_imports/core/datetime_utils.py +++ b/seed/pydantic/optional/src/seed/objects_with_imports/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/pydantic/optional/src/seed/objects_with_imports/core/pydantic_utilities.py b/seed/pydantic/optional/src/seed/objects_with_imports/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/pydantic/optional/src/seed/objects_with_imports/core/pydantic_utilities.py +++ b/seed/pydantic/optional/src/seed/objects_with_imports/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/pydantic/optional/src/seed/objects_with_imports/core/serialization.py b/seed/pydantic/optional/src/seed/objects_with_imports/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/pydantic/optional/src/seed/objects_with_imports/core/serialization.py +++ b/seed/pydantic/optional/src/seed/objects_with_imports/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/pydantic/optional/tests/custom/test_client.py b/seed/pydantic/optional/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/pydantic/optional/tests/custom/test_client.py +++ b/seed/pydantic/optional/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/pydantic/package-yml/pyproject.toml b/seed/pydantic/package-yml/pyproject.toml index fc55c0b8777..08d45f8fe9c 100644 --- a/seed/pydantic/package-yml/pyproject.toml +++ b/seed/pydantic/package-yml/pyproject.toml @@ -41,6 +41,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/pydantic/package-yml/src/seed/package_yml/core/datetime_utils.py b/seed/pydantic/package-yml/src/seed/package_yml/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/pydantic/package-yml/src/seed/package_yml/core/datetime_utils.py +++ b/seed/pydantic/package-yml/src/seed/package_yml/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/pydantic/package-yml/src/seed/package_yml/core/pydantic_utilities.py b/seed/pydantic/package-yml/src/seed/package_yml/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/pydantic/package-yml/src/seed/package_yml/core/pydantic_utilities.py +++ b/seed/pydantic/package-yml/src/seed/package_yml/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/pydantic/package-yml/src/seed/package_yml/core/serialization.py b/seed/pydantic/package-yml/src/seed/package_yml/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/pydantic/package-yml/src/seed/package_yml/core/serialization.py +++ b/seed/pydantic/package-yml/src/seed/package_yml/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/pydantic/package-yml/src/seed/package_yml/echo_request.py b/seed/pydantic/package-yml/src/seed/package_yml/echo_request.py index 230dd5029f6..26f5ca7ff1b 100644 --- a/seed/pydantic/package-yml/src/seed/package_yml/echo_request.py +++ b/seed/pydantic/package-yml/src/seed/package_yml/echo_request.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from .core.pydantic_utilities import UniversalBaseModel +from .core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from .core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class EchoRequest(UniversalBaseModel): name: str size: int if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/package-yml/tests/custom/test_client.py b/seed/pydantic/package-yml/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/pydantic/package-yml/tests/custom/test_client.py +++ b/seed/pydantic/package-yml/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/pydantic/pagination/pyproject.toml b/seed/pydantic/pagination/pyproject.toml index 19b9c1030c8..cad104683a1 100644 --- a/seed/pydantic/pagination/pyproject.toml +++ b/seed/pydantic/pagination/pyproject.toml @@ -41,6 +41,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/pydantic/pagination/src/seed/pagination/core/datetime_utils.py b/seed/pydantic/pagination/src/seed/pagination/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/pydantic/pagination/src/seed/pagination/core/datetime_utils.py +++ b/seed/pydantic/pagination/src/seed/pagination/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/pydantic/pagination/src/seed/pagination/core/pydantic_utilities.py b/seed/pydantic/pagination/src/seed/pagination/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/pydantic/pagination/src/seed/pagination/core/pydantic_utilities.py +++ b/seed/pydantic/pagination/src/seed/pagination/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/pydantic/pagination/src/seed/pagination/core/serialization.py b/seed/pydantic/pagination/src/seed/pagination/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/pydantic/pagination/src/seed/pagination/core/serialization.py +++ b/seed/pydantic/pagination/src/seed/pagination/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/pydantic/pagination/src/seed/pagination/resources/users/list_users_extended_response.py b/seed/pydantic/pagination/src/seed/pagination/resources/users/list_users_extended_response.py index c426c7bf5d2..a2879636095 100644 --- a/seed/pydantic/pagination/src/seed/pagination/resources/users/list_users_extended_response.py +++ b/seed/pydantic/pagination/src/seed/pagination/resources/users/list_users_extended_response.py @@ -1,11 +1,9 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from .user_page import UserPage import pydantic - from ...core.pydantic_utilities import IS_PYDANTIC_V2 -from .user_page import UserPage +import typing class ListUsersExtendedResponse(UserPage): @@ -15,7 +13,9 @@ class ListUsersExtendedResponse(UserPage): """ if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/pagination/src/seed/pagination/resources/users/list_users_pagination_response.py b/seed/pydantic/pagination/src/seed/pagination/resources/users/list_users_pagination_response.py index 55122b4f919..8b9ab4fc238 100644 --- a/seed/pydantic/pagination/src/seed/pagination/resources/users/list_users_pagination_response.py +++ b/seed/pydantic/pagination/src/seed/pagination/resources/users/list_users_pagination_response.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .page import Page +import pydantic from .user import User +from ...core.pydantic_utilities import IS_PYDANTIC_V2 class ListUsersPaginationResponse(UniversalBaseModel): @@ -19,7 +18,9 @@ class ListUsersPaginationResponse(UniversalBaseModel): data: typing.List[User] if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/pagination/src/seed/pagination/resources/users/next_page.py b/seed/pydantic/pagination/src/seed/pagination/resources/users/next_page.py index 4c82aa99a1f..285e5e44e73 100644 --- a/seed/pydantic/pagination/src/seed/pagination/resources/users/next_page.py +++ b/seed/pydantic/pagination/src/seed/pagination/resources/users/next_page.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class NextPage(UniversalBaseModel): page: int starting_after: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/pagination/src/seed/pagination/resources/users/page.py b/seed/pydantic/pagination/src/seed/pagination/resources/users/page.py index 0baf1fe1b24..39d697bf7cb 100644 --- a/seed/pydantic/pagination/src/seed/pagination/resources/users/page.py +++ b/seed/pydantic/pagination/src/seed/pagination/resources/users/page.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ...core.pydantic_utilities import UniversalBaseModel import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +import typing from .next_page import NextPage +from ...core.pydantic_utilities import IS_PYDANTIC_V2 class Page(UniversalBaseModel): @@ -19,7 +18,9 @@ class Page(UniversalBaseModel): total_page: int if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/pagination/src/seed/pagination/resources/users/user.py b/seed/pydantic/pagination/src/seed/pagination/resources/users/user.py index 5e579275883..565aaf97725 100644 --- a/seed/pydantic/pagination/src/seed/pagination/resources/users/user.py +++ b/seed/pydantic/pagination/src/seed/pagination/resources/users/user.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class User(UniversalBaseModel): name: str id: int if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/pagination/src/seed/pagination/resources/users/user_list_container.py b/seed/pydantic/pagination/src/seed/pagination/resources/users/user_list_container.py index f29b66bd426..234d1fe40ee 100644 --- a/seed/pydantic/pagination/src/seed/pagination/resources/users/user_list_container.py +++ b/seed/pydantic/pagination/src/seed/pagination/resources/users/user_list_container.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .user import User +from ...core.pydantic_utilities import IS_PYDANTIC_V2 +import pydantic class UserListContainer(UniversalBaseModel): users: typing.List[User] if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/pagination/src/seed/pagination/resources/users/user_page.py b/seed/pydantic/pagination/src/seed/pagination/resources/users/user_page.py index 74cf8b74ecf..9a8010d2e2c 100644 --- a/seed/pydantic/pagination/src/seed/pagination/resources/users/user_page.py +++ b/seed/pydantic/pagination/src/seed/pagination/resources/users/user_page.py @@ -1,20 +1,21 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from .user_list_container import UserListContainer import typing import uuid - +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .user_list_container import UserListContainer - class UserPage(UniversalBaseModel): data: UserListContainer next: typing.Optional[uuid.UUID] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/pagination/src/seed/pagination/resources/users/username_container.py b/seed/pydantic/pagination/src/seed/pagination/resources/users/username_container.py index 36eeb79b3fa..0b667cf876b 100644 --- a/seed/pydantic/pagination/src/seed/pagination/resources/users/username_container.py +++ b/seed/pydantic/pagination/src/seed/pagination/resources/users/username_container.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel import typing - +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class UsernameContainer(UniversalBaseModel): results: typing.List[str] if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/pagination/src/seed/pagination/resources/users/with_cursor.py b/seed/pydantic/pagination/src/seed/pagination/resources/users/with_cursor.py index 1ae520652ab..df9ece4149a 100644 --- a/seed/pydantic/pagination/src/seed/pagination/resources/users/with_cursor.py +++ b/seed/pydantic/pagination/src/seed/pagination/resources/users/with_cursor.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel import typing - +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class WithCursor(UniversalBaseModel): cursor: typing.Optional[str] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/pagination/src/seed/pagination/resources/users/with_page.py b/seed/pydantic/pagination/src/seed/pagination/resources/users/with_page.py index b9647492000..a607b1c2641 100644 --- a/seed/pydantic/pagination/src/seed/pagination/resources/users/with_page.py +++ b/seed/pydantic/pagination/src/seed/pagination/resources/users/with_page.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel import typing - +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class WithPage(UniversalBaseModel): page: typing.Optional[int] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/pagination/src/seed/pagination/username_cursor.py b/seed/pydantic/pagination/src/seed/pagination/username_cursor.py index 71aeaca6e9c..ad97b8c4d07 100644 --- a/seed/pydantic/pagination/src/seed/pagination/username_cursor.py +++ b/seed/pydantic/pagination/src/seed/pagination/username_cursor.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from .core.pydantic_utilities import UniversalBaseModel +from .username_page import UsernamePage +from .core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from .core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .username_page import UsernamePage - class UsernameCursor(UniversalBaseModel): cursor: UsernamePage if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/pagination/src/seed/pagination/username_page.py b/seed/pydantic/pagination/src/seed/pagination/username_page.py index d5bb4867428..e6dfa354e6e 100644 --- a/seed/pydantic/pagination/src/seed/pagination/username_page.py +++ b/seed/pydantic/pagination/src/seed/pagination/username_page.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from .core.pydantic_utilities import UniversalBaseModel import typing - +from .core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from .core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class UsernamePage(UniversalBaseModel): after: typing.Optional[str] = None data: typing.List[str] if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/pagination/tests/custom/test_client.py b/seed/pydantic/pagination/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/pydantic/pagination/tests/custom/test_client.py +++ b/seed/pydantic/pagination/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/pydantic/plain-text/pyproject.toml b/seed/pydantic/plain-text/pyproject.toml index d6ee938ba6e..52bfd755e9a 100644 --- a/seed/pydantic/plain-text/pyproject.toml +++ b/seed/pydantic/plain-text/pyproject.toml @@ -40,6 +40,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/pydantic/plain-text/src/seed/plain_text/core/datetime_utils.py b/seed/pydantic/plain-text/src/seed/plain_text/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/pydantic/plain-text/src/seed/plain_text/core/datetime_utils.py +++ b/seed/pydantic/plain-text/src/seed/plain_text/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/pydantic/plain-text/src/seed/plain_text/core/pydantic_utilities.py b/seed/pydantic/plain-text/src/seed/plain_text/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/pydantic/plain-text/src/seed/plain_text/core/pydantic_utilities.py +++ b/seed/pydantic/plain-text/src/seed/plain_text/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/pydantic/plain-text/src/seed/plain_text/core/serialization.py b/seed/pydantic/plain-text/src/seed/plain_text/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/pydantic/plain-text/src/seed/plain_text/core/serialization.py +++ b/seed/pydantic/plain-text/src/seed/plain_text/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/pydantic/plain-text/tests/custom/test_client.py b/seed/pydantic/plain-text/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/pydantic/plain-text/tests/custom/test_client.py +++ b/seed/pydantic/plain-text/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/pydantic/query-parameters/pyproject.toml b/seed/pydantic/query-parameters/pyproject.toml index 31de2965c3f..a54182bd442 100644 --- a/seed/pydantic/query-parameters/pyproject.toml +++ b/seed/pydantic/query-parameters/pyproject.toml @@ -41,6 +41,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/pydantic/query-parameters/src/seed/query_parameters/core/datetime_utils.py b/seed/pydantic/query-parameters/src/seed/query_parameters/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/pydantic/query-parameters/src/seed/query_parameters/core/datetime_utils.py +++ b/seed/pydantic/query-parameters/src/seed/query_parameters/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/pydantic/query-parameters/src/seed/query_parameters/core/pydantic_utilities.py b/seed/pydantic/query-parameters/src/seed/query_parameters/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/pydantic/query-parameters/src/seed/query_parameters/core/pydantic_utilities.py +++ b/seed/pydantic/query-parameters/src/seed/query_parameters/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/pydantic/query-parameters/src/seed/query_parameters/core/serialization.py b/seed/pydantic/query-parameters/src/seed/query_parameters/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/pydantic/query-parameters/src/seed/query_parameters/core/serialization.py +++ b/seed/pydantic/query-parameters/src/seed/query_parameters/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/pydantic/query-parameters/src/seed/query_parameters/resources/user/nested_user.py b/seed/pydantic/query-parameters/src/seed/query_parameters/resources/user/nested_user.py index 8713ae85e4a..7b93f587636 100644 --- a/seed/pydantic/query-parameters/src/seed/query_parameters/resources/user/nested_user.py +++ b/seed/pydantic/query-parameters/src/seed/query_parameters/resources/user/nested_user.py @@ -1,19 +1,20 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from .user import User +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .user import User - class NestedUser(UniversalBaseModel): name: str user: User if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/query-parameters/src/seed/query_parameters/resources/user/user.py b/seed/pydantic/query-parameters/src/seed/query_parameters/resources/user/user.py index 778a8445cef..949b16db7d6 100644 --- a/seed/pydantic/query-parameters/src/seed/query_parameters/resources/user/user.py +++ b/seed/pydantic/query-parameters/src/seed/query_parameters/resources/user/user.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel import typing - +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class User(UniversalBaseModel): name: str tags: typing.List[str] if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/query-parameters/tests/custom/test_client.py b/seed/pydantic/query-parameters/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/pydantic/query-parameters/tests/custom/test_client.py +++ b/seed/pydantic/query-parameters/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/pydantic/reserved-keywords/pyproject.toml b/seed/pydantic/reserved-keywords/pyproject.toml index ba4f013c2e4..2b14fec1e76 100644 --- a/seed/pydantic/reserved-keywords/pyproject.toml +++ b/seed/pydantic/reserved-keywords/pyproject.toml @@ -41,6 +41,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/pydantic/reserved-keywords/src/seed/nursery_api/core/datetime_utils.py b/seed/pydantic/reserved-keywords/src/seed/nursery_api/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/pydantic/reserved-keywords/src/seed/nursery_api/core/datetime_utils.py +++ b/seed/pydantic/reserved-keywords/src/seed/nursery_api/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/pydantic/reserved-keywords/src/seed/nursery_api/core/pydantic_utilities.py b/seed/pydantic/reserved-keywords/src/seed/nursery_api/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/pydantic/reserved-keywords/src/seed/nursery_api/core/pydantic_utilities.py +++ b/seed/pydantic/reserved-keywords/src/seed/nursery_api/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/pydantic/reserved-keywords/src/seed/nursery_api/core/serialization.py b/seed/pydantic/reserved-keywords/src/seed/nursery_api/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/pydantic/reserved-keywords/src/seed/nursery_api/core/serialization.py +++ b/seed/pydantic/reserved-keywords/src/seed/nursery_api/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/pydantic/reserved-keywords/src/seed/nursery_api/resources/package/package.py b/seed/pydantic/reserved-keywords/src/seed/nursery_api/resources/package/package.py index bc7a472fa2d..ce9cb67f97f 100644 --- a/seed/pydantic/reserved-keywords/src/seed/nursery_api/resources/package/package.py +++ b/seed/pydantic/reserved-keywords/src/seed/nursery_api/resources/package/package.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class Package(UniversalBaseModel): name: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/reserved-keywords/src/seed/nursery_api/resources/package/record.py b/seed/pydantic/reserved-keywords/src/seed/nursery_api/resources/package/record.py index 1d70e9723e4..3eed67a629b 100644 --- a/seed/pydantic/reserved-keywords/src/seed/nursery_api/resources/package/record.py +++ b/seed/pydantic/reserved-keywords/src/seed/nursery_api/resources/package/record.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel import typing - import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 class Record(UniversalBaseModel): @@ -12,7 +11,9 @@ class Record(UniversalBaseModel): f_3_d: int = pydantic.Field(alias="3d") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/reserved-keywords/tests/custom/test_client.py b/seed/pydantic/reserved-keywords/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/pydantic/reserved-keywords/tests/custom/test_client.py +++ b/seed/pydantic/reserved-keywords/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/pydantic/response-property/pyproject.toml b/seed/pydantic/response-property/pyproject.toml index 25564e10313..6a8490bd071 100644 --- a/seed/pydantic/response-property/pyproject.toml +++ b/seed/pydantic/response-property/pyproject.toml @@ -41,6 +41,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/pydantic/response-property/src/seed/response_property/core/datetime_utils.py b/seed/pydantic/response-property/src/seed/response_property/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/pydantic/response-property/src/seed/response_property/core/datetime_utils.py +++ b/seed/pydantic/response-property/src/seed/response_property/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/pydantic/response-property/src/seed/response_property/core/pydantic_utilities.py b/seed/pydantic/response-property/src/seed/response_property/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/pydantic/response-property/src/seed/response_property/core/pydantic_utilities.py +++ b/seed/pydantic/response-property/src/seed/response_property/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/pydantic/response-property/src/seed/response_property/core/serialization.py b/seed/pydantic/response-property/src/seed/response_property/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/pydantic/response-property/src/seed/response_property/core/serialization.py +++ b/seed/pydantic/response-property/src/seed/response_property/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/pydantic/response-property/src/seed/response_property/optional_string_response.py b/seed/pydantic/response-property/src/seed/response_property/optional_string_response.py index 587d8cb4304..ae82973f9b2 100644 --- a/seed/pydantic/response-property/src/seed/response_property/optional_string_response.py +++ b/seed/pydantic/response-property/src/seed/response_property/optional_string_response.py @@ -1,7 +1,6 @@ # This file was auto-generated by Fern from our API Definition. import typing - from .string_response import StringResponse OptionalStringResponse = typing.Optional[StringResponse] diff --git a/seed/pydantic/response-property/src/seed/response_property/resources/service/movie.py b/seed/pydantic/response-property/src/seed/response_property/resources/service/movie.py index f19c611b1b7..7aec46e2e23 100644 --- a/seed/pydantic/response-property/src/seed/response_property/resources/service/movie.py +++ b/seed/pydantic/response-property/src/seed/response_property/resources/service/movie.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class Movie(UniversalBaseModel): id: str name: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/response-property/src/seed/response_property/resources/service/optional_with_docs.py b/seed/pydantic/response-property/src/seed/response_property/resources/service/optional_with_docs.py index 66a04dd87ae..1c33464f33b 100644 --- a/seed/pydantic/response-property/src/seed/response_property/resources/service/optional_with_docs.py +++ b/seed/pydantic/response-property/src/seed/response_property/resources/service/optional_with_docs.py @@ -1,7 +1,6 @@ # This file was auto-generated by Fern from our API Definition. import typing - from .with_docs import WithDocs OptionalWithDocs = typing.Optional[WithDocs] diff --git a/seed/pydantic/response-property/src/seed/response_property/resources/service/response.py b/seed/pydantic/response-property/src/seed/response_property/resources/service/response.py index c6dc8088bd9..d6079fcf585 100644 --- a/seed/pydantic/response-property/src/seed/response_property/resources/service/response.py +++ b/seed/pydantic/response-property/src/seed/response_property/resources/service/response.py @@ -1,20 +1,20 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2 from ...with_metadata import WithMetadata -from .movie import Movie from .with_docs import WithDocs +from .movie import Movie +from ...core.pydantic_utilities import IS_PYDANTIC_V2 +import typing +import pydantic class Response(WithMetadata, WithDocs): data: Movie if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/response-property/src/seed/response_property/resources/service/with_docs.py b/seed/pydantic/response-property/src/seed/response_property/resources/service/with_docs.py index b114c70ca91..ee4a7bd0c5b 100644 --- a/seed/pydantic/response-property/src/seed/response_property/resources/service/with_docs.py +++ b/seed/pydantic/response-property/src/seed/response_property/resources/service/with_docs.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class WithDocs(UniversalBaseModel): docs: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/response-property/src/seed/response_property/string_response.py b/seed/pydantic/response-property/src/seed/response_property/string_response.py index e55bfca68f6..146e32aeb5f 100644 --- a/seed/pydantic/response-property/src/seed/response_property/string_response.py +++ b/seed/pydantic/response-property/src/seed/response_property/string_response.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from .core.pydantic_utilities import UniversalBaseModel +from .core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from .core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class StringResponse(UniversalBaseModel): data: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/response-property/src/seed/response_property/with_metadata.py b/seed/pydantic/response-property/src/seed/response_property/with_metadata.py index 1c5cbc113c8..6c8f05e4936 100644 --- a/seed/pydantic/response-property/src/seed/response_property/with_metadata.py +++ b/seed/pydantic/response-property/src/seed/response_property/with_metadata.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from .core.pydantic_utilities import UniversalBaseModel import typing - +from .core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from .core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class WithMetadata(UniversalBaseModel): metadata: typing.Dict[str, str] if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/response-property/tests/custom/test_client.py b/seed/pydantic/response-property/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/pydantic/response-property/tests/custom/test_client.py +++ b/seed/pydantic/response-property/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/pydantic/root/src/seed/root/core/abstract_fern_service.py b/seed/pydantic/root/src/seed/root/core/abstract_fern_service.py index da7c8dc49c4..9966b4876da 100644 --- a/seed/pydantic/root/src/seed/root/core/abstract_fern_service.py +++ b/seed/pydantic/root/src/seed/root/core/abstract_fern_service.py @@ -7,5 +7,4 @@ class AbstractFernService(abc.ABC): @classmethod - def _init_fern(cls, router: fastapi.APIRouter) -> None: - ... + def _init_fern(cls, router: fastapi.APIRouter) -> None: ... diff --git a/seed/pydantic/root/src/seed/root/core/datetime_utils.py b/seed/pydantic/root/src/seed/root/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/pydantic/root/src/seed/root/core/datetime_utils.py +++ b/seed/pydantic/root/src/seed/root/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/pydantic/root/src/seed/root/core/exceptions/__init__.py b/seed/pydantic/root/src/seed/root/core/exceptions/__init__.py index 297d6e06f5f..dae4b8980c1 100644 --- a/seed/pydantic/root/src/seed/root/core/exceptions/__init__.py +++ b/seed/pydantic/root/src/seed/root/core/exceptions/__init__.py @@ -1,7 +1,11 @@ # This file was auto-generated by Fern from our API Definition. from .fern_http_exception import FernHTTPException -from .handlers import default_exception_handler, fern_http_exception_handler, http_exception_handler +from .handlers import ( + default_exception_handler, + fern_http_exception_handler, + http_exception_handler, +) from .unauthorized import UnauthorizedException __all__ = [ diff --git a/seed/pydantic/root/src/seed/root/core/exceptions/fern_http_exception.py b/seed/pydantic/root/src/seed/root/core/exceptions/fern_http_exception.py index bdf03862487..a5925c21510 100644 --- a/seed/pydantic/root/src/seed/root/core/exceptions/fern_http_exception.py +++ b/seed/pydantic/root/src/seed/root/core/exceptions/fern_http_exception.py @@ -8,7 +8,10 @@ class FernHTTPException(abc.ABC, fastapi.HTTPException): def __init__( - self, status_code: int, name: typing.Optional[str] = None, content: typing.Optional[typing.Any] = None + self, + status_code: int, + name: typing.Optional[str] = None, + content: typing.Optional[typing.Any] = None, ): super().__init__(status_code=status_code) self.name = name @@ -17,4 +20,6 @@ def __init__( def to_json_response(self) -> fastapi.responses.JSONResponse: content = fastapi.encoders.jsonable_encoder(self.content, exclude_none=True) - return fastapi.responses.JSONResponse(content=content, status_code=self.status_code) + return fastapi.responses.JSONResponse( + content=content, status_code=self.status_code + ) diff --git a/seed/pydantic/root/src/seed/root/core/exceptions/handlers.py b/seed/pydantic/root/src/seed/root/core/exceptions/handlers.py index fe5ac5419c7..6e7a82773f6 100644 --- a/seed/pydantic/root/src/seed/root/core/exceptions/handlers.py +++ b/seed/pydantic/root/src/seed/root/core/exceptions/handlers.py @@ -12,21 +12,33 @@ def fern_http_exception_handler( request: fastapi.requests.Request, exc: FernHTTPException, skip_log: bool = False ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) return exc.to_json_response() def http_exception_handler( - request: fastapi.requests.Request, exc: starlette.exceptions.HTTPException, skip_log: bool = False + request: fastapi.requests.Request, + exc: starlette.exceptions.HTTPException, + skip_log: bool = False, ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=exc.status_code, content=exc.detail).to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=exc.status_code, content=exc.detail + ).to_json_response() def default_exception_handler( request: fastapi.requests.Request, exc: Exception, skip_log: bool = False ) -> fastapi.responses.JSONResponse: if not skip_log: - logging.getLogger(__name__).error(f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc) - return FernHTTPException(status_code=500, content="Internal Server Error").to_json_response() + logging.getLogger(__name__).error( + f"{exc.__class__.__name__} in {request.url.path}", exc_info=exc + ) + return FernHTTPException( + status_code=500, content="Internal Server Error" + ).to_json_response() diff --git a/seed/pydantic/root/src/seed/root/core/route_args.py b/seed/pydantic/root/src/seed/root/core/route_args.py index 4228e2fe05d..bd940bf4ddd 100644 --- a/seed/pydantic/root/src/seed/root/core/route_args.py +++ b/seed/pydantic/root/src/seed/root/core/route_args.py @@ -20,9 +20,15 @@ class RouteArgs(typing_extensions.TypedDict): DEFAULT_ROUTE_ARGS = RouteArgs(openapi_extra=None, tags=None, include_in_schema=True) -def get_route_args(endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str) -> RouteArgs: - unwrapped = inspect.unwrap(endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY))) - route_args = typing.cast(RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS)) +def get_route_args( + endpoint_function: typing.Callable[..., typing.Any], *, default_tag: str +) -> RouteArgs: + unwrapped = inspect.unwrap( + endpoint_function, stop=(lambda f: hasattr(f, FERN_CONFIG_KEY)) + ) + route_args = typing.cast( + RouteArgs, getattr(unwrapped, FERN_CONFIG_KEY, DEFAULT_ROUTE_ARGS) + ) if route_args["tags"] is None: return RouteArgs( openapi_extra=route_args["openapi_extra"], @@ -56,7 +62,11 @@ def decorator(endpoint_function: T) -> T: setattr( endpoint_function, FERN_CONFIG_KEY, - RouteArgs(openapi_extra=openapi_extra, tags=tags, include_in_schema=include_in_schema), + RouteArgs( + openapi_extra=openapi_extra, + tags=tags, + include_in_schema=include_in_schema, + ), ) return endpoint_function diff --git a/seed/pydantic/root/src/seed/root/register.py b/seed/pydantic/root/src/seed/root/register.py index 99f1eba2d3c..2b87dd8bcd0 100644 --- a/seed/pydantic/root/src/seed/root/register.py +++ b/seed/pydantic/root/src/seed/root/register.py @@ -11,7 +11,11 @@ from fastapi import params from .core.abstract_fern_service import AbstractFernService -from .core.exceptions import default_exception_handler, fern_http_exception_handler, http_exception_handler +from .core.exceptions import ( + default_exception_handler, + fern_http_exception_handler, + http_exception_handler, +) from .core.exceptions.fern_http_exception import FernHTTPException from .resources.service.service.service import AbstractServiceService from .service.service import AbstractRootService @@ -22,13 +26,15 @@ def register( *, root: AbstractRootService, service: AbstractServiceService, - dependencies: typing.Optional[typing.Sequence[params.Depends]] = None + dependencies: typing.Optional[typing.Sequence[params.Depends]] = None, ) -> None: _app.include_router(__register_service(root), dependencies=dependencies) _app.include_router(__register_service(service), dependencies=dependencies) _app.add_exception_handler(FernHTTPException, fern_http_exception_handler) - _app.add_exception_handler(starlette.exceptions.HTTPException, http_exception_handler) + _app.add_exception_handler( + starlette.exceptions.HTTPException, http_exception_handler + ) _app.add_exception_handler(Exception, default_exception_handler) @@ -40,7 +46,9 @@ def __register_service(service: AbstractFernService) -> fastapi.APIRouter: def register_validators(module: types.ModuleType) -> None: validators_directory: str = os.path.dirname(module.__file__) # type: ignore - for path in glob.glob(os.path.join(validators_directory, "**/*.py"), recursive=True): + for path in glob.glob( + os.path.join(validators_directory, "**/*.py"), recursive=True + ): if os.path.isfile(path): relative_path = os.path.relpath(path, start=validators_directory) module_path = ".".join([module.__name__] + relative_path[:-3].split("/")) diff --git a/seed/pydantic/root/src/seed/root/resources/service/service/service.py b/seed/pydantic/root/src/seed/root/resources/service/service/service.py index 0a8ba159fab..65b1f9b4d39 100644 --- a/seed/pydantic/root/src/seed/root/resources/service/service/service.py +++ b/seed/pydantic/root/src/seed/root/resources/service/service/service.py @@ -24,8 +24,7 @@ class AbstractServiceService(AbstractFernService): """ @abc.abstractmethod - def nop(self, *, nested_id: str) -> None: - ... + def nop(self, *, nested_id: str) -> None: ... """ Below are internal methods used by Fern to register your implementation. @@ -40,14 +39,20 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_nop(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.nop) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "nested_id": new_parameters.append(parameter.replace(default=fastapi.Path(...))) else: new_parameters.append(parameter) - setattr(cls.nop, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.nop, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.nop) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> None: diff --git a/seed/pydantic/root/src/seed/root/service/service.py b/seed/pydantic/root/src/seed/root/service/service.py index 566e2aa3017..c22b4ad2907 100644 --- a/seed/pydantic/root/src/seed/root/service/service.py +++ b/seed/pydantic/root/src/seed/root/service/service.py @@ -23,8 +23,7 @@ class AbstractRootService(AbstractFernService): """ @abc.abstractmethod - def echo(self, *, body: str) -> str: - ... + def echo(self, *, body: str) -> str: ... """ Below are internal methods used by Fern to register your implementation. @@ -39,14 +38,20 @@ def _init_fern(cls, router: fastapi.APIRouter) -> None: def __init_echo(cls, router: fastapi.APIRouter) -> None: endpoint_function = inspect.signature(cls.echo) new_parameters: typing.List[inspect.Parameter] = [] - for index, (parameter_name, parameter) in enumerate(endpoint_function.parameters.items()): + for index, (parameter_name, parameter) in enumerate( + endpoint_function.parameters.items() + ): if index == 0: new_parameters.append(parameter.replace(default=fastapi.Depends(cls))) elif parameter_name == "body": new_parameters.append(parameter.replace(default=fastapi.Body(...))) else: new_parameters.append(parameter) - setattr(cls.echo, "__signature__", endpoint_function.replace(parameters=new_parameters)) + setattr( + cls.echo, + "__signature__", + endpoint_function.replace(parameters=new_parameters), + ) @functools.wraps(cls.echo) def wrapper(*args: typing.Any, **kwargs: typing.Any) -> str: diff --git a/seed/pydantic/root/tests/test_client.py b/seed/pydantic/root/tests/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/pydantic/root/tests/test_client.py +++ b/seed/pydantic/root/tests/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/pydantic/server-sent-events/pyproject.toml b/seed/pydantic/server-sent-events/pyproject.toml index 746c3e1ccc5..3ecc58493cc 100644 --- a/seed/pydantic/server-sent-events/pyproject.toml +++ b/seed/pydantic/server-sent-events/pyproject.toml @@ -41,6 +41,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/pydantic/server-sent-events/src/seed/server_sent_events/core/datetime_utils.py b/seed/pydantic/server-sent-events/src/seed/server_sent_events/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/pydantic/server-sent-events/src/seed/server_sent_events/core/datetime_utils.py +++ b/seed/pydantic/server-sent-events/src/seed/server_sent_events/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/pydantic/server-sent-events/src/seed/server_sent_events/core/pydantic_utilities.py b/seed/pydantic/server-sent-events/src/seed/server_sent_events/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/pydantic/server-sent-events/src/seed/server_sent_events/core/pydantic_utilities.py +++ b/seed/pydantic/server-sent-events/src/seed/server_sent_events/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/pydantic/server-sent-events/src/seed/server_sent_events/core/serialization.py b/seed/pydantic/server-sent-events/src/seed/server_sent_events/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/pydantic/server-sent-events/src/seed/server_sent_events/core/serialization.py +++ b/seed/pydantic/server-sent-events/src/seed/server_sent_events/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/pydantic/server-sent-events/src/seed/server_sent_events/resources/completions/streamed_completion.py b/seed/pydantic/server-sent-events/src/seed/server_sent_events/resources/completions/streamed_completion.py index db95ed0ddb9..2a6089db912 100644 --- a/seed/pydantic/server-sent-events/src/seed/server_sent_events/resources/completions/streamed_completion.py +++ b/seed/pydantic/server-sent-events/src/seed/server_sent_events/resources/completions/streamed_completion.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel import typing - +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class StreamedCompletion(UniversalBaseModel): delta: str tokens: typing.Optional[int] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/server-sent-events/tests/custom/test_client.py b/seed/pydantic/server-sent-events/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/pydantic/server-sent-events/tests/custom/test_client.py +++ b/seed/pydantic/server-sent-events/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/pydantic/single-url-environment-default/pyproject.toml b/seed/pydantic/single-url-environment-default/pyproject.toml index 9db8c2138bf..df101caf24c 100644 --- a/seed/pydantic/single-url-environment-default/pyproject.toml +++ b/seed/pydantic/single-url-environment-default/pyproject.toml @@ -40,6 +40,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/pydantic/single-url-environment-default/src/seed/single_url_environment_default/core/datetime_utils.py b/seed/pydantic/single-url-environment-default/src/seed/single_url_environment_default/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/pydantic/single-url-environment-default/src/seed/single_url_environment_default/core/datetime_utils.py +++ b/seed/pydantic/single-url-environment-default/src/seed/single_url_environment_default/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/pydantic/single-url-environment-default/src/seed/single_url_environment_default/core/pydantic_utilities.py b/seed/pydantic/single-url-environment-default/src/seed/single_url_environment_default/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/pydantic/single-url-environment-default/src/seed/single_url_environment_default/core/pydantic_utilities.py +++ b/seed/pydantic/single-url-environment-default/src/seed/single_url_environment_default/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/pydantic/single-url-environment-default/src/seed/single_url_environment_default/core/serialization.py b/seed/pydantic/single-url-environment-default/src/seed/single_url_environment_default/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/pydantic/single-url-environment-default/src/seed/single_url_environment_default/core/serialization.py +++ b/seed/pydantic/single-url-environment-default/src/seed/single_url_environment_default/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/pydantic/single-url-environment-default/tests/custom/test_client.py b/seed/pydantic/single-url-environment-default/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/pydantic/single-url-environment-default/tests/custom/test_client.py +++ b/seed/pydantic/single-url-environment-default/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/pydantic/single-url-environment-no-default/pyproject.toml b/seed/pydantic/single-url-environment-no-default/pyproject.toml index 364a881136f..ab2cc7edc5c 100644 --- a/seed/pydantic/single-url-environment-no-default/pyproject.toml +++ b/seed/pydantic/single-url-environment-no-default/pyproject.toml @@ -40,6 +40,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/pydantic/single-url-environment-no-default/src/seed/single_url_environment_no_default/core/datetime_utils.py b/seed/pydantic/single-url-environment-no-default/src/seed/single_url_environment_no_default/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/pydantic/single-url-environment-no-default/src/seed/single_url_environment_no_default/core/datetime_utils.py +++ b/seed/pydantic/single-url-environment-no-default/src/seed/single_url_environment_no_default/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/pydantic/single-url-environment-no-default/src/seed/single_url_environment_no_default/core/pydantic_utilities.py b/seed/pydantic/single-url-environment-no-default/src/seed/single_url_environment_no_default/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/pydantic/single-url-environment-no-default/src/seed/single_url_environment_no_default/core/pydantic_utilities.py +++ b/seed/pydantic/single-url-environment-no-default/src/seed/single_url_environment_no_default/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/pydantic/single-url-environment-no-default/src/seed/single_url_environment_no_default/core/serialization.py b/seed/pydantic/single-url-environment-no-default/src/seed/single_url_environment_no_default/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/pydantic/single-url-environment-no-default/src/seed/single_url_environment_no_default/core/serialization.py +++ b/seed/pydantic/single-url-environment-no-default/src/seed/single_url_environment_no_default/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/pydantic/single-url-environment-no-default/tests/custom/test_client.py b/seed/pydantic/single-url-environment-no-default/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/pydantic/single-url-environment-no-default/tests/custom/test_client.py +++ b/seed/pydantic/single-url-environment-no-default/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/pydantic/streaming-parameter/pyproject.toml b/seed/pydantic/streaming-parameter/pyproject.toml index bf179bf8984..3e1fb3bb203 100644 --- a/seed/pydantic/streaming-parameter/pyproject.toml +++ b/seed/pydantic/streaming-parameter/pyproject.toml @@ -41,6 +41,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/pydantic/streaming-parameter/src/seed/streaming/core/datetime_utils.py b/seed/pydantic/streaming-parameter/src/seed/streaming/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/pydantic/streaming-parameter/src/seed/streaming/core/datetime_utils.py +++ b/seed/pydantic/streaming-parameter/src/seed/streaming/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/pydantic/streaming-parameter/src/seed/streaming/core/pydantic_utilities.py b/seed/pydantic/streaming-parameter/src/seed/streaming/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/pydantic/streaming-parameter/src/seed/streaming/core/pydantic_utilities.py +++ b/seed/pydantic/streaming-parameter/src/seed/streaming/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/pydantic/streaming-parameter/src/seed/streaming/core/serialization.py b/seed/pydantic/streaming-parameter/src/seed/streaming/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/pydantic/streaming-parameter/src/seed/streaming/core/serialization.py +++ b/seed/pydantic/streaming-parameter/src/seed/streaming/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/pydantic/streaming-parameter/src/seed/streaming/resources/dummy/regular_response.py b/seed/pydantic/streaming-parameter/src/seed/streaming/resources/dummy/regular_response.py index 50337ca3d78..55067a4f44f 100644 --- a/seed/pydantic/streaming-parameter/src/seed/streaming/resources/dummy/regular_response.py +++ b/seed/pydantic/streaming-parameter/src/seed/streaming/resources/dummy/regular_response.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel import typing - +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class RegularResponse(UniversalBaseModel): id: str name: typing.Optional[str] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/streaming-parameter/src/seed/streaming/resources/dummy/stream_response.py b/seed/pydantic/streaming-parameter/src/seed/streaming/resources/dummy/stream_response.py index 92a7079910c..623103f9c4d 100644 --- a/seed/pydantic/streaming-parameter/src/seed/streaming/resources/dummy/stream_response.py +++ b/seed/pydantic/streaming-parameter/src/seed/streaming/resources/dummy/stream_response.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel import typing - +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class StreamResponse(UniversalBaseModel): id: str name: typing.Optional[str] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/streaming-parameter/tests/custom/test_client.py b/seed/pydantic/streaming-parameter/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/pydantic/streaming-parameter/tests/custom/test_client.py +++ b/seed/pydantic/streaming-parameter/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/pydantic/streaming/pyproject.toml b/seed/pydantic/streaming/pyproject.toml index 2cae148148f..27275d6eff3 100644 --- a/seed/pydantic/streaming/pyproject.toml +++ b/seed/pydantic/streaming/pyproject.toml @@ -41,6 +41,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/pydantic/streaming/src/seed/streaming/core/datetime_utils.py b/seed/pydantic/streaming/src/seed/streaming/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/pydantic/streaming/src/seed/streaming/core/datetime_utils.py +++ b/seed/pydantic/streaming/src/seed/streaming/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/pydantic/streaming/src/seed/streaming/core/pydantic_utilities.py b/seed/pydantic/streaming/src/seed/streaming/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/pydantic/streaming/src/seed/streaming/core/pydantic_utilities.py +++ b/seed/pydantic/streaming/src/seed/streaming/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/pydantic/streaming/src/seed/streaming/core/serialization.py b/seed/pydantic/streaming/src/seed/streaming/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/pydantic/streaming/src/seed/streaming/core/serialization.py +++ b/seed/pydantic/streaming/src/seed/streaming/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/pydantic/streaming/src/seed/streaming/resources/dummy/stream_response.py b/seed/pydantic/streaming/src/seed/streaming/resources/dummy/stream_response.py index 92a7079910c..623103f9c4d 100644 --- a/seed/pydantic/streaming/src/seed/streaming/resources/dummy/stream_response.py +++ b/seed/pydantic/streaming/src/seed/streaming/resources/dummy/stream_response.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel import typing - +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class StreamResponse(UniversalBaseModel): id: str name: typing.Optional[str] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/streaming/tests/custom/test_client.py b/seed/pydantic/streaming/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/pydantic/streaming/tests/custom/test_client.py +++ b/seed/pydantic/streaming/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/pydantic/trace/pyproject.toml b/seed/pydantic/trace/pyproject.toml index 22db5810011..d12fecfa6c1 100644 --- a/seed/pydantic/trace/pyproject.toml +++ b/seed/pydantic/trace/pyproject.toml @@ -41,6 +41,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/pydantic/trace/src/seed/trace/core/datetime_utils.py b/seed/pydantic/trace/src/seed/trace/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/pydantic/trace/src/seed/trace/core/datetime_utils.py +++ b/seed/pydantic/trace/src/seed/trace/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/pydantic/trace/src/seed/trace/core/pydantic_utilities.py b/seed/pydantic/trace/src/seed/trace/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/pydantic/trace/src/seed/trace/core/pydantic_utilities.py +++ b/seed/pydantic/trace/src/seed/trace/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/pydantic/trace/src/seed/trace/core/serialization.py b/seed/pydantic/trace/src/seed/trace/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/pydantic/trace/src/seed/trace/core/serialization.py +++ b/seed/pydantic/trace/src/seed/trace/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/pydantic/trace/src/seed/trace/resources/admin/test.py b/seed/pydantic/trace/src/seed/trace/resources/admin/test.py index 8a0c012ed80..8e5fe30fd0c 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/admin/test.py +++ b/seed/pydantic/trace/src/seed/trace/resources/admin/test.py @@ -1,10 +1,8 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - -import typing - from ...core.pydantic_utilities import UniversalBaseModel +import typing class Test_And(UniversalBaseModel): diff --git a/seed/pydantic/trace/src/seed/trace/resources/commons/binary_tree_node_and_tree_value.py b/seed/pydantic/trace/src/seed/trace/resources/commons/binary_tree_node_and_tree_value.py index 3f096353eb9..1ed57005261 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/commons/binary_tree_node_and_tree_value.py +++ b/seed/pydantic/trace/src/seed/trace/resources/commons/binary_tree_node_and_tree_value.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ...core.pydantic_utilities import UniversalBaseModel +from .node_id import NodeId import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .binary_tree_value import BinaryTreeValue -from .node_id import NodeId +from ...core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class BinaryTreeNodeAndTreeValue(UniversalBaseModel): @@ -14,7 +13,9 @@ class BinaryTreeNodeAndTreeValue(UniversalBaseModel): full_tree: BinaryTreeValue = pydantic.Field(alias="fullTree") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/commons/binary_tree_node_value.py b/seed/pydantic/trace/src/seed/trace/resources/commons/binary_tree_node_value.py index 72db1c4678a..b24d3860188 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/commons/binary_tree_node_value.py +++ b/seed/pydantic/trace/src/seed/trace/resources/commons/binary_tree_node_value.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ...core.pydantic_utilities import UniversalBaseModel from .node_id import NodeId +import pydantic +import typing +from ...core.pydantic_utilities import IS_PYDANTIC_V2 class BinaryTreeNodeValue(UniversalBaseModel): @@ -15,7 +14,9 @@ class BinaryTreeNodeValue(UniversalBaseModel): left: typing.Optional[NodeId] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/commons/binary_tree_value.py b/seed/pydantic/trace/src/seed/trace/resources/commons/binary_tree_value.py index a8da1f148d2..62cd4662d48 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/commons/binary_tree_value.py +++ b/seed/pydantic/trace/src/seed/trace/resources/commons/binary_tree_value.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .binary_tree_node_value import BinaryTreeNodeValue from .node_id import NodeId +from .binary_tree_node_value import BinaryTreeNodeValue +from ...core.pydantic_utilities import IS_PYDANTIC_V2 +import pydantic class BinaryTreeValue(UniversalBaseModel): @@ -14,7 +13,9 @@ class BinaryTreeValue(UniversalBaseModel): nodes: typing.Dict[NodeId, BinaryTreeNodeValue] if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/commons/debug_key_value_pairs.py b/seed/pydantic/trace/src/seed/trace/resources/commons/debug_key_value_pairs.py index 06cde0228cc..a69807829f3 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/commons/debug_key_value_pairs.py +++ b/seed/pydantic/trace/src/seed/trace/resources/commons/debug_key_value_pairs.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel, update_forward_refs +from ...core.pydantic_utilities import update_forward_refs class DebugKeyValuePairs(UniversalBaseModel): @@ -14,7 +13,9 @@ class DebugKeyValuePairs(UniversalBaseModel): value: DebugVariableValue if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/commons/debug_map_value.py b/seed/pydantic/trace/src/seed/trace/resources/commons/debug_map_value.py index 2695ae59aca..eb09c726479 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/commons/debug_map_value.py +++ b/seed/pydantic/trace/src/seed/trace/resources/commons/debug_map_value.py @@ -1,19 +1,22 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ...core.pydantic_utilities import UniversalBaseModel import typing - import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel, update_forward_refs +from ...core.pydantic_utilities import IS_PYDANTIC_V2 +from ...core.pydantic_utilities import update_forward_refs class DebugMapValue(UniversalBaseModel): - key_value_pairs: typing.List[DebugKeyValuePairs] = pydantic.Field(alias="keyValuePairs") + key_value_pairs: typing.List[DebugKeyValuePairs] = pydantic.Field( + alias="keyValuePairs" + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/commons/debug_variable_value.py b/seed/pydantic/trace/src/seed/trace/resources/commons/debug_variable_value.py index 64e5f9fa006..e748003af32 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/commons/debug_variable_value.py +++ b/seed/pydantic/trace/src/seed/trace/resources/commons/debug_variable_value.py @@ -1,23 +1,22 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ...core.pydantic_utilities import UniversalBaseModel import typing - import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel, update_forward_refs -from .binary_tree_node_and_tree_value import BinaryTreeNodeAndTreeValue -from .binary_tree_node_value import BinaryTreeNodeValue +from ...core.pydantic_utilities import IS_PYDANTIC_V2 +from .node_id import NodeId from .binary_tree_value import BinaryTreeValue -from .doubly_linked_list_node_and_list_value import DoublyLinkedListNodeAndListValue -from .doubly_linked_list_node_value import DoublyLinkedListNodeValue +from .singly_linked_list_value import SinglyLinkedListValue from .doubly_linked_list_value import DoublyLinkedListValue +from .singly_linked_list_node_value import SinglyLinkedListNodeValue from .generic_value import GenericValue -from .node_id import NodeId +from .doubly_linked_list_node_and_list_value import DoublyLinkedListNodeAndListValue +from .binary_tree_node_value import BinaryTreeNodeValue from .singly_linked_list_node_and_list_value import SinglyLinkedListNodeAndListValue -from .singly_linked_list_node_value import SinglyLinkedListNodeValue -from .singly_linked_list_value import SinglyLinkedListValue +from .doubly_linked_list_node_value import DoublyLinkedListNodeValue +from .binary_tree_node_and_tree_value import BinaryTreeNodeAndTreeValue +from ...core.pydantic_utilities import update_forward_refs class DebugVariableValue_IntegerValue(UniversalBaseModel): @@ -47,10 +46,14 @@ class DebugVariableValue_CharValue(UniversalBaseModel): class DebugVariableValue_MapValue(UniversalBaseModel): type: typing.Literal["mapValue"] = "mapValue" - key_value_pairs: typing.List[DebugKeyValuePairs] = pydantic.Field(alias="keyValuePairs") + key_value_pairs: typing.List[DebugKeyValuePairs] = pydantic.Field( + alias="keyValuePairs" + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -68,7 +71,9 @@ class DebugVariableValue_BinaryTreeNodeValue(UniversalBaseModel): full_tree: BinaryTreeValue = pydantic.Field(alias="fullTree") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -81,7 +86,9 @@ class DebugVariableValue_SinglyLinkedListNodeValue(UniversalBaseModel): full_list: SinglyLinkedListValue = pydantic.Field(alias="fullList") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -94,7 +101,9 @@ class DebugVariableValue_DoublyLinkedListNodeValue(UniversalBaseModel): full_list: DoublyLinkedListValue = pydantic.Field(alias="fullList") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -105,7 +114,9 @@ class DebugVariableValue_UndefinedValue(UniversalBaseModel): type: typing.Literal["undefinedValue"] = "undefinedValue" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -116,7 +127,9 @@ class DebugVariableValue_NullValue(UniversalBaseModel): type: typing.Literal["nullValue"] = "nullValue" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -125,11 +138,15 @@ class Config: class DebugVariableValue_GenericValue(UniversalBaseModel): type: typing.Literal["genericValue"] = "genericValue" - stringified_type: typing.Optional[str] = pydantic.Field(alias="stringifiedType", default=None) + stringified_type: typing.Optional[str] = pydantic.Field( + alias="stringifiedType", default=None + ) stringified_value: str = pydantic.Field(alias="stringifiedValue") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/commons/doubly_linked_list_node_and_list_value.py b/seed/pydantic/trace/src/seed/trace/resources/commons/doubly_linked_list_node_and_list_value.py index 39baf07b22a..4f57a570a46 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/commons/doubly_linked_list_node_and_list_value.py +++ b/seed/pydantic/trace/src/seed/trace/resources/commons/doubly_linked_list_node_and_list_value.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ...core.pydantic_utilities import UniversalBaseModel +from .node_id import NodeId import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .doubly_linked_list_value import DoublyLinkedListValue -from .node_id import NodeId +from ...core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class DoublyLinkedListNodeAndListValue(UniversalBaseModel): @@ -14,7 +13,9 @@ class DoublyLinkedListNodeAndListValue(UniversalBaseModel): full_list: DoublyLinkedListValue = pydantic.Field(alias="fullList") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/commons/doubly_linked_list_node_value.py b/seed/pydantic/trace/src/seed/trace/resources/commons/doubly_linked_list_node_value.py index 146d1b8eab6..f3c15a1f863 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/commons/doubly_linked_list_node_value.py +++ b/seed/pydantic/trace/src/seed/trace/resources/commons/doubly_linked_list_node_value.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ...core.pydantic_utilities import UniversalBaseModel from .node_id import NodeId +import pydantic +import typing +from ...core.pydantic_utilities import IS_PYDANTIC_V2 class DoublyLinkedListNodeValue(UniversalBaseModel): @@ -15,7 +14,9 @@ class DoublyLinkedListNodeValue(UniversalBaseModel): prev: typing.Optional[NodeId] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/commons/doubly_linked_list_value.py b/seed/pydantic/trace/src/seed/trace/resources/commons/doubly_linked_list_value.py index ccaa702efc8..1c902abb59b 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/commons/doubly_linked_list_value.py +++ b/seed/pydantic/trace/src/seed/trace/resources/commons/doubly_linked_list_value.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .doubly_linked_list_node_value import DoublyLinkedListNodeValue from .node_id import NodeId +from .doubly_linked_list_node_value import DoublyLinkedListNodeValue +from ...core.pydantic_utilities import IS_PYDANTIC_V2 +import pydantic class DoublyLinkedListValue(UniversalBaseModel): @@ -14,7 +13,9 @@ class DoublyLinkedListValue(UniversalBaseModel): nodes: typing.Dict[NodeId, DoublyLinkedListNodeValue] if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/commons/file_info.py b/seed/pydantic/trace/src/seed/trace/resources/commons/file_info.py index c69ed98e6bc..725682b949a 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/commons/file_info.py +++ b/seed/pydantic/trace/src/seed/trace/resources/commons/file_info.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class FileInfo(UniversalBaseModel): filename: str contents: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/commons/generic_value.py b/seed/pydantic/trace/src/seed/trace/resources/commons/generic_value.py index d705ade903c..493a85ae8e2 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/commons/generic_value.py +++ b/seed/pydantic/trace/src/seed/trace/resources/commons/generic_value.py @@ -1,18 +1,21 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel import typing - import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 class GenericValue(UniversalBaseModel): - stringified_type: typing.Optional[str] = pydantic.Field(alias="stringifiedType", default=None) + stringified_type: typing.Optional[str] = pydantic.Field( + alias="stringifiedType", default=None + ) stringified_value: str = pydantic.Field(alias="stringifiedValue") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/commons/key_value_pair.py b/seed/pydantic/trace/src/seed/trace/resources/commons/key_value_pair.py index a65453d5cb0..d6ebc90e8e5 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/commons/key_value_pair.py +++ b/seed/pydantic/trace/src/seed/trace/resources/commons/key_value_pair.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel, update_forward_refs +from ...core.pydantic_utilities import update_forward_refs class KeyValuePair(UniversalBaseModel): @@ -14,7 +13,9 @@ class KeyValuePair(UniversalBaseModel): value: VariableValue if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/commons/list_type.py b/seed/pydantic/trace/src/seed/trace/resources/commons/list_type.py index 8b275686e62..d98bf1f9348 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/commons/list_type.py +++ b/seed/pydantic/trace/src/seed/trace/resources/commons/list_type.py @@ -1,23 +1,26 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - -import typing - +from ...core.pydantic_utilities import UniversalBaseModel import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel, update_forward_refs +import typing +from ...core.pydantic_utilities import IS_PYDANTIC_V2 +from ...core.pydantic_utilities import update_forward_refs class ListType(UniversalBaseModel): value_type: VariableType = pydantic.Field(alias="valueType") - is_fixed_length: typing.Optional[bool] = pydantic.Field(alias="isFixedLength", default=None) + is_fixed_length: typing.Optional[bool] = pydantic.Field( + alias="isFixedLength", default=None + ) """ Whether this list is fixed-size (for languages that supports fixed-size lists). Defaults to false. """ if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/commons/map_type.py b/seed/pydantic/trace/src/seed/trace/resources/commons/map_type.py index 4dce4c4e3d3..266d154611d 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/commons/map_type.py +++ b/seed/pydantic/trace/src/seed/trace/resources/commons/map_type.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - -import typing - +from ...core.pydantic_utilities import UniversalBaseModel import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel, update_forward_refs +from ...core.pydantic_utilities import IS_PYDANTIC_V2 +import typing +from ...core.pydantic_utilities import update_forward_refs class MapType(UniversalBaseModel): @@ -14,7 +13,9 @@ class MapType(UniversalBaseModel): value_type: VariableType = pydantic.Field(alias="valueType") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/commons/map_value.py b/seed/pydantic/trace/src/seed/trace/resources/commons/map_value.py index f83389c00f9..955528067dd 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/commons/map_value.py +++ b/seed/pydantic/trace/src/seed/trace/resources/commons/map_value.py @@ -1,19 +1,20 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ...core.pydantic_utilities import UniversalBaseModel import typing - import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel, update_forward_refs +from ...core.pydantic_utilities import IS_PYDANTIC_V2 +from ...core.pydantic_utilities import update_forward_refs class MapValue(UniversalBaseModel): key_value_pairs: typing.List[KeyValuePair] = pydantic.Field(alias="keyValuePairs") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/commons/singly_linked_list_node_and_list_value.py b/seed/pydantic/trace/src/seed/trace/resources/commons/singly_linked_list_node_and_list_value.py index 645d3c2c1d1..883d592b771 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/commons/singly_linked_list_node_and_list_value.py +++ b/seed/pydantic/trace/src/seed/trace/resources/commons/singly_linked_list_node_and_list_value.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ...core.pydantic_utilities import UniversalBaseModel from .node_id import NodeId +import pydantic from .singly_linked_list_value import SinglyLinkedListValue +from ...core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class SinglyLinkedListNodeAndListValue(UniversalBaseModel): @@ -14,7 +13,9 @@ class SinglyLinkedListNodeAndListValue(UniversalBaseModel): full_list: SinglyLinkedListValue = pydantic.Field(alias="fullList") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/commons/singly_linked_list_node_value.py b/seed/pydantic/trace/src/seed/trace/resources/commons/singly_linked_list_node_value.py index b51f2073199..0be0c148891 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/commons/singly_linked_list_node_value.py +++ b/seed/pydantic/trace/src/seed/trace/resources/commons/singly_linked_list_node_value.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ...core.pydantic_utilities import UniversalBaseModel from .node_id import NodeId +import pydantic +import typing +from ...core.pydantic_utilities import IS_PYDANTIC_V2 class SinglyLinkedListNodeValue(UniversalBaseModel): @@ -14,7 +13,9 @@ class SinglyLinkedListNodeValue(UniversalBaseModel): next: typing.Optional[NodeId] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/commons/singly_linked_list_value.py b/seed/pydantic/trace/src/seed/trace/resources/commons/singly_linked_list_value.py index 36d1abbbbf4..a650bf119c8 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/commons/singly_linked_list_value.py +++ b/seed/pydantic/trace/src/seed/trace/resources/commons/singly_linked_list_value.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .node_id import NodeId from .singly_linked_list_node_value import SinglyLinkedListNodeValue +from ...core.pydantic_utilities import IS_PYDANTIC_V2 +import pydantic class SinglyLinkedListValue(UniversalBaseModel): @@ -14,7 +13,9 @@ class SinglyLinkedListValue(UniversalBaseModel): nodes: typing.Dict[NodeId, SinglyLinkedListNodeValue] if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/commons/test_case.py b/seed/pydantic/trace/src/seed/trace/resources/commons/test_case.py index 18c8f833350..736d8991a25 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/commons/test_case.py +++ b/seed/pydantic/trace/src/seed/trace/resources/commons/test_case.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .variable_value import VariableValue +from ...core.pydantic_utilities import IS_PYDANTIC_V2 +import pydantic class TestCase(UniversalBaseModel): @@ -13,7 +12,9 @@ class TestCase(UniversalBaseModel): params: typing.List[VariableValue] if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/commons/test_case_with_expected_result.py b/seed/pydantic/trace/src/seed/trace/resources/commons/test_case_with_expected_result.py index 2b5bb9fe418..65e97b979ae 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/commons/test_case_with_expected_result.py +++ b/seed/pydantic/trace/src/seed/trace/resources/commons/test_case_with_expected_result.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ...core.pydantic_utilities import UniversalBaseModel from .test_case import TestCase +import pydantic from .variable_value import VariableValue +from ...core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class TestCaseWithExpectedResult(UniversalBaseModel): @@ -14,7 +13,9 @@ class TestCaseWithExpectedResult(UniversalBaseModel): expected_result: VariableValue = pydantic.Field(alias="expectedResult") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/commons/variable_type.py b/seed/pydantic/trace/src/seed/trace/resources/commons/variable_type.py index 6c2322aa54e..17313838fd9 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/commons/variable_type.py +++ b/seed/pydantic/trace/src/seed/trace/resources/commons/variable_type.py @@ -1,19 +1,19 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ...core.pydantic_utilities import UniversalBaseModel import typing - +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class VariableType_IntegerType(UniversalBaseModel): type: typing.Literal["integerType"] = "integerType" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -24,7 +24,9 @@ class VariableType_DoubleType(UniversalBaseModel): type: typing.Literal["doubleType"] = "doubleType" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -35,7 +37,9 @@ class VariableType_BooleanType(UniversalBaseModel): type: typing.Literal["booleanType"] = "booleanType" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -46,7 +50,9 @@ class VariableType_StringType(UniversalBaseModel): type: typing.Literal["stringType"] = "stringType" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -57,7 +63,9 @@ class VariableType_CharType(UniversalBaseModel): type: typing.Literal["charType"] = "charType" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -67,10 +75,14 @@ class Config: class VariableType_ListType(UniversalBaseModel): type: typing.Literal["listType"] = "listType" value_type: VariableType = pydantic.Field(alias="valueType") - is_fixed_length: typing.Optional[bool] = pydantic.Field(alias="isFixedLength", default=None) + is_fixed_length: typing.Optional[bool] = pydantic.Field( + alias="isFixedLength", default=None + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -83,7 +95,9 @@ class VariableType_MapType(UniversalBaseModel): value_type: VariableType = pydantic.Field(alias="valueType") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -94,7 +108,9 @@ class VariableType_BinaryTreeType(UniversalBaseModel): type: typing.Literal["binaryTreeType"] = "binaryTreeType" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -105,7 +121,9 @@ class VariableType_SinglyLinkedListType(UniversalBaseModel): type: typing.Literal["singlyLinkedListType"] = "singlyLinkedListType" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -116,7 +134,9 @@ class VariableType_DoublyLinkedListType(UniversalBaseModel): type: typing.Literal["doublyLinkedListType"] = "doublyLinkedListType" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/commons/variable_value.py b/seed/pydantic/trace/src/seed/trace/resources/commons/variable_value.py index da98ba857d5..9374b41bbc0 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/commons/variable_value.py +++ b/seed/pydantic/trace/src/seed/trace/resources/commons/variable_value.py @@ -1,19 +1,18 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ...core.pydantic_utilities import UniversalBaseModel import typing - import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel, update_forward_refs -from .binary_tree_node_value import BinaryTreeNodeValue -from .binary_tree_value import BinaryTreeValue -from .doubly_linked_list_node_value import DoublyLinkedListNodeValue -from .doubly_linked_list_value import DoublyLinkedListValue +from ...core.pydantic_utilities import IS_PYDANTIC_V2 from .node_id import NodeId +from .binary_tree_node_value import BinaryTreeNodeValue from .singly_linked_list_node_value import SinglyLinkedListNodeValue +from .doubly_linked_list_node_value import DoublyLinkedListNodeValue from .singly_linked_list_value import SinglyLinkedListValue +from .binary_tree_value import BinaryTreeValue +from .doubly_linked_list_value import DoublyLinkedListValue +from ...core.pydantic_utilities import update_forward_refs class VariableValue_IntegerValue(UniversalBaseModel): @@ -46,7 +45,9 @@ class VariableValue_MapValue(UniversalBaseModel): key_value_pairs: typing.List[KeyValuePair] = pydantic.Field(alias="keyValuePairs") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -64,7 +65,9 @@ class VariableValue_BinaryTreeValue(UniversalBaseModel): nodes: typing.Dict[NodeId, BinaryTreeNodeValue] if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -77,7 +80,9 @@ class VariableValue_SinglyLinkedListValue(UniversalBaseModel): nodes: typing.Dict[NodeId, SinglyLinkedListNodeValue] if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -90,7 +95,9 @@ class VariableValue_DoublyLinkedListValue(UniversalBaseModel): nodes: typing.Dict[NodeId, DoublyLinkedListNodeValue] if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -101,7 +108,9 @@ class VariableValue_NullValue(UniversalBaseModel): type: typing.Literal["nullValue"] = "nullValue" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/lang_server/lang_server_request.py b/seed/pydantic/trace/src/seed/trace/resources/lang_server/lang_server_request.py index d4fd933882f..cc7ef00783c 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/lang_server/lang_server_request.py +++ b/seed/pydantic/trace/src/seed/trace/resources/lang_server/lang_server_request.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel import typing - +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class LangServerRequest(UniversalBaseModel): request: typing.Any if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/lang_server/lang_server_response.py b/seed/pydantic/trace/src/seed/trace/resources/lang_server/lang_server_response.py index aae1621757a..3f532e3ed22 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/lang_server/lang_server_response.py +++ b/seed/pydantic/trace/src/seed/trace/resources/lang_server/lang_server_response.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel import typing - +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class LangServerResponse(UniversalBaseModel): response: typing.Any if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/migration/migration.py b/seed/pydantic/trace/src/seed/trace/resources/migration/migration.py index 31413874b5a..bcfd250be61 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/migration/migration.py +++ b/seed/pydantic/trace/src/seed/trace/resources/migration/migration.py @@ -1,19 +1,20 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from .migration_status import MigrationStatus +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .migration_status import MigrationStatus - class Migration(UniversalBaseModel): name: str status: MigrationStatus if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/migration/migration_status.py b/seed/pydantic/trace/src/seed/trace/resources/migration/migration_status.py index c5a2e76b4af..e14e67e1b5a 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/migration/migration_status.py +++ b/seed/pydantic/trace/src/seed/trace/resources/migration/migration_status.py @@ -2,4 +2,6 @@ import typing -MigrationStatus = typing.Union[typing.Literal["RUNNING", "FAILED", "FINISHED"], typing.Any] +MigrationStatus = typing.Union[ + typing.Literal["RUNNING", "FAILED", "FINISHED"], typing.Any +] diff --git a/seed/pydantic/trace/src/seed/trace/resources/playlist/__init__.py b/seed/pydantic/trace/src/seed/trace/resources/playlist/__init__.py index d4667234a8a..93239244d73 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/playlist/__init__.py +++ b/seed/pydantic/trace/src/seed/trace/resources/playlist/__init__.py @@ -3,7 +3,10 @@ from .playlist import Playlist from .playlist_create_request import PlaylistCreateRequest from .playlist_id import PlaylistId -from .playlist_id_not_found_error_body import PlaylistIdNotFoundErrorBody, PlaylistIdNotFoundErrorBody_PlaylistId +from .playlist_id_not_found_error_body import ( + PlaylistIdNotFoundErrorBody, + PlaylistIdNotFoundErrorBody_PlaylistId, +) from .reserved_keyword_enum import ReservedKeywordEnum from .update_playlist_request import UpdatePlaylistRequest diff --git a/seed/pydantic/trace/src/seed/trace/resources/playlist/playlist.py b/seed/pydantic/trace/src/seed/trace/resources/playlist/playlist.py index f8024085ca9..419e2feaf45 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/playlist/playlist.py +++ b/seed/pydantic/trace/src/seed/trace/resources/playlist/playlist.py @@ -1,13 +1,11 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2 -from ..commons.user_id import UserId from .playlist_create_request import PlaylistCreateRequest from .playlist_id import PlaylistId +from ..commons.user_id import UserId +import pydantic +from ...core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class Playlist(PlaylistCreateRequest): @@ -15,7 +13,9 @@ class Playlist(PlaylistCreateRequest): owner_id: UserId = pydantic.Field(alias="owner-id") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/playlist/playlist_create_request.py b/seed/pydantic/trace/src/seed/trace/resources/playlist/playlist_create_request.py index f31bccb81c2..be9d6581e48 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/playlist/playlist_create_request.py +++ b/seed/pydantic/trace/src/seed/trace/resources/playlist/playlist_create_request.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from ..commons.problem_id import ProblemId +from ...core.pydantic_utilities import IS_PYDANTIC_V2 +import pydantic class PlaylistCreateRequest(UniversalBaseModel): @@ -13,7 +12,9 @@ class PlaylistCreateRequest(UniversalBaseModel): problems: typing.List[ProblemId] if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/playlist/playlist_id_not_found_error_body.py b/seed/pydantic/trace/src/seed/trace/resources/playlist/playlist_id_not_found_error_body.py index 854ac9f59e5..a500528ecaa 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/playlist/playlist_id_not_found_error_body.py +++ b/seed/pydantic/trace/src/seed/trace/resources/playlist/playlist_id_not_found_error_body.py @@ -1,11 +1,9 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - -import typing - from ...core.pydantic_utilities import UniversalBaseModel from .playlist_id import PlaylistId +import typing class PlaylistIdNotFoundErrorBody_PlaylistId(UniversalBaseModel): diff --git a/seed/pydantic/trace/src/seed/trace/resources/playlist/update_playlist_request.py b/seed/pydantic/trace/src/seed/trace/resources/playlist/update_playlist_request.py index 37c449d31a3..d99bcd1664e 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/playlist/update_playlist_request.py +++ b/seed/pydantic/trace/src/seed/trace/resources/playlist/update_playlist_request.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from ..commons.problem_id import ProblemId +import pydantic +from ...core.pydantic_utilities import IS_PYDANTIC_V2 class UpdatePlaylistRequest(UniversalBaseModel): @@ -16,7 +15,9 @@ class UpdatePlaylistRequest(UniversalBaseModel): """ if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/problem/__init__.py b/seed/pydantic/trace/src/seed/trace/resources/problem/__init__.py index 35e2b592b37..c1dc58af5a4 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/problem/__init__.py +++ b/seed/pydantic/trace/src/seed/trace/resources/problem/__init__.py @@ -2,7 +2,11 @@ from .create_problem_error import CreateProblemError, CreateProblemError_Generic from .create_problem_request import CreateProblemRequest -from .create_problem_response import CreateProblemResponse, CreateProblemResponse_Error, CreateProblemResponse_Success +from .create_problem_response import ( + CreateProblemResponse, + CreateProblemResponse_Error, + CreateProblemResponse_Success, +) from .generic_create_problem_error import GenericCreateProblemError from .get_default_starter_files_response import GetDefaultStarterFilesResponse from .problem_description import ProblemDescription diff --git a/seed/pydantic/trace/src/seed/trace/resources/problem/create_problem_error.py b/seed/pydantic/trace/src/seed/trace/resources/problem/create_problem_error.py index 0a3dca5420d..e3e8142abbe 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/problem/create_problem_error.py +++ b/seed/pydantic/trace/src/seed/trace/resources/problem/create_problem_error.py @@ -1,22 +1,24 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ...core.pydantic_utilities import UniversalBaseModel import typing - import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 class CreateProblemError_Generic(UniversalBaseModel): - error_type: typing.Literal["generic"] = pydantic.Field(alias="_type", default="generic") + error_type: typing.Literal["generic"] = pydantic.Field( + alias="_type", default="generic" + ) message: str type: str stacktrace: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/problem/create_problem_request.py b/seed/pydantic/trace/src/seed/trace/resources/problem/create_problem_request.py index 15be0c7c75d..be725a5768f 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/problem/create_problem_request.py +++ b/seed/pydantic/trace/src/seed/trace/resources/problem/create_problem_request.py @@ -1,16 +1,15 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ...core.pydantic_utilities import UniversalBaseModel import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from ..commons.language import Language -from ..commons.test_case_with_expected_result import TestCaseWithExpectedResult -from ..commons.variable_type import VariableType from .problem_description import ProblemDescription +import typing +from ..commons.language import Language from .problem_files import ProblemFiles from .variable_type_and_name import VariableTypeAndName +from ..commons.variable_type import VariableType +from ..commons.test_case_with_expected_result import TestCaseWithExpectedResult +from ...core.pydantic_utilities import IS_PYDANTIC_V2 class CreateProblemRequest(UniversalBaseModel): @@ -23,7 +22,9 @@ class CreateProblemRequest(UniversalBaseModel): method_name: str = pydantic.Field(alias="methodName") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/problem/create_problem_response.py b/seed/pydantic/trace/src/seed/trace/resources/problem/create_problem_response.py index d3564919efa..f619f314a5b 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/problem/create_problem_response.py +++ b/seed/pydantic/trace/src/seed/trace/resources/problem/create_problem_response.py @@ -1,11 +1,9 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - -import typing - from ...core.pydantic_utilities import UniversalBaseModel from ..commons.problem_id import ProblemId +import typing from .create_problem_error import CreateProblemError @@ -19,4 +17,6 @@ class CreateProblemResponse_Error(UniversalBaseModel): type: typing.Literal["error"] = "error" -CreateProblemResponse = typing.Union[CreateProblemResponse_Success, CreateProblemResponse_Error] +CreateProblemResponse = typing.Union[ + CreateProblemResponse_Success, CreateProblemResponse_Error +] diff --git a/seed/pydantic/trace/src/seed/trace/resources/problem/generic_create_problem_error.py b/seed/pydantic/trace/src/seed/trace/resources/problem/generic_create_problem_error.py index 306752b8858..2893a683338 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/problem/generic_create_problem_error.py +++ b/seed/pydantic/trace/src/seed/trace/resources/problem/generic_create_problem_error.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class GenericCreateProblemError(UniversalBaseModel): message: str @@ -13,7 +12,9 @@ class GenericCreateProblemError(UniversalBaseModel): stacktrace: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/problem/get_default_starter_files_response.py b/seed/pydantic/trace/src/seed/trace/resources/problem/get_default_starter_files_response.py index 3a321d39b38..0a201ef9bbb 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/problem/get_default_starter_files_response.py +++ b/seed/pydantic/trace/src/seed/trace/resources/problem/get_default_starter_files_response.py @@ -1,19 +1,20 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from ..commons.language import Language from .problem_files import ProblemFiles +from ...core.pydantic_utilities import IS_PYDANTIC_V2 +import pydantic class GetDefaultStarterFilesResponse(UniversalBaseModel): files: typing.Dict[Language, ProblemFiles] if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/problem/problem_description.py b/seed/pydantic/trace/src/seed/trace/resources/problem/problem_description.py index cbb81591b2e..c5653fa24e6 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/problem/problem_description.py +++ b/seed/pydantic/trace/src/seed/trace/resources/problem/problem_description.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .problem_description_board import ProblemDescriptionBoard +from ...core.pydantic_utilities import IS_PYDANTIC_V2 +import pydantic class ProblemDescription(UniversalBaseModel): boards: typing.List[ProblemDescriptionBoard] if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/problem/problem_description_board.py b/seed/pydantic/trace/src/seed/trace/resources/problem/problem_description_board.py index e2e4e431f07..aae57e79d5e 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/problem/problem_description_board.py +++ b/seed/pydantic/trace/src/seed/trace/resources/problem/problem_description_board.py @@ -1,10 +1,8 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - -import typing - from ...core.pydantic_utilities import UniversalBaseModel +import typing class ProblemDescriptionBoard_Html(UniversalBaseModel): @@ -23,6 +21,8 @@ class ProblemDescriptionBoard_TestCaseId(UniversalBaseModel): ProblemDescriptionBoard = typing.Union[ - ProblemDescriptionBoard_Html, ProblemDescriptionBoard_Variable, ProblemDescriptionBoard_TestCaseId + ProblemDescriptionBoard_Html, + ProblemDescriptionBoard_Variable, + ProblemDescriptionBoard_TestCaseId, ] from ..commons.variable_value import VariableValue # noqa: E402 diff --git a/seed/pydantic/trace/src/seed/trace/resources/problem/problem_files.py b/seed/pydantic/trace/src/seed/trace/resources/problem/problem_files.py index 8e51e490b3b..e271551e09c 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/problem/problem_files.py +++ b/seed/pydantic/trace/src/seed/trace/resources/problem/problem_files.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ...core.pydantic_utilities import UniversalBaseModel from ..commons.file_info import FileInfo +import pydantic +import typing +from ...core.pydantic_utilities import IS_PYDANTIC_V2 class ProblemFiles(UniversalBaseModel): @@ -13,7 +12,9 @@ class ProblemFiles(UniversalBaseModel): read_only_files: typing.List[FileInfo] = pydantic.Field(alias="readOnlyFiles") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/problem/problem_info.py b/seed/pydantic/trace/src/seed/trace/resources/problem/problem_info.py index 60a8bd59022..63f05381dac 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/problem/problem_info.py +++ b/seed/pydantic/trace/src/seed/trace/resources/problem/problem_info.py @@ -1,17 +1,16 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from ..commons.language import Language +from ...core.pydantic_utilities import UniversalBaseModel from ..commons.problem_id import ProblemId -from ..commons.test_case_with_expected_result import TestCaseWithExpectedResult -from ..commons.variable_type import VariableType +import pydantic from .problem_description import ProblemDescription +import typing +from ..commons.language import Language from .problem_files import ProblemFiles from .variable_type_and_name import VariableTypeAndName +from ..commons.variable_type import VariableType +from ..commons.test_case_with_expected_result import TestCaseWithExpectedResult +from ...core.pydantic_utilities import IS_PYDANTIC_V2 class ProblemInfo(UniversalBaseModel): @@ -27,7 +26,9 @@ class ProblemInfo(UniversalBaseModel): supports_custom_test_cases: bool = pydantic.Field(alias="supportsCustomTestCases") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/problem/update_problem_response.py b/seed/pydantic/trace/src/seed/trace/resources/problem/update_problem_response.py index 1eab317e7d5..36737cb485b 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/problem/update_problem_response.py +++ b/seed/pydantic/trace/src/seed/trace/resources/problem/update_problem_response.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ...core.pydantic_utilities import UniversalBaseModel import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class UpdateProblemResponse(UniversalBaseModel): problem_version: int = pydantic.Field(alias="problemVersion") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/problem/variable_type_and_name.py b/seed/pydantic/trace/src/seed/trace/resources/problem/variable_type_and_name.py index c3b47ac2a0d..41f4617625d 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/problem/variable_type_and_name.py +++ b/seed/pydantic/trace/src/seed/trace/resources/problem/variable_type_and_name.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ...core.pydantic_utilities import UniversalBaseModel from ..commons.variable_type import VariableType +import pydantic +from ...core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class VariableTypeAndName(UniversalBaseModel): @@ -13,7 +12,9 @@ class VariableTypeAndName(UniversalBaseModel): name: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/submission/__init__.py b/seed/pydantic/trace/src/seed/trace/resources/submission/__init__.py index 5e3287b03b1..a6e67f79fc9 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/submission/__init__.py +++ b/seed/pydantic/trace/src/seed/trace/resources/submission/__init__.py @@ -1,6 +1,11 @@ # This file was auto-generated by Fern from our API Definition. -from .actual_result import ActualResult, ActualResult_Exception, ActualResult_ExceptionV2, ActualResult_Value +from .actual_result import ( + ActualResult, + ActualResult_Exception, + ActualResult_ExceptionV2, + ActualResult_Value, +) from .building_executor_response import BuildingExecutorResponse from .code_execution_update import ( CodeExecutionUpdate, @@ -18,7 +23,12 @@ ) from .compile_error import CompileError from .custom_test_cases_unsupported import CustomTestCasesUnsupported -from .error_info import ErrorInfo, ErrorInfo_CompileError, ErrorInfo_InternalError, ErrorInfo_RuntimeError +from .error_info import ( + ErrorInfo, + ErrorInfo_CompileError, + ErrorInfo_InternalError, + ErrorInfo_RuntimeError, +) from .errored_response import ErroredResponse from .exception_info import ExceptionInfo from .exception_v_2 import ExceptionV2, ExceptionV2_Generic, ExceptionV2_Timeout @@ -84,12 +94,24 @@ SubmissionStatusForTestCase_GradedV2, SubmissionStatusForTestCase_Traced, ) -from .submission_status_v_2 import SubmissionStatusV2, SubmissionStatusV2_Test, SubmissionStatusV2_Workspace +from .submission_status_v_2 import ( + SubmissionStatusV2, + SubmissionStatusV2_Test, + SubmissionStatusV2_Workspace, +) from .submission_type_enum import SubmissionTypeEnum -from .submission_type_state import SubmissionTypeState, SubmissionTypeState_Test, SubmissionTypeState_Workspace +from .submission_type_state import ( + SubmissionTypeState, + SubmissionTypeState_Test, + SubmissionTypeState_Workspace, +) from .submit_request_v_2 import SubmitRequestV2 from .terminated_response import TerminatedResponse -from .test_case_grade import TestCaseGrade, TestCaseGrade_Hidden, TestCaseGrade_NonHidden +from .test_case_grade import ( + TestCaseGrade, + TestCaseGrade_Hidden, + TestCaseGrade_NonHidden, +) from .test_case_hidden_grade import TestCaseHiddenGrade from .test_case_non_hidden_grade import TestCaseNonHiddenGrade from .test_case_result import TestCaseResult diff --git a/seed/pydantic/trace/src/seed/trace/resources/submission/actual_result.py b/seed/pydantic/trace/src/seed/trace/resources/submission/actual_result.py index 51a401ec348..d1740ac8176 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/submission/actual_result.py +++ b/seed/pydantic/trace/src/seed/trace/resources/submission/actual_result.py @@ -1,12 +1,10 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ...core.pydantic_utilities import UniversalBaseModel import typing - import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 from .exception_v_2 import ExceptionV2 @@ -22,7 +20,9 @@ class ActualResult_Exception(UniversalBaseModel): exception_stacktrace: str = pydantic.Field(alias="exceptionStacktrace") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -34,5 +34,7 @@ class ActualResult_ExceptionV2(UniversalBaseModel): type: typing.Literal["exceptionV2"] = "exceptionV2" -ActualResult = typing.Union[ActualResult_Value, ActualResult_Exception, ActualResult_ExceptionV2] +ActualResult = typing.Union[ + ActualResult_Value, ActualResult_Exception, ActualResult_ExceptionV2 +] from ..commons.variable_value import VariableValue # noqa: E402 diff --git a/seed/pydantic/trace/src/seed/trace/resources/submission/building_executor_response.py b/seed/pydantic/trace/src/seed/trace/resources/submission/building_executor_response.py index be9f49e2ab1..367a4bd82c9 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/submission/building_executor_response.py +++ b/seed/pydantic/trace/src/seed/trace/resources/submission/building_executor_response.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ...core.pydantic_utilities import UniversalBaseModel +from .submission_id import SubmissionId import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .execution_session_status import ExecutionSessionStatus -from .submission_id import SubmissionId +from ...core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class BuildingExecutorResponse(UniversalBaseModel): @@ -14,7 +13,9 @@ class BuildingExecutorResponse(UniversalBaseModel): status: ExecutionSessionStatus if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/submission/code_execution_update.py b/seed/pydantic/trace/src/seed/trace/resources/submission/code_execution_update.py index 654ed4c7d48..c41779ee0e5 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/submission/code_execution_update.py +++ b/seed/pydantic/trace/src/seed/trace/resources/submission/code_execution_update.py @@ -1,24 +1,22 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ...core.pydantic_utilities import UniversalBaseModel import typing - +from .submission_id import SubmissionId import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from ..v_2.resources.problem.test_case_id import TestCaseId -from .error_info import ErrorInfo from .execution_session_status import ExecutionSessionStatus -from .invalid_request_cause import InvalidRequestCause -from .lightweight_stackframe_information import LightweightStackframeInformation +from ...core.pydantic_utilities import IS_PYDANTIC_V2 from .running_submission_state import RunningSubmissionState -from .submission_id import SubmissionId -from .submission_request import SubmissionRequest -from .test_case_grade import TestCaseGrade +from .error_info import ErrorInfo from .test_case_result_with_stdout import TestCaseResultWithStdout -from .traced_file import TracedFile +from ..v_2.resources.problem.test_case_id import TestCaseId +from .test_case_grade import TestCaseGrade from .workspace_run_details import WorkspaceRunDetails +from .lightweight_stackframe_information import LightweightStackframeInformation +from .traced_file import TracedFile +from .submission_request import SubmissionRequest +from .invalid_request_cause import InvalidRequestCause class CodeExecutionUpdate_BuildingExecutor(UniversalBaseModel): @@ -27,7 +25,9 @@ class CodeExecutionUpdate_BuildingExecutor(UniversalBaseModel): status: ExecutionSessionStatus if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -40,7 +40,9 @@ class CodeExecutionUpdate_Running(UniversalBaseModel): state: RunningSubmissionState if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -53,7 +55,9 @@ class CodeExecutionUpdate_Errored(UniversalBaseModel): error_info: ErrorInfo = pydantic.Field(alias="errorInfo") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -65,7 +69,9 @@ class CodeExecutionUpdate_Stopped(UniversalBaseModel): submission_id: SubmissionId = pydantic.Field(alias="submissionId") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -75,10 +81,14 @@ class Config: class CodeExecutionUpdate_Graded(UniversalBaseModel): type: typing.Literal["graded"] = "graded" submission_id: SubmissionId = pydantic.Field(alias="submissionId") - test_cases: typing.Dict[str, TestCaseResultWithStdout] = pydantic.Field(alias="testCases") + test_cases: typing.Dict[str, TestCaseResultWithStdout] = pydantic.Field( + alias="testCases" + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -88,10 +98,14 @@ class Config: class CodeExecutionUpdate_GradedV2(UniversalBaseModel): type: typing.Literal["gradedV2"] = "gradedV2" submission_id: SubmissionId = pydantic.Field(alias="submissionId") - test_cases: typing.Dict[TestCaseId, TestCaseGrade] = pydantic.Field(alias="testCases") + test_cases: typing.Dict[TestCaseId, TestCaseGrade] = pydantic.Field( + alias="testCases" + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -104,7 +118,9 @@ class CodeExecutionUpdate_WorkspaceRan(UniversalBaseModel): run_details: WorkspaceRunDetails = pydantic.Field(alias="runDetails") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -114,13 +130,21 @@ class Config: class CodeExecutionUpdate_Recording(UniversalBaseModel): type: typing.Literal["recording"] = "recording" submission_id: SubmissionId = pydantic.Field(alias="submissionId") - test_case_id: typing.Optional[str] = pydantic.Field(alias="testCaseId", default=None) + test_case_id: typing.Optional[str] = pydantic.Field( + alias="testCaseId", default=None + ) line_number: int = pydantic.Field(alias="lineNumber") - lightweight_stack_info: LightweightStackframeInformation = pydantic.Field(alias="lightweightStackInfo") - traced_file: typing.Optional[TracedFile] = pydantic.Field(alias="tracedFile", default=None) + lightweight_stack_info: LightweightStackframeInformation = pydantic.Field( + alias="lightweightStackInfo" + ) + traced_file: typing.Optional[TracedFile] = pydantic.Field( + alias="tracedFile", default=None + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -131,10 +155,14 @@ class CodeExecutionUpdate_Recorded(UniversalBaseModel): type: typing.Literal["recorded"] = "recorded" submission_id: SubmissionId = pydantic.Field(alias="submissionId") trace_responses_size: int = pydantic.Field(alias="traceResponsesSize") - test_case_id: typing.Optional[str] = pydantic.Field(alias="testCaseId", default=None) + test_case_id: typing.Optional[str] = pydantic.Field( + alias="testCaseId", default=None + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -147,7 +175,9 @@ class CodeExecutionUpdate_InvalidRequest(UniversalBaseModel): cause: InvalidRequestCause if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -159,7 +189,9 @@ class CodeExecutionUpdate_Finished(UniversalBaseModel): submission_id: SubmissionId = pydantic.Field(alias="submissionId") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/submission/compile_error.py b/seed/pydantic/trace/src/seed/trace/resources/submission/compile_error.py index d9a67b21d3c..a4807fd73b3 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/submission/compile_error.py +++ b/seed/pydantic/trace/src/seed/trace/resources/submission/compile_error.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class CompileError(UniversalBaseModel): message: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/submission/custom_test_cases_unsupported.py b/seed/pydantic/trace/src/seed/trace/resources/submission/custom_test_cases_unsupported.py index 3bfe597fa5c..d9d3be8da71 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/submission/custom_test_cases_unsupported.py +++ b/seed/pydantic/trace/src/seed/trace/resources/submission/custom_test_cases_unsupported.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ...core.pydantic_utilities import UniversalBaseModel from ..commons.problem_id import ProblemId +import pydantic from .submission_id import SubmissionId +from ...core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class CustomTestCasesUnsupported(UniversalBaseModel): @@ -14,7 +13,9 @@ class CustomTestCasesUnsupported(UniversalBaseModel): submission_id: SubmissionId = pydantic.Field(alias="submissionId") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/submission/error_info.py b/seed/pydantic/trace/src/seed/trace/resources/submission/error_info.py index 3a010c883c1..55f68bc882c 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/submission/error_info.py +++ b/seed/pydantic/trace/src/seed/trace/resources/submission/error_info.py @@ -1,12 +1,10 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ...core.pydantic_utilities import UniversalBaseModel import typing - +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .exception_info import ExceptionInfo @@ -15,7 +13,9 @@ class ErrorInfo_CompileError(UniversalBaseModel): message: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -27,7 +27,9 @@ class ErrorInfo_RuntimeError(UniversalBaseModel): message: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -39,11 +41,15 @@ class ErrorInfo_InternalError(UniversalBaseModel): exception_info: ExceptionInfo = pydantic.Field(alias="exceptionInfo") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: extra = pydantic.Extra.allow -ErrorInfo = typing.Union[ErrorInfo_CompileError, ErrorInfo_RuntimeError, ErrorInfo_InternalError] +ErrorInfo = typing.Union[ + ErrorInfo_CompileError, ErrorInfo_RuntimeError, ErrorInfo_InternalError +] diff --git a/seed/pydantic/trace/src/seed/trace/resources/submission/errored_response.py b/seed/pydantic/trace/src/seed/trace/resources/submission/errored_response.py index c4eeee1e86c..ab46d5605b5 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/submission/errored_response.py +++ b/seed/pydantic/trace/src/seed/trace/resources/submission/errored_response.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ...core.pydantic_utilities import UniversalBaseModel +from .submission_id import SubmissionId import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .error_info import ErrorInfo -from .submission_id import SubmissionId +from ...core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class ErroredResponse(UniversalBaseModel): @@ -14,7 +13,9 @@ class ErroredResponse(UniversalBaseModel): error_info: ErrorInfo = pydantic.Field(alias="errorInfo") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/submission/exception_info.py b/seed/pydantic/trace/src/seed/trace/resources/submission/exception_info.py index 78a2b3b79e5..d0df13db267 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/submission/exception_info.py +++ b/seed/pydantic/trace/src/seed/trace/resources/submission/exception_info.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ...core.pydantic_utilities import UniversalBaseModel import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class ExceptionInfo(UniversalBaseModel): @@ -13,7 +12,9 @@ class ExceptionInfo(UniversalBaseModel): exception_stacktrace: str = pydantic.Field(alias="exceptionStacktrace") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/submission/exception_v_2.py b/seed/pydantic/trace/src/seed/trace/resources/submission/exception_v_2.py index c47c1a753e3..5d07cefcbd6 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/submission/exception_v_2.py +++ b/seed/pydantic/trace/src/seed/trace/resources/submission/exception_v_2.py @@ -1,12 +1,10 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ...core.pydantic_utilities import UniversalBaseModel import typing - import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 class ExceptionV2_Generic(UniversalBaseModel): @@ -16,7 +14,9 @@ class ExceptionV2_Generic(UniversalBaseModel): exception_stacktrace: str = pydantic.Field(alias="exceptionStacktrace") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -27,7 +27,9 @@ class ExceptionV2_Timeout(UniversalBaseModel): type: typing.Literal["timeout"] = "timeout" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/submission/execution_session_response.py b/seed/pydantic/trace/src/seed/trace/resources/submission/execution_session_response.py index 36c54ced5bd..fa42c41653c 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/submission/execution_session_response.py +++ b/seed/pydantic/trace/src/seed/trace/resources/submission/execution_session_response.py @@ -1,22 +1,25 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ...core.pydantic_utilities import UniversalBaseModel import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +import typing from ..commons.language import Language from .execution_session_status import ExecutionSessionStatus +from ...core.pydantic_utilities import IS_PYDANTIC_V2 class ExecutionSessionResponse(UniversalBaseModel): session_id: str = pydantic.Field(alias="sessionId") - execution_session_url: typing.Optional[str] = pydantic.Field(alias="executionSessionUrl", default=None) + execution_session_url: typing.Optional[str] = pydantic.Field( + alias="executionSessionUrl", default=None + ) language: Language status: ExecutionSessionStatus if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/submission/execution_session_state.py b/seed/pydantic/trace/src/seed/trace/resources/submission/execution_session_state.py index 048053cabf0..175668936e0 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/submission/execution_session_state.py +++ b/seed/pydantic/trace/src/seed/trace/resources/submission/execution_session_state.py @@ -1,16 +1,17 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel import typing - import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from ..commons.language import Language from .execution_session_status import ExecutionSessionStatus +from ...core.pydantic_utilities import IS_PYDANTIC_V2 class ExecutionSessionState(UniversalBaseModel): - last_time_contacted: typing.Optional[str] = pydantic.Field(alias="lastTimeContacted", default=None) + last_time_contacted: typing.Optional[str] = pydantic.Field( + alias="lastTimeContacted", default=None + ) session_id: str = pydantic.Field(alias="sessionId") """ The auto-generated session id. Formatted as a uuid. @@ -22,7 +23,9 @@ class ExecutionSessionState(UniversalBaseModel): status: ExecutionSessionStatus if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/submission/existing_submission_executing.py b/seed/pydantic/trace/src/seed/trace/resources/submission/existing_submission_executing.py index c84c07a1a64..146065adb7e 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/submission/existing_submission_executing.py +++ b/seed/pydantic/trace/src/seed/trace/resources/submission/existing_submission_executing.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ...core.pydantic_utilities import UniversalBaseModel from .submission_id import SubmissionId +import pydantic +from ...core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class ExistingSubmissionExecuting(UniversalBaseModel): submission_id: SubmissionId = pydantic.Field(alias="submissionId") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/submission/expression_location.py b/seed/pydantic/trace/src/seed/trace/resources/submission/expression_location.py index dab6ded3f7a..0459ba7bc3f 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/submission/expression_location.py +++ b/seed/pydantic/trace/src/seed/trace/resources/submission/expression_location.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class ExpressionLocation(UniversalBaseModel): start: int offset: int if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/submission/finished_response.py b/seed/pydantic/trace/src/seed/trace/resources/submission/finished_response.py index b3f4c4f162f..172191317d8 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/submission/finished_response.py +++ b/seed/pydantic/trace/src/seed/trace/resources/submission/finished_response.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ...core.pydantic_utilities import UniversalBaseModel from .submission_id import SubmissionId +import pydantic +from ...core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class FinishedResponse(UniversalBaseModel): submission_id: SubmissionId = pydantic.Field(alias="submissionId") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/submission/get_execution_session_state_response.py b/seed/pydantic/trace/src/seed/trace/resources/submission/get_execution_session_state_response.py index f84faabcbb7..3a6addd72ef 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/submission/get_execution_session_state_response.py +++ b/seed/pydantic/trace/src/seed/trace/resources/submission/get_execution_session_state_response.py @@ -1,20 +1,23 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .execution_session_state import ExecutionSessionState +import pydantic +from ...core.pydantic_utilities import IS_PYDANTIC_V2 class GetExecutionSessionStateResponse(UniversalBaseModel): states: typing.Dict[str, ExecutionSessionState] - num_warming_instances: typing.Optional[int] = pydantic.Field(alias="numWarmingInstances", default=None) + num_warming_instances: typing.Optional[int] = pydantic.Field( + alias="numWarmingInstances", default=None + ) warming_session_ids: typing.List[str] = pydantic.Field(alias="warmingSessionIds") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/submission/get_submission_state_response.py b/seed/pydantic/trace/src/seed/trace/resources/submission/get_submission_state_response.py index 09ae95ee7f0..1ab14a58be0 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/submission/get_submission_state_response.py +++ b/seed/pydantic/trace/src/seed/trace/resources/submission/get_submission_state_response.py @@ -1,23 +1,28 @@ # This file was auto-generated by Fern from our API Definition. -import datetime as dt +from ...core.pydantic_utilities import UniversalBaseModel import typing - +import datetime as dt import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from ..commons.language import Language from .submission_type_state import SubmissionTypeState +from ...core.pydantic_utilities import IS_PYDANTIC_V2 class GetSubmissionStateResponse(UniversalBaseModel): - time_submitted: typing.Optional[dt.datetime] = pydantic.Field(alias="timeSubmitted", default=None) + time_submitted: typing.Optional[dt.datetime] = pydantic.Field( + alias="timeSubmitted", default=None + ) submission: str language: Language - submission_type_state: SubmissionTypeState = pydantic.Field(alias="submissionTypeState") + submission_type_state: SubmissionTypeState = pydantic.Field( + alias="submissionTypeState" + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/submission/get_trace_responses_page_request.py b/seed/pydantic/trace/src/seed/trace/resources/submission/get_trace_responses_page_request.py index 901ed90d1b3..cada0bed724 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/submission/get_trace_responses_page_request.py +++ b/seed/pydantic/trace/src/seed/trace/resources/submission/get_trace_responses_page_request.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel import typing - +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class GetTraceResponsesPageRequest(UniversalBaseModel): offset: typing.Optional[int] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/submission/graded_response.py b/seed/pydantic/trace/src/seed/trace/resources/submission/graded_response.py index 80a89c27f1c..ae1ee6c2613 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/submission/graded_response.py +++ b/seed/pydantic/trace/src/seed/trace/resources/submission/graded_response.py @@ -1,20 +1,23 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ...core.pydantic_utilities import UniversalBaseModel from .submission_id import SubmissionId +import pydantic +import typing from .test_case_result_with_stdout import TestCaseResultWithStdout +from ...core.pydantic_utilities import IS_PYDANTIC_V2 class GradedResponse(UniversalBaseModel): submission_id: SubmissionId = pydantic.Field(alias="submissionId") - test_cases: typing.Dict[str, TestCaseResultWithStdout] = pydantic.Field(alias="testCases") + test_cases: typing.Dict[str, TestCaseResultWithStdout] = pydantic.Field( + alias="testCases" + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/submission/graded_response_v_2.py b/seed/pydantic/trace/src/seed/trace/resources/submission/graded_response_v_2.py index 3458c2c8976..7a86f20d71d 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/submission/graded_response_v_2.py +++ b/seed/pydantic/trace/src/seed/trace/resources/submission/graded_response_v_2.py @@ -1,21 +1,24 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ...core.pydantic_utilities import UniversalBaseModel +from .submission_id import SubmissionId import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +import typing from ..v_2.resources.problem.test_case_id import TestCaseId -from .submission_id import SubmissionId from .test_case_grade import TestCaseGrade +from ...core.pydantic_utilities import IS_PYDANTIC_V2 class GradedResponseV2(UniversalBaseModel): submission_id: SubmissionId = pydantic.Field(alias="submissionId") - test_cases: typing.Dict[TestCaseId, TestCaseGrade] = pydantic.Field(alias="testCases") + test_cases: typing.Dict[TestCaseId, TestCaseGrade] = pydantic.Field( + alias="testCases" + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/submission/graded_test_case_update.py b/seed/pydantic/trace/src/seed/trace/resources/submission/graded_test_case_update.py index ed4d643fe5e..307b90569a5 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/submission/graded_test_case_update.py +++ b/seed/pydantic/trace/src/seed/trace/resources/submission/graded_test_case_update.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ...core.pydantic_utilities import UniversalBaseModel from ..v_2.resources.problem.test_case_id import TestCaseId +import pydantic from .test_case_grade import TestCaseGrade +from ...core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class GradedTestCaseUpdate(UniversalBaseModel): @@ -14,7 +13,9 @@ class GradedTestCaseUpdate(UniversalBaseModel): grade: TestCaseGrade if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/submission/initialize_problem_request.py b/seed/pydantic/trace/src/seed/trace/resources/submission/initialize_problem_request.py index 1cebd620107..63e1d06c392 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/submission/initialize_problem_request.py +++ b/seed/pydantic/trace/src/seed/trace/resources/submission/initialize_problem_request.py @@ -1,19 +1,22 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ...core.pydantic_utilities import UniversalBaseModel from ..commons.problem_id import ProblemId +import pydantic +import typing +from ...core.pydantic_utilities import IS_PYDANTIC_V2 class InitializeProblemRequest(UniversalBaseModel): problem_id: ProblemId = pydantic.Field(alias="problemId") - problem_version: typing.Optional[int] = pydantic.Field(alias="problemVersion", default=None) + problem_version: typing.Optional[int] = pydantic.Field( + alias="problemVersion", default=None + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/submission/internal_error.py b/seed/pydantic/trace/src/seed/trace/resources/submission/internal_error.py index e471f2c2aad..5537e4752ae 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/submission/internal_error.py +++ b/seed/pydantic/trace/src/seed/trace/resources/submission/internal_error.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ...core.pydantic_utilities import UniversalBaseModel from .exception_info import ExceptionInfo +import pydantic +from ...core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class InternalError(UniversalBaseModel): exception_info: ExceptionInfo = pydantic.Field(alias="exceptionInfo") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/submission/invalid_request_cause.py b/seed/pydantic/trace/src/seed/trace/resources/submission/invalid_request_cause.py index 028a2544abc..e0e96075aab 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/submission/invalid_request_cause.py +++ b/seed/pydantic/trace/src/seed/trace/resources/submission/invalid_request_cause.py @@ -1,15 +1,13 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ...core.pydantic_utilities import UniversalBaseModel import typing - +from .submission_id import SubmissionId import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from ..commons.language import Language +from ...core.pydantic_utilities import IS_PYDANTIC_V2 from ..commons.problem_id import ProblemId -from .submission_id import SubmissionId +from ..commons.language import Language class InvalidRequestCause_SubmissionIdNotFound(UniversalBaseModel): @@ -17,7 +15,9 @@ class InvalidRequestCause_SubmissionIdNotFound(UniversalBaseModel): missing_submission_id: SubmissionId = pydantic.Field(alias="missingSubmissionId") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -30,7 +30,9 @@ class InvalidRequestCause_CustomTestCasesUnsupported(UniversalBaseModel): submission_id: SubmissionId = pydantic.Field(alias="submissionId") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -43,7 +45,9 @@ class InvalidRequestCause_UnexpectedLanguage(UniversalBaseModel): actual_language: Language = pydantic.Field(alias="actualLanguage") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/submission/invalid_request_response.py b/seed/pydantic/trace/src/seed/trace/resources/submission/invalid_request_response.py index ed791f8300b..a4752f46e59 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/submission/invalid_request_response.py +++ b/seed/pydantic/trace/src/seed/trace/resources/submission/invalid_request_response.py @@ -1,20 +1,21 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from .submission_request import SubmissionRequest +from .invalid_request_cause import InvalidRequestCause +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .invalid_request_cause import InvalidRequestCause -from .submission_request import SubmissionRequest - class InvalidRequestResponse(UniversalBaseModel): request: SubmissionRequest cause: InvalidRequestCause if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/submission/lightweight_stackframe_information.py b/seed/pydantic/trace/src/seed/trace/resources/submission/lightweight_stackframe_information.py index 773ead74919..6ca26e2c443 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/submission/lightweight_stackframe_information.py +++ b/seed/pydantic/trace/src/seed/trace/resources/submission/lightweight_stackframe_information.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ...core.pydantic_utilities import UniversalBaseModel import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class LightweightStackframeInformation(UniversalBaseModel): @@ -12,7 +11,9 @@ class LightweightStackframeInformation(UniversalBaseModel): top_stack_frame_method_name: str = pydantic.Field(alias="topStackFrameMethodName") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/submission/recorded_response_notification.py b/seed/pydantic/trace/src/seed/trace/resources/submission/recorded_response_notification.py index c48371340b9..b32a692b743 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/submission/recorded_response_notification.py +++ b/seed/pydantic/trace/src/seed/trace/resources/submission/recorded_response_notification.py @@ -1,20 +1,23 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ...core.pydantic_utilities import UniversalBaseModel from .submission_id import SubmissionId +import pydantic +import typing +from ...core.pydantic_utilities import IS_PYDANTIC_V2 class RecordedResponseNotification(UniversalBaseModel): submission_id: SubmissionId = pydantic.Field(alias="submissionId") trace_responses_size: int = pydantic.Field(alias="traceResponsesSize") - test_case_id: typing.Optional[str] = pydantic.Field(alias="testCaseId", default=None) + test_case_id: typing.Optional[str] = pydantic.Field( + alias="testCaseId", default=None + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/submission/recorded_test_case_update.py b/seed/pydantic/trace/src/seed/trace/resources/submission/recorded_test_case_update.py index 7cf9ce31c49..220aa5706f8 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/submission/recorded_test_case_update.py +++ b/seed/pydantic/trace/src/seed/trace/resources/submission/recorded_test_case_update.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ...core.pydantic_utilities import UniversalBaseModel from ..v_2.resources.problem.test_case_id import TestCaseId +import pydantic +from ...core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class RecordedTestCaseUpdate(UniversalBaseModel): @@ -13,7 +12,9 @@ class RecordedTestCaseUpdate(UniversalBaseModel): trace_responses_size: int = pydantic.Field(alias="traceResponsesSize") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/submission/recording_response_notification.py b/seed/pydantic/trace/src/seed/trace/resources/submission/recording_response_notification.py index 56c239397e4..8ddb5e7deda 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/submission/recording_response_notification.py +++ b/seed/pydantic/trace/src/seed/trace/resources/submission/recording_response_notification.py @@ -1,24 +1,31 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ...core.pydantic_utilities import UniversalBaseModel +from .submission_id import SubmissionId import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +import typing from .lightweight_stackframe_information import LightweightStackframeInformation -from .submission_id import SubmissionId from .traced_file import TracedFile +from ...core.pydantic_utilities import IS_PYDANTIC_V2 class RecordingResponseNotification(UniversalBaseModel): submission_id: SubmissionId = pydantic.Field(alias="submissionId") - test_case_id: typing.Optional[str] = pydantic.Field(alias="testCaseId", default=None) + test_case_id: typing.Optional[str] = pydantic.Field( + alias="testCaseId", default=None + ) line_number: int = pydantic.Field(alias="lineNumber") - lightweight_stack_info: LightweightStackframeInformation = pydantic.Field(alias="lightweightStackInfo") - traced_file: typing.Optional[TracedFile] = pydantic.Field(alias="tracedFile", default=None) + lightweight_stack_info: LightweightStackframeInformation = pydantic.Field( + alias="lightweightStackInfo" + ) + traced_file: typing.Optional[TracedFile] = pydantic.Field( + alias="tracedFile", default=None + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/submission/running_response.py b/seed/pydantic/trace/src/seed/trace/resources/submission/running_response.py index 1b9744368b4..277467dd7d6 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/submission/running_response.py +++ b/seed/pydantic/trace/src/seed/trace/resources/submission/running_response.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ...core.pydantic_utilities import UniversalBaseModel +from .submission_id import SubmissionId import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .running_submission_state import RunningSubmissionState -from .submission_id import SubmissionId +from ...core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class RunningResponse(UniversalBaseModel): @@ -14,7 +13,9 @@ class RunningResponse(UniversalBaseModel): state: RunningSubmissionState if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/submission/runtime_error.py b/seed/pydantic/trace/src/seed/trace/resources/submission/runtime_error.py index 7f0222dd156..9ac51354879 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/submission/runtime_error.py +++ b/seed/pydantic/trace/src/seed/trace/resources/submission/runtime_error.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class RuntimeError(UniversalBaseModel): message: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/submission/scope.py b/seed/pydantic/trace/src/seed/trace/resources/submission/scope.py index cfa9fdfd32b..cf1cd0f4225 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/submission/scope.py +++ b/seed/pydantic/trace/src/seed/trace/resources/submission/scope.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from ..commons.debug_variable_value import DebugVariableValue +from ...core.pydantic_utilities import IS_PYDANTIC_V2 +import pydantic class Scope(UniversalBaseModel): variables: typing.Dict[str, DebugVariableValue] if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/submission/stack_frame.py b/seed/pydantic/trace/src/seed/trace/resources/submission/stack_frame.py index e1b6ecf1936..dcd93cebe59 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/submission/stack_frame.py +++ b/seed/pydantic/trace/src/seed/trace/resources/submission/stack_frame.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ...core.pydantic_utilities import UniversalBaseModel import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +import typing from .scope import Scope +from ...core.pydantic_utilities import IS_PYDANTIC_V2 class StackFrame(UniversalBaseModel): @@ -14,7 +13,9 @@ class StackFrame(UniversalBaseModel): scopes: typing.List[Scope] if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/submission/stack_information.py b/seed/pydantic/trace/src/seed/trace/resources/submission/stack_information.py index 4db73c92ea1..c2e855ceba5 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/submission/stack_information.py +++ b/seed/pydantic/trace/src/seed/trace/resources/submission/stack_information.py @@ -1,19 +1,22 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ...core.pydantic_utilities import UniversalBaseModel import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +import typing from .stack_frame import StackFrame +from ...core.pydantic_utilities import IS_PYDANTIC_V2 class StackInformation(UniversalBaseModel): num_stack_frames: int = pydantic.Field(alias="numStackFrames") - top_stack_frame: typing.Optional[StackFrame] = pydantic.Field(alias="topStackFrame", default=None) + top_stack_frame: typing.Optional[StackFrame] = pydantic.Field( + alias="topStackFrame", default=None + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/submission/stderr_response.py b/seed/pydantic/trace/src/seed/trace/resources/submission/stderr_response.py index bd723a5ea26..c24fcf1e2ad 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/submission/stderr_response.py +++ b/seed/pydantic/trace/src/seed/trace/resources/submission/stderr_response.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ...core.pydantic_utilities import UniversalBaseModel from .submission_id import SubmissionId +import pydantic +from ...core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class StderrResponse(UniversalBaseModel): @@ -13,7 +12,9 @@ class StderrResponse(UniversalBaseModel): stderr: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/submission/stdout_response.py b/seed/pydantic/trace/src/seed/trace/resources/submission/stdout_response.py index 6870ead6050..6091a57824c 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/submission/stdout_response.py +++ b/seed/pydantic/trace/src/seed/trace/resources/submission/stdout_response.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ...core.pydantic_utilities import UniversalBaseModel from .submission_id import SubmissionId +import pydantic +from ...core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class StdoutResponse(UniversalBaseModel): @@ -13,7 +12,9 @@ class StdoutResponse(UniversalBaseModel): stdout: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/submission/stop_request.py b/seed/pydantic/trace/src/seed/trace/resources/submission/stop_request.py index 3ad23fe2c7e..1341573fd4d 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/submission/stop_request.py +++ b/seed/pydantic/trace/src/seed/trace/resources/submission/stop_request.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ...core.pydantic_utilities import UniversalBaseModel from .submission_id import SubmissionId +import pydantic +from ...core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class StopRequest(UniversalBaseModel): submission_id: SubmissionId = pydantic.Field(alias="submissionId") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/submission/stopped_response.py b/seed/pydantic/trace/src/seed/trace/resources/submission/stopped_response.py index 9af93a907e4..3c096a95687 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/submission/stopped_response.py +++ b/seed/pydantic/trace/src/seed/trace/resources/submission/stopped_response.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ...core.pydantic_utilities import UniversalBaseModel from .submission_id import SubmissionId +import pydantic +from ...core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class StoppedResponse(UniversalBaseModel): submission_id: SubmissionId = pydantic.Field(alias="submissionId") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/submission/submission_file_info.py b/seed/pydantic/trace/src/seed/trace/resources/submission/submission_file_info.py index bc72c487363..ace6a22f9ff 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/submission/submission_file_info.py +++ b/seed/pydantic/trace/src/seed/trace/resources/submission/submission_file_info.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class SubmissionFileInfo(UniversalBaseModel): directory: str @@ -13,7 +12,9 @@ class SubmissionFileInfo(UniversalBaseModel): contents: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/submission/submission_id_not_found.py b/seed/pydantic/trace/src/seed/trace/resources/submission/submission_id_not_found.py index 0d954b3ad85..0f1fd90447f 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/submission/submission_id_not_found.py +++ b/seed/pydantic/trace/src/seed/trace/resources/submission/submission_id_not_found.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ...core.pydantic_utilities import UniversalBaseModel from .submission_id import SubmissionId +import pydantic +from ...core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class SubmissionIdNotFound(UniversalBaseModel): missing_submission_id: SubmissionId = pydantic.Field(alias="missingSubmissionId") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/submission/submission_request.py b/seed/pydantic/trace/src/seed/trace/resources/submission/submission_request.py index 97165b12931..d94a6cf88fd 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/submission/submission_request.py +++ b/seed/pydantic/trace/src/seed/trace/resources/submission/submission_request.py @@ -1,25 +1,27 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ...core.pydantic_utilities import UniversalBaseModel import typing - +from ..commons.problem_id import ProblemId import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 +from .submission_id import SubmissionId from ..commons.language import Language -from ..commons.problem_id import ProblemId from .submission_file_info import SubmissionFileInfo -from .submission_id import SubmissionId class SubmissionRequest_InitializeProblemRequest(UniversalBaseModel): type: typing.Literal["initializeProblemRequest"] = "initializeProblemRequest" problem_id: ProblemId = pydantic.Field(alias="problemId") - problem_version: typing.Optional[int] = pydantic.Field(alias="problemVersion", default=None) + problem_version: typing.Optional[int] = pydantic.Field( + alias="problemVersion", default=None + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -30,7 +32,9 @@ class SubmissionRequest_InitializeWorkspaceRequest(UniversalBaseModel): type: typing.Literal["initializeWorkspaceRequest"] = "initializeWorkspaceRequest" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -41,13 +45,19 @@ class SubmissionRequest_SubmitV2(UniversalBaseModel): type: typing.Literal["submitV2"] = "submitV2" submission_id: SubmissionId = pydantic.Field(alias="submissionId") language: Language - submission_files: typing.List[SubmissionFileInfo] = pydantic.Field(alias="submissionFiles") + submission_files: typing.List[SubmissionFileInfo] = pydantic.Field( + alias="submissionFiles" + ) problem_id: ProblemId = pydantic.Field(alias="problemId") - problem_version: typing.Optional[int] = pydantic.Field(alias="problemVersion", default=None) + problem_version: typing.Optional[int] = pydantic.Field( + alias="problemVersion", default=None + ) user_id: typing.Optional[str] = pydantic.Field(alias="userId", default=None) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -58,11 +68,15 @@ class SubmissionRequest_WorkspaceSubmit(UniversalBaseModel): type: typing.Literal["workspaceSubmit"] = "workspaceSubmit" submission_id: SubmissionId = pydantic.Field(alias="submissionId") language: Language - submission_files: typing.List[SubmissionFileInfo] = pydantic.Field(alias="submissionFiles") + submission_files: typing.List[SubmissionFileInfo] = pydantic.Field( + alias="submissionFiles" + ) user_id: typing.Optional[str] = pydantic.Field(alias="userId", default=None) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -74,7 +88,9 @@ class SubmissionRequest_Stop(UniversalBaseModel): submission_id: SubmissionId = pydantic.Field(alias="submissionId") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/submission/submission_response.py b/seed/pydantic/trace/src/seed/trace/resources/submission/submission_response.py index ccd1780b251..c3d0e1a6fc2 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/submission/submission_response.py +++ b/seed/pydantic/trace/src/seed/trace/resources/submission/submission_response.py @@ -1,12 +1,10 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ...core.pydantic_utilities import UniversalBaseModel import typing - +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from ..commons.problem_id import ProblemId from .code_execution_update import CodeExecutionUpdate @@ -15,7 +13,9 @@ class SubmissionResponse_ServerInitialized(UniversalBaseModel): type: typing.Literal["serverInitialized"] = "serverInitialized" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -31,7 +31,9 @@ class SubmissionResponse_WorkspaceInitialized(UniversalBaseModel): type: typing.Literal["workspaceInitialized"] = "workspaceInitialized" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -45,7 +47,9 @@ class SubmissionResponse_ServerErrored(UniversalBaseModel): exception_stacktrace: str = pydantic.Field(alias="exceptionStacktrace") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -61,7 +65,9 @@ class SubmissionResponse_Terminated(UniversalBaseModel): type: typing.Literal["terminated"] = "terminated" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/submission/submission_status_for_test_case.py b/seed/pydantic/trace/src/seed/trace/resources/submission/submission_status_for_test_case.py index cf4e4c952b5..37ad7741503 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/submission/submission_status_for_test_case.py +++ b/seed/pydantic/trace/src/seed/trace/resources/submission/submission_status_for_test_case.py @@ -1,14 +1,12 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ...core.pydantic_utilities import UniversalBaseModel import typing - +from .test_case_result import TestCaseResult +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .test_case_grade import TestCaseGrade -from .test_case_result import TestCaseResult from .test_case_result_with_stdout import TestCaseResultWithStdout @@ -18,7 +16,9 @@ class SubmissionStatusForTestCase_Graded(UniversalBaseModel): stdout: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -36,7 +36,9 @@ class SubmissionStatusForTestCase_Traced(UniversalBaseModel): trace_responses_size: int = pydantic.Field(alias="traceResponsesSize") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -44,5 +46,7 @@ class Config: SubmissionStatusForTestCase = typing.Union[ - SubmissionStatusForTestCase_Graded, SubmissionStatusForTestCase_GradedV2, SubmissionStatusForTestCase_Traced + SubmissionStatusForTestCase_Graded, + SubmissionStatusForTestCase_GradedV2, + SubmissionStatusForTestCase_Traced, ] diff --git a/seed/pydantic/trace/src/seed/trace/resources/submission/submission_status_v_2.py b/seed/pydantic/trace/src/seed/trace/resources/submission/submission_status_v_2.py index b7406aeb24d..77e3fe0a73c 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/submission/submission_status_v_2.py +++ b/seed/pydantic/trace/src/seed/trace/resources/submission/submission_status_v_2.py @@ -1,15 +1,13 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ...core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from .test_submission_update import TestSubmissionUpdate from ..commons.problem_id import ProblemId +import pydantic from ..v_2.resources.problem.problem_info_v_2 import ProblemInfoV2 -from .test_submission_update import TestSubmissionUpdate +from ...core.pydantic_utilities import IS_PYDANTIC_V2 from .workspace_submission_update import WorkspaceSubmissionUpdate @@ -21,7 +19,9 @@ class SubmissionStatusV2_Test(UniversalBaseModel): problem_info: ProblemInfoV2 = pydantic.Field(alias="problemInfo") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -33,7 +33,9 @@ class SubmissionStatusV2_Workspace(UniversalBaseModel): updates: typing.List[WorkspaceSubmissionUpdate] if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/submission/submission_type_state.py b/seed/pydantic/trace/src/seed/trace/resources/submission/submission_type_state.py index c9725f6a039..6ce95a2c8df 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/submission/submission_type_state.py +++ b/seed/pydantic/trace/src/seed/trace/resources/submission/submission_type_state.py @@ -1,15 +1,13 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ...core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from ..commons.problem_id import ProblemId +import pydantic from ..commons.test_case import TestCase from .test_submission_status import TestSubmissionStatus +from ...core.pydantic_utilities import IS_PYDANTIC_V2 from .workspace_submission_status import WorkspaceSubmissionStatus @@ -21,7 +19,9 @@ class SubmissionTypeState_Test(UniversalBaseModel): status: TestSubmissionStatus if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -33,11 +33,15 @@ class SubmissionTypeState_Workspace(UniversalBaseModel): status: WorkspaceSubmissionStatus if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: extra = pydantic.Extra.allow -SubmissionTypeState = typing.Union[SubmissionTypeState_Test, SubmissionTypeState_Workspace] +SubmissionTypeState = typing.Union[ + SubmissionTypeState_Test, SubmissionTypeState_Workspace +] diff --git a/seed/pydantic/trace/src/seed/trace/resources/submission/submit_request_v_2.py b/seed/pydantic/trace/src/seed/trace/resources/submission/submit_request_v_2.py index 574d0995740..c6f3f91561a 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/submission/submit_request_v_2.py +++ b/seed/pydantic/trace/src/seed/trace/resources/submission/submit_request_v_2.py @@ -1,26 +1,31 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ...core.pydantic_utilities import UniversalBaseModel +from .submission_id import SubmissionId import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from ..commons.language import Language -from ..commons.problem_id import ProblemId +import typing from .submission_file_info import SubmissionFileInfo -from .submission_id import SubmissionId +from ..commons.problem_id import ProblemId +from ...core.pydantic_utilities import IS_PYDANTIC_V2 class SubmitRequestV2(UniversalBaseModel): submission_id: SubmissionId = pydantic.Field(alias="submissionId") language: Language - submission_files: typing.List[SubmissionFileInfo] = pydantic.Field(alias="submissionFiles") + submission_files: typing.List[SubmissionFileInfo] = pydantic.Field( + alias="submissionFiles" + ) problem_id: ProblemId = pydantic.Field(alias="problemId") - problem_version: typing.Optional[int] = pydantic.Field(alias="problemVersion", default=None) + problem_version: typing.Optional[int] = pydantic.Field( + alias="problemVersion", default=None + ) user_id: typing.Optional[str] = pydantic.Field(alias="userId", default=None) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/submission/terminated_response.py b/seed/pydantic/trace/src/seed/trace/resources/submission/terminated_response.py index 78a4e3829ba..bed0f106a31 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/submission/terminated_response.py +++ b/seed/pydantic/trace/src/seed/trace/resources/submission/terminated_response.py @@ -1,15 +1,16 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class TerminatedResponse(UniversalBaseModel): if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/submission/test_case_grade.py b/seed/pydantic/trace/src/seed/trace/resources/submission/test_case_grade.py index 75db0c767d9..12c6d0b65d7 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/submission/test_case_grade.py +++ b/seed/pydantic/trace/src/seed/trace/resources/submission/test_case_grade.py @@ -1,12 +1,10 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ...core.pydantic_utilities import UniversalBaseModel import typing - +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from ..commons.variable_value import VariableValue from .exception_v_2 import ExceptionV2 @@ -16,7 +14,9 @@ class TestCaseGrade_Hidden(UniversalBaseModel): passed: bool if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -26,12 +26,16 @@ class Config: class TestCaseGrade_NonHidden(UniversalBaseModel): type: typing.Literal["nonHidden"] = "nonHidden" passed: bool - actual_result: typing.Optional[VariableValue] = pydantic.Field(alias="actualResult", default=None) + actual_result: typing.Optional[VariableValue] = pydantic.Field( + alias="actualResult", default=None + ) exception: typing.Optional[ExceptionV2] = None stdout: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/submission/test_case_hidden_grade.py b/seed/pydantic/trace/src/seed/trace/resources/submission/test_case_hidden_grade.py index a8250bcf5a1..fb640cccd9f 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/submission/test_case_hidden_grade.py +++ b/seed/pydantic/trace/src/seed/trace/resources/submission/test_case_hidden_grade.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class TestCaseHiddenGrade(UniversalBaseModel): passed: bool if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/submission/test_case_non_hidden_grade.py b/seed/pydantic/trace/src/seed/trace/resources/submission/test_case_non_hidden_grade.py index c533c9d6315..75b1a4f54b9 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/submission/test_case_non_hidden_grade.py +++ b/seed/pydantic/trace/src/seed/trace/resources/submission/test_case_non_hidden_grade.py @@ -1,22 +1,25 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from ..commons.variable_value import VariableValue +import pydantic from .exception_v_2 import ExceptionV2 +from ...core.pydantic_utilities import IS_PYDANTIC_V2 class TestCaseNonHiddenGrade(UniversalBaseModel): passed: bool - actual_result: typing.Optional[VariableValue] = pydantic.Field(alias="actualResult", default=None) + actual_result: typing.Optional[VariableValue] = pydantic.Field( + alias="actualResult", default=None + ) exception: typing.Optional[ExceptionV2] = None stdout: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/submission/test_case_result.py b/seed/pydantic/trace/src/seed/trace/resources/submission/test_case_result.py index 272b4efb6fb..d7d8eb4fb5a 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/submission/test_case_result.py +++ b/seed/pydantic/trace/src/seed/trace/resources/submission/test_case_result.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ...core.pydantic_utilities import UniversalBaseModel from ..commons.variable_value import VariableValue +import pydantic from .actual_result import ActualResult +from ...core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class TestCaseResult(UniversalBaseModel): @@ -15,7 +14,9 @@ class TestCaseResult(UniversalBaseModel): passed: bool if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/submission/test_case_result_with_stdout.py b/seed/pydantic/trace/src/seed/trace/resources/submission/test_case_result_with_stdout.py index c974cf1c054..2b418d107fe 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/submission/test_case_result_with_stdout.py +++ b/seed/pydantic/trace/src/seed/trace/resources/submission/test_case_result_with_stdout.py @@ -1,19 +1,20 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from .test_case_result import TestCaseResult +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .test_case_result import TestCaseResult - class TestCaseResultWithStdout(UniversalBaseModel): result: TestCaseResult stdout: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/submission/test_submission_state.py b/seed/pydantic/trace/src/seed/trace/resources/submission/test_submission_state.py index 46cb5447e5b..971cc91181f 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/submission/test_submission_state.py +++ b/seed/pydantic/trace/src/seed/trace/resources/submission/test_submission_state.py @@ -1,13 +1,12 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ...core.pydantic_utilities import UniversalBaseModel from ..commons.problem_id import ProblemId +import pydantic +import typing from ..commons.test_case import TestCase from .test_submission_status import TestSubmissionStatus +from ...core.pydantic_utilities import IS_PYDANTIC_V2 class TestSubmissionState(UniversalBaseModel): @@ -17,7 +16,9 @@ class TestSubmissionState(UniversalBaseModel): status: TestSubmissionStatus if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/submission/test_submission_status.py b/seed/pydantic/trace/src/seed/trace/resources/submission/test_submission_status.py index 700963baded..cfe74d1d138 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/submission/test_submission_status.py +++ b/seed/pydantic/trace/src/seed/trace/resources/submission/test_submission_status.py @@ -1,38 +1,38 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ...core.pydantic_utilities import UniversalBaseModel import typing - +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from ..commons.binary_tree_node_value import BinaryTreeNodeValue -from ..commons.binary_tree_value import BinaryTreeValue -from ..commons.doubly_linked_list_node_value import DoublyLinkedListNodeValue -from ..commons.doubly_linked_list_value import DoublyLinkedListValue -from ..commons.node_id import NodeId -from ..commons.singly_linked_list_node_value import SinglyLinkedListNodeValue -from ..commons.singly_linked_list_value import SinglyLinkedListValue -from .actual_result import ActualResult from .error_info import ErrorInfo -from .exception_info import ExceptionInfo -from .exception_v_2 import ExceptionV2 from .running_submission_state import RunningSubmissionState from .submission_status_for_test_case import SubmissionStatusForTestCase -from .test_case_grade import TestCaseGrade -from .test_case_hidden_grade import TestCaseHiddenGrade -from .test_case_non_hidden_grade import TestCaseNonHiddenGrade +from ..commons.node_id import NodeId +from .exception_v_2 import ExceptionV2 from .test_case_result import TestCaseResult -from .test_case_result_with_stdout import TestCaseResultWithStdout +from .test_case_non_hidden_grade import TestCaseNonHiddenGrade +from .actual_result import ActualResult +from ..commons.doubly_linked_list_node_value import DoublyLinkedListNodeValue from .traced_test_case import TracedTestCase +from ..commons.singly_linked_list_node_value import SinglyLinkedListNodeValue +from ..commons.binary_tree_value import BinaryTreeValue +from ..commons.singly_linked_list_value import SinglyLinkedListValue +from .test_case_hidden_grade import TestCaseHiddenGrade +from ..commons.binary_tree_node_value import BinaryTreeNodeValue +from ..commons.doubly_linked_list_value import DoublyLinkedListValue +from .test_case_result_with_stdout import TestCaseResultWithStdout +from .exception_info import ExceptionInfo +from .test_case_grade import TestCaseGrade class TestSubmissionStatus_Stopped(UniversalBaseModel): type: typing.Literal["stopped"] = "stopped" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -60,6 +60,6 @@ class TestSubmissionStatus_TestCaseIdToState(UniversalBaseModel): TestSubmissionStatus_Running, TestSubmissionStatus_TestCaseIdToState, ] -from ..commons.key_value_pair import KeyValuePair # noqa: E402 -from ..commons.map_value import MapValue # noqa: E402 from ..commons.variable_value import VariableValue # noqa: E402 +from ..commons.map_value import MapValue # noqa: E402 +from ..commons.key_value_pair import KeyValuePair # noqa: E402 diff --git a/seed/pydantic/trace/src/seed/trace/resources/submission/test_submission_status_v_2.py b/seed/pydantic/trace/src/seed/trace/resources/submission/test_submission_status_v_2.py index ff22eda6bba..4f94eefb24c 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/submission/test_submission_status_v_2.py +++ b/seed/pydantic/trace/src/seed/trace/resources/submission/test_submission_status_v_2.py @@ -1,13 +1,12 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from .test_submission_update import TestSubmissionUpdate from ..commons.problem_id import ProblemId +import pydantic from ..v_2.resources.problem.problem_info_v_2 import ProblemInfoV2 -from .test_submission_update import TestSubmissionUpdate +from ...core.pydantic_utilities import IS_PYDANTIC_V2 class TestSubmissionStatusV2(UniversalBaseModel): @@ -17,7 +16,9 @@ class TestSubmissionStatusV2(UniversalBaseModel): problem_info: ProblemInfoV2 = pydantic.Field(alias="problemInfo") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/submission/test_submission_update.py b/seed/pydantic/trace/src/seed/trace/resources/submission/test_submission_update.py index 09170425903..e7afc927534 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/submission/test_submission_update.py +++ b/seed/pydantic/trace/src/seed/trace/resources/submission/test_submission_update.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel import datetime as dt -import typing - import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .test_submission_update_info import TestSubmissionUpdateInfo +from ...core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class TestSubmissionUpdate(UniversalBaseModel): @@ -14,7 +13,9 @@ class TestSubmissionUpdate(UniversalBaseModel): update_info: TestSubmissionUpdateInfo = pydantic.Field(alias="updateInfo") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/submission/test_submission_update_info.py b/seed/pydantic/trace/src/seed/trace/resources/submission/test_submission_update_info.py index 4570651d71b..635fa2e3442 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/submission/test_submission_update_info.py +++ b/seed/pydantic/trace/src/seed/trace/resources/submission/test_submission_update_info.py @@ -1,15 +1,13 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ...core.pydantic_utilities import UniversalBaseModel +from .running_submission_state import RunningSubmissionState import typing - +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from ..v_2.resources.problem.test_case_id import TestCaseId from .error_info import ErrorInfo -from .running_submission_state import RunningSubmissionState +from ..v_2.resources.problem.test_case_id import TestCaseId from .test_case_grade import TestCaseGrade @@ -22,7 +20,9 @@ class TestSubmissionUpdateInfo_Stopped(UniversalBaseModel): type: typing.Literal["stopped"] = "stopped" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -40,7 +40,9 @@ class TestSubmissionUpdateInfo_GradedTestCase(UniversalBaseModel): grade: TestCaseGrade if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -53,7 +55,9 @@ class TestSubmissionUpdateInfo_RecordedTestCase(UniversalBaseModel): trace_responses_size: int = pydantic.Field(alias="traceResponsesSize") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -64,7 +68,9 @@ class TestSubmissionUpdateInfo_Finished(UniversalBaseModel): type: typing.Literal["finished"] = "finished" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/submission/trace_response.py b/seed/pydantic/trace/src/seed/trace/resources/submission/trace_response.py index a49b04c78de..f243dfe2c43 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/submission/trace_response.py +++ b/seed/pydantic/trace/src/seed/trace/resources/submission/trace_response.py @@ -1,26 +1,31 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ...core.pydantic_utilities import UniversalBaseModel +from .submission_id import SubmissionId import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +import typing from ..commons.debug_variable_value import DebugVariableValue from .expression_location import ExpressionLocation from .stack_information import StackInformation -from .submission_id import SubmissionId +from ...core.pydantic_utilities import IS_PYDANTIC_V2 class TraceResponse(UniversalBaseModel): submission_id: SubmissionId = pydantic.Field(alias="submissionId") line_number: int = pydantic.Field(alias="lineNumber") - return_value: typing.Optional[DebugVariableValue] = pydantic.Field(alias="returnValue", default=None) - expression_location: typing.Optional[ExpressionLocation] = pydantic.Field(alias="expressionLocation", default=None) + return_value: typing.Optional[DebugVariableValue] = pydantic.Field( + alias="returnValue", default=None + ) + expression_location: typing.Optional[ExpressionLocation] = pydantic.Field( + alias="expressionLocation", default=None + ) stack: StackInformation stdout: typing.Optional[str] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/submission/trace_response_v_2.py b/seed/pydantic/trace/src/seed/trace/resources/submission/trace_response_v_2.py index 2a80850bf58..a4d60230db1 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/submission/trace_response_v_2.py +++ b/seed/pydantic/trace/src/seed/trace/resources/submission/trace_response_v_2.py @@ -1,28 +1,33 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ...core.pydantic_utilities import UniversalBaseModel +from .submission_id import SubmissionId import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from .traced_file import TracedFile +import typing from ..commons.debug_variable_value import DebugVariableValue from .expression_location import ExpressionLocation from .stack_information import StackInformation -from .submission_id import SubmissionId -from .traced_file import TracedFile +from ...core.pydantic_utilities import IS_PYDANTIC_V2 class TraceResponseV2(UniversalBaseModel): submission_id: SubmissionId = pydantic.Field(alias="submissionId") line_number: int = pydantic.Field(alias="lineNumber") file: TracedFile - return_value: typing.Optional[DebugVariableValue] = pydantic.Field(alias="returnValue", default=None) - expression_location: typing.Optional[ExpressionLocation] = pydantic.Field(alias="expressionLocation", default=None) + return_value: typing.Optional[DebugVariableValue] = pydantic.Field( + alias="returnValue", default=None + ) + expression_location: typing.Optional[ExpressionLocation] = pydantic.Field( + alias="expressionLocation", default=None + ) stack: StackInformation stdout: typing.Optional[str] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/submission/trace_responses_page.py b/seed/pydantic/trace/src/seed/trace/resources/submission/trace_responses_page.py index 0c411a58424..27f3314964e 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/submission/trace_responses_page.py +++ b/seed/pydantic/trace/src/seed/trace/resources/submission/trace_responses_page.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel import typing - import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .trace_response import TraceResponse +from ...core.pydantic_utilities import IS_PYDANTIC_V2 class TraceResponsesPage(UniversalBaseModel): @@ -18,7 +17,9 @@ class TraceResponsesPage(UniversalBaseModel): trace_responses: typing.List[TraceResponse] = pydantic.Field(alias="traceResponses") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/submission/trace_responses_page_v_2.py b/seed/pydantic/trace/src/seed/trace/resources/submission/trace_responses_page_v_2.py index 37de34872b4..72f8cb9004e 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/submission/trace_responses_page_v_2.py +++ b/seed/pydantic/trace/src/seed/trace/resources/submission/trace_responses_page_v_2.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel import typing - import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .trace_response_v_2 import TraceResponseV2 +from ...core.pydantic_utilities import IS_PYDANTIC_V2 class TraceResponsesPageV2(UniversalBaseModel): @@ -15,10 +14,14 @@ class TraceResponsesPageV2(UniversalBaseModel): The offset is the id of the next trace response to load. """ - trace_responses: typing.List[TraceResponseV2] = pydantic.Field(alias="traceResponses") + trace_responses: typing.List[TraceResponseV2] = pydantic.Field( + alias="traceResponses" + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/submission/traced_file.py b/seed/pydantic/trace/src/seed/trace/resources/submission/traced_file.py index 248df3bbd4a..486d7a0866f 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/submission/traced_file.py +++ b/seed/pydantic/trace/src/seed/trace/resources/submission/traced_file.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class TracedFile(UniversalBaseModel): filename: str directory: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/submission/traced_test_case.py b/seed/pydantic/trace/src/seed/trace/resources/submission/traced_test_case.py index e4c7bed8f26..e21a2c9df12 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/submission/traced_test_case.py +++ b/seed/pydantic/trace/src/seed/trace/resources/submission/traced_test_case.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ...core.pydantic_utilities import UniversalBaseModel from .test_case_result_with_stdout import TestCaseResultWithStdout +import pydantic +from ...core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class TracedTestCase(UniversalBaseModel): @@ -13,7 +12,9 @@ class TracedTestCase(UniversalBaseModel): trace_responses_size: int = pydantic.Field(alias="traceResponsesSize") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/submission/unexpected_language_error.py b/seed/pydantic/trace/src/seed/trace/resources/submission/unexpected_language_error.py index edcd6db920f..041d9d4810d 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/submission/unexpected_language_error.py +++ b/seed/pydantic/trace/src/seed/trace/resources/submission/unexpected_language_error.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ...core.pydantic_utilities import UniversalBaseModel from ..commons.language import Language +import pydantic +from ...core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class UnexpectedLanguageError(UniversalBaseModel): @@ -13,7 +12,9 @@ class UnexpectedLanguageError(UniversalBaseModel): actual_language: Language = pydantic.Field(alias="actualLanguage") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/submission/workspace_files.py b/seed/pydantic/trace/src/seed/trace/resources/submission/workspace_files.py index 829a7278704..89974a3f5ad 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/submission/workspace_files.py +++ b/seed/pydantic/trace/src/seed/trace/resources/submission/workspace_files.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ...core.pydantic_utilities import UniversalBaseModel from ..commons.file_info import FileInfo +import pydantic +import typing +from ...core.pydantic_utilities import IS_PYDANTIC_V2 class WorkspaceFiles(UniversalBaseModel): @@ -13,7 +12,9 @@ class WorkspaceFiles(UniversalBaseModel): read_only_files: typing.List[FileInfo] = pydantic.Field(alias="readOnlyFiles") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/submission/workspace_ran_response.py b/seed/pydantic/trace/src/seed/trace/resources/submission/workspace_ran_response.py index d38a77ee797..bf7bdab27b2 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/submission/workspace_ran_response.py +++ b/seed/pydantic/trace/src/seed/trace/resources/submission/workspace_ran_response.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ...core.pydantic_utilities import UniversalBaseModel from .submission_id import SubmissionId +import pydantic from .workspace_run_details import WorkspaceRunDetails +from ...core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class WorkspaceRanResponse(UniversalBaseModel): @@ -14,7 +13,9 @@ class WorkspaceRanResponse(UniversalBaseModel): run_details: WorkspaceRunDetails = pydantic.Field(alias="runDetails") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/submission/workspace_run_details.py b/seed/pydantic/trace/src/seed/trace/resources/submission/workspace_run_details.py index 6107e944cc6..1b009866ee3 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/submission/workspace_run_details.py +++ b/seed/pydantic/trace/src/seed/trace/resources/submission/workspace_run_details.py @@ -1,21 +1,24 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel import typing - +from .exception_v_2 import ExceptionV2 import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .exception_info import ExceptionInfo -from .exception_v_2 import ExceptionV2 +from ...core.pydantic_utilities import IS_PYDANTIC_V2 class WorkspaceRunDetails(UniversalBaseModel): - exception_v_2: typing.Optional[ExceptionV2] = pydantic.Field(alias="exceptionV2", default=None) + exception_v_2: typing.Optional[ExceptionV2] = pydantic.Field( + alias="exceptionV2", default=None + ) exception: typing.Optional[ExceptionInfo] = None stdout: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/submission/workspace_starter_files_response.py b/seed/pydantic/trace/src/seed/trace/resources/submission/workspace_starter_files_response.py index 3378179da78..52e9fb07055 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/submission/workspace_starter_files_response.py +++ b/seed/pydantic/trace/src/seed/trace/resources/submission/workspace_starter_files_response.py @@ -1,19 +1,20 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from ..commons.language import Language from .workspace_files import WorkspaceFiles +from ...core.pydantic_utilities import IS_PYDANTIC_V2 +import pydantic class WorkspaceStarterFilesResponse(UniversalBaseModel): files: typing.Dict[Language, WorkspaceFiles] if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/submission/workspace_starter_files_response_v_2.py b/seed/pydantic/trace/src/seed/trace/resources/submission/workspace_starter_files_response_v_2.py index 259f79796ac..44f2168151a 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/submission/workspace_starter_files_response_v_2.py +++ b/seed/pydantic/trace/src/seed/trace/resources/submission/workspace_starter_files_response_v_2.py @@ -1,19 +1,22 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from ..commons.language import Language from ..v_2.resources.problem.files import Files +import pydantic +from ...core.pydantic_utilities import IS_PYDANTIC_V2 class WorkspaceStarterFilesResponseV2(UniversalBaseModel): - files_by_language: typing.Dict[Language, Files] = pydantic.Field(alias="filesByLanguage") + files_by_language: typing.Dict[Language, Files] = pydantic.Field( + alias="filesByLanguage" + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/submission/workspace_submission_state.py b/seed/pydantic/trace/src/seed/trace/resources/submission/workspace_submission_state.py index 1ac2198502f..8e20b29ecf1 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/submission/workspace_submission_state.py +++ b/seed/pydantic/trace/src/seed/trace/resources/submission/workspace_submission_state.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from .workspace_submission_status import WorkspaceSubmissionStatus +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .workspace_submission_status import WorkspaceSubmissionStatus - class WorkspaceSubmissionState(UniversalBaseModel): status: WorkspaceSubmissionStatus if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/submission/workspace_submission_status.py b/seed/pydantic/trace/src/seed/trace/resources/submission/workspace_submission_status.py index 6ee5ab631fd..f14eb291090 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/submission/workspace_submission_status.py +++ b/seed/pydantic/trace/src/seed/trace/resources/submission/workspace_submission_status.py @@ -1,23 +1,23 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ...core.pydantic_utilities import UniversalBaseModel import typing - +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .error_info import ErrorInfo -from .exception_info import ExceptionInfo -from .exception_v_2 import ExceptionV2 from .running_submission_state import RunningSubmissionState +from .exception_v_2 import ExceptionV2 +from .exception_info import ExceptionInfo class WorkspaceSubmissionStatus_Stopped(UniversalBaseModel): type: typing.Literal["stopped"] = "stopped" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -36,12 +36,16 @@ class WorkspaceSubmissionStatus_Running(UniversalBaseModel): class WorkspaceSubmissionStatus_Ran(UniversalBaseModel): type: typing.Literal["ran"] = "ran" - exception_v_2: typing.Optional[ExceptionV2] = pydantic.Field(alias="exceptionV2", default=None) + exception_v_2: typing.Optional[ExceptionV2] = pydantic.Field( + alias="exceptionV2", default=None + ) exception: typing.Optional[ExceptionInfo] = None stdout: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -50,12 +54,16 @@ class Config: class WorkspaceSubmissionStatus_Traced(UniversalBaseModel): type: typing.Literal["traced"] = "traced" - exception_v_2: typing.Optional[ExceptionV2] = pydantic.Field(alias="exceptionV2", default=None) + exception_v_2: typing.Optional[ExceptionV2] = pydantic.Field( + alias="exceptionV2", default=None + ) exception: typing.Optional[ExceptionInfo] = None stdout: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/submission/workspace_submission_status_v_2.py b/seed/pydantic/trace/src/seed/trace/resources/submission/workspace_submission_status_v_2.py index ce49e5ab4e6..cf72f344518 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/submission/workspace_submission_status_v_2.py +++ b/seed/pydantic/trace/src/seed/trace/resources/submission/workspace_submission_status_v_2.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .workspace_submission_update import WorkspaceSubmissionUpdate +from ...core.pydantic_utilities import IS_PYDANTIC_V2 +import pydantic class WorkspaceSubmissionStatusV2(UniversalBaseModel): updates: typing.List[WorkspaceSubmissionUpdate] if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/submission/workspace_submission_update.py b/seed/pydantic/trace/src/seed/trace/resources/submission/workspace_submission_update.py index 4d1a1456cd6..12420edfe44 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/submission/workspace_submission_update.py +++ b/seed/pydantic/trace/src/seed/trace/resources/submission/workspace_submission_update.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel import datetime as dt -import typing - import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .workspace_submission_update_info import WorkspaceSubmissionUpdateInfo +from ...core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class WorkspaceSubmissionUpdate(UniversalBaseModel): @@ -14,7 +13,9 @@ class WorkspaceSubmissionUpdate(UniversalBaseModel): update_info: WorkspaceSubmissionUpdateInfo = pydantic.Field(alias="updateInfo") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/submission/workspace_submission_update_info.py b/seed/pydantic/trace/src/seed/trace/resources/submission/workspace_submission_update_info.py index bc6a4329717..aa269b3786c 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/submission/workspace_submission_update_info.py +++ b/seed/pydantic/trace/src/seed/trace/resources/submission/workspace_submission_update_info.py @@ -1,16 +1,14 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ...core.pydantic_utilities import UniversalBaseModel +from .running_submission_state import RunningSubmissionState import typing - +from .exception_v_2 import ExceptionV2 import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .error_info import ErrorInfo from .exception_info import ExceptionInfo -from .exception_v_2 import ExceptionV2 -from .running_submission_state import RunningSubmissionState +from ...core.pydantic_utilities import IS_PYDANTIC_V2 +from .error_info import ErrorInfo class WorkspaceSubmissionUpdateInfo_Running(UniversalBaseModel): @@ -20,12 +18,16 @@ class WorkspaceSubmissionUpdateInfo_Running(UniversalBaseModel): class WorkspaceSubmissionUpdateInfo_Ran(UniversalBaseModel): type: typing.Literal["ran"] = "ran" - exception_v_2: typing.Optional[ExceptionV2] = pydantic.Field(alias="exceptionV2", default=None) + exception_v_2: typing.Optional[ExceptionV2] = pydantic.Field( + alias="exceptionV2", default=None + ) exception: typing.Optional[ExceptionInfo] = None stdout: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -36,7 +38,9 @@ class WorkspaceSubmissionUpdateInfo_Stopped(UniversalBaseModel): type: typing.Literal["stopped"] = "stopped" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -47,7 +51,9 @@ class WorkspaceSubmissionUpdateInfo_Traced(UniversalBaseModel): type: typing.Literal["traced"] = "traced" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -59,7 +65,9 @@ class WorkspaceSubmissionUpdateInfo_TracedV2(UniversalBaseModel): trace_responses_size: int = pydantic.Field(alias="traceResponsesSize") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -75,7 +83,9 @@ class WorkspaceSubmissionUpdateInfo_Finished(UniversalBaseModel): type: typing.Literal["finished"] = "finished" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/submission/workspace_submit_request.py b/seed/pydantic/trace/src/seed/trace/resources/submission/workspace_submit_request.py index 1dac7d2cf50..8ff64e0d77c 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/submission/workspace_submit_request.py +++ b/seed/pydantic/trace/src/seed/trace/resources/submission/workspace_submit_request.py @@ -1,23 +1,26 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ...core.pydantic_utilities import UniversalBaseModel +from .submission_id import SubmissionId import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from ..commons.language import Language +import typing from .submission_file_info import SubmissionFileInfo -from .submission_id import SubmissionId +from ...core.pydantic_utilities import IS_PYDANTIC_V2 class WorkspaceSubmitRequest(UniversalBaseModel): submission_id: SubmissionId = pydantic.Field(alias="submissionId") language: Language - submission_files: typing.List[SubmissionFileInfo] = pydantic.Field(alias="submissionFiles") + submission_files: typing.List[SubmissionFileInfo] = pydantic.Field( + alias="submissionFiles" + ) user_id: typing.Optional[str] = pydantic.Field(alias="userId", default=None) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/submission/workspace_traced_update.py b/seed/pydantic/trace/src/seed/trace/resources/submission/workspace_traced_update.py index b043a000bf4..ed7c8c8e385 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/submission/workspace_traced_update.py +++ b/seed/pydantic/trace/src/seed/trace/resources/submission/workspace_traced_update.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ...core.pydantic_utilities import UniversalBaseModel import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class WorkspaceTracedUpdate(UniversalBaseModel): trace_responses_size: int = pydantic.Field(alias="traceResponsesSize") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/__init__.py b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/__init__.py index b2b1239aeec..94e8654458c 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/__init__.py +++ b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/__init__.py @@ -14,7 +14,9 @@ from .file_info_v_2 import FileInfoV2 from .files import Files from .function_implementation import FunctionImplementation -from .function_implementation_for_multiple_languages import FunctionImplementationForMultipleLanguages +from .function_implementation_for_multiple_languages import ( + FunctionImplementationForMultipleLanguages, +) from .function_signature import ( FunctionSignature, FunctionSignature_NonVoid, @@ -27,7 +29,9 @@ from .get_function_signature_request import GetFunctionSignatureRequest from .get_function_signature_response import GetFunctionSignatureResponse from .get_generated_test_case_file_request import GetGeneratedTestCaseFileRequest -from .get_generated_test_case_template_file_request import GetGeneratedTestCaseTemplateFileRequest +from .get_generated_test_case_template_file_request import ( + GetGeneratedTestCaseTemplateFileRequest, +) from .lightweight_problem_info_v_2 import LightweightProblemInfoV2 from .non_void_function_definition import NonVoidFunctionDefinition from .non_void_function_signature import NonVoidFunctionSignature @@ -35,7 +39,11 @@ from .parameter_id import ParameterId from .problem_info_v_2 import ProblemInfoV2 from .test_case_expects import TestCaseExpects -from .test_case_function import TestCaseFunction, TestCaseFunction_Custom, TestCaseFunction_WithActualResult +from .test_case_function import ( + TestCaseFunction, + TestCaseFunction_Custom, + TestCaseFunction_WithActualResult, +) from .test_case_id import TestCaseId from .test_case_implementation import TestCaseImplementation from .test_case_implementation_description import TestCaseImplementationDescription @@ -53,11 +61,17 @@ from .test_case_template import TestCaseTemplate from .test_case_template_id import TestCaseTemplateId from .test_case_v_2 import TestCaseV2 -from .test_case_with_actual_result_implementation import TestCaseWithActualResultImplementation +from .test_case_with_actual_result_implementation import ( + TestCaseWithActualResultImplementation, +) from .void_function_definition import VoidFunctionDefinition -from .void_function_definition_that_takes_actual_result import VoidFunctionDefinitionThatTakesActualResult +from .void_function_definition_that_takes_actual_result import ( + VoidFunctionDefinitionThatTakesActualResult, +) from .void_function_signature import VoidFunctionSignature -from .void_function_signature_that_takes_actual_result import VoidFunctionSignatureThatTakesActualResult +from .void_function_signature_that_takes_actual_result import ( + VoidFunctionSignatureThatTakesActualResult, +) __all__ = [ "AssertCorrectnessCheck", diff --git a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/assert_correctness_check.py b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/assert_correctness_check.py index e4998e80aaf..ee3d3347953 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/assert_correctness_check.py +++ b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/assert_correctness_check.py @@ -1,23 +1,27 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from .....core.pydantic_utilities import UniversalBaseModel import typing - +from .parameter_id import ParameterId import pydantic - -from .....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .function_implementation_for_multiple_languages import FunctionImplementationForMultipleLanguages +from .....core.pydantic_utilities import IS_PYDANTIC_V2 from .parameter import Parameter -from .parameter_id import ParameterId +from .function_implementation_for_multiple_languages import ( + FunctionImplementationForMultipleLanguages, +) class AssertCorrectnessCheck_DeepEquality(UniversalBaseModel): type: typing.Literal["deepEquality"] = "deepEquality" - expected_value_parameter_id: ParameterId = pydantic.Field(alias="expectedValueParameterId") + expected_value_parameter_id: ParameterId = pydantic.Field( + alias="expectedValueParameterId" + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -26,15 +30,21 @@ class Config: class AssertCorrectnessCheck_Custom(UniversalBaseModel): type: typing.Literal["custom"] = "custom" - additional_parameters: typing.List[Parameter] = pydantic.Field(alias="additionalParameters") + additional_parameters: typing.List[Parameter] = pydantic.Field( + alias="additionalParameters" + ) code: FunctionImplementationForMultipleLanguages if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: extra = pydantic.Extra.allow -AssertCorrectnessCheck = typing.Union[AssertCorrectnessCheck_DeepEquality, AssertCorrectnessCheck_Custom] +AssertCorrectnessCheck = typing.Union[ + AssertCorrectnessCheck_DeepEquality, AssertCorrectnessCheck_Custom +] diff --git a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/basic_custom_files.py b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/basic_custom_files.py index f3419ffb35b..07ef5bb9df1 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/basic_custom_files.py +++ b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/basic_custom_files.py @@ -1,24 +1,29 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from .....core.pydantic_utilities import UniversalBaseModel import pydantic - -from .....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from .non_void_function_signature import NonVoidFunctionSignature +import typing from ....commons.language import Language -from .basic_test_case_template import BasicTestCaseTemplate from .files import Files -from .non_void_function_signature import NonVoidFunctionSignature +from .basic_test_case_template import BasicTestCaseTemplate +from .....core.pydantic_utilities import IS_PYDANTIC_V2 class BasicCustomFiles(UniversalBaseModel): method_name: str = pydantic.Field(alias="methodName") signature: NonVoidFunctionSignature - additional_files: typing.Dict[Language, Files] = pydantic.Field(alias="additionalFiles") - basic_test_case_template: BasicTestCaseTemplate = pydantic.Field(alias="basicTestCaseTemplate") + additional_files: typing.Dict[Language, Files] = pydantic.Field( + alias="additionalFiles" + ) + basic_test_case_template: BasicTestCaseTemplate = pydantic.Field( + alias="basicTestCaseTemplate" + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/basic_test_case_template.py b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/basic_test_case_template.py index 1ad2734c5c0..11cc84000c3 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/basic_test_case_template.py +++ b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/basic_test_case_template.py @@ -1,23 +1,26 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from .....core.pydantic_utilities import UniversalBaseModel +from .test_case_template_id import TestCaseTemplateId import pydantic - -from .....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .parameter_id import ParameterId from .test_case_implementation_description import TestCaseImplementationDescription -from .test_case_template_id import TestCaseTemplateId +from .parameter_id import ParameterId +from .....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class BasicTestCaseTemplate(UniversalBaseModel): template_id: TestCaseTemplateId = pydantic.Field(alias="templateId") name: str description: TestCaseImplementationDescription - expected_value_parameter_id: ParameterId = pydantic.Field(alias="expectedValueParameterId") + expected_value_parameter_id: ParameterId = pydantic.Field( + alias="expectedValueParameterId" + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/create_problem_request_v_2.py b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/create_problem_request_v_2.py index e72b79dea47..e636714feac 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/create_problem_request_v_2.py +++ b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/create_problem_request_v_2.py @@ -1,28 +1,33 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from .....core.pydantic_utilities import UniversalBaseModel import pydantic - -from .....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from ....commons.language import Language from ....problem.problem_description import ProblemDescription from .custom_files import CustomFiles +import typing from .test_case_template import TestCaseTemplate from .test_case_v_2 import TestCaseV2 +from ....commons.language import Language +from .....core.pydantic_utilities import IS_PYDANTIC_V2 class CreateProblemRequestV2(UniversalBaseModel): problem_name: str = pydantic.Field(alias="problemName") problem_description: ProblemDescription = pydantic.Field(alias="problemDescription") custom_files: CustomFiles = pydantic.Field(alias="customFiles") - custom_test_case_templates: typing.List[TestCaseTemplate] = pydantic.Field(alias="customTestCaseTemplates") + custom_test_case_templates: typing.List[TestCaseTemplate] = pydantic.Field( + alias="customTestCaseTemplates" + ) testcases: typing.List[TestCaseV2] - supported_languages: typing.Set[Language] = pydantic.Field(alias="supportedLanguages") + supported_languages: typing.Set[Language] = pydantic.Field( + alias="supportedLanguages" + ) is_public: bool = pydantic.Field(alias="isPublic") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/custom_files.py b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/custom_files.py index 7db555afcbf..c67c8d414c7 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/custom_files.py +++ b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/custom_files.py @@ -1,28 +1,32 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from .....core.pydantic_utilities import UniversalBaseModel import typing - import pydantic - -from .....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from .non_void_function_signature import NonVoidFunctionSignature from ....commons.language import Language +from .files import Files from .basic_test_case_template import BasicTestCaseTemplate +from .....core.pydantic_utilities import IS_PYDANTIC_V2 from .file_info_v_2 import FileInfoV2 -from .files import Files -from .non_void_function_signature import NonVoidFunctionSignature class CustomFiles_Basic(UniversalBaseModel): type: typing.Literal["basic"] = "basic" method_name: str = pydantic.Field(alias="methodName") signature: NonVoidFunctionSignature - additional_files: typing.Dict[Language, Files] = pydantic.Field(alias="additionalFiles") - basic_test_case_template: BasicTestCaseTemplate = pydantic.Field(alias="basicTestCaseTemplate") + additional_files: typing.Dict[Language, Files] = pydantic.Field( + alias="additionalFiles" + ) + basic_test_case_template: BasicTestCaseTemplate = pydantic.Field( + alias="basicTestCaseTemplate" + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/deep_equality_correctness_check.py b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/deep_equality_correctness_check.py index 3114c451353..c3595cb72c3 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/deep_equality_correctness_check.py +++ b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/deep_equality_correctness_check.py @@ -1,18 +1,21 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from .....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from .....core.pydantic_utilities import UniversalBaseModel from .parameter_id import ParameterId +import pydantic +from .....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class DeepEqualityCorrectnessCheck(UniversalBaseModel): - expected_value_parameter_id: ParameterId = pydantic.Field(alias="expectedValueParameterId") + expected_value_parameter_id: ParameterId = pydantic.Field( + alias="expectedValueParameterId" + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/default_provided_file.py b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/default_provided_file.py index 21f2040021f..1bbe947ffc0 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/default_provided_file.py +++ b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/default_provided_file.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. +from .....core.pydantic_utilities import UniversalBaseModel +from .file_info_v_2 import FileInfoV2 import typing - -import pydantic - -from .....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from ....commons.variable_type import VariableType -from .file_info_v_2 import FileInfoV2 +import pydantic +from .....core.pydantic_utilities import IS_PYDANTIC_V2 class DefaultProvidedFile(UniversalBaseModel): @@ -14,7 +13,9 @@ class DefaultProvidedFile(UniversalBaseModel): related_types: typing.List[VariableType] = pydantic.Field(alias="relatedTypes") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/file_info_v_2.py b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/file_info_v_2.py index fe999d56c78..511a217aa18 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/file_info_v_2.py +++ b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/file_info_v_2.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from .....core.pydantic_utilities import UniversalBaseModel +from .....core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from .....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class FileInfoV2(UniversalBaseModel): filename: str @@ -14,7 +13,9 @@ class FileInfoV2(UniversalBaseModel): editable: bool if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/files.py b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/files.py index 3d176bb7073..f74c5740ee1 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/files.py +++ b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/files.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from .....core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from .....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .file_info_v_2 import FileInfoV2 +from .....core.pydantic_utilities import IS_PYDANTIC_V2 +import pydantic class Files(UniversalBaseModel): files: typing.List[FileInfoV2] if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/function_implementation.py b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/function_implementation.py index f18ddd87471..ef88212cb5f 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/function_implementation.py +++ b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/function_implementation.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from .....core.pydantic_utilities import UniversalBaseModel import typing - +from .....core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from .....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class FunctionImplementation(UniversalBaseModel): impl: str imports: typing.Optional[str] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/function_implementation_for_multiple_languages.py b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/function_implementation_for_multiple_languages.py index ae3b473cc58..0c5aa27754c 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/function_implementation_for_multiple_languages.py +++ b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/function_implementation_for_multiple_languages.py @@ -1,19 +1,22 @@ # This file was auto-generated by Fern from our API Definition. +from .....core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from .....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from ....commons.language import Language from .function_implementation import FunctionImplementation +import pydantic +from .....core.pydantic_utilities import IS_PYDANTIC_V2 class FunctionImplementationForMultipleLanguages(UniversalBaseModel): - code_by_language: typing.Dict[Language, FunctionImplementation] = pydantic.Field(alias="codeByLanguage") + code_by_language: typing.Dict[Language, FunctionImplementation] = pydantic.Field( + alias="codeByLanguage" + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/function_signature.py b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/function_signature.py index a86c843c7ab..99b05c953c5 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/function_signature.py +++ b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/function_signature.py @@ -1,14 +1,12 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from .....core.pydantic_utilities import UniversalBaseModel import typing - +from .parameter import Parameter +from .....core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic - -from .....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from ....commons.variable_type import VariableType -from .parameter import Parameter class FunctionSignature_Void(UniversalBaseModel): @@ -16,7 +14,9 @@ class FunctionSignature_Void(UniversalBaseModel): parameters: typing.List[Parameter] if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -29,7 +29,9 @@ class FunctionSignature_NonVoid(UniversalBaseModel): return_type: VariableType = pydantic.Field(alias="returnType") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -42,7 +44,9 @@ class FunctionSignature_VoidThatTakesActualResult(UniversalBaseModel): actual_result_type: VariableType = pydantic.Field(alias="actualResultType") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -50,5 +54,7 @@ class Config: FunctionSignature = typing.Union[ - FunctionSignature_Void, FunctionSignature_NonVoid, FunctionSignature_VoidThatTakesActualResult + FunctionSignature_Void, + FunctionSignature_NonVoid, + FunctionSignature_VoidThatTakesActualResult, ] diff --git a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/generated_files.py b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/generated_files.py index 312a9d8ba9e..4a1bdb34040 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/generated_files.py +++ b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/generated_files.py @@ -1,21 +1,26 @@ # This file was auto-generated by Fern from our API Definition. +from .....core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from .....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from ....commons.language import Language from .files import Files +import pydantic +from .....core.pydantic_utilities import IS_PYDANTIC_V2 class GeneratedFiles(UniversalBaseModel): - generated_test_case_files: typing.Dict[Language, Files] = pydantic.Field(alias="generatedTestCaseFiles") - generated_template_files: typing.Dict[Language, Files] = pydantic.Field(alias="generatedTemplateFiles") + generated_test_case_files: typing.Dict[Language, Files] = pydantic.Field( + alias="generatedTestCaseFiles" + ) + generated_template_files: typing.Dict[Language, Files] = pydantic.Field( + alias="generatedTemplateFiles" + ) other: typing.Dict[Language, Files] if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/get_basic_solution_file_request.py b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/get_basic_solution_file_request.py index 82808296224..96a2f40eed9 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/get_basic_solution_file_request.py +++ b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/get_basic_solution_file_request.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from .....core.pydantic_utilities import UniversalBaseModel import pydantic - -from .....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .non_void_function_signature import NonVoidFunctionSignature +from .....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class GetBasicSolutionFileRequest(UniversalBaseModel): @@ -13,7 +12,9 @@ class GetBasicSolutionFileRequest(UniversalBaseModel): signature: NonVoidFunctionSignature if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/get_basic_solution_file_response.py b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/get_basic_solution_file_response.py index 72d83420c11..063c4ba61dd 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/get_basic_solution_file_response.py +++ b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/get_basic_solution_file_response.py @@ -1,19 +1,22 @@ # This file was auto-generated by Fern from our API Definition. +from .....core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from .....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from ....commons.language import Language from .file_info_v_2 import FileInfoV2 +import pydantic +from .....core.pydantic_utilities import IS_PYDANTIC_V2 class GetBasicSolutionFileResponse(UniversalBaseModel): - solution_file_by_language: typing.Dict[Language, FileInfoV2] = pydantic.Field(alias="solutionFileByLanguage") + solution_file_by_language: typing.Dict[Language, FileInfoV2] = pydantic.Field( + alias="solutionFileByLanguage" + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/get_function_signature_request.py b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/get_function_signature_request.py index 529917c3fa7..ac5feadcbdb 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/get_function_signature_request.py +++ b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/get_function_signature_request.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from .....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from .....core.pydantic_utilities import UniversalBaseModel from .function_signature import FunctionSignature +import pydantic +from .....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class GetFunctionSignatureRequest(UniversalBaseModel): function_signature: FunctionSignature = pydantic.Field(alias="functionSignature") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/get_function_signature_response.py b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/get_function_signature_response.py index a7495e9d769..43eb9eed28e 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/get_function_signature_response.py +++ b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/get_function_signature_response.py @@ -1,18 +1,21 @@ # This file was auto-generated by Fern from our API Definition. +from .....core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from .....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from ....commons.language import Language +import pydantic +from .....core.pydantic_utilities import IS_PYDANTIC_V2 class GetFunctionSignatureResponse(UniversalBaseModel): - function_by_language: typing.Dict[Language, str] = pydantic.Field(alias="functionByLanguage") + function_by_language: typing.Dict[Language, str] = pydantic.Field( + alias="functionByLanguage" + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/get_generated_test_case_file_request.py b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/get_generated_test_case_file_request.py index 1c78f19c29b..bdcbc9ebd8d 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/get_generated_test_case_file_request.py +++ b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/get_generated_test_case_file_request.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. +from .....core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from .....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .test_case_template import TestCaseTemplate from .test_case_v_2 import TestCaseV2 +import pydantic +from .....core.pydantic_utilities import IS_PYDANTIC_V2 class GetGeneratedTestCaseFileRequest(UniversalBaseModel): @@ -14,7 +13,9 @@ class GetGeneratedTestCaseFileRequest(UniversalBaseModel): test_case: TestCaseV2 = pydantic.Field(alias="testCase") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/get_generated_test_case_template_file_request.py b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/get_generated_test_case_template_file_request.py index 595f4452df0..1a6798dbb3a 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/get_generated_test_case_template_file_request.py +++ b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/get_generated_test_case_template_file_request.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from .....core.pydantic_utilities import UniversalBaseModel +from .test_case_template import TestCaseTemplate +from .....core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from .....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .test_case_template import TestCaseTemplate - class GetGeneratedTestCaseTemplateFileRequest(UniversalBaseModel): template: TestCaseTemplate if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/lightweight_problem_info_v_2.py b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/lightweight_problem_info_v_2.py index a6b2f086266..f3248db77d2 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/lightweight_problem_info_v_2.py +++ b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/lightweight_problem_info_v_2.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from .....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from .....core.pydantic_utilities import UniversalBaseModel from ....commons.problem_id import ProblemId +import pydantic +import typing from ....commons.variable_type import VariableType +from .....core.pydantic_utilities import IS_PYDANTIC_V2 class LightweightProblemInfoV2(UniversalBaseModel): @@ -16,7 +15,9 @@ class LightweightProblemInfoV2(UniversalBaseModel): variable_types: typing.List[VariableType] = pydantic.Field(alias="variableTypes") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/non_void_function_definition.py b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/non_void_function_definition.py index 82261e277d1..7113f2f6b1d 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/non_void_function_definition.py +++ b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/non_void_function_definition.py @@ -1,20 +1,23 @@ # This file was auto-generated by Fern from our API Definition. +from .....core.pydantic_utilities import UniversalBaseModel +from .non_void_function_signature import NonVoidFunctionSignature +from .function_implementation_for_multiple_languages import ( + FunctionImplementationForMultipleLanguages, +) +from .....core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from .....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .function_implementation_for_multiple_languages import FunctionImplementationForMultipleLanguages -from .non_void_function_signature import NonVoidFunctionSignature - class NonVoidFunctionDefinition(UniversalBaseModel): signature: NonVoidFunctionSignature code: FunctionImplementationForMultipleLanguages if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/non_void_function_signature.py b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/non_void_function_signature.py index c6bd527b547..7d9b0252acc 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/non_void_function_signature.py +++ b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/non_void_function_signature.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. +from .....core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from .....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from ....commons.variable_type import VariableType from .parameter import Parameter +from ....commons.variable_type import VariableType +import pydantic +from .....core.pydantic_utilities import IS_PYDANTIC_V2 class NonVoidFunctionSignature(UniversalBaseModel): @@ -14,7 +13,9 @@ class NonVoidFunctionSignature(UniversalBaseModel): return_type: VariableType = pydantic.Field(alias="returnType") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/parameter.py b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/parameter.py index eb0562d0eb8..0dd17811468 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/parameter.py +++ b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/parameter.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from .....core.pydantic_utilities import UniversalBaseModel +from .parameter_id import ParameterId import pydantic - -from .....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from ....commons.variable_type import VariableType -from .parameter_id import ParameterId +from .....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class Parameter(UniversalBaseModel): @@ -15,7 +14,9 @@ class Parameter(UniversalBaseModel): variable_type: VariableType = pydantic.Field(alias="variableType") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/problem_info_v_2.py b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/problem_info_v_2.py index 67fcd57ab81..db4019f386f 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/problem_info_v_2.py +++ b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/problem_info_v_2.py @@ -1,17 +1,16 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from .....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from ....commons.language import Language +from .....core.pydantic_utilities import UniversalBaseModel from ....commons.problem_id import ProblemId +import pydantic from ....problem.problem_description import ProblemDescription +import typing +from ....commons.language import Language from .custom_files import CustomFiles from .generated_files import GeneratedFiles from .test_case_template import TestCaseTemplate from .test_case_v_2 import TestCaseV2 +from .....core.pydantic_utilities import IS_PYDANTIC_V2 class ProblemInfoV2(UniversalBaseModel): @@ -19,15 +18,21 @@ class ProblemInfoV2(UniversalBaseModel): problem_description: ProblemDescription = pydantic.Field(alias="problemDescription") problem_name: str = pydantic.Field(alias="problemName") problem_version: int = pydantic.Field(alias="problemVersion") - supported_languages: typing.Set[Language] = pydantic.Field(alias="supportedLanguages") + supported_languages: typing.Set[Language] = pydantic.Field( + alias="supportedLanguages" + ) custom_files: CustomFiles = pydantic.Field(alias="customFiles") generated_files: GeneratedFiles = pydantic.Field(alias="generatedFiles") - custom_test_case_templates: typing.List[TestCaseTemplate] = pydantic.Field(alias="customTestCaseTemplates") + custom_test_case_templates: typing.List[TestCaseTemplate] = pydantic.Field( + alias="customTestCaseTemplates" + ) testcases: typing.List[TestCaseV2] is_public: bool = pydantic.Field(alias="isPublic") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/test_case_expects.py b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/test_case_expects.py index 27f8c3ccc23..f0c878a54af 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/test_case_expects.py +++ b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/test_case_expects.py @@ -1,17 +1,20 @@ # This file was auto-generated by Fern from our API Definition. +from .....core.pydantic_utilities import UniversalBaseModel import typing - import pydantic - -from .....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from .....core.pydantic_utilities import IS_PYDANTIC_V2 class TestCaseExpects(UniversalBaseModel): - expected_stdout: typing.Optional[str] = pydantic.Field(alias="expectedStdout", default=None) + expected_stdout: typing.Optional[str] = pydantic.Field( + alias="expectedStdout", default=None + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/test_case_function.py b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/test_case_function.py index ffb43424c18..265ee1cef46 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/test_case_function.py +++ b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/test_case_function.py @@ -1,25 +1,31 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from .....core.pydantic_utilities import UniversalBaseModel import typing - +from .non_void_function_definition import NonVoidFunctionDefinition import pydantic - -from .....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .assert_correctness_check import AssertCorrectnessCheck -from .function_implementation_for_multiple_languages import FunctionImplementationForMultipleLanguages -from .non_void_function_definition import NonVoidFunctionDefinition +from .....core.pydantic_utilities import IS_PYDANTIC_V2 from .parameter import Parameter +from .function_implementation_for_multiple_languages import ( + FunctionImplementationForMultipleLanguages, +) class TestCaseFunction_WithActualResult(UniversalBaseModel): type: typing.Literal["withActualResult"] = "withActualResult" - get_actual_result: NonVoidFunctionDefinition = pydantic.Field(alias="getActualResult") - assert_correctness_check: AssertCorrectnessCheck = pydantic.Field(alias="assertCorrectnessCheck") + get_actual_result: NonVoidFunctionDefinition = pydantic.Field( + alias="getActualResult" + ) + assert_correctness_check: AssertCorrectnessCheck = pydantic.Field( + alias="assertCorrectnessCheck" + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -32,11 +38,15 @@ class TestCaseFunction_Custom(UniversalBaseModel): code: FunctionImplementationForMultipleLanguages if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: extra = pydantic.Extra.allow -TestCaseFunction = typing.Union[TestCaseFunction_WithActualResult, TestCaseFunction_Custom] +TestCaseFunction = typing.Union[ + TestCaseFunction_WithActualResult, TestCaseFunction_Custom +] diff --git a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/test_case_implementation.py b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/test_case_implementation.py index 210d5494de9..70396ed6353 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/test_case_implementation.py +++ b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/test_case_implementation.py @@ -1,20 +1,21 @@ # This file was auto-generated by Fern from our API Definition. +from .....core.pydantic_utilities import UniversalBaseModel +from .test_case_implementation_description import TestCaseImplementationDescription +from .test_case_function import TestCaseFunction +from .....core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from .....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .test_case_function import TestCaseFunction -from .test_case_implementation_description import TestCaseImplementationDescription - class TestCaseImplementation(UniversalBaseModel): description: TestCaseImplementationDescription function: TestCaseFunction if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/test_case_implementation_description.py b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/test_case_implementation_description.py index dbb05c11567..a422f5abb2b 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/test_case_implementation_description.py +++ b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/test_case_implementation_description.py @@ -1,18 +1,21 @@ # This file was auto-generated by Fern from our API Definition. +from .....core.pydantic_utilities import UniversalBaseModel import typing - +from .test_case_implementation_description_board import ( + TestCaseImplementationDescriptionBoard, +) +from .....core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from .....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .test_case_implementation_description_board import TestCaseImplementationDescriptionBoard - class TestCaseImplementationDescription(UniversalBaseModel): boards: typing.List[TestCaseImplementationDescriptionBoard] if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/test_case_implementation_description_board.py b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/test_case_implementation_description_board.py index 63ddd127100..daba836fb21 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/test_case_implementation_description_board.py +++ b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/test_case_implementation_description_board.py @@ -1,10 +1,8 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - -import typing - from .....core.pydantic_utilities import UniversalBaseModel +import typing from .parameter_id import ParameterId @@ -19,5 +17,6 @@ class TestCaseImplementationDescriptionBoard_ParamId(UniversalBaseModel): TestCaseImplementationDescriptionBoard = typing.Union[ - TestCaseImplementationDescriptionBoard_Html, TestCaseImplementationDescriptionBoard_ParamId + TestCaseImplementationDescriptionBoard_Html, + TestCaseImplementationDescriptionBoard_ParamId, ] diff --git a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/test_case_implementation_reference.py b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/test_case_implementation_reference.py index 476d70177ab..167a2f214e7 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/test_case_implementation_reference.py +++ b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/test_case_implementation_reference.py @@ -1,15 +1,13 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from .....core.pydantic_utilities import UniversalBaseModel +from .test_case_template_id import TestCaseTemplateId import typing - -import pydantic - -from .....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .test_case_function import TestCaseFunction from .test_case_implementation_description import TestCaseImplementationDescription -from .test_case_template_id import TestCaseTemplateId +from .test_case_function import TestCaseFunction +from .....core.pydantic_utilities import IS_PYDANTIC_V2 +import pydantic class TestCaseImplementationReference_TemplateId(UniversalBaseModel): @@ -23,7 +21,9 @@ class TestCaseImplementationReference_Implementation(UniversalBaseModel): function: TestCaseFunction if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -31,5 +31,6 @@ class Config: TestCaseImplementationReference = typing.Union[ - TestCaseImplementationReference_TemplateId, TestCaseImplementationReference_Implementation + TestCaseImplementationReference_TemplateId, + TestCaseImplementationReference_Implementation, ] diff --git a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/test_case_metadata.py b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/test_case_metadata.py index df039799346..ba872351d4a 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/test_case_metadata.py +++ b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/test_case_metadata.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. +from .....core.pydantic_utilities import UniversalBaseModel +from .test_case_id import TestCaseId +from .....core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from .....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .test_case_id import TestCaseId - class TestCaseMetadata(UniversalBaseModel): id: TestCaseId @@ -14,7 +13,9 @@ class TestCaseMetadata(UniversalBaseModel): hidden: bool if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/test_case_template.py b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/test_case_template.py index 9f88ef197fb..89dcdc90823 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/test_case_template.py +++ b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/test_case_template.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from .....core.pydantic_utilities import UniversalBaseModel +from .test_case_template_id import TestCaseTemplateId import pydantic - -from .....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .test_case_implementation import TestCaseImplementation -from .test_case_template_id import TestCaseTemplateId +from .....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class TestCaseTemplate(UniversalBaseModel): @@ -15,7 +14,9 @@ class TestCaseTemplate(UniversalBaseModel): implementation: TestCaseImplementation if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/test_case_v_2.py b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/test_case_v_2.py index a85e78cd11c..6077bfb13aa 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/test_case_v_2.py +++ b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/test_case_v_2.py @@ -1,15 +1,14 @@ # This file was auto-generated by Fern from our API Definition. +from .....core.pydantic_utilities import UniversalBaseModel +from .test_case_metadata import TestCaseMetadata +from .test_case_implementation_reference import TestCaseImplementationReference import typing - -import pydantic - -from .....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from ....commons.variable_value import VariableValue from .parameter_id import ParameterId +from ....commons.variable_value import VariableValue from .test_case_expects import TestCaseExpects -from .test_case_implementation_reference import TestCaseImplementationReference -from .test_case_metadata import TestCaseMetadata +from .....core.pydantic_utilities import IS_PYDANTIC_V2 +import pydantic class TestCaseV2(UniversalBaseModel): @@ -19,7 +18,9 @@ class TestCaseV2(UniversalBaseModel): expects: typing.Optional[TestCaseExpects] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/test_case_with_actual_result_implementation.py b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/test_case_with_actual_result_implementation.py index 15d8bbc6860..24997bebb84 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/test_case_with_actual_result_implementation.py +++ b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/test_case_with_actual_result_implementation.py @@ -1,20 +1,25 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from .....core.pydantic_utilities import UniversalBaseModel +from .non_void_function_definition import NonVoidFunctionDefinition import pydantic - -from .....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .assert_correctness_check import AssertCorrectnessCheck -from .non_void_function_definition import NonVoidFunctionDefinition +from .....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class TestCaseWithActualResultImplementation(UniversalBaseModel): - get_actual_result: NonVoidFunctionDefinition = pydantic.Field(alias="getActualResult") - assert_correctness_check: AssertCorrectnessCheck = pydantic.Field(alias="assertCorrectnessCheck") + get_actual_result: NonVoidFunctionDefinition = pydantic.Field( + alias="getActualResult" + ) + assert_correctness_check: AssertCorrectnessCheck = pydantic.Field( + alias="assertCorrectnessCheck" + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/void_function_definition.py b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/void_function_definition.py index 7ddc43aa740..900ed1f6047 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/void_function_definition.py +++ b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/void_function_definition.py @@ -1,12 +1,13 @@ # This file was auto-generated by Fern from our API Definition. +from .....core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from .....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .function_implementation_for_multiple_languages import FunctionImplementationForMultipleLanguages from .parameter import Parameter +from .function_implementation_for_multiple_languages import ( + FunctionImplementationForMultipleLanguages, +) +from .....core.pydantic_utilities import IS_PYDANTIC_V2 +import pydantic class VoidFunctionDefinition(UniversalBaseModel): @@ -14,7 +15,9 @@ class VoidFunctionDefinition(UniversalBaseModel): code: FunctionImplementationForMultipleLanguages if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/void_function_definition_that_takes_actual_result.py b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/void_function_definition_that_takes_actual_result.py index be5fe9c3289..2728e6d869f 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/void_function_definition_that_takes_actual_result.py +++ b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/void_function_definition_that_takes_actual_result.py @@ -1,12 +1,13 @@ # This file was auto-generated by Fern from our API Definition. +from .....core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from .....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .function_implementation_for_multiple_languages import FunctionImplementationForMultipleLanguages from .parameter import Parameter +import pydantic +from .function_implementation_for_multiple_languages import ( + FunctionImplementationForMultipleLanguages, +) +from .....core.pydantic_utilities import IS_PYDANTIC_V2 class VoidFunctionDefinitionThatTakesActualResult(UniversalBaseModel): @@ -14,11 +15,15 @@ class VoidFunctionDefinitionThatTakesActualResult(UniversalBaseModel): The generated signature will include an additional param, actualResult """ - additional_parameters: typing.List[Parameter] = pydantic.Field(alias="additionalParameters") + additional_parameters: typing.List[Parameter] = pydantic.Field( + alias="additionalParameters" + ) code: FunctionImplementationForMultipleLanguages if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/void_function_signature.py b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/void_function_signature.py index bbe48e29429..04fa59c9a77 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/void_function_signature.py +++ b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/void_function_signature.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from .....core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from .....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .parameter import Parameter +from .....core.pydantic_utilities import IS_PYDANTIC_V2 +import pydantic class VoidFunctionSignature(UniversalBaseModel): parameters: typing.List[Parameter] if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/void_function_signature_that_takes_actual_result.py b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/void_function_signature_that_takes_actual_result.py index ff9cf27ec04..33f5507bbcf 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/void_function_signature_that_takes_actual_result.py +++ b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/problem/void_function_signature_that_takes_actual_result.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. +from .....core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from .....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from ....commons.variable_type import VariableType from .parameter import Parameter +from ....commons.variable_type import VariableType +import pydantic +from .....core.pydantic_utilities import IS_PYDANTIC_V2 class VoidFunctionSignatureThatTakesActualResult(UniversalBaseModel): @@ -14,7 +13,9 @@ class VoidFunctionSignatureThatTakesActualResult(UniversalBaseModel): actual_result_type: VariableType = pydantic.Field(alias="actualResultType") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/__init__.py b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/__init__.py index b2b1239aeec..94e8654458c 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/__init__.py +++ b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/__init__.py @@ -14,7 +14,9 @@ from .file_info_v_2 import FileInfoV2 from .files import Files from .function_implementation import FunctionImplementation -from .function_implementation_for_multiple_languages import FunctionImplementationForMultipleLanguages +from .function_implementation_for_multiple_languages import ( + FunctionImplementationForMultipleLanguages, +) from .function_signature import ( FunctionSignature, FunctionSignature_NonVoid, @@ -27,7 +29,9 @@ from .get_function_signature_request import GetFunctionSignatureRequest from .get_function_signature_response import GetFunctionSignatureResponse from .get_generated_test_case_file_request import GetGeneratedTestCaseFileRequest -from .get_generated_test_case_template_file_request import GetGeneratedTestCaseTemplateFileRequest +from .get_generated_test_case_template_file_request import ( + GetGeneratedTestCaseTemplateFileRequest, +) from .lightweight_problem_info_v_2 import LightweightProblemInfoV2 from .non_void_function_definition import NonVoidFunctionDefinition from .non_void_function_signature import NonVoidFunctionSignature @@ -35,7 +39,11 @@ from .parameter_id import ParameterId from .problem_info_v_2 import ProblemInfoV2 from .test_case_expects import TestCaseExpects -from .test_case_function import TestCaseFunction, TestCaseFunction_Custom, TestCaseFunction_WithActualResult +from .test_case_function import ( + TestCaseFunction, + TestCaseFunction_Custom, + TestCaseFunction_WithActualResult, +) from .test_case_id import TestCaseId from .test_case_implementation import TestCaseImplementation from .test_case_implementation_description import TestCaseImplementationDescription @@ -53,11 +61,17 @@ from .test_case_template import TestCaseTemplate from .test_case_template_id import TestCaseTemplateId from .test_case_v_2 import TestCaseV2 -from .test_case_with_actual_result_implementation import TestCaseWithActualResultImplementation +from .test_case_with_actual_result_implementation import ( + TestCaseWithActualResultImplementation, +) from .void_function_definition import VoidFunctionDefinition -from .void_function_definition_that_takes_actual_result import VoidFunctionDefinitionThatTakesActualResult +from .void_function_definition_that_takes_actual_result import ( + VoidFunctionDefinitionThatTakesActualResult, +) from .void_function_signature import VoidFunctionSignature -from .void_function_signature_that_takes_actual_result import VoidFunctionSignatureThatTakesActualResult +from .void_function_signature_that_takes_actual_result import ( + VoidFunctionSignatureThatTakesActualResult, +) __all__ = [ "AssertCorrectnessCheck", diff --git a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/assert_correctness_check.py b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/assert_correctness_check.py index 79c21f54843..55802743233 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/assert_correctness_check.py +++ b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/assert_correctness_check.py @@ -1,23 +1,27 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from .......core.pydantic_utilities import UniversalBaseModel import typing - +from .parameter_id import ParameterId import pydantic - -from .......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .function_implementation_for_multiple_languages import FunctionImplementationForMultipleLanguages +from .......core.pydantic_utilities import IS_PYDANTIC_V2 from .parameter import Parameter -from .parameter_id import ParameterId +from .function_implementation_for_multiple_languages import ( + FunctionImplementationForMultipleLanguages, +) class AssertCorrectnessCheck_DeepEquality(UniversalBaseModel): type: typing.Literal["deepEquality"] = "deepEquality" - expected_value_parameter_id: ParameterId = pydantic.Field(alias="expectedValueParameterId") + expected_value_parameter_id: ParameterId = pydantic.Field( + alias="expectedValueParameterId" + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -26,15 +30,21 @@ class Config: class AssertCorrectnessCheck_Custom(UniversalBaseModel): type: typing.Literal["custom"] = "custom" - additional_parameters: typing.List[Parameter] = pydantic.Field(alias="additionalParameters") + additional_parameters: typing.List[Parameter] = pydantic.Field( + alias="additionalParameters" + ) code: FunctionImplementationForMultipleLanguages if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: extra = pydantic.Extra.allow -AssertCorrectnessCheck = typing.Union[AssertCorrectnessCheck_DeepEquality, AssertCorrectnessCheck_Custom] +AssertCorrectnessCheck = typing.Union[ + AssertCorrectnessCheck_DeepEquality, AssertCorrectnessCheck_Custom +] diff --git a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/basic_custom_files.py b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/basic_custom_files.py index 4d034816d2f..6380a92f016 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/basic_custom_files.py +++ b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/basic_custom_files.py @@ -1,24 +1,29 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from .......core.pydantic_utilities import UniversalBaseModel import pydantic - -from .......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from .non_void_function_signature import NonVoidFunctionSignature +import typing from ......commons.language import Language -from .basic_test_case_template import BasicTestCaseTemplate from .files import Files -from .non_void_function_signature import NonVoidFunctionSignature +from .basic_test_case_template import BasicTestCaseTemplate +from .......core.pydantic_utilities import IS_PYDANTIC_V2 class BasicCustomFiles(UniversalBaseModel): method_name: str = pydantic.Field(alias="methodName") signature: NonVoidFunctionSignature - additional_files: typing.Dict[Language, Files] = pydantic.Field(alias="additionalFiles") - basic_test_case_template: BasicTestCaseTemplate = pydantic.Field(alias="basicTestCaseTemplate") + additional_files: typing.Dict[Language, Files] = pydantic.Field( + alias="additionalFiles" + ) + basic_test_case_template: BasicTestCaseTemplate = pydantic.Field( + alias="basicTestCaseTemplate" + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/basic_test_case_template.py b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/basic_test_case_template.py index 5c1ace3ce44..3a21548f707 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/basic_test_case_template.py +++ b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/basic_test_case_template.py @@ -1,23 +1,26 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from .......core.pydantic_utilities import UniversalBaseModel +from .test_case_template_id import TestCaseTemplateId import pydantic - -from .......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .parameter_id import ParameterId from .test_case_implementation_description import TestCaseImplementationDescription -from .test_case_template_id import TestCaseTemplateId +from .parameter_id import ParameterId +from .......core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class BasicTestCaseTemplate(UniversalBaseModel): template_id: TestCaseTemplateId = pydantic.Field(alias="templateId") name: str description: TestCaseImplementationDescription - expected_value_parameter_id: ParameterId = pydantic.Field(alias="expectedValueParameterId") + expected_value_parameter_id: ParameterId = pydantic.Field( + alias="expectedValueParameterId" + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/create_problem_request_v_2.py b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/create_problem_request_v_2.py index f2f51759a3f..0f04407d5a8 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/create_problem_request_v_2.py +++ b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/create_problem_request_v_2.py @@ -1,28 +1,33 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from .......core.pydantic_utilities import UniversalBaseModel import pydantic - -from .......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from ......commons.language import Language from ......problem.problem_description import ProblemDescription from .custom_files import CustomFiles +import typing from .test_case_template import TestCaseTemplate from .test_case_v_2 import TestCaseV2 +from ......commons.language import Language +from .......core.pydantic_utilities import IS_PYDANTIC_V2 class CreateProblemRequestV2(UniversalBaseModel): problem_name: str = pydantic.Field(alias="problemName") problem_description: ProblemDescription = pydantic.Field(alias="problemDescription") custom_files: CustomFiles = pydantic.Field(alias="customFiles") - custom_test_case_templates: typing.List[TestCaseTemplate] = pydantic.Field(alias="customTestCaseTemplates") + custom_test_case_templates: typing.List[TestCaseTemplate] = pydantic.Field( + alias="customTestCaseTemplates" + ) testcases: typing.List[TestCaseV2] - supported_languages: typing.Set[Language] = pydantic.Field(alias="supportedLanguages") + supported_languages: typing.Set[Language] = pydantic.Field( + alias="supportedLanguages" + ) is_public: bool = pydantic.Field(alias="isPublic") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/custom_files.py b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/custom_files.py index ceeb4b57ae7..d665036d972 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/custom_files.py +++ b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/custom_files.py @@ -1,28 +1,32 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from .......core.pydantic_utilities import UniversalBaseModel import typing - import pydantic - -from .......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from .non_void_function_signature import NonVoidFunctionSignature from ......commons.language import Language +from .files import Files from .basic_test_case_template import BasicTestCaseTemplate +from .......core.pydantic_utilities import IS_PYDANTIC_V2 from .file_info_v_2 import FileInfoV2 -from .files import Files -from .non_void_function_signature import NonVoidFunctionSignature class CustomFiles_Basic(UniversalBaseModel): type: typing.Literal["basic"] = "basic" method_name: str = pydantic.Field(alias="methodName") signature: NonVoidFunctionSignature - additional_files: typing.Dict[Language, Files] = pydantic.Field(alias="additionalFiles") - basic_test_case_template: BasicTestCaseTemplate = pydantic.Field(alias="basicTestCaseTemplate") + additional_files: typing.Dict[Language, Files] = pydantic.Field( + alias="additionalFiles" + ) + basic_test_case_template: BasicTestCaseTemplate = pydantic.Field( + alias="basicTestCaseTemplate" + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/deep_equality_correctness_check.py b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/deep_equality_correctness_check.py index 08acf42a7dc..e0938a5205c 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/deep_equality_correctness_check.py +++ b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/deep_equality_correctness_check.py @@ -1,18 +1,21 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from .......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from .......core.pydantic_utilities import UniversalBaseModel from .parameter_id import ParameterId +import pydantic +from .......core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class DeepEqualityCorrectnessCheck(UniversalBaseModel): - expected_value_parameter_id: ParameterId = pydantic.Field(alias="expectedValueParameterId") + expected_value_parameter_id: ParameterId = pydantic.Field( + alias="expectedValueParameterId" + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/default_provided_file.py b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/default_provided_file.py index e6d549ddb75..ef28f934edb 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/default_provided_file.py +++ b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/default_provided_file.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. +from .......core.pydantic_utilities import UniversalBaseModel +from .file_info_v_2 import FileInfoV2 import typing - -import pydantic - -from .......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from ......commons.variable_type import VariableType -from .file_info_v_2 import FileInfoV2 +import pydantic +from .......core.pydantic_utilities import IS_PYDANTIC_V2 class DefaultProvidedFile(UniversalBaseModel): @@ -14,7 +13,9 @@ class DefaultProvidedFile(UniversalBaseModel): related_types: typing.List[VariableType] = pydantic.Field(alias="relatedTypes") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/file_info_v_2.py b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/file_info_v_2.py index 46e3ca69fab..c0e36320f79 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/file_info_v_2.py +++ b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/file_info_v_2.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from .......core.pydantic_utilities import UniversalBaseModel +from .......core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from .......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class FileInfoV2(UniversalBaseModel): filename: str @@ -14,7 +13,9 @@ class FileInfoV2(UniversalBaseModel): editable: bool if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/files.py b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/files.py index 5e4cc926ff8..8bd906d795d 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/files.py +++ b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/files.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from .......core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from .......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .file_info_v_2 import FileInfoV2 +from .......core.pydantic_utilities import IS_PYDANTIC_V2 +import pydantic class Files(UniversalBaseModel): files: typing.List[FileInfoV2] if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/function_implementation.py b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/function_implementation.py index 57c167b6370..d489c78dcbc 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/function_implementation.py +++ b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/function_implementation.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from .......core.pydantic_utilities import UniversalBaseModel import typing - +from .......core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from .......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class FunctionImplementation(UniversalBaseModel): impl: str imports: typing.Optional[str] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/function_implementation_for_multiple_languages.py b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/function_implementation_for_multiple_languages.py index 0fcf95c2783..604854d2525 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/function_implementation_for_multiple_languages.py +++ b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/function_implementation_for_multiple_languages.py @@ -1,19 +1,22 @@ # This file was auto-generated by Fern from our API Definition. +from .......core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from .......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from ......commons.language import Language from .function_implementation import FunctionImplementation +import pydantic +from .......core.pydantic_utilities import IS_PYDANTIC_V2 class FunctionImplementationForMultipleLanguages(UniversalBaseModel): - code_by_language: typing.Dict[Language, FunctionImplementation] = pydantic.Field(alias="codeByLanguage") + code_by_language: typing.Dict[Language, FunctionImplementation] = pydantic.Field( + alias="codeByLanguage" + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/function_signature.py b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/function_signature.py index ac38c232adc..85b67435e50 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/function_signature.py +++ b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/function_signature.py @@ -1,14 +1,12 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from .......core.pydantic_utilities import UniversalBaseModel import typing - +from .parameter import Parameter +from .......core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic - -from .......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from ......commons.variable_type import VariableType -from .parameter import Parameter class FunctionSignature_Void(UniversalBaseModel): @@ -16,7 +14,9 @@ class FunctionSignature_Void(UniversalBaseModel): parameters: typing.List[Parameter] if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -29,7 +29,9 @@ class FunctionSignature_NonVoid(UniversalBaseModel): return_type: VariableType = pydantic.Field(alias="returnType") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -42,7 +44,9 @@ class FunctionSignature_VoidThatTakesActualResult(UniversalBaseModel): actual_result_type: VariableType = pydantic.Field(alias="actualResultType") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -50,5 +54,7 @@ class Config: FunctionSignature = typing.Union[ - FunctionSignature_Void, FunctionSignature_NonVoid, FunctionSignature_VoidThatTakesActualResult + FunctionSignature_Void, + FunctionSignature_NonVoid, + FunctionSignature_VoidThatTakesActualResult, ] diff --git a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/generated_files.py b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/generated_files.py index 62d6ffdd83c..7901fbebd5c 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/generated_files.py +++ b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/generated_files.py @@ -1,21 +1,26 @@ # This file was auto-generated by Fern from our API Definition. +from .......core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from .......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from ......commons.language import Language from .files import Files +import pydantic +from .......core.pydantic_utilities import IS_PYDANTIC_V2 class GeneratedFiles(UniversalBaseModel): - generated_test_case_files: typing.Dict[Language, Files] = pydantic.Field(alias="generatedTestCaseFiles") - generated_template_files: typing.Dict[Language, Files] = pydantic.Field(alias="generatedTemplateFiles") + generated_test_case_files: typing.Dict[Language, Files] = pydantic.Field( + alias="generatedTestCaseFiles" + ) + generated_template_files: typing.Dict[Language, Files] = pydantic.Field( + alias="generatedTemplateFiles" + ) other: typing.Dict[Language, Files] if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/get_basic_solution_file_request.py b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/get_basic_solution_file_request.py index e8821c7fcf1..10bbac544ec 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/get_basic_solution_file_request.py +++ b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/get_basic_solution_file_request.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from .......core.pydantic_utilities import UniversalBaseModel import pydantic - -from .......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .non_void_function_signature import NonVoidFunctionSignature +from .......core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class GetBasicSolutionFileRequest(UniversalBaseModel): @@ -13,7 +12,9 @@ class GetBasicSolutionFileRequest(UniversalBaseModel): signature: NonVoidFunctionSignature if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/get_basic_solution_file_response.py b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/get_basic_solution_file_response.py index dc7f4cb670d..0298139d70a 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/get_basic_solution_file_response.py +++ b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/get_basic_solution_file_response.py @@ -1,19 +1,22 @@ # This file was auto-generated by Fern from our API Definition. +from .......core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from .......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from ......commons.language import Language from .file_info_v_2 import FileInfoV2 +import pydantic +from .......core.pydantic_utilities import IS_PYDANTIC_V2 class GetBasicSolutionFileResponse(UniversalBaseModel): - solution_file_by_language: typing.Dict[Language, FileInfoV2] = pydantic.Field(alias="solutionFileByLanguage") + solution_file_by_language: typing.Dict[Language, FileInfoV2] = pydantic.Field( + alias="solutionFileByLanguage" + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/get_function_signature_request.py b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/get_function_signature_request.py index e1e1b0d348d..b579f2f666a 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/get_function_signature_request.py +++ b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/get_function_signature_request.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from .......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from .......core.pydantic_utilities import UniversalBaseModel from .function_signature import FunctionSignature +import pydantic +from .......core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class GetFunctionSignatureRequest(UniversalBaseModel): function_signature: FunctionSignature = pydantic.Field(alias="functionSignature") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/get_function_signature_response.py b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/get_function_signature_response.py index 3610a3a92bd..a2d7ae02c42 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/get_function_signature_response.py +++ b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/get_function_signature_response.py @@ -1,18 +1,21 @@ # This file was auto-generated by Fern from our API Definition. +from .......core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from .......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from ......commons.language import Language +import pydantic +from .......core.pydantic_utilities import IS_PYDANTIC_V2 class GetFunctionSignatureResponse(UniversalBaseModel): - function_by_language: typing.Dict[Language, str] = pydantic.Field(alias="functionByLanguage") + function_by_language: typing.Dict[Language, str] = pydantic.Field( + alias="functionByLanguage" + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/get_generated_test_case_file_request.py b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/get_generated_test_case_file_request.py index bff9d4eb529..ddf3bcb97e2 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/get_generated_test_case_file_request.py +++ b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/get_generated_test_case_file_request.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. +from .......core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from .......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .test_case_template import TestCaseTemplate from .test_case_v_2 import TestCaseV2 +import pydantic +from .......core.pydantic_utilities import IS_PYDANTIC_V2 class GetGeneratedTestCaseFileRequest(UniversalBaseModel): @@ -14,7 +13,9 @@ class GetGeneratedTestCaseFileRequest(UniversalBaseModel): test_case: TestCaseV2 = pydantic.Field(alias="testCase") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/get_generated_test_case_template_file_request.py b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/get_generated_test_case_template_file_request.py index 9f6c6b4bbe7..81bd4dad026 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/get_generated_test_case_template_file_request.py +++ b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/get_generated_test_case_template_file_request.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from .......core.pydantic_utilities import UniversalBaseModel +from .test_case_template import TestCaseTemplate +from .......core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from .......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .test_case_template import TestCaseTemplate - class GetGeneratedTestCaseTemplateFileRequest(UniversalBaseModel): template: TestCaseTemplate if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/lightweight_problem_info_v_2.py b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/lightweight_problem_info_v_2.py index 44b15c4c4b3..7b3f6485473 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/lightweight_problem_info_v_2.py +++ b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/lightweight_problem_info_v_2.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from .......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from .......core.pydantic_utilities import UniversalBaseModel from ......commons.problem_id import ProblemId +import pydantic +import typing from ......commons.variable_type import VariableType +from .......core.pydantic_utilities import IS_PYDANTIC_V2 class LightweightProblemInfoV2(UniversalBaseModel): @@ -16,7 +15,9 @@ class LightweightProblemInfoV2(UniversalBaseModel): variable_types: typing.List[VariableType] = pydantic.Field(alias="variableTypes") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/non_void_function_definition.py b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/non_void_function_definition.py index 785cde08b4b..8e264f5ce5d 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/non_void_function_definition.py +++ b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/non_void_function_definition.py @@ -1,20 +1,23 @@ # This file was auto-generated by Fern from our API Definition. +from .......core.pydantic_utilities import UniversalBaseModel +from .non_void_function_signature import NonVoidFunctionSignature +from .function_implementation_for_multiple_languages import ( + FunctionImplementationForMultipleLanguages, +) +from .......core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from .......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .function_implementation_for_multiple_languages import FunctionImplementationForMultipleLanguages -from .non_void_function_signature import NonVoidFunctionSignature - class NonVoidFunctionDefinition(UniversalBaseModel): signature: NonVoidFunctionSignature code: FunctionImplementationForMultipleLanguages if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/non_void_function_signature.py b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/non_void_function_signature.py index 7997af7d939..914e2de42c6 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/non_void_function_signature.py +++ b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/non_void_function_signature.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. +from .......core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from .......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from ......commons.variable_type import VariableType from .parameter import Parameter +from ......commons.variable_type import VariableType +import pydantic +from .......core.pydantic_utilities import IS_PYDANTIC_V2 class NonVoidFunctionSignature(UniversalBaseModel): @@ -14,7 +13,9 @@ class NonVoidFunctionSignature(UniversalBaseModel): return_type: VariableType = pydantic.Field(alias="returnType") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/parameter.py b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/parameter.py index 77ab6278325..ebfb1721e94 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/parameter.py +++ b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/parameter.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from .......core.pydantic_utilities import UniversalBaseModel +from .parameter_id import ParameterId import pydantic - -from .......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from ......commons.variable_type import VariableType -from .parameter_id import ParameterId +from .......core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class Parameter(UniversalBaseModel): @@ -15,7 +14,9 @@ class Parameter(UniversalBaseModel): variable_type: VariableType = pydantic.Field(alias="variableType") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/problem_info_v_2.py b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/problem_info_v_2.py index c53a125f21d..d9f60a04fd5 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/problem_info_v_2.py +++ b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/problem_info_v_2.py @@ -1,17 +1,16 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from .......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from ......commons.language import Language +from .......core.pydantic_utilities import UniversalBaseModel from ......commons.problem_id import ProblemId +import pydantic from ......problem.problem_description import ProblemDescription +import typing +from ......commons.language import Language from .custom_files import CustomFiles from .generated_files import GeneratedFiles from .test_case_template import TestCaseTemplate from .test_case_v_2 import TestCaseV2 +from .......core.pydantic_utilities import IS_PYDANTIC_V2 class ProblemInfoV2(UniversalBaseModel): @@ -19,15 +18,21 @@ class ProblemInfoV2(UniversalBaseModel): problem_description: ProblemDescription = pydantic.Field(alias="problemDescription") problem_name: str = pydantic.Field(alias="problemName") problem_version: int = pydantic.Field(alias="problemVersion") - supported_languages: typing.Set[Language] = pydantic.Field(alias="supportedLanguages") + supported_languages: typing.Set[Language] = pydantic.Field( + alias="supportedLanguages" + ) custom_files: CustomFiles = pydantic.Field(alias="customFiles") generated_files: GeneratedFiles = pydantic.Field(alias="generatedFiles") - custom_test_case_templates: typing.List[TestCaseTemplate] = pydantic.Field(alias="customTestCaseTemplates") + custom_test_case_templates: typing.List[TestCaseTemplate] = pydantic.Field( + alias="customTestCaseTemplates" + ) testcases: typing.List[TestCaseV2] is_public: bool = pydantic.Field(alias="isPublic") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/test_case_expects.py b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/test_case_expects.py index 2e978bf1805..852cb2e46c0 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/test_case_expects.py +++ b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/test_case_expects.py @@ -1,17 +1,20 @@ # This file was auto-generated by Fern from our API Definition. +from .......core.pydantic_utilities import UniversalBaseModel import typing - import pydantic - -from .......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from .......core.pydantic_utilities import IS_PYDANTIC_V2 class TestCaseExpects(UniversalBaseModel): - expected_stdout: typing.Optional[str] = pydantic.Field(alias="expectedStdout", default=None) + expected_stdout: typing.Optional[str] = pydantic.Field( + alias="expectedStdout", default=None + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/test_case_function.py b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/test_case_function.py index 372ca066170..fc2d336f7ce 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/test_case_function.py +++ b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/test_case_function.py @@ -1,25 +1,31 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from .......core.pydantic_utilities import UniversalBaseModel import typing - +from .non_void_function_definition import NonVoidFunctionDefinition import pydantic - -from .......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .assert_correctness_check import AssertCorrectnessCheck -from .function_implementation_for_multiple_languages import FunctionImplementationForMultipleLanguages -from .non_void_function_definition import NonVoidFunctionDefinition +from .......core.pydantic_utilities import IS_PYDANTIC_V2 from .parameter import Parameter +from .function_implementation_for_multiple_languages import ( + FunctionImplementationForMultipleLanguages, +) class TestCaseFunction_WithActualResult(UniversalBaseModel): type: typing.Literal["withActualResult"] = "withActualResult" - get_actual_result: NonVoidFunctionDefinition = pydantic.Field(alias="getActualResult") - assert_correctness_check: AssertCorrectnessCheck = pydantic.Field(alias="assertCorrectnessCheck") + get_actual_result: NonVoidFunctionDefinition = pydantic.Field( + alias="getActualResult" + ) + assert_correctness_check: AssertCorrectnessCheck = pydantic.Field( + alias="assertCorrectnessCheck" + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -32,11 +38,15 @@ class TestCaseFunction_Custom(UniversalBaseModel): code: FunctionImplementationForMultipleLanguages if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: extra = pydantic.Extra.allow -TestCaseFunction = typing.Union[TestCaseFunction_WithActualResult, TestCaseFunction_Custom] +TestCaseFunction = typing.Union[ + TestCaseFunction_WithActualResult, TestCaseFunction_Custom +] diff --git a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/test_case_implementation.py b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/test_case_implementation.py index 96407457039..d3ff5d720df 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/test_case_implementation.py +++ b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/test_case_implementation.py @@ -1,20 +1,21 @@ # This file was auto-generated by Fern from our API Definition. +from .......core.pydantic_utilities import UniversalBaseModel +from .test_case_implementation_description import TestCaseImplementationDescription +from .test_case_function import TestCaseFunction +from .......core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from .......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .test_case_function import TestCaseFunction -from .test_case_implementation_description import TestCaseImplementationDescription - class TestCaseImplementation(UniversalBaseModel): description: TestCaseImplementationDescription function: TestCaseFunction if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/test_case_implementation_description.py b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/test_case_implementation_description.py index e88c20f1be6..c6ae3fb3759 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/test_case_implementation_description.py +++ b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/test_case_implementation_description.py @@ -1,18 +1,21 @@ # This file was auto-generated by Fern from our API Definition. +from .......core.pydantic_utilities import UniversalBaseModel import typing - +from .test_case_implementation_description_board import ( + TestCaseImplementationDescriptionBoard, +) +from .......core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from .......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .test_case_implementation_description_board import TestCaseImplementationDescriptionBoard - class TestCaseImplementationDescription(UniversalBaseModel): boards: typing.List[TestCaseImplementationDescriptionBoard] if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/test_case_implementation_description_board.py b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/test_case_implementation_description_board.py index 0e7e09c8839..39c584de43c 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/test_case_implementation_description_board.py +++ b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/test_case_implementation_description_board.py @@ -1,10 +1,8 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - -import typing - from .......core.pydantic_utilities import UniversalBaseModel +import typing from .parameter_id import ParameterId @@ -19,5 +17,6 @@ class TestCaseImplementationDescriptionBoard_ParamId(UniversalBaseModel): TestCaseImplementationDescriptionBoard = typing.Union[ - TestCaseImplementationDescriptionBoard_Html, TestCaseImplementationDescriptionBoard_ParamId + TestCaseImplementationDescriptionBoard_Html, + TestCaseImplementationDescriptionBoard_ParamId, ] diff --git a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/test_case_implementation_reference.py b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/test_case_implementation_reference.py index 2aaa7645a4d..9cfb9561906 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/test_case_implementation_reference.py +++ b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/test_case_implementation_reference.py @@ -1,15 +1,13 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from .......core.pydantic_utilities import UniversalBaseModel +from .test_case_template_id import TestCaseTemplateId import typing - -import pydantic - -from .......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .test_case_function import TestCaseFunction from .test_case_implementation_description import TestCaseImplementationDescription -from .test_case_template_id import TestCaseTemplateId +from .test_case_function import TestCaseFunction +from .......core.pydantic_utilities import IS_PYDANTIC_V2 +import pydantic class TestCaseImplementationReference_TemplateId(UniversalBaseModel): @@ -23,7 +21,9 @@ class TestCaseImplementationReference_Implementation(UniversalBaseModel): function: TestCaseFunction if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -31,5 +31,6 @@ class Config: TestCaseImplementationReference = typing.Union[ - TestCaseImplementationReference_TemplateId, TestCaseImplementationReference_Implementation + TestCaseImplementationReference_TemplateId, + TestCaseImplementationReference_Implementation, ] diff --git a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/test_case_metadata.py b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/test_case_metadata.py index 7fed2f02f1c..0e48bfa43ef 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/test_case_metadata.py +++ b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/test_case_metadata.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. +from .......core.pydantic_utilities import UniversalBaseModel +from .test_case_id import TestCaseId +from .......core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from .......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .test_case_id import TestCaseId - class TestCaseMetadata(UniversalBaseModel): id: TestCaseId @@ -14,7 +13,9 @@ class TestCaseMetadata(UniversalBaseModel): hidden: bool if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/test_case_template.py b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/test_case_template.py index c2dcbdc153b..173aacd90f6 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/test_case_template.py +++ b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/test_case_template.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from .......core.pydantic_utilities import UniversalBaseModel +from .test_case_template_id import TestCaseTemplateId import pydantic - -from .......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .test_case_implementation import TestCaseImplementation -from .test_case_template_id import TestCaseTemplateId +from .......core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class TestCaseTemplate(UniversalBaseModel): @@ -15,7 +14,9 @@ class TestCaseTemplate(UniversalBaseModel): implementation: TestCaseImplementation if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/test_case_v_2.py b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/test_case_v_2.py index 6d779ed2b3a..d3b7d929a0f 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/test_case_v_2.py +++ b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/test_case_v_2.py @@ -1,15 +1,14 @@ # This file was auto-generated by Fern from our API Definition. +from .......core.pydantic_utilities import UniversalBaseModel +from .test_case_metadata import TestCaseMetadata +from .test_case_implementation_reference import TestCaseImplementationReference import typing - -import pydantic - -from .......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from ......commons.variable_value import VariableValue from .parameter_id import ParameterId +from ......commons.variable_value import VariableValue from .test_case_expects import TestCaseExpects -from .test_case_implementation_reference import TestCaseImplementationReference -from .test_case_metadata import TestCaseMetadata +from .......core.pydantic_utilities import IS_PYDANTIC_V2 +import pydantic class TestCaseV2(UniversalBaseModel): @@ -19,7 +18,9 @@ class TestCaseV2(UniversalBaseModel): expects: typing.Optional[TestCaseExpects] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/test_case_with_actual_result_implementation.py b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/test_case_with_actual_result_implementation.py index 2ec48ef8b1b..b389d1ebef6 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/test_case_with_actual_result_implementation.py +++ b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/test_case_with_actual_result_implementation.py @@ -1,20 +1,25 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from .......core.pydantic_utilities import UniversalBaseModel +from .non_void_function_definition import NonVoidFunctionDefinition import pydantic - -from .......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .assert_correctness_check import AssertCorrectnessCheck -from .non_void_function_definition import NonVoidFunctionDefinition +from .......core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class TestCaseWithActualResultImplementation(UniversalBaseModel): - get_actual_result: NonVoidFunctionDefinition = pydantic.Field(alias="getActualResult") - assert_correctness_check: AssertCorrectnessCheck = pydantic.Field(alias="assertCorrectnessCheck") + get_actual_result: NonVoidFunctionDefinition = pydantic.Field( + alias="getActualResult" + ) + assert_correctness_check: AssertCorrectnessCheck = pydantic.Field( + alias="assertCorrectnessCheck" + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/void_function_definition.py b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/void_function_definition.py index 0baf1d4c2a8..9b6faf1b2e3 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/void_function_definition.py +++ b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/void_function_definition.py @@ -1,12 +1,13 @@ # This file was auto-generated by Fern from our API Definition. +from .......core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from .......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .function_implementation_for_multiple_languages import FunctionImplementationForMultipleLanguages from .parameter import Parameter +from .function_implementation_for_multiple_languages import ( + FunctionImplementationForMultipleLanguages, +) +from .......core.pydantic_utilities import IS_PYDANTIC_V2 +import pydantic class VoidFunctionDefinition(UniversalBaseModel): @@ -14,7 +15,9 @@ class VoidFunctionDefinition(UniversalBaseModel): code: FunctionImplementationForMultipleLanguages if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/void_function_definition_that_takes_actual_result.py b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/void_function_definition_that_takes_actual_result.py index b304aaf5ec7..2f97d0b9191 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/void_function_definition_that_takes_actual_result.py +++ b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/void_function_definition_that_takes_actual_result.py @@ -1,12 +1,13 @@ # This file was auto-generated by Fern from our API Definition. +from .......core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from .......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .function_implementation_for_multiple_languages import FunctionImplementationForMultipleLanguages from .parameter import Parameter +import pydantic +from .function_implementation_for_multiple_languages import ( + FunctionImplementationForMultipleLanguages, +) +from .......core.pydantic_utilities import IS_PYDANTIC_V2 class VoidFunctionDefinitionThatTakesActualResult(UniversalBaseModel): @@ -14,11 +15,15 @@ class VoidFunctionDefinitionThatTakesActualResult(UniversalBaseModel): The generated signature will include an additional param, actualResult """ - additional_parameters: typing.List[Parameter] = pydantic.Field(alias="additionalParameters") + additional_parameters: typing.List[Parameter] = pydantic.Field( + alias="additionalParameters" + ) code: FunctionImplementationForMultipleLanguages if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/void_function_signature.py b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/void_function_signature.py index be6787da00b..856b479892e 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/void_function_signature.py +++ b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/void_function_signature.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from .......core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from .......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .parameter import Parameter +from .......core.pydantic_utilities import IS_PYDANTIC_V2 +import pydantic class VoidFunctionSignature(UniversalBaseModel): parameters: typing.List[Parameter] if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/void_function_signature_that_takes_actual_result.py b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/void_function_signature_that_takes_actual_result.py index fdea08528c3..3bcfbebffbf 100644 --- a/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/void_function_signature_that_takes_actual_result.py +++ b/seed/pydantic/trace/src/seed/trace/resources/v_2/resources/v_3/resources/problem/void_function_signature_that_takes_actual_result.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. +from .......core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from .......core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from ......commons.variable_type import VariableType from .parameter import Parameter +from ......commons.variable_type import VariableType +import pydantic +from .......core.pydantic_utilities import IS_PYDANTIC_V2 class VoidFunctionSignatureThatTakesActualResult(UniversalBaseModel): @@ -14,7 +13,9 @@ class VoidFunctionSignatureThatTakesActualResult(UniversalBaseModel): actual_result_type: VariableType = pydantic.Field(alias="actualResultType") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/trace/tests/custom/test_client.py b/seed/pydantic/trace/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/pydantic/trace/tests/custom/test_client.py +++ b/seed/pydantic/trace/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/pydantic/undiscriminated-unions/pyproject.toml b/seed/pydantic/undiscriminated-unions/pyproject.toml index f1579395baf..bbd72f47786 100644 --- a/seed/pydantic/undiscriminated-unions/pyproject.toml +++ b/seed/pydantic/undiscriminated-unions/pyproject.toml @@ -40,6 +40,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/pydantic/undiscriminated-unions/src/seed/undiscriminated_unions/core/datetime_utils.py b/seed/pydantic/undiscriminated-unions/src/seed/undiscriminated_unions/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/pydantic/undiscriminated-unions/src/seed/undiscriminated_unions/core/datetime_utils.py +++ b/seed/pydantic/undiscriminated-unions/src/seed/undiscriminated_unions/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/pydantic/undiscriminated-unions/src/seed/undiscriminated_unions/core/pydantic_utilities.py b/seed/pydantic/undiscriminated-unions/src/seed/undiscriminated_unions/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/pydantic/undiscriminated-unions/src/seed/undiscriminated_unions/core/pydantic_utilities.py +++ b/seed/pydantic/undiscriminated-unions/src/seed/undiscriminated_unions/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/pydantic/undiscriminated-unions/src/seed/undiscriminated_unions/core/serialization.py b/seed/pydantic/undiscriminated-unions/src/seed/undiscriminated_unions/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/pydantic/undiscriminated-unions/src/seed/undiscriminated_unions/core/serialization.py +++ b/seed/pydantic/undiscriminated-unions/src/seed/undiscriminated_unions/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/pydantic/undiscriminated-unions/src/seed/undiscriminated_unions/resources/union/key.py b/seed/pydantic/undiscriminated-unions/src/seed/undiscriminated_unions/resources/union/key.py index 3c379619874..c143ecf00b2 100644 --- a/seed/pydantic/undiscriminated-unions/src/seed/undiscriminated_unions/resources/union/key.py +++ b/seed/pydantic/undiscriminated-unions/src/seed/undiscriminated_unions/resources/union/key.py @@ -1,7 +1,6 @@ # This file was auto-generated by Fern from our API Definition. import typing - from .key_type import KeyType Key = typing.Union[KeyType, typing.Literal["default"]] diff --git a/seed/pydantic/undiscriminated-unions/src/seed/undiscriminated_unions/resources/union/metadata.py b/seed/pydantic/undiscriminated-unions/src/seed/undiscriminated_unions/resources/union/metadata.py index 9d3134f13ad..2c53a1101bc 100644 --- a/seed/pydantic/undiscriminated-unions/src/seed/undiscriminated_unions/resources/union/metadata.py +++ b/seed/pydantic/undiscriminated-unions/src/seed/undiscriminated_unions/resources/union/metadata.py @@ -1,7 +1,6 @@ # This file was auto-generated by Fern from our API Definition. import typing - from .key import Key """ diff --git a/seed/pydantic/undiscriminated-unions/src/seed/undiscriminated_unions/resources/union/my_union.py b/seed/pydantic/undiscriminated-unions/src/seed/undiscriminated_unions/resources/union/my_union.py index 6b8c3dae2f4..9a8a6426908 100644 --- a/seed/pydantic/undiscriminated-unions/src/seed/undiscriminated_unions/resources/union/my_union.py +++ b/seed/pydantic/undiscriminated-unions/src/seed/undiscriminated_unions/resources/union/my_union.py @@ -2,4 +2,11 @@ import typing -MyUnion = typing.Union[str, typing.List[str], int, typing.List[int], typing.List[typing.List[int]], typing.Set[str]] +MyUnion = typing.Union[ + str, + typing.List[str], + int, + typing.List[int], + typing.List[typing.List[int]], + typing.Set[str], +] diff --git a/seed/pydantic/undiscriminated-unions/tests/custom/test_client.py b/seed/pydantic/undiscriminated-unions/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/pydantic/undiscriminated-unions/tests/custom/test_client.py +++ b/seed/pydantic/undiscriminated-unions/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/pydantic/unions/pyproject.toml b/seed/pydantic/unions/pyproject.toml index 09aaaa82f41..271c21d5201 100644 --- a/seed/pydantic/unions/pyproject.toml +++ b/seed/pydantic/unions/pyproject.toml @@ -41,6 +41,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/pydantic/unions/src/seed/unions/core/datetime_utils.py b/seed/pydantic/unions/src/seed/unions/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/pydantic/unions/src/seed/unions/core/datetime_utils.py +++ b/seed/pydantic/unions/src/seed/unions/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/pydantic/unions/src/seed/unions/core/pydantic_utilities.py b/seed/pydantic/unions/src/seed/unions/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/pydantic/unions/src/seed/unions/core/pydantic_utilities.py +++ b/seed/pydantic/unions/src/seed/unions/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/pydantic/unions/src/seed/unions/core/serialization.py b/seed/pydantic/unions/src/seed/unions/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/pydantic/unions/src/seed/unions/core/serialization.py +++ b/seed/pydantic/unions/src/seed/unions/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/pydantic/unions/src/seed/unions/resources/types/__init__.py b/seed/pydantic/unions/src/seed/unions/resources/types/__init__.py index 42d3faa423c..cb9ecd1e17f 100644 --- a/seed/pydantic/unions/src/seed/unions/resources/types/__init__.py +++ b/seed/pydantic/unions/src/seed/unions/resources/types/__init__.py @@ -9,13 +9,37 @@ UnionWithBaseProperties_Integer, UnionWithBaseProperties_String, ) -from .union_with_discriminant import UnionWithDiscriminant, UnionWithDiscriminant_Bar, UnionWithDiscriminant_Foo +from .union_with_discriminant import ( + UnionWithDiscriminant, + UnionWithDiscriminant_Bar, + UnionWithDiscriminant_Foo, +) from .union_with_literal import UnionWithLiteral, UnionWithLiteral_Fern -from .union_with_optional_time import UnionWithOptionalTime, UnionWithOptionalTime_Date, UnionWithOptionalTime_Dateimte -from .union_with_primitive import UnionWithPrimitive, UnionWithPrimitive_Integer, UnionWithPrimitive_String -from .union_with_single_element import UnionWithSingleElement, UnionWithSingleElement_Foo -from .union_with_time import UnionWithTime, UnionWithTime_Date, UnionWithTime_Datetime, UnionWithTime_Value -from .union_with_unknown import UnionWithUnknown, UnionWithUnknown_Foo, UnionWithUnknown_Unknown +from .union_with_optional_time import ( + UnionWithOptionalTime, + UnionWithOptionalTime_Date, + UnionWithOptionalTime_Dateimte, +) +from .union_with_primitive import ( + UnionWithPrimitive, + UnionWithPrimitive_Integer, + UnionWithPrimitive_String, +) +from .union_with_single_element import ( + UnionWithSingleElement, + UnionWithSingleElement_Foo, +) +from .union_with_time import ( + UnionWithTime, + UnionWithTime_Date, + UnionWithTime_Datetime, + UnionWithTime_Value, +) +from .union_with_unknown import ( + UnionWithUnknown, + UnionWithUnknown_Foo, + UnionWithUnknown_Unknown, +) from .union_without_key import UnionWithoutKey, UnionWithoutKey_Bar, UnionWithoutKey_Foo __all__ = [ diff --git a/seed/pydantic/unions/src/seed/unions/resources/types/bar.py b/seed/pydantic/unions/src/seed/unions/resources/types/bar.py index 8029fd54f11..e2ddee92607 100644 --- a/seed/pydantic/unions/src/seed/unions/resources/types/bar.py +++ b/seed/pydantic/unions/src/seed/unions/resources/types/bar.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class Bar(UniversalBaseModel): name: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/unions/src/seed/unions/resources/types/foo.py b/seed/pydantic/unions/src/seed/unions/resources/types/foo.py index 4321ffe0f28..234d6fd6e0c 100644 --- a/seed/pydantic/unions/src/seed/unions/resources/types/foo.py +++ b/seed/pydantic/unions/src/seed/unions/resources/types/foo.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class Foo(UniversalBaseModel): name: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/unions/src/seed/unions/resources/types/union.py b/seed/pydantic/unions/src/seed/unions/resources/types/union.py index aa9edf9ec25..64077a0a591 100644 --- a/seed/pydantic/unions/src/seed/unions/resources/types/union.py +++ b/seed/pydantic/unions/src/seed/unions/resources/types/union.py @@ -1,12 +1,10 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - -import typing - from ...core.pydantic_utilities import UniversalBaseModel -from .bar import Bar from .foo import Foo +import typing +from .bar import Bar class Union_Foo(UniversalBaseModel): diff --git a/seed/pydantic/unions/src/seed/unions/resources/types/union_with_base_properties.py b/seed/pydantic/unions/src/seed/unions/resources/types/union_with_base_properties.py index dcd258b46c1..f44d250074b 100644 --- a/seed/pydantic/unions/src/seed/unions/resources/types/union_with_base_properties.py +++ b/seed/pydantic/unions/src/seed/unions/resources/types/union_with_base_properties.py @@ -1,19 +1,19 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class Base(UniversalBaseModel): id: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -35,7 +35,9 @@ class UnionWithBaseProperties_Foo(Base): name: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -43,5 +45,7 @@ class Config: UnionWithBaseProperties = typing.Union[ - UnionWithBaseProperties_Integer, UnionWithBaseProperties_String, UnionWithBaseProperties_Foo + UnionWithBaseProperties_Integer, + UnionWithBaseProperties_String, + UnionWithBaseProperties_Foo, ] diff --git a/seed/pydantic/unions/src/seed/unions/resources/types/union_with_discriminant.py b/seed/pydantic/unions/src/seed/unions/resources/types/union_with_discriminant.py index e9f280f5a66..05f0131c010 100644 --- a/seed/pydantic/unions/src/seed/unions/resources/types/union_with_discriminant.py +++ b/seed/pydantic/unions/src/seed/unions/resources/types/union_with_discriminant.py @@ -1,14 +1,11 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ...core.pydantic_utilities import UniversalBaseModel +from .foo import Foo import typing - import pydantic - -from ...core.pydantic_utilities import UniversalBaseModel from .bar import Bar -from .foo import Foo class UnionWithDiscriminant_Foo(UniversalBaseModel): @@ -21,4 +18,6 @@ class UnionWithDiscriminant_Bar(UniversalBaseModel): type: typing.Literal["bar"] = pydantic.Field(alias="_type", default="bar") -UnionWithDiscriminant = typing.Union[UnionWithDiscriminant_Foo, UnionWithDiscriminant_Bar] +UnionWithDiscriminant = typing.Union[ + UnionWithDiscriminant_Foo, UnionWithDiscriminant_Bar +] diff --git a/seed/pydantic/unions/src/seed/unions/resources/types/union_with_literal.py b/seed/pydantic/unions/src/seed/unions/resources/types/union_with_literal.py index f2a3b379e52..13713e317a8 100644 --- a/seed/pydantic/unions/src/seed/unions/resources/types/union_with_literal.py +++ b/seed/pydantic/unions/src/seed/unions/resources/types/union_with_literal.py @@ -1,19 +1,19 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ...core.pydantic_utilities import UniversalBaseModel import typing - +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class Base(UniversalBaseModel): base: typing.Literal["base"] = "base" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/unions/src/seed/unions/resources/types/union_with_optional_time.py b/seed/pydantic/unions/src/seed/unions/resources/types/union_with_optional_time.py index 4b8145e61cf..4fae4ca5276 100644 --- a/seed/pydantic/unions/src/seed/unions/resources/types/union_with_optional_time.py +++ b/seed/pydantic/unions/src/seed/unions/resources/types/union_with_optional_time.py @@ -1,11 +1,9 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - -import datetime as dt -import typing - from ...core.pydantic_utilities import UniversalBaseModel +import typing +import datetime as dt class UnionWithOptionalTime_Date(UniversalBaseModel): @@ -18,4 +16,6 @@ class UnionWithOptionalTime_Dateimte(UniversalBaseModel): type: typing.Literal["dateimte"] = "dateimte" -UnionWithOptionalTime = typing.Union[UnionWithOptionalTime_Date, UnionWithOptionalTime_Dateimte] +UnionWithOptionalTime = typing.Union[ + UnionWithOptionalTime_Date, UnionWithOptionalTime_Dateimte +] diff --git a/seed/pydantic/unions/src/seed/unions/resources/types/union_with_primitive.py b/seed/pydantic/unions/src/seed/unions/resources/types/union_with_primitive.py index 2db60152f47..4eaacc700a3 100644 --- a/seed/pydantic/unions/src/seed/unions/resources/types/union_with_primitive.py +++ b/seed/pydantic/unions/src/seed/unions/resources/types/union_with_primitive.py @@ -1,10 +1,8 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - -import typing - from ...core.pydantic_utilities import UniversalBaseModel +import typing class UnionWithPrimitive_Integer(UniversalBaseModel): diff --git a/seed/pydantic/unions/src/seed/unions/resources/types/union_with_single_element.py b/seed/pydantic/unions/src/seed/unions/resources/types/union_with_single_element.py index ebd5468eef6..c2786085f27 100644 --- a/seed/pydantic/unions/src/seed/unions/resources/types/union_with_single_element.py +++ b/seed/pydantic/unions/src/seed/unions/resources/types/union_with_single_element.py @@ -1,20 +1,20 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ...core.pydantic_utilities import UniversalBaseModel import typing - +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class UnionWithSingleElement_Foo(UniversalBaseModel): type: typing.Literal["foo"] = "foo" name: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/unions/src/seed/unions/resources/types/union_with_time.py b/seed/pydantic/unions/src/seed/unions/resources/types/union_with_time.py index 10708aad632..8e061ed885a 100644 --- a/seed/pydantic/unions/src/seed/unions/resources/types/union_with_time.py +++ b/seed/pydantic/unions/src/seed/unions/resources/types/union_with_time.py @@ -1,11 +1,9 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - -import datetime as dt -import typing - from ...core.pydantic_utilities import UniversalBaseModel +import typing +import datetime as dt class UnionWithTime_Value(UniversalBaseModel): @@ -23,4 +21,6 @@ class UnionWithTime_Datetime(UniversalBaseModel): type: typing.Literal["datetime"] = "datetime" -UnionWithTime = typing.Union[UnionWithTime_Value, UnionWithTime_Date, UnionWithTime_Datetime] +UnionWithTime = typing.Union[ + UnionWithTime_Value, UnionWithTime_Date, UnionWithTime_Datetime +] diff --git a/seed/pydantic/unions/src/seed/unions/resources/types/union_with_unknown.py b/seed/pydantic/unions/src/seed/unions/resources/types/union_with_unknown.py index 6275658e4d2..e2a41e7113e 100644 --- a/seed/pydantic/unions/src/seed/unions/resources/types/union_with_unknown.py +++ b/seed/pydantic/unions/src/seed/unions/resources/types/union_with_unknown.py @@ -1,20 +1,20 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ...core.pydantic_utilities import UniversalBaseModel import typing - +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class UnionWithUnknown_Foo(UniversalBaseModel): type: typing.Literal["foo"] = "foo" name: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -25,7 +25,9 @@ class UnionWithUnknown_Unknown(UniversalBaseModel): type: typing.Literal["unknown"] = "unknown" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/unions/src/seed/unions/resources/types/union_without_key.py b/seed/pydantic/unions/src/seed/unions/resources/types/union_without_key.py index 0ebca7cc7fc..5a84c9cb401 100644 --- a/seed/pydantic/unions/src/seed/unions/resources/types/union_without_key.py +++ b/seed/pydantic/unions/src/seed/unions/resources/types/union_without_key.py @@ -1,20 +1,20 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ...core.pydantic_utilities import UniversalBaseModel import typing - +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class UnionWithoutKey_Foo(UniversalBaseModel): type: typing.Literal["foo"] = "foo" name: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -26,7 +26,9 @@ class UnionWithoutKey_Bar(UniversalBaseModel): name: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/unions/src/seed/unions/resources/union/__init__.py b/seed/pydantic/unions/src/seed/unions/resources/union/__init__.py index 37b403a91b5..4664e28cf75 100644 --- a/seed/pydantic/unions/src/seed/unions/resources/union/__init__.py +++ b/seed/pydantic/unions/src/seed/unions/resources/union/__init__.py @@ -5,4 +5,11 @@ from .shape import Shape, Shape_Circle, Shape_Square from .square import Square -__all__ = ["Circle", "GetShapeRequest", "Shape", "Shape_Circle", "Shape_Square", "Square"] +__all__ = [ + "Circle", + "GetShapeRequest", + "Shape", + "Shape_Circle", + "Shape_Square", + "Square", +] diff --git a/seed/pydantic/unions/src/seed/unions/resources/union/circle.py b/seed/pydantic/unions/src/seed/unions/resources/union/circle.py index 71013af01cf..c2853d62ce2 100644 --- a/seed/pydantic/unions/src/seed/unions/resources/union/circle.py +++ b/seed/pydantic/unions/src/seed/unions/resources/union/circle.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class Circle(UniversalBaseModel): radius: float if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/unions/src/seed/unions/resources/union/get_shape_request.py b/seed/pydantic/unions/src/seed/unions/resources/union/get_shape_request.py index f2dc5159524..c22eaaad550 100644 --- a/seed/pydantic/unions/src/seed/unions/resources/union/get_shape_request.py +++ b/seed/pydantic/unions/src/seed/unions/resources/union/get_shape_request.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class GetShapeRequest(UniversalBaseModel): id: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/unions/src/seed/unions/resources/union/shape.py b/seed/pydantic/unions/src/seed/unions/resources/union/shape.py index d9a109c6e0b..73de96e2f05 100644 --- a/seed/pydantic/unions/src/seed/unions/resources/union/shape.py +++ b/seed/pydantic/unions/src/seed/unions/resources/union/shape.py @@ -1,19 +1,19 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class Base(UniversalBaseModel): id: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -25,7 +25,9 @@ class Shape_Circle(Base): radius: float if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -37,7 +39,9 @@ class Shape_Square(Base): length: float if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/unions/src/seed/unions/resources/union/square.py b/seed/pydantic/unions/src/seed/unions/resources/union/square.py index 44a09c4477c..36010605da0 100644 --- a/seed/pydantic/unions/src/seed/unions/resources/union/square.py +++ b/seed/pydantic/unions/src/seed/unions/resources/union/square.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class Square(UniversalBaseModel): length: float if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/unions/tests/custom/test_client.py b/seed/pydantic/unions/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/pydantic/unions/tests/custom/test_client.py +++ b/seed/pydantic/unions/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/pydantic/unknown/pyproject.toml b/seed/pydantic/unknown/pyproject.toml index 86e78f4a874..0ea7bb036e5 100644 --- a/seed/pydantic/unknown/pyproject.toml +++ b/seed/pydantic/unknown/pyproject.toml @@ -41,6 +41,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/pydantic/unknown/src/seed/unknown_as_any/core/datetime_utils.py b/seed/pydantic/unknown/src/seed/unknown_as_any/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/pydantic/unknown/src/seed/unknown_as_any/core/datetime_utils.py +++ b/seed/pydantic/unknown/src/seed/unknown_as_any/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/pydantic/unknown/src/seed/unknown_as_any/core/pydantic_utilities.py b/seed/pydantic/unknown/src/seed/unknown_as_any/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/pydantic/unknown/src/seed/unknown_as_any/core/pydantic_utilities.py +++ b/seed/pydantic/unknown/src/seed/unknown_as_any/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/pydantic/unknown/src/seed/unknown_as_any/core/serialization.py b/seed/pydantic/unknown/src/seed/unknown_as_any/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/pydantic/unknown/src/seed/unknown_as_any/core/serialization.py +++ b/seed/pydantic/unknown/src/seed/unknown_as_any/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/pydantic/unknown/src/seed/unknown_as_any/resources/unknown/my_object.py b/seed/pydantic/unknown/src/seed/unknown_as_any/resources/unknown/my_object.py index dca24039b4d..bb5d1bb8a6d 100644 --- a/seed/pydantic/unknown/src/seed/unknown_as_any/resources/unknown/my_object.py +++ b/seed/pydantic/unknown/src/seed/unknown_as_any/resources/unknown/my_object.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel import typing - +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class MyObject(UniversalBaseModel): unknown: typing.Any if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/unknown/tests/custom/test_client.py b/seed/pydantic/unknown/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/pydantic/unknown/tests/custom/test_client.py +++ b/seed/pydantic/unknown/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/pydantic/validation/pyproject.toml b/seed/pydantic/validation/pyproject.toml index 6cfa427aa9e..9ddcb8f4256 100644 --- a/seed/pydantic/validation/pyproject.toml +++ b/seed/pydantic/validation/pyproject.toml @@ -41,6 +41,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/pydantic/validation/src/seed/validation/__init__.py b/seed/pydantic/validation/src/seed/validation/__init__.py index d30f52138d4..51957e8c8c5 100644 --- a/seed/pydantic/validation/src/seed/validation/__init__.py +++ b/seed/pydantic/validation/src/seed/validation/__init__.py @@ -8,4 +8,12 @@ from .type import Type from .word import Word -__all__ = ["Double", "LargeInteger", "Sentence", "Shape", "SmallInteger", "Type", "Word"] +__all__ = [ + "Double", + "LargeInteger", + "Sentence", + "Shape", + "SmallInteger", + "Type", + "Word", +] diff --git a/seed/pydantic/validation/src/seed/validation/core/datetime_utils.py b/seed/pydantic/validation/src/seed/validation/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/pydantic/validation/src/seed/validation/core/datetime_utils.py +++ b/seed/pydantic/validation/src/seed/validation/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/pydantic/validation/src/seed/validation/core/pydantic_utilities.py b/seed/pydantic/validation/src/seed/validation/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/pydantic/validation/src/seed/validation/core/pydantic_utilities.py +++ b/seed/pydantic/validation/src/seed/validation/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/pydantic/validation/src/seed/validation/core/serialization.py b/seed/pydantic/validation/src/seed/validation/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/pydantic/validation/src/seed/validation/core/serialization.py +++ b/seed/pydantic/validation/src/seed/validation/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/pydantic/validation/src/seed/validation/type.py b/seed/pydantic/validation/src/seed/validation/type.py index ab71124463b..7c0f1dec1dc 100644 --- a/seed/pydantic/validation/src/seed/validation/type.py +++ b/seed/pydantic/validation/src/seed/validation/type.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. +from .core.pydantic_utilities import UniversalBaseModel +from .shape import Shape +from .core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from .core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .shape import Shape - class Type(UniversalBaseModel): """ @@ -30,7 +29,9 @@ class Type(UniversalBaseModel): shape: Shape if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/validation/tests/custom/test_client.py b/seed/pydantic/validation/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/pydantic/validation/tests/custom/test_client.py +++ b/seed/pydantic/validation/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/pydantic/variables/pyproject.toml b/seed/pydantic/variables/pyproject.toml index 6aa1eb10c1d..82d64148d2a 100644 --- a/seed/pydantic/variables/pyproject.toml +++ b/seed/pydantic/variables/pyproject.toml @@ -40,6 +40,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/pydantic/variables/src/seed/variables/core/datetime_utils.py b/seed/pydantic/variables/src/seed/variables/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/pydantic/variables/src/seed/variables/core/datetime_utils.py +++ b/seed/pydantic/variables/src/seed/variables/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/pydantic/variables/src/seed/variables/core/pydantic_utilities.py b/seed/pydantic/variables/src/seed/variables/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/pydantic/variables/src/seed/variables/core/pydantic_utilities.py +++ b/seed/pydantic/variables/src/seed/variables/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/pydantic/variables/src/seed/variables/core/serialization.py b/seed/pydantic/variables/src/seed/variables/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/pydantic/variables/src/seed/variables/core/serialization.py +++ b/seed/pydantic/variables/src/seed/variables/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/pydantic/variables/tests/custom/test_client.py b/seed/pydantic/variables/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/pydantic/variables/tests/custom/test_client.py +++ b/seed/pydantic/variables/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/pydantic/version-no-default/pyproject.toml b/seed/pydantic/version-no-default/pyproject.toml index 282cfd250a5..08c97a67415 100644 --- a/seed/pydantic/version-no-default/pyproject.toml +++ b/seed/pydantic/version-no-default/pyproject.toml @@ -41,6 +41,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/pydantic/version-no-default/src/seed/version/core/datetime_utils.py b/seed/pydantic/version-no-default/src/seed/version/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/pydantic/version-no-default/src/seed/version/core/datetime_utils.py +++ b/seed/pydantic/version-no-default/src/seed/version/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/pydantic/version-no-default/src/seed/version/core/pydantic_utilities.py b/seed/pydantic/version-no-default/src/seed/version/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/pydantic/version-no-default/src/seed/version/core/pydantic_utilities.py +++ b/seed/pydantic/version-no-default/src/seed/version/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/pydantic/version-no-default/src/seed/version/core/serialization.py b/seed/pydantic/version-no-default/src/seed/version/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/pydantic/version-no-default/src/seed/version/core/serialization.py +++ b/seed/pydantic/version-no-default/src/seed/version/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/pydantic/version-no-default/src/seed/version/resources/user/user.py b/seed/pydantic/version-no-default/src/seed/version/resources/user/user.py index 9b7b4d46696..08d0bc82f84 100644 --- a/seed/pydantic/version-no-default/src/seed/version/resources/user/user.py +++ b/seed/pydantic/version-no-default/src/seed/version/resources/user/user.py @@ -1,19 +1,20 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from .user_id import UserId +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .user_id import UserId - class User(UniversalBaseModel): id: UserId name: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/version-no-default/tests/custom/test_client.py b/seed/pydantic/version-no-default/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/pydantic/version-no-default/tests/custom/test_client.py +++ b/seed/pydantic/version-no-default/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/pydantic/version/pyproject.toml b/seed/pydantic/version/pyproject.toml index 95eb254ba71..9827c60419d 100644 --- a/seed/pydantic/version/pyproject.toml +++ b/seed/pydantic/version/pyproject.toml @@ -41,6 +41,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/pydantic/version/src/seed/version/core/datetime_utils.py b/seed/pydantic/version/src/seed/version/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/pydantic/version/src/seed/version/core/datetime_utils.py +++ b/seed/pydantic/version/src/seed/version/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/pydantic/version/src/seed/version/core/pydantic_utilities.py b/seed/pydantic/version/src/seed/version/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/pydantic/version/src/seed/version/core/pydantic_utilities.py +++ b/seed/pydantic/version/src/seed/version/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/pydantic/version/src/seed/version/core/serialization.py b/seed/pydantic/version/src/seed/version/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/pydantic/version/src/seed/version/core/serialization.py +++ b/seed/pydantic/version/src/seed/version/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/pydantic/version/src/seed/version/resources/user/user.py b/seed/pydantic/version/src/seed/version/resources/user/user.py index 9b7b4d46696..08d0bc82f84 100644 --- a/seed/pydantic/version/src/seed/version/resources/user/user.py +++ b/seed/pydantic/version/src/seed/version/resources/user/user.py @@ -1,19 +1,20 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from .user_id import UserId +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .user_id import UserId - class User(UniversalBaseModel): id: UserId name: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/pydantic/version/tests/custom/test_client.py b/seed/pydantic/version/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/pydantic/version/tests/custom/test_client.py +++ b/seed/pydantic/version/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/pydantic/websocket/pyproject.toml b/seed/pydantic/websocket/pyproject.toml index 0273c1e07b2..233b5c56b37 100644 --- a/seed/pydantic/websocket/pyproject.toml +++ b/seed/pydantic/websocket/pyproject.toml @@ -40,6 +40,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/pydantic/websocket/src/seed/websocket/core/datetime_utils.py b/seed/pydantic/websocket/src/seed/websocket/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/pydantic/websocket/src/seed/websocket/core/datetime_utils.py +++ b/seed/pydantic/websocket/src/seed/websocket/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/pydantic/websocket/src/seed/websocket/core/pydantic_utilities.py b/seed/pydantic/websocket/src/seed/websocket/core/pydantic_utilities.py index 7c5418b5cf7..a93b06c3fca 100644 --- a/seed/pydantic/websocket/src/seed/websocket/core/pydantic_utilities.py +++ b/seed/pydantic/websocket/src/seed/websocket/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/pydantic/websocket/src/seed/websocket/core/serialization.py b/seed/pydantic/websocket/src/seed/websocket/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/pydantic/websocket/src/seed/websocket/core/serialization.py +++ b/seed/pydantic/websocket/src/seed/websocket/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/pydantic/websocket/tests/custom/test_client.py b/seed/pydantic/websocket/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/pydantic/websocket/tests/custom/test_client.py +++ b/seed/pydantic/websocket/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/python-sdk/alias-extends/pyproject.toml b/seed/python-sdk/alias-extends/pyproject.toml index d504d7617b7..db97ccb3def 100644 --- a/seed/python-sdk/alias-extends/pyproject.toml +++ b/seed/python-sdk/alias-extends/pyproject.toml @@ -43,6 +43,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/python-sdk/alias-extends/src/seed/__init__.py b/seed/python-sdk/alias-extends/src/seed/__init__.py index b5fdfda437c..52426d09df5 100644 --- a/seed/python-sdk/alias-extends/src/seed/__init__.py +++ b/seed/python-sdk/alias-extends/src/seed/__init__.py @@ -4,4 +4,11 @@ from .client import AsyncSeedAliasExtends, SeedAliasExtends from .version import __version__ -__all__ = ["AliasType", "AsyncSeedAliasExtends", "Child", "Parent", "SeedAliasExtends", "__version__"] +__all__ = [ + "AliasType", + "AsyncSeedAliasExtends", + "Child", + "Parent", + "SeedAliasExtends", + "__version__", +] diff --git a/seed/python-sdk/alias-extends/src/seed/client.py b/seed/python-sdk/alias-extends/src/seed/client.py index 34f650cade3..681303930e9 100644 --- a/seed/python-sdk/alias-extends/src/seed/client.py +++ b/seed/python-sdk/alias-extends/src/seed/client.py @@ -1,13 +1,12 @@ # This file was auto-generated by Fern from our API Definition. import typing -from json.decoder import JSONDecodeError - import httpx - -from .core.api_error import ApiError -from .core.client_wrapper import AsyncClientWrapper, SyncClientWrapper +from .core.client_wrapper import SyncClientWrapper from .core.request_options import RequestOptions +from json.decoder import JSONDecodeError +from .core.api_error import ApiError +from .core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -46,21 +45,29 @@ def __init__( base_url: str, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.Client] = None + httpx_client: typing.Optional[httpx.Client] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = SyncClientWrapper( base_url=base_url, httpx_client=httpx_client if httpx_client is not None - else httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.Client( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.Client(timeout=_defaulted_timeout), timeout=_defaulted_timeout, ) def extended_inline_request_body( - self, *, child: str, parent: str, request_options: typing.Optional[RequestOptions] = None + self, + *, + child: str, + parent: str, + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ Parameters @@ -91,7 +98,10 @@ def extended_inline_request_body( _response = self._client_wrapper.httpx_client.request( "extends/extended-inline-request-body", method="POST", - json={"child": child, "parent": parent}, + json={ + "child": child, + "parent": parent, + }, request_options=request_options, omit=OMIT, ) @@ -137,21 +147,29 @@ def __init__( base_url: str, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.AsyncClient] = None + httpx_client: typing.Optional[httpx.AsyncClient] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = AsyncClientWrapper( base_url=base_url, httpx_client=httpx_client if httpx_client is not None - else httpx.AsyncClient(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.AsyncClient( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.AsyncClient(timeout=_defaulted_timeout), timeout=_defaulted_timeout, ) async def extended_inline_request_body( - self, *, child: str, parent: str, request_options: typing.Optional[RequestOptions] = None + self, + *, + child: str, + parent: str, + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ Parameters @@ -190,7 +208,10 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( "extends/extended-inline-request-body", method="POST", - json={"child": child, "parent": parent}, + json={ + "child": child, + "parent": parent, + }, request_options=request_options, omit=OMIT, ) diff --git a/seed/python-sdk/alias-extends/src/seed/core/api_error.py b/seed/python-sdk/alias-extends/src/seed/core/api_error.py index 2e9fc5431cd..da734b58068 100644 --- a/seed/python-sdk/alias-extends/src/seed/core/api_error.py +++ b/seed/python-sdk/alias-extends/src/seed/core/api_error.py @@ -7,7 +7,9 @@ class ApiError(Exception): status_code: typing.Optional[int] body: typing.Any - def __init__(self, *, status_code: typing.Optional[int] = None, body: typing.Any = None): + def __init__( + self, *, status_code: typing.Optional[int] = None, body: typing.Any = None + ): self.status_code = status_code self.body = body diff --git a/seed/python-sdk/alias-extends/src/seed/core/client_wrapper.py b/seed/python-sdk/alias-extends/src/seed/core/client_wrapper.py index 96c69525624..e753ea94417 100644 --- a/seed/python-sdk/alias-extends/src/seed/core/client_wrapper.py +++ b/seed/python-sdk/alias-extends/src/seed/core/client_wrapper.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .http_client import AsyncHttpClient, HttpClient +from .http_client import HttpClient +from .http_client import AsyncHttpClient class BaseClientWrapper: @@ -28,7 +27,13 @@ def get_timeout(self) -> typing.Optional[float]: class SyncClientWrapper(BaseClientWrapper): - def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, httpx_client: httpx.Client): + def __init__( + self, + *, + base_url: str, + timeout: typing.Optional[float] = None, + httpx_client: httpx.Client, + ): super().__init__(base_url=base_url, timeout=timeout) self.httpx_client = HttpClient( httpx_client=httpx_client, @@ -39,7 +44,13 @@ def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, htt class AsyncClientWrapper(BaseClientWrapper): - def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, httpx_client: httpx.AsyncClient): + def __init__( + self, + *, + base_url: str, + timeout: typing.Optional[float] = None, + httpx_client: httpx.AsyncClient, + ): super().__init__(base_url=base_url, timeout=timeout) self.httpx_client = AsyncHttpClient( httpx_client=httpx_client, diff --git a/seed/python-sdk/alias-extends/src/seed/core/datetime_utils.py b/seed/python-sdk/alias-extends/src/seed/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/python-sdk/alias-extends/src/seed/core/datetime_utils.py +++ b/seed/python-sdk/alias-extends/src/seed/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/python-sdk/alias-extends/src/seed/core/file.py b/seed/python-sdk/alias-extends/src/seed/core/file.py index cb0d40bbbf3..6e0f92bfcb1 100644 --- a/seed/python-sdk/alias-extends/src/seed/core/file.py +++ b/seed/python-sdk/alias-extends/src/seed/core/file.py @@ -13,12 +13,17 @@ # (filename, file (or bytes), content_type) typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str]], # (filename, file (or bytes), content_type, headers) - typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str], typing.Mapping[str, str]], + typing.Tuple[ + typing.Optional[str], + FileContent, + typing.Optional[str], + typing.Mapping[str, str], + ], ] def convert_file_dict_to_httpx_tuples( - d: typing.Dict[str, typing.Union[File, typing.List[File]]] + d: typing.Dict[str, typing.Union[File, typing.List[File]]], ) -> typing.List[typing.Tuple[str, File]]: """ The format we use is a list of tuples, where the first element is the diff --git a/seed/python-sdk/alias-extends/src/seed/core/http_client.py b/seed/python-sdk/alias-extends/src/seed/core/http_client.py index 9333d8a7f15..091f71bc185 100644 --- a/seed/python-sdk/alias-extends/src/seed/core/http_client.py +++ b/seed/python-sdk/alias-extends/src/seed/core/http_client.py @@ -77,7 +77,9 @@ def _retry_timeout(response: httpx.Response, retries: int) -> float: return retry_after # Apply exponential backoff, capped at MAX_RETRY_DELAY_SECONDS. - retry_delay = min(INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS) + retry_delay = min( + INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS + ) # Add a randomness / jitter to the retry delay to avoid overwhelming the server with retries. timeout = retry_delay * (1 - 0.25 * random()) @@ -90,7 +92,8 @@ def _should_retry(response: httpx.Response) -> bool: def remove_omit_from_dict( - original: typing.Dict[str, typing.Optional[typing.Any]], omit: typing.Optional[typing.Any] + original: typing.Dict[str, typing.Optional[typing.Any]], + omit: typing.Optional[typing.Any], ) -> typing.Dict[str, typing.Any]: if omit is None: return original @@ -108,7 +111,8 @@ def maybe_filter_request_body( ) -> typing.Optional[typing.Any]: if data is None: return ( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else None ) @@ -118,7 +122,8 @@ def maybe_filter_request_body( data_content = { **(jsonable_encoder(remove_omit_from_dict(data, omit))), # type: ignore **( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else {} ), @@ -162,7 +167,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url def request( @@ -174,8 +181,12 @@ def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -184,11 +195,14 @@ def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) response = self.httpx_client.request( method=method, @@ -198,7 +212,11 @@ def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -209,7 +227,10 @@ def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -222,11 +243,15 @@ def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: time.sleep(_retry_timeout(response=response, retries=retries)) @@ -256,8 +281,12 @@ def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -266,11 +295,14 @@ def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) with self.httpx_client.stream( method=method, @@ -280,7 +312,11 @@ def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -291,7 +327,9 @@ def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -304,7 +342,9 @@ def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream @@ -327,7 +367,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url async def request( @@ -339,8 +381,12 @@ async def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -349,11 +395,14 @@ async def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) # Add the input to each of these and do None-safety checks response = await self.httpx_client.request( @@ -364,7 +413,11 @@ async def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -375,7 +428,10 @@ async def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -388,11 +444,15 @@ async def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: await asyncio.sleep(_retry_timeout(response=response, retries=retries)) @@ -421,8 +481,12 @@ async def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -431,11 +495,14 @@ async def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) async with self.httpx_client.stream( method=method, @@ -445,7 +512,11 @@ async def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -456,7 +527,9 @@ async def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -469,7 +542,9 @@ async def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream diff --git a/seed/python-sdk/alias-extends/src/seed/core/jsonable_encoder.py b/seed/python-sdk/alias-extends/src/seed/core/jsonable_encoder.py index d3fd328fd41..12a8b52fc22 100644 --- a/seed/python-sdk/alias-extends/src/seed/core/jsonable_encoder.py +++ b/seed/python-sdk/alias-extends/src/seed/core/jsonable_encoder.py @@ -19,13 +19,19 @@ import pydantic from .datetime_utils import serialize_datetime -from .pydantic_utilities import IS_PYDANTIC_V2, encode_by_type, to_jsonable_with_fallback +from .pydantic_utilities import ( + IS_PYDANTIC_V2, + encode_by_type, + to_jsonable_with_fallback, +) SetIntStr = Set[Union[int, str]] DictIntStrAny = Dict[Union[int, str], Any] -def jsonable_encoder(obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None) -> Any: +def jsonable_encoder( + obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None +) -> Any: custom_encoder = custom_encoder or {} if custom_encoder: if type(obj) in custom_encoder: diff --git a/seed/python-sdk/alias-extends/src/seed/core/pydantic_utilities.py b/seed/python-sdk/alias-extends/src/seed/core/pydantic_utilities.py index 170a563d6eb..c63935c32a2 100644 --- a/seed/python-sdk/alias-extends/src/seed/core/pydantic_utilities.py +++ b/seed/python-sdk/alias-extends/src/seed/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) # type: ignore # Pydantic v1 diff --git a/seed/python-sdk/alias-extends/src/seed/core/query_encoder.py b/seed/python-sdk/alias-extends/src/seed/core/query_encoder.py index 24076d72ee9..7cb98f52cd7 100644 --- a/seed/python-sdk/alias-extends/src/seed/core/query_encoder.py +++ b/seed/python-sdk/alias-extends/src/seed/core/query_encoder.py @@ -7,7 +7,9 @@ # Flattens dicts to be of the form {"key[subkey][subkey2]": value} where value is not a dict -def traverse_query_dict(dict_flat: Dict[str, Any], key_prefix: Optional[str] = None) -> Dict[str, Any]: +def traverse_query_dict( + dict_flat: Dict[str, Any], key_prefix: Optional[str] = None +) -> Dict[str, Any]: result = {} for k, v in dict_flat.items(): key = f"{key_prefix}[{k}]" if key_prefix is not None else k @@ -30,4 +32,8 @@ def single_query_encoder(query_key: str, query_value: Any) -> Dict[str, Any]: def encode_query(query: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: - return dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) if query is not None else None + return ( + dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) + if query is not None + else None + ) diff --git a/seed/python-sdk/alias-extends/src/seed/core/serialization.py b/seed/python-sdk/alias-extends/src/seed/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/python-sdk/alias-extends/src/seed/core/serialization.py +++ b/seed/python-sdk/alias-extends/src/seed/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/python-sdk/alias-extends/src/seed/types/child.py b/seed/python-sdk/alias-extends/src/seed/types/child.py index 8bc4752b866..d23c490b202 100644 --- a/seed/python-sdk/alias-extends/src/seed/types/child.py +++ b/seed/python-sdk/alias-extends/src/seed/types/child.py @@ -1,12 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from .parent import Parent +from ..core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ..core.pydantic_utilities import IS_PYDANTIC_V2 -from .parent import Parent - class Child(Parent): """ @@ -23,7 +21,9 @@ class Child(Parent): child: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/alias-extends/src/seed/types/parent.py b/seed/python-sdk/alias-extends/src/seed/types/parent.py index ff9ac6ac3cb..2b90f96b968 100644 --- a/seed/python-sdk/alias-extends/src/seed/types/parent.py +++ b/seed/python-sdk/alias-extends/src/seed/types/parent.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from ..core.pydantic_utilities import UniversalBaseModel +from ..core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class Parent(UniversalBaseModel): """ @@ -21,7 +20,9 @@ class Parent(UniversalBaseModel): parent: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/alias-extends/src/seed/version.py b/seed/python-sdk/alias-extends/src/seed/version.py index 8093dc025c3..1d2ebf33b22 100644 --- a/seed/python-sdk/alias-extends/src/seed/version.py +++ b/seed/python-sdk/alias-extends/src/seed/version.py @@ -1,4 +1,3 @@ - from importlib import metadata __version__ = metadata.version("fern_alias-extends") diff --git a/seed/python-sdk/alias-extends/tests/conftest.py b/seed/python-sdk/alias-extends/tests/conftest.py index 56d2cb80c55..c1f6af60887 100644 --- a/seed/python-sdk/alias-extends/tests/conftest.py +++ b/seed/python-sdk/alias-extends/tests/conftest.py @@ -1,9 +1,9 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedAliasExtends import os - import pytest -from seed import AsyncSeedAliasExtends, SeedAliasExtends +from seed import AsyncSeedAliasExtends @pytest.fixture diff --git a/seed/python-sdk/alias-extends/tests/custom/test_client.py b/seed/python-sdk/alias-extends/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/python-sdk/alias-extends/tests/custom/test_client.py +++ b/seed/python-sdk/alias-extends/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/python-sdk/alias-extends/tests/test_root.py b/seed/python-sdk/alias-extends/tests/test_root.py index bff235b6549..cdfb4fa93d8 100644 --- a/seed/python-sdk/alias-extends/tests/test_root.py +++ b/seed/python-sdk/alias-extends/tests/test_root.py @@ -1,10 +1,16 @@ # This file was auto-generated by Fern from our API Definition. -from seed import AsyncSeedAliasExtends, SeedAliasExtends +from seed import SeedAliasExtends +from seed import AsyncSeedAliasExtends -async def test_extended_inline_request_body(client: SeedAliasExtends, async_client: AsyncSeedAliasExtends) -> None: +async def test_extended_inline_request_body( + client: SeedAliasExtends, async_client: AsyncSeedAliasExtends +) -> None: # Type ignore to avoid mypy complaining about the function not being meant to return a value assert client.extended_inline_request_body(child="string", parent="string") is None # type: ignore[func-returns-value] - assert await async_client.extended_inline_request_body(child="string", parent="string") is None # type: ignore[func-returns-value] + assert ( + await async_client.extended_inline_request_body(child="string", parent="string") + is None + ) # type: ignore[func-returns-value] diff --git a/seed/python-sdk/alias-extends/tests/utilities.py b/seed/python-sdk/alias-extends/tests/utilities.py index 13da208eb3a..e8f4472564c 100644 --- a/seed/python-sdk/alias-extends/tests/utilities.py +++ b/seed/python-sdk/alias-extends/tests/utilities.py @@ -3,11 +3,14 @@ import typing import uuid -import pydantic from dateutil import parser +import pydantic + -def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> typing.Any: +def cast_field( + json_expectation: typing.Any, type_expectation: typing.Any +) -> typing.Any: # Cast these specific types which come through as string and expect our # models to cast to the correct type. if type_expectation == "uuid": @@ -25,7 +28,9 @@ def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> ty return json_expectation -def validate_field(response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any) -> None: +def validate_field( + response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectation == "no_validate": return @@ -44,7 +49,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(entry_expectation, dict): is_container_of_complex_type = True validate_response( - response=response[idx], json_expectation=ex, type_expectations=entry_expectation + response=response[idx], + json_expectation=ex, + type_expectations=entry_expectation, ) else: cast_json_expectation.append(cast_field(ex, entry_expectation)) @@ -56,7 +63,10 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # if any of the values of the set have a type_expectation of a dict, we're assuming it's a pydantic # model and keeping it a list. if container_expectation != "set" or not any( - map(lambda value: isinstance(value, dict), list(contents_expectation.values())) + map( + lambda value: isinstance(value, dict), + list(contents_expectation.values()), + ) ): json_expectation = cast_field(json_expectation, container_expectation) elif isinstance(type_expectation, tuple): @@ -65,9 +75,15 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(contents_expectation, dict): json_expectation = { cast_field( - key, contents_expectation.get(idx)[0] if contents_expectation.get(idx) is not None else None # type: ignore + key, + contents_expectation.get(idx)[0] + if contents_expectation.get(idx) is not None + else None, # type: ignore ): cast_field( - value, contents_expectation.get(idx)[1] if contents_expectation.get(idx) is not None else None # type: ignore + value, + contents_expectation.get(idx)[1] + if contents_expectation.get(idx) is not None + else None, # type: ignore ) for idx, (key, value) in enumerate(json_expectation.items()) } @@ -86,7 +102,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # Arg type_expectations is a deeply nested structure that matches the response, but with the values replaced with the expected types -def validate_response(response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any) -> None: +def validate_response( + response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectations == "no_validate": return @@ -96,11 +114,17 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e and not isinstance(response, dict) and not issubclass(type(response), pydantic.BaseModel) ): - validate_field(response=response, json_expectation=json_expectation, type_expectation=type_expectations) + validate_field( + response=response, + json_expectation=json_expectation, + type_expectation=type_expectations, + ) return if isinstance(response, list): - assert len(response) == len(json_expectation), "Length mismatch, expected: {0}, Actual: {1}".format( + assert len(response) == len( + json_expectation + ), "Length mismatch, expected: {0}, Actual: {1}".format( len(response), len(json_expectation) ) content_expectation = type_expectations @@ -108,7 +132,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e content_expectation = type_expectations[1] for idx, item in enumerate(response): validate_response( - response=item, json_expectation=json_expectation[idx], type_expectations=content_expectation[idx] + response=item, + json_expectation=json_expectation[idx], + type_expectations=content_expectation[idx], ) else: response_json = response @@ -116,7 +142,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e response_json = response.dict(by_alias=True) for key, value in json_expectation.items(): - assert key in response_json, "Field {0} not found within the response object: {1}".format( + assert ( + key in response_json + ), "Field {0} not found within the response object: {1}".format( key, response_json ) @@ -128,11 +156,19 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e # Otherwise, we're just validating a single field that's a pydantic model. if isinstance(value, dict) and not isinstance(type_expectation, tuple): validate_response( - response=response_json[key], json_expectation=value, type_expectations=type_expectation + response=response_json[key], + json_expectation=value, + type_expectations=type_expectation, ) else: - validate_field(response=response_json[key], json_expectation=value, type_expectation=type_expectation) + validate_field( + response=response_json[key], + json_expectation=value, + type_expectation=type_expectation, + ) # Ensure there are no additional fields here either del response_json[key] - assert len(response_json) == 0, "Additional fields found, expected None: {0}".format(response_json) + assert ( + len(response_json) == 0 + ), "Additional fields found, expected None: {0}".format(response_json) diff --git a/seed/python-sdk/alias-extends/tests/utils/assets/models/__init__.py b/seed/python-sdk/alias-extends/tests/utils/assets/models/__init__.py index 2cf01263529..3a1c852e71e 100644 --- a/seed/python-sdk/alias-extends/tests/utils/assets/models/__init__.py +++ b/seed/python-sdk/alias-extends/tests/utils/assets/models/__init__.py @@ -5,7 +5,7 @@ from .circle import CircleParams from .object_with_defaults import ObjectWithDefaultsParams from .object_with_optional_field import ObjectWithOptionalFieldParams -from .shape import Shape_CircleParams, Shape_SquareParams, ShapeParams +from .shape import ShapeParams, Shape_CircleParams, Shape_SquareParams from .square import SquareParams from .undiscriminated_shape import UndiscriminatedShapeParams diff --git a/seed/python-sdk/alias-extends/tests/utils/assets/models/circle.py b/seed/python-sdk/alias-extends/tests/utils/assets/models/circle.py index af7a1bf8a8e..253f12d38b3 100644 --- a/seed/python-sdk/alias-extends/tests/utils/assets/models/circle.py +++ b/seed/python-sdk/alias-extends/tests/utils/assets/models/circle.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class CircleParams(typing_extensions.TypedDict): - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] diff --git a/seed/python-sdk/alias-extends/tests/utils/assets/models/object_with_optional_field.py b/seed/python-sdk/alias-extends/tests/utils/assets/models/object_with_optional_field.py index 3ad93d5f305..ebe7dc80547 100644 --- a/seed/python-sdk/alias-extends/tests/utils/assets/models/object_with_optional_field.py +++ b/seed/python-sdk/alias-extends/tests/utils/assets/models/object_with_optional_field.py @@ -7,8 +7,8 @@ import uuid import typing_extensions -from seed.core.serialization import FieldMetadata +from seed.core.serialization import FieldMetadata from .color import Color from .shape import ShapeParams from .undiscriminated_shape import UndiscriminatedShapeParams @@ -18,16 +18,30 @@ class ObjectWithOptionalFieldParams(typing_extensions.TypedDict): literal: typing.Literal["lit_one"] string: typing_extensions.NotRequired[str] integer: typing_extensions.NotRequired[int] - long_: typing_extensions.NotRequired[typing_extensions.Annotated[int, FieldMetadata(alias="long")]] + long_: typing_extensions.NotRequired[ + typing_extensions.Annotated[int, FieldMetadata(alias="long")] + ] double: typing_extensions.NotRequired[float] - bool_: typing_extensions.NotRequired[typing_extensions.Annotated[bool, FieldMetadata(alias="bool")]] + bool_: typing_extensions.NotRequired[ + typing_extensions.Annotated[bool, FieldMetadata(alias="bool")] + ] datetime: typing_extensions.NotRequired[dt.datetime] date: typing_extensions.NotRequired[dt.date] - uuid_: typing_extensions.NotRequired[typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")]] - base_64: typing_extensions.NotRequired[typing_extensions.Annotated[str, FieldMetadata(alias="base64")]] - list_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")]] - set_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")]] - map_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")]] + uuid_: typing_extensions.NotRequired[ + typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")] + ] + base_64: typing_extensions.NotRequired[ + typing_extensions.Annotated[str, FieldMetadata(alias="base64")] + ] + list_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")] + ] + set_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")] + ] + map_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")] + ] enum: typing_extensions.NotRequired[Color] union: typing_extensions.NotRequired[ShapeParams] second_union: typing_extensions.NotRequired[ShapeParams] diff --git a/seed/python-sdk/alias-extends/tests/utils/assets/models/shape.py b/seed/python-sdk/alias-extends/tests/utils/assets/models/shape.py index 2c33c877951..816ffc51bdc 100644 --- a/seed/python-sdk/alias-extends/tests/utils/assets/models/shape.py +++ b/seed/python-sdk/alias-extends/tests/utils/assets/models/shape.py @@ -7,6 +7,7 @@ import typing import typing_extensions + from seed.core.serialization import FieldMetadata @@ -15,13 +16,21 @@ class Base(typing_extensions.TypedDict): class Shape_CircleParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["circle"], FieldMetadata(alias="shapeType")] - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["circle"], FieldMetadata(alias="shapeType") + ] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] class Shape_SquareParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["square"], FieldMetadata(alias="shapeType")] - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["square"], FieldMetadata(alias="shapeType") + ] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] ShapeParams = typing.Union[Shape_CircleParams, Shape_SquareParams] diff --git a/seed/python-sdk/alias-extends/tests/utils/assets/models/square.py b/seed/python-sdk/alias-extends/tests/utils/assets/models/square.py index b9b7dd319bc..bcf08a723c5 100644 --- a/seed/python-sdk/alias-extends/tests/utils/assets/models/square.py +++ b/seed/python-sdk/alias-extends/tests/utils/assets/models/square.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class SquareParams(typing_extensions.TypedDict): - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] diff --git a/seed/python-sdk/alias-extends/tests/utils/test_http_client.py b/seed/python-sdk/alias-extends/tests/utils/test_http_client.py index edd11ca7afb..f5a874a75f3 100644 --- a/seed/python-sdk/alias-extends/tests/utils/test_http_client.py +++ b/seed/python-sdk/alias-extends/tests/utils/test_http_client.py @@ -9,12 +9,17 @@ def get_request_options() -> RequestOptions: def test_get_json_request_body() -> None: - json_body, data_body = get_request_body(json={"hello": "world"}, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json={"hello": "world"}, data=None, request_options=None, omit=None + ) assert json_body == {"hello": "world"} assert data_body is None json_body_extras, data_body_extras = get_request_body( - json={"goodbye": "world"}, data=None, request_options=get_request_options(), omit=None + json={"goodbye": "world"}, + data=None, + request_options=get_request_options(), + omit=None, ) assert json_body_extras == {"goodbye": "world", "see you": "later"} @@ -22,12 +27,17 @@ def test_get_json_request_body() -> None: def test_get_files_request_body() -> None: - json_body, data_body = get_request_body(json=None, data={"hello": "world"}, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data={"hello": "world"}, request_options=None, omit=None + ) assert data_body == {"hello": "world"} assert json_body is None json_body_extras, data_body_extras = get_request_body( - json=None, data={"goodbye": "world"}, request_options=get_request_options(), omit=None + json=None, + data={"goodbye": "world"}, + request_options=get_request_options(), + omit=None, ) assert data_body_extras == {"goodbye": "world", "see you": "later"} @@ -35,7 +45,9 @@ def test_get_files_request_body() -> None: def test_get_none_request_body() -> None: - json_body, data_body = get_request_body(json=None, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data=None, request_options=None, omit=None + ) assert data_body is None assert json_body is None diff --git a/seed/python-sdk/alias-extends/tests/utils/test_query_encoding.py b/seed/python-sdk/alias-extends/tests/utils/test_query_encoding.py index 247e1551b46..fbc8f402167 100644 --- a/seed/python-sdk/alias-extends/tests/utils/test_query_encoding.py +++ b/seed/python-sdk/alias-extends/tests/utils/test_query_encoding.py @@ -4,9 +4,15 @@ def test_query_encoding() -> None: - assert encode_query({"hello world": "hello world"}) == {"hello world": "hello world"} - assert encode_query({"hello_world": {"hello": "world"}}) == {"hello_world[hello]": "world"} - assert encode_query({"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"}) == { + assert encode_query({"hello world": "hello world"}) == { + "hello world": "hello world" + } + assert encode_query({"hello_world": {"hello": "world"}}) == { + "hello_world[hello]": "world" + } + assert encode_query( + {"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"} + ) == { "hello_world[hello][world]": "today", "hello_world[test]": "this", "hi": "there", diff --git a/seed/python-sdk/alias-extends/tests/utils/test_serialization.py b/seed/python-sdk/alias-extends/tests/utils/test_serialization.py index 58b1ed66e6d..5ca956916dd 100644 --- a/seed/python-sdk/alias-extends/tests/utils/test_serialization.py +++ b/seed/python-sdk/alias-extends/tests/utils/test_serialization.py @@ -1,10 +1,12 @@ # This file was auto-generated by Fern from our API Definition. -from typing import Any, List +from typing import List, Any -from seed.core.serialization import convert_and_respect_annotation_metadata +from seed.core.serialization import ( + convert_and_respect_annotation_metadata, +) +from .assets.models import ShapeParams, ObjectWithOptionalFieldParams -from .assets.models import ObjectWithOptionalFieldParams, ShapeParams UNION_TEST: ShapeParams = {"radius_measurement": 1.0, "shape_type": "circle", "id": "1"} UNION_TEST_CONVERTED = {"shapeType": "circle", "radiusMeasurement": 1.0, "id": "1"} @@ -18,20 +20,54 @@ def test_convert_and_respect_annotation_metadata() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) - assert converted == {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"} + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) + assert converted == { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + } def test_convert_and_respect_annotation_metadata_in_list() -> None: data: List[ObjectWithOptionalFieldParams] = [ - {"string": "string", "long_": 12345, "bool_": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long_": 67890, "list_": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long_": 12345, + "bool_": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long_": 67890, + "list_": [], + "literal": "lit_one", + "any": "any", + }, ] - converted = convert_and_respect_annotation_metadata(object_=data, annotation=List[ObjectWithOptionalFieldParams]) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=List[ObjectWithOptionalFieldParams] + ) assert converted == [ - {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long": 67890, "list": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long": 67890, + "list": [], + "literal": "lit_one", + "any": "any", + }, ] @@ -43,7 +79,9 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) assert converted == { "string": "string", @@ -55,12 +93,16 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: def test_convert_and_respect_annotation_metadata_in_union() -> None: - converted = convert_and_respect_annotation_metadata(object_=UNION_TEST, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=UNION_TEST, annotation=ShapeParams + ) assert converted == UNION_TEST_CONVERTED def test_convert_and_respect_annotation_metadata_with_empty_object() -> None: data: Any = {} - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ShapeParams + ) assert converted == data diff --git a/seed/python-sdk/alias/pyproject.toml b/seed/python-sdk/alias/pyproject.toml index 350af97a526..fb013d43c47 100644 --- a/seed/python-sdk/alias/pyproject.toml +++ b/seed/python-sdk/alias/pyproject.toml @@ -43,6 +43,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/python-sdk/alias/src/seed/client.py b/seed/python-sdk/alias/src/seed/client.py index 9b7951f8c21..c1709cf5014 100644 --- a/seed/python-sdk/alias/src/seed/client.py +++ b/seed/python-sdk/alias/src/seed/client.py @@ -1,15 +1,14 @@ # This file was auto-generated by Fern from our API Definition. import typing -from json.decoder import JSONDecodeError - import httpx - -from .core.api_error import ApiError -from .core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from .core.jsonable_encoder import jsonable_encoder -from .core.request_options import RequestOptions +from .core.client_wrapper import SyncClientWrapper from .types.type_id import TypeId +from .core.request_options import RequestOptions +from .core.jsonable_encoder import jsonable_encoder +from json.decoder import JSONDecodeError +from .core.api_error import ApiError +from .core.client_wrapper import AsyncClientWrapper class SeedAlias: @@ -47,18 +46,27 @@ def __init__( follow_redirects: typing.Optional[bool] = True, httpx_client: typing.Optional[httpx.Client] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = SyncClientWrapper( base_url=base_url, httpx_client=httpx_client if httpx_client is not None - else httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.Client( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.Client(timeout=_defaulted_timeout), timeout=_defaulted_timeout, ) - def get(self, type_id: TypeId, *, request_options: typing.Optional[RequestOptions] = None) -> None: + def get( + self, + type_id: TypeId, + *, + request_options: typing.Optional[RequestOptions] = None, + ) -> None: """ Parameters ---------- @@ -83,7 +91,9 @@ def get(self, type_id: TypeId, *, request_options: typing.Optional[RequestOption ) """ _response = self._client_wrapper.httpx_client.request( - f"{jsonable_encoder(type_id)}", method="GET", request_options=request_options + f"{jsonable_encoder(type_id)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: @@ -129,18 +139,27 @@ def __init__( follow_redirects: typing.Optional[bool] = True, httpx_client: typing.Optional[httpx.AsyncClient] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = AsyncClientWrapper( base_url=base_url, httpx_client=httpx_client if httpx_client is not None - else httpx.AsyncClient(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.AsyncClient( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.AsyncClient(timeout=_defaulted_timeout), timeout=_defaulted_timeout, ) - async def get(self, type_id: TypeId, *, request_options: typing.Optional[RequestOptions] = None) -> None: + async def get( + self, + type_id: TypeId, + *, + request_options: typing.Optional[RequestOptions] = None, + ) -> None: """ Parameters ---------- @@ -173,7 +192,9 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - f"{jsonable_encoder(type_id)}", method="GET", request_options=request_options + f"{jsonable_encoder(type_id)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: diff --git a/seed/python-sdk/alias/src/seed/core/api_error.py b/seed/python-sdk/alias/src/seed/core/api_error.py index 2e9fc5431cd..da734b58068 100644 --- a/seed/python-sdk/alias/src/seed/core/api_error.py +++ b/seed/python-sdk/alias/src/seed/core/api_error.py @@ -7,7 +7,9 @@ class ApiError(Exception): status_code: typing.Optional[int] body: typing.Any - def __init__(self, *, status_code: typing.Optional[int] = None, body: typing.Any = None): + def __init__( + self, *, status_code: typing.Optional[int] = None, body: typing.Any = None + ): self.status_code = status_code self.body = body diff --git a/seed/python-sdk/alias/src/seed/core/client_wrapper.py b/seed/python-sdk/alias/src/seed/core/client_wrapper.py index 808252942db..45af8938e31 100644 --- a/seed/python-sdk/alias/src/seed/core/client_wrapper.py +++ b/seed/python-sdk/alias/src/seed/core/client_wrapper.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .http_client import AsyncHttpClient, HttpClient +from .http_client import HttpClient +from .http_client import AsyncHttpClient class BaseClientWrapper: @@ -28,7 +27,13 @@ def get_timeout(self) -> typing.Optional[float]: class SyncClientWrapper(BaseClientWrapper): - def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, httpx_client: httpx.Client): + def __init__( + self, + *, + base_url: str, + timeout: typing.Optional[float] = None, + httpx_client: httpx.Client, + ): super().__init__(base_url=base_url, timeout=timeout) self.httpx_client = HttpClient( httpx_client=httpx_client, @@ -39,7 +44,13 @@ def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, htt class AsyncClientWrapper(BaseClientWrapper): - def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, httpx_client: httpx.AsyncClient): + def __init__( + self, + *, + base_url: str, + timeout: typing.Optional[float] = None, + httpx_client: httpx.AsyncClient, + ): super().__init__(base_url=base_url, timeout=timeout) self.httpx_client = AsyncHttpClient( httpx_client=httpx_client, diff --git a/seed/python-sdk/alias/src/seed/core/datetime_utils.py b/seed/python-sdk/alias/src/seed/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/python-sdk/alias/src/seed/core/datetime_utils.py +++ b/seed/python-sdk/alias/src/seed/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/python-sdk/alias/src/seed/core/file.py b/seed/python-sdk/alias/src/seed/core/file.py index cb0d40bbbf3..6e0f92bfcb1 100644 --- a/seed/python-sdk/alias/src/seed/core/file.py +++ b/seed/python-sdk/alias/src/seed/core/file.py @@ -13,12 +13,17 @@ # (filename, file (or bytes), content_type) typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str]], # (filename, file (or bytes), content_type, headers) - typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str], typing.Mapping[str, str]], + typing.Tuple[ + typing.Optional[str], + FileContent, + typing.Optional[str], + typing.Mapping[str, str], + ], ] def convert_file_dict_to_httpx_tuples( - d: typing.Dict[str, typing.Union[File, typing.List[File]]] + d: typing.Dict[str, typing.Union[File, typing.List[File]]], ) -> typing.List[typing.Tuple[str, File]]: """ The format we use is a list of tuples, where the first element is the diff --git a/seed/python-sdk/alias/src/seed/core/http_client.py b/seed/python-sdk/alias/src/seed/core/http_client.py index 9333d8a7f15..091f71bc185 100644 --- a/seed/python-sdk/alias/src/seed/core/http_client.py +++ b/seed/python-sdk/alias/src/seed/core/http_client.py @@ -77,7 +77,9 @@ def _retry_timeout(response: httpx.Response, retries: int) -> float: return retry_after # Apply exponential backoff, capped at MAX_RETRY_DELAY_SECONDS. - retry_delay = min(INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS) + retry_delay = min( + INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS + ) # Add a randomness / jitter to the retry delay to avoid overwhelming the server with retries. timeout = retry_delay * (1 - 0.25 * random()) @@ -90,7 +92,8 @@ def _should_retry(response: httpx.Response) -> bool: def remove_omit_from_dict( - original: typing.Dict[str, typing.Optional[typing.Any]], omit: typing.Optional[typing.Any] + original: typing.Dict[str, typing.Optional[typing.Any]], + omit: typing.Optional[typing.Any], ) -> typing.Dict[str, typing.Any]: if omit is None: return original @@ -108,7 +111,8 @@ def maybe_filter_request_body( ) -> typing.Optional[typing.Any]: if data is None: return ( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else None ) @@ -118,7 +122,8 @@ def maybe_filter_request_body( data_content = { **(jsonable_encoder(remove_omit_from_dict(data, omit))), # type: ignore **( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else {} ), @@ -162,7 +167,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url def request( @@ -174,8 +181,12 @@ def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -184,11 +195,14 @@ def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) response = self.httpx_client.request( method=method, @@ -198,7 +212,11 @@ def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -209,7 +227,10 @@ def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -222,11 +243,15 @@ def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: time.sleep(_retry_timeout(response=response, retries=retries)) @@ -256,8 +281,12 @@ def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -266,11 +295,14 @@ def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) with self.httpx_client.stream( method=method, @@ -280,7 +312,11 @@ def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -291,7 +327,9 @@ def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -304,7 +342,9 @@ def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream @@ -327,7 +367,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url async def request( @@ -339,8 +381,12 @@ async def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -349,11 +395,14 @@ async def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) # Add the input to each of these and do None-safety checks response = await self.httpx_client.request( @@ -364,7 +413,11 @@ async def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -375,7 +428,10 @@ async def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -388,11 +444,15 @@ async def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: await asyncio.sleep(_retry_timeout(response=response, retries=retries)) @@ -421,8 +481,12 @@ async def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -431,11 +495,14 @@ async def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) async with self.httpx_client.stream( method=method, @@ -445,7 +512,11 @@ async def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -456,7 +527,9 @@ async def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -469,7 +542,9 @@ async def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream diff --git a/seed/python-sdk/alias/src/seed/core/jsonable_encoder.py b/seed/python-sdk/alias/src/seed/core/jsonable_encoder.py index d3fd328fd41..12a8b52fc22 100644 --- a/seed/python-sdk/alias/src/seed/core/jsonable_encoder.py +++ b/seed/python-sdk/alias/src/seed/core/jsonable_encoder.py @@ -19,13 +19,19 @@ import pydantic from .datetime_utils import serialize_datetime -from .pydantic_utilities import IS_PYDANTIC_V2, encode_by_type, to_jsonable_with_fallback +from .pydantic_utilities import ( + IS_PYDANTIC_V2, + encode_by_type, + to_jsonable_with_fallback, +) SetIntStr = Set[Union[int, str]] DictIntStrAny = Dict[Union[int, str], Any] -def jsonable_encoder(obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None) -> Any: +def jsonable_encoder( + obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None +) -> Any: custom_encoder = custom_encoder or {} if custom_encoder: if type(obj) in custom_encoder: diff --git a/seed/python-sdk/alias/src/seed/core/pydantic_utilities.py b/seed/python-sdk/alias/src/seed/core/pydantic_utilities.py index 170a563d6eb..c63935c32a2 100644 --- a/seed/python-sdk/alias/src/seed/core/pydantic_utilities.py +++ b/seed/python-sdk/alias/src/seed/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) # type: ignore # Pydantic v1 diff --git a/seed/python-sdk/alias/src/seed/core/query_encoder.py b/seed/python-sdk/alias/src/seed/core/query_encoder.py index 24076d72ee9..7cb98f52cd7 100644 --- a/seed/python-sdk/alias/src/seed/core/query_encoder.py +++ b/seed/python-sdk/alias/src/seed/core/query_encoder.py @@ -7,7 +7,9 @@ # Flattens dicts to be of the form {"key[subkey][subkey2]": value} where value is not a dict -def traverse_query_dict(dict_flat: Dict[str, Any], key_prefix: Optional[str] = None) -> Dict[str, Any]: +def traverse_query_dict( + dict_flat: Dict[str, Any], key_prefix: Optional[str] = None +) -> Dict[str, Any]: result = {} for k, v in dict_flat.items(): key = f"{key_prefix}[{k}]" if key_prefix is not None else k @@ -30,4 +32,8 @@ def single_query_encoder(query_key: str, query_value: Any) -> Dict[str, Any]: def encode_query(query: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: - return dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) if query is not None else None + return ( + dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) + if query is not None + else None + ) diff --git a/seed/python-sdk/alias/src/seed/core/serialization.py b/seed/python-sdk/alias/src/seed/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/python-sdk/alias/src/seed/core/serialization.py +++ b/seed/python-sdk/alias/src/seed/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/python-sdk/alias/src/seed/types/type.py b/seed/python-sdk/alias/src/seed/types/type.py index 437a1e2c551..d2810ef4100 100644 --- a/seed/python-sdk/alias/src/seed/types/type.py +++ b/seed/python-sdk/alias/src/seed/types/type.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. +from ..core.pydantic_utilities import UniversalBaseModel +from .type_id import TypeId +from ..core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .type_id import TypeId - class Type(UniversalBaseModel): """ @@ -26,7 +25,9 @@ class Type(UniversalBaseModel): name: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/alias/src/seed/types/type_id.py b/seed/python-sdk/alias/src/seed/types/type_id.py index 5cd53c920d5..c5f3b3bb32e 100644 --- a/seed/python-sdk/alias/src/seed/types/type_id.py +++ b/seed/python-sdk/alias/src/seed/types/type_id.py @@ -3,4 +3,5 @@ """ "type-kaljhv87" """ + TypeId = str diff --git a/seed/python-sdk/alias/src/seed/version.py b/seed/python-sdk/alias/src/seed/version.py index 04901095f01..4ee338edbf9 100644 --- a/seed/python-sdk/alias/src/seed/version.py +++ b/seed/python-sdk/alias/src/seed/version.py @@ -1,4 +1,3 @@ - from importlib import metadata __version__ = metadata.version("fern_alias") diff --git a/seed/python-sdk/alias/tests/conftest.py b/seed/python-sdk/alias/tests/conftest.py index e789608eeec..a5a6ed2b47e 100644 --- a/seed/python-sdk/alias/tests/conftest.py +++ b/seed/python-sdk/alias/tests/conftest.py @@ -1,9 +1,9 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedAlias import os - import pytest -from seed import AsyncSeedAlias, SeedAlias +from seed import AsyncSeedAlias @pytest.fixture diff --git a/seed/python-sdk/alias/tests/custom/test_client.py b/seed/python-sdk/alias/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/python-sdk/alias/tests/custom/test_client.py +++ b/seed/python-sdk/alias/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/python-sdk/alias/tests/test_root.py b/seed/python-sdk/alias/tests/test_root.py index 83e9594399b..f286973df35 100644 --- a/seed/python-sdk/alias/tests/test_root.py +++ b/seed/python-sdk/alias/tests/test_root.py @@ -1,6 +1,7 @@ # This file was auto-generated by Fern from our API Definition. -from seed import AsyncSeedAlias, SeedAlias +from seed import SeedAlias +from seed import AsyncSeedAlias async def test_get(client: SeedAlias, async_client: AsyncSeedAlias) -> None: diff --git a/seed/python-sdk/alias/tests/utilities.py b/seed/python-sdk/alias/tests/utilities.py index 13da208eb3a..e8f4472564c 100644 --- a/seed/python-sdk/alias/tests/utilities.py +++ b/seed/python-sdk/alias/tests/utilities.py @@ -3,11 +3,14 @@ import typing import uuid -import pydantic from dateutil import parser +import pydantic + -def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> typing.Any: +def cast_field( + json_expectation: typing.Any, type_expectation: typing.Any +) -> typing.Any: # Cast these specific types which come through as string and expect our # models to cast to the correct type. if type_expectation == "uuid": @@ -25,7 +28,9 @@ def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> ty return json_expectation -def validate_field(response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any) -> None: +def validate_field( + response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectation == "no_validate": return @@ -44,7 +49,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(entry_expectation, dict): is_container_of_complex_type = True validate_response( - response=response[idx], json_expectation=ex, type_expectations=entry_expectation + response=response[idx], + json_expectation=ex, + type_expectations=entry_expectation, ) else: cast_json_expectation.append(cast_field(ex, entry_expectation)) @@ -56,7 +63,10 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # if any of the values of the set have a type_expectation of a dict, we're assuming it's a pydantic # model and keeping it a list. if container_expectation != "set" or not any( - map(lambda value: isinstance(value, dict), list(contents_expectation.values())) + map( + lambda value: isinstance(value, dict), + list(contents_expectation.values()), + ) ): json_expectation = cast_field(json_expectation, container_expectation) elif isinstance(type_expectation, tuple): @@ -65,9 +75,15 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(contents_expectation, dict): json_expectation = { cast_field( - key, contents_expectation.get(idx)[0] if contents_expectation.get(idx) is not None else None # type: ignore + key, + contents_expectation.get(idx)[0] + if contents_expectation.get(idx) is not None + else None, # type: ignore ): cast_field( - value, contents_expectation.get(idx)[1] if contents_expectation.get(idx) is not None else None # type: ignore + value, + contents_expectation.get(idx)[1] + if contents_expectation.get(idx) is not None + else None, # type: ignore ) for idx, (key, value) in enumerate(json_expectation.items()) } @@ -86,7 +102,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # Arg type_expectations is a deeply nested structure that matches the response, but with the values replaced with the expected types -def validate_response(response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any) -> None: +def validate_response( + response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectations == "no_validate": return @@ -96,11 +114,17 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e and not isinstance(response, dict) and not issubclass(type(response), pydantic.BaseModel) ): - validate_field(response=response, json_expectation=json_expectation, type_expectation=type_expectations) + validate_field( + response=response, + json_expectation=json_expectation, + type_expectation=type_expectations, + ) return if isinstance(response, list): - assert len(response) == len(json_expectation), "Length mismatch, expected: {0}, Actual: {1}".format( + assert len(response) == len( + json_expectation + ), "Length mismatch, expected: {0}, Actual: {1}".format( len(response), len(json_expectation) ) content_expectation = type_expectations @@ -108,7 +132,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e content_expectation = type_expectations[1] for idx, item in enumerate(response): validate_response( - response=item, json_expectation=json_expectation[idx], type_expectations=content_expectation[idx] + response=item, + json_expectation=json_expectation[idx], + type_expectations=content_expectation[idx], ) else: response_json = response @@ -116,7 +142,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e response_json = response.dict(by_alias=True) for key, value in json_expectation.items(): - assert key in response_json, "Field {0} not found within the response object: {1}".format( + assert ( + key in response_json + ), "Field {0} not found within the response object: {1}".format( key, response_json ) @@ -128,11 +156,19 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e # Otherwise, we're just validating a single field that's a pydantic model. if isinstance(value, dict) and not isinstance(type_expectation, tuple): validate_response( - response=response_json[key], json_expectation=value, type_expectations=type_expectation + response=response_json[key], + json_expectation=value, + type_expectations=type_expectation, ) else: - validate_field(response=response_json[key], json_expectation=value, type_expectation=type_expectation) + validate_field( + response=response_json[key], + json_expectation=value, + type_expectation=type_expectation, + ) # Ensure there are no additional fields here either del response_json[key] - assert len(response_json) == 0, "Additional fields found, expected None: {0}".format(response_json) + assert ( + len(response_json) == 0 + ), "Additional fields found, expected None: {0}".format(response_json) diff --git a/seed/python-sdk/alias/tests/utils/assets/models/__init__.py b/seed/python-sdk/alias/tests/utils/assets/models/__init__.py index 2cf01263529..3a1c852e71e 100644 --- a/seed/python-sdk/alias/tests/utils/assets/models/__init__.py +++ b/seed/python-sdk/alias/tests/utils/assets/models/__init__.py @@ -5,7 +5,7 @@ from .circle import CircleParams from .object_with_defaults import ObjectWithDefaultsParams from .object_with_optional_field import ObjectWithOptionalFieldParams -from .shape import Shape_CircleParams, Shape_SquareParams, ShapeParams +from .shape import ShapeParams, Shape_CircleParams, Shape_SquareParams from .square import SquareParams from .undiscriminated_shape import UndiscriminatedShapeParams diff --git a/seed/python-sdk/alias/tests/utils/assets/models/circle.py b/seed/python-sdk/alias/tests/utils/assets/models/circle.py index af7a1bf8a8e..253f12d38b3 100644 --- a/seed/python-sdk/alias/tests/utils/assets/models/circle.py +++ b/seed/python-sdk/alias/tests/utils/assets/models/circle.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class CircleParams(typing_extensions.TypedDict): - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] diff --git a/seed/python-sdk/alias/tests/utils/assets/models/object_with_optional_field.py b/seed/python-sdk/alias/tests/utils/assets/models/object_with_optional_field.py index 3ad93d5f305..ebe7dc80547 100644 --- a/seed/python-sdk/alias/tests/utils/assets/models/object_with_optional_field.py +++ b/seed/python-sdk/alias/tests/utils/assets/models/object_with_optional_field.py @@ -7,8 +7,8 @@ import uuid import typing_extensions -from seed.core.serialization import FieldMetadata +from seed.core.serialization import FieldMetadata from .color import Color from .shape import ShapeParams from .undiscriminated_shape import UndiscriminatedShapeParams @@ -18,16 +18,30 @@ class ObjectWithOptionalFieldParams(typing_extensions.TypedDict): literal: typing.Literal["lit_one"] string: typing_extensions.NotRequired[str] integer: typing_extensions.NotRequired[int] - long_: typing_extensions.NotRequired[typing_extensions.Annotated[int, FieldMetadata(alias="long")]] + long_: typing_extensions.NotRequired[ + typing_extensions.Annotated[int, FieldMetadata(alias="long")] + ] double: typing_extensions.NotRequired[float] - bool_: typing_extensions.NotRequired[typing_extensions.Annotated[bool, FieldMetadata(alias="bool")]] + bool_: typing_extensions.NotRequired[ + typing_extensions.Annotated[bool, FieldMetadata(alias="bool")] + ] datetime: typing_extensions.NotRequired[dt.datetime] date: typing_extensions.NotRequired[dt.date] - uuid_: typing_extensions.NotRequired[typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")]] - base_64: typing_extensions.NotRequired[typing_extensions.Annotated[str, FieldMetadata(alias="base64")]] - list_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")]] - set_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")]] - map_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")]] + uuid_: typing_extensions.NotRequired[ + typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")] + ] + base_64: typing_extensions.NotRequired[ + typing_extensions.Annotated[str, FieldMetadata(alias="base64")] + ] + list_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")] + ] + set_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")] + ] + map_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")] + ] enum: typing_extensions.NotRequired[Color] union: typing_extensions.NotRequired[ShapeParams] second_union: typing_extensions.NotRequired[ShapeParams] diff --git a/seed/python-sdk/alias/tests/utils/assets/models/shape.py b/seed/python-sdk/alias/tests/utils/assets/models/shape.py index 2c33c877951..816ffc51bdc 100644 --- a/seed/python-sdk/alias/tests/utils/assets/models/shape.py +++ b/seed/python-sdk/alias/tests/utils/assets/models/shape.py @@ -7,6 +7,7 @@ import typing import typing_extensions + from seed.core.serialization import FieldMetadata @@ -15,13 +16,21 @@ class Base(typing_extensions.TypedDict): class Shape_CircleParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["circle"], FieldMetadata(alias="shapeType")] - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["circle"], FieldMetadata(alias="shapeType") + ] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] class Shape_SquareParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["square"], FieldMetadata(alias="shapeType")] - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["square"], FieldMetadata(alias="shapeType") + ] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] ShapeParams = typing.Union[Shape_CircleParams, Shape_SquareParams] diff --git a/seed/python-sdk/alias/tests/utils/assets/models/square.py b/seed/python-sdk/alias/tests/utils/assets/models/square.py index b9b7dd319bc..bcf08a723c5 100644 --- a/seed/python-sdk/alias/tests/utils/assets/models/square.py +++ b/seed/python-sdk/alias/tests/utils/assets/models/square.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class SquareParams(typing_extensions.TypedDict): - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] diff --git a/seed/python-sdk/alias/tests/utils/test_http_client.py b/seed/python-sdk/alias/tests/utils/test_http_client.py index edd11ca7afb..f5a874a75f3 100644 --- a/seed/python-sdk/alias/tests/utils/test_http_client.py +++ b/seed/python-sdk/alias/tests/utils/test_http_client.py @@ -9,12 +9,17 @@ def get_request_options() -> RequestOptions: def test_get_json_request_body() -> None: - json_body, data_body = get_request_body(json={"hello": "world"}, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json={"hello": "world"}, data=None, request_options=None, omit=None + ) assert json_body == {"hello": "world"} assert data_body is None json_body_extras, data_body_extras = get_request_body( - json={"goodbye": "world"}, data=None, request_options=get_request_options(), omit=None + json={"goodbye": "world"}, + data=None, + request_options=get_request_options(), + omit=None, ) assert json_body_extras == {"goodbye": "world", "see you": "later"} @@ -22,12 +27,17 @@ def test_get_json_request_body() -> None: def test_get_files_request_body() -> None: - json_body, data_body = get_request_body(json=None, data={"hello": "world"}, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data={"hello": "world"}, request_options=None, omit=None + ) assert data_body == {"hello": "world"} assert json_body is None json_body_extras, data_body_extras = get_request_body( - json=None, data={"goodbye": "world"}, request_options=get_request_options(), omit=None + json=None, + data={"goodbye": "world"}, + request_options=get_request_options(), + omit=None, ) assert data_body_extras == {"goodbye": "world", "see you": "later"} @@ -35,7 +45,9 @@ def test_get_files_request_body() -> None: def test_get_none_request_body() -> None: - json_body, data_body = get_request_body(json=None, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data=None, request_options=None, omit=None + ) assert data_body is None assert json_body is None diff --git a/seed/python-sdk/alias/tests/utils/test_query_encoding.py b/seed/python-sdk/alias/tests/utils/test_query_encoding.py index 247e1551b46..fbc8f402167 100644 --- a/seed/python-sdk/alias/tests/utils/test_query_encoding.py +++ b/seed/python-sdk/alias/tests/utils/test_query_encoding.py @@ -4,9 +4,15 @@ def test_query_encoding() -> None: - assert encode_query({"hello world": "hello world"}) == {"hello world": "hello world"} - assert encode_query({"hello_world": {"hello": "world"}}) == {"hello_world[hello]": "world"} - assert encode_query({"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"}) == { + assert encode_query({"hello world": "hello world"}) == { + "hello world": "hello world" + } + assert encode_query({"hello_world": {"hello": "world"}}) == { + "hello_world[hello]": "world" + } + assert encode_query( + {"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"} + ) == { "hello_world[hello][world]": "today", "hello_world[test]": "this", "hi": "there", diff --git a/seed/python-sdk/alias/tests/utils/test_serialization.py b/seed/python-sdk/alias/tests/utils/test_serialization.py index 58b1ed66e6d..5ca956916dd 100644 --- a/seed/python-sdk/alias/tests/utils/test_serialization.py +++ b/seed/python-sdk/alias/tests/utils/test_serialization.py @@ -1,10 +1,12 @@ # This file was auto-generated by Fern from our API Definition. -from typing import Any, List +from typing import List, Any -from seed.core.serialization import convert_and_respect_annotation_metadata +from seed.core.serialization import ( + convert_and_respect_annotation_metadata, +) +from .assets.models import ShapeParams, ObjectWithOptionalFieldParams -from .assets.models import ObjectWithOptionalFieldParams, ShapeParams UNION_TEST: ShapeParams = {"radius_measurement": 1.0, "shape_type": "circle", "id": "1"} UNION_TEST_CONVERTED = {"shapeType": "circle", "radiusMeasurement": 1.0, "id": "1"} @@ -18,20 +20,54 @@ def test_convert_and_respect_annotation_metadata() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) - assert converted == {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"} + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) + assert converted == { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + } def test_convert_and_respect_annotation_metadata_in_list() -> None: data: List[ObjectWithOptionalFieldParams] = [ - {"string": "string", "long_": 12345, "bool_": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long_": 67890, "list_": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long_": 12345, + "bool_": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long_": 67890, + "list_": [], + "literal": "lit_one", + "any": "any", + }, ] - converted = convert_and_respect_annotation_metadata(object_=data, annotation=List[ObjectWithOptionalFieldParams]) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=List[ObjectWithOptionalFieldParams] + ) assert converted == [ - {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long": 67890, "list": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long": 67890, + "list": [], + "literal": "lit_one", + "any": "any", + }, ] @@ -43,7 +79,9 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) assert converted == { "string": "string", @@ -55,12 +93,16 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: def test_convert_and_respect_annotation_metadata_in_union() -> None: - converted = convert_and_respect_annotation_metadata(object_=UNION_TEST, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=UNION_TEST, annotation=ShapeParams + ) assert converted == UNION_TEST_CONVERTED def test_convert_and_respect_annotation_metadata_with_empty_object() -> None: data: Any = {} - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ShapeParams + ) assert converted == data diff --git a/seed/python-sdk/api-wide-base-path/pyproject.toml b/seed/python-sdk/api-wide-base-path/pyproject.toml index a3d73b7a235..28364ae7799 100644 --- a/seed/python-sdk/api-wide-base-path/pyproject.toml +++ b/seed/python-sdk/api-wide-base-path/pyproject.toml @@ -43,6 +43,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/python-sdk/api-wide-base-path/src/seed/client.py b/seed/python-sdk/api-wide-base-path/src/seed/client.py index c1613b2b436..4018360cc50 100644 --- a/seed/python-sdk/api-wide-base-path/src/seed/client.py +++ b/seed/python-sdk/api-wide-base-path/src/seed/client.py @@ -1,11 +1,11 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from .service.client import AsyncServiceClient, ServiceClient +from .core.client_wrapper import SyncClientWrapper +from .service.client import ServiceClient +from .core.client_wrapper import AsyncClientWrapper +from .service.client import AsyncServiceClient class SeedApiWideBasePath: @@ -41,14 +41,18 @@ def __init__( base_url: str, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.Client] = None + httpx_client: typing.Optional[httpx.Client] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = SyncClientWrapper( base_url=base_url, httpx_client=httpx_client if httpx_client is not None - else httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.Client( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.Client(timeout=_defaulted_timeout), timeout=_defaulted_timeout, @@ -89,14 +93,18 @@ def __init__( base_url: str, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.AsyncClient] = None + httpx_client: typing.Optional[httpx.AsyncClient] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = AsyncClientWrapper( base_url=base_url, httpx_client=httpx_client if httpx_client is not None - else httpx.AsyncClient(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.AsyncClient( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.AsyncClient(timeout=_defaulted_timeout), timeout=_defaulted_timeout, diff --git a/seed/python-sdk/api-wide-base-path/src/seed/core/api_error.py b/seed/python-sdk/api-wide-base-path/src/seed/core/api_error.py index 2e9fc5431cd..da734b58068 100644 --- a/seed/python-sdk/api-wide-base-path/src/seed/core/api_error.py +++ b/seed/python-sdk/api-wide-base-path/src/seed/core/api_error.py @@ -7,7 +7,9 @@ class ApiError(Exception): status_code: typing.Optional[int] body: typing.Any - def __init__(self, *, status_code: typing.Optional[int] = None, body: typing.Any = None): + def __init__( + self, *, status_code: typing.Optional[int] = None, body: typing.Any = None + ): self.status_code = status_code self.body = body diff --git a/seed/python-sdk/api-wide-base-path/src/seed/core/client_wrapper.py b/seed/python-sdk/api-wide-base-path/src/seed/core/client_wrapper.py index 31a8c614467..6b14c3e5109 100644 --- a/seed/python-sdk/api-wide-base-path/src/seed/core/client_wrapper.py +++ b/seed/python-sdk/api-wide-base-path/src/seed/core/client_wrapper.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .http_client import AsyncHttpClient, HttpClient +from .http_client import HttpClient +from .http_client import AsyncHttpClient class BaseClientWrapper: @@ -28,7 +27,13 @@ def get_timeout(self) -> typing.Optional[float]: class SyncClientWrapper(BaseClientWrapper): - def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, httpx_client: httpx.Client): + def __init__( + self, + *, + base_url: str, + timeout: typing.Optional[float] = None, + httpx_client: httpx.Client, + ): super().__init__(base_url=base_url, timeout=timeout) self.httpx_client = HttpClient( httpx_client=httpx_client, @@ -39,7 +44,13 @@ def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, htt class AsyncClientWrapper(BaseClientWrapper): - def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, httpx_client: httpx.AsyncClient): + def __init__( + self, + *, + base_url: str, + timeout: typing.Optional[float] = None, + httpx_client: httpx.AsyncClient, + ): super().__init__(base_url=base_url, timeout=timeout) self.httpx_client = AsyncHttpClient( httpx_client=httpx_client, diff --git a/seed/python-sdk/api-wide-base-path/src/seed/core/datetime_utils.py b/seed/python-sdk/api-wide-base-path/src/seed/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/python-sdk/api-wide-base-path/src/seed/core/datetime_utils.py +++ b/seed/python-sdk/api-wide-base-path/src/seed/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/python-sdk/api-wide-base-path/src/seed/core/file.py b/seed/python-sdk/api-wide-base-path/src/seed/core/file.py index cb0d40bbbf3..6e0f92bfcb1 100644 --- a/seed/python-sdk/api-wide-base-path/src/seed/core/file.py +++ b/seed/python-sdk/api-wide-base-path/src/seed/core/file.py @@ -13,12 +13,17 @@ # (filename, file (or bytes), content_type) typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str]], # (filename, file (or bytes), content_type, headers) - typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str], typing.Mapping[str, str]], + typing.Tuple[ + typing.Optional[str], + FileContent, + typing.Optional[str], + typing.Mapping[str, str], + ], ] def convert_file_dict_to_httpx_tuples( - d: typing.Dict[str, typing.Union[File, typing.List[File]]] + d: typing.Dict[str, typing.Union[File, typing.List[File]]], ) -> typing.List[typing.Tuple[str, File]]: """ The format we use is a list of tuples, where the first element is the diff --git a/seed/python-sdk/api-wide-base-path/src/seed/core/http_client.py b/seed/python-sdk/api-wide-base-path/src/seed/core/http_client.py index 9333d8a7f15..091f71bc185 100644 --- a/seed/python-sdk/api-wide-base-path/src/seed/core/http_client.py +++ b/seed/python-sdk/api-wide-base-path/src/seed/core/http_client.py @@ -77,7 +77,9 @@ def _retry_timeout(response: httpx.Response, retries: int) -> float: return retry_after # Apply exponential backoff, capped at MAX_RETRY_DELAY_SECONDS. - retry_delay = min(INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS) + retry_delay = min( + INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS + ) # Add a randomness / jitter to the retry delay to avoid overwhelming the server with retries. timeout = retry_delay * (1 - 0.25 * random()) @@ -90,7 +92,8 @@ def _should_retry(response: httpx.Response) -> bool: def remove_omit_from_dict( - original: typing.Dict[str, typing.Optional[typing.Any]], omit: typing.Optional[typing.Any] + original: typing.Dict[str, typing.Optional[typing.Any]], + omit: typing.Optional[typing.Any], ) -> typing.Dict[str, typing.Any]: if omit is None: return original @@ -108,7 +111,8 @@ def maybe_filter_request_body( ) -> typing.Optional[typing.Any]: if data is None: return ( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else None ) @@ -118,7 +122,8 @@ def maybe_filter_request_body( data_content = { **(jsonable_encoder(remove_omit_from_dict(data, omit))), # type: ignore **( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else {} ), @@ -162,7 +167,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url def request( @@ -174,8 +181,12 @@ def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -184,11 +195,14 @@ def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) response = self.httpx_client.request( method=method, @@ -198,7 +212,11 @@ def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -209,7 +227,10 @@ def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -222,11 +243,15 @@ def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: time.sleep(_retry_timeout(response=response, retries=retries)) @@ -256,8 +281,12 @@ def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -266,11 +295,14 @@ def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) with self.httpx_client.stream( method=method, @@ -280,7 +312,11 @@ def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -291,7 +327,9 @@ def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -304,7 +342,9 @@ def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream @@ -327,7 +367,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url async def request( @@ -339,8 +381,12 @@ async def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -349,11 +395,14 @@ async def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) # Add the input to each of these and do None-safety checks response = await self.httpx_client.request( @@ -364,7 +413,11 @@ async def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -375,7 +428,10 @@ async def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -388,11 +444,15 @@ async def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: await asyncio.sleep(_retry_timeout(response=response, retries=retries)) @@ -421,8 +481,12 @@ async def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -431,11 +495,14 @@ async def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) async with self.httpx_client.stream( method=method, @@ -445,7 +512,11 @@ async def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -456,7 +527,9 @@ async def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -469,7 +542,9 @@ async def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream diff --git a/seed/python-sdk/api-wide-base-path/src/seed/core/jsonable_encoder.py b/seed/python-sdk/api-wide-base-path/src/seed/core/jsonable_encoder.py index d3fd328fd41..12a8b52fc22 100644 --- a/seed/python-sdk/api-wide-base-path/src/seed/core/jsonable_encoder.py +++ b/seed/python-sdk/api-wide-base-path/src/seed/core/jsonable_encoder.py @@ -19,13 +19,19 @@ import pydantic from .datetime_utils import serialize_datetime -from .pydantic_utilities import IS_PYDANTIC_V2, encode_by_type, to_jsonable_with_fallback +from .pydantic_utilities import ( + IS_PYDANTIC_V2, + encode_by_type, + to_jsonable_with_fallback, +) SetIntStr = Set[Union[int, str]] DictIntStrAny = Dict[Union[int, str], Any] -def jsonable_encoder(obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None) -> Any: +def jsonable_encoder( + obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None +) -> Any: custom_encoder = custom_encoder or {} if custom_encoder: if type(obj) in custom_encoder: diff --git a/seed/python-sdk/api-wide-base-path/src/seed/core/pydantic_utilities.py b/seed/python-sdk/api-wide-base-path/src/seed/core/pydantic_utilities.py index 170a563d6eb..c63935c32a2 100644 --- a/seed/python-sdk/api-wide-base-path/src/seed/core/pydantic_utilities.py +++ b/seed/python-sdk/api-wide-base-path/src/seed/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) # type: ignore # Pydantic v1 diff --git a/seed/python-sdk/api-wide-base-path/src/seed/core/query_encoder.py b/seed/python-sdk/api-wide-base-path/src/seed/core/query_encoder.py index 24076d72ee9..7cb98f52cd7 100644 --- a/seed/python-sdk/api-wide-base-path/src/seed/core/query_encoder.py +++ b/seed/python-sdk/api-wide-base-path/src/seed/core/query_encoder.py @@ -7,7 +7,9 @@ # Flattens dicts to be of the form {"key[subkey][subkey2]": value} where value is not a dict -def traverse_query_dict(dict_flat: Dict[str, Any], key_prefix: Optional[str] = None) -> Dict[str, Any]: +def traverse_query_dict( + dict_flat: Dict[str, Any], key_prefix: Optional[str] = None +) -> Dict[str, Any]: result = {} for k, v in dict_flat.items(): key = f"{key_prefix}[{k}]" if key_prefix is not None else k @@ -30,4 +32,8 @@ def single_query_encoder(query_key: str, query_value: Any) -> Dict[str, Any]: def encode_query(query: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: - return dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) if query is not None else None + return ( + dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) + if query is not None + else None + ) diff --git a/seed/python-sdk/api-wide-base-path/src/seed/core/serialization.py b/seed/python-sdk/api-wide-base-path/src/seed/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/python-sdk/api-wide-base-path/src/seed/core/serialization.py +++ b/seed/python-sdk/api-wide-base-path/src/seed/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/python-sdk/api-wide-base-path/src/seed/service/client.py b/seed/python-sdk/api-wide-base-path/src/seed/service/client.py index d86d24164c7..d4c463ee31e 100644 --- a/seed/python-sdk/api-wide-base-path/src/seed/service/client.py +++ b/seed/python-sdk/api-wide-base-path/src/seed/service/client.py @@ -1,12 +1,12 @@ # This file was auto-generated by Fern from our API Definition. +from ..core.client_wrapper import SyncClientWrapper import typing +from ..core.request_options import RequestOptions +from ..core.jsonable_encoder import jsonable_encoder from json.decoder import JSONDecodeError - from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.jsonable_encoder import jsonable_encoder -from ..core.request_options import RequestOptions +from ..core.client_wrapper import AsyncClientWrapper class ServiceClient: diff --git a/seed/python-sdk/api-wide-base-path/src/seed/version.py b/seed/python-sdk/api-wide-base-path/src/seed/version.py index ee133b40b3e..9996dec5edf 100644 --- a/seed/python-sdk/api-wide-base-path/src/seed/version.py +++ b/seed/python-sdk/api-wide-base-path/src/seed/version.py @@ -1,4 +1,3 @@ - from importlib import metadata __version__ = metadata.version("fern_api-wide-base-path") diff --git a/seed/python-sdk/api-wide-base-path/tests/conftest.py b/seed/python-sdk/api-wide-base-path/tests/conftest.py index 4d6b4ed24d8..3e5c5b2b97a 100644 --- a/seed/python-sdk/api-wide-base-path/tests/conftest.py +++ b/seed/python-sdk/api-wide-base-path/tests/conftest.py @@ -1,9 +1,9 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedApiWideBasePath import os - import pytest -from seed import AsyncSeedApiWideBasePath, SeedApiWideBasePath +from seed import AsyncSeedApiWideBasePath @pytest.fixture diff --git a/seed/python-sdk/api-wide-base-path/tests/custom/test_client.py b/seed/python-sdk/api-wide-base-path/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/python-sdk/api-wide-base-path/tests/custom/test_client.py +++ b/seed/python-sdk/api-wide-base-path/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/python-sdk/api-wide-base-path/tests/test_service.py b/seed/python-sdk/api-wide-base-path/tests/test_service.py index 5334af55745..d7e651a5bc6 100644 --- a/seed/python-sdk/api-wide-base-path/tests/test_service.py +++ b/seed/python-sdk/api-wide-base-path/tests/test_service.py @@ -1,10 +1,29 @@ # This file was auto-generated by Fern from our API Definition. -from seed import AsyncSeedApiWideBasePath, SeedApiWideBasePath +from seed import SeedApiWideBasePath +from seed import AsyncSeedApiWideBasePath -async def test_post(client: SeedApiWideBasePath, async_client: AsyncSeedApiWideBasePath) -> None: +async def test_post( + client: SeedApiWideBasePath, async_client: AsyncSeedApiWideBasePath +) -> None: # Type ignore to avoid mypy complaining about the function not being meant to return a value - assert client.service.post(path_param="string", service_param="string", resource_param="string", endpoint_param=1) is None # type: ignore[func-returns-value] + assert ( + client.service.post( + path_param="string", + service_param="string", + resource_param="string", + endpoint_param=1, + ) + is None + ) # type: ignore[func-returns-value] - assert await async_client.service.post(path_param="string", service_param="string", resource_param="string", endpoint_param=1) is None # type: ignore[func-returns-value] + assert ( + await async_client.service.post( + path_param="string", + service_param="string", + resource_param="string", + endpoint_param=1, + ) + is None + ) # type: ignore[func-returns-value] diff --git a/seed/python-sdk/api-wide-base-path/tests/utilities.py b/seed/python-sdk/api-wide-base-path/tests/utilities.py index 13da208eb3a..e8f4472564c 100644 --- a/seed/python-sdk/api-wide-base-path/tests/utilities.py +++ b/seed/python-sdk/api-wide-base-path/tests/utilities.py @@ -3,11 +3,14 @@ import typing import uuid -import pydantic from dateutil import parser +import pydantic + -def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> typing.Any: +def cast_field( + json_expectation: typing.Any, type_expectation: typing.Any +) -> typing.Any: # Cast these specific types which come through as string and expect our # models to cast to the correct type. if type_expectation == "uuid": @@ -25,7 +28,9 @@ def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> ty return json_expectation -def validate_field(response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any) -> None: +def validate_field( + response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectation == "no_validate": return @@ -44,7 +49,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(entry_expectation, dict): is_container_of_complex_type = True validate_response( - response=response[idx], json_expectation=ex, type_expectations=entry_expectation + response=response[idx], + json_expectation=ex, + type_expectations=entry_expectation, ) else: cast_json_expectation.append(cast_field(ex, entry_expectation)) @@ -56,7 +63,10 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # if any of the values of the set have a type_expectation of a dict, we're assuming it's a pydantic # model and keeping it a list. if container_expectation != "set" or not any( - map(lambda value: isinstance(value, dict), list(contents_expectation.values())) + map( + lambda value: isinstance(value, dict), + list(contents_expectation.values()), + ) ): json_expectation = cast_field(json_expectation, container_expectation) elif isinstance(type_expectation, tuple): @@ -65,9 +75,15 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(contents_expectation, dict): json_expectation = { cast_field( - key, contents_expectation.get(idx)[0] if contents_expectation.get(idx) is not None else None # type: ignore + key, + contents_expectation.get(idx)[0] + if contents_expectation.get(idx) is not None + else None, # type: ignore ): cast_field( - value, contents_expectation.get(idx)[1] if contents_expectation.get(idx) is not None else None # type: ignore + value, + contents_expectation.get(idx)[1] + if contents_expectation.get(idx) is not None + else None, # type: ignore ) for idx, (key, value) in enumerate(json_expectation.items()) } @@ -86,7 +102,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # Arg type_expectations is a deeply nested structure that matches the response, but with the values replaced with the expected types -def validate_response(response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any) -> None: +def validate_response( + response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectations == "no_validate": return @@ -96,11 +114,17 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e and not isinstance(response, dict) and not issubclass(type(response), pydantic.BaseModel) ): - validate_field(response=response, json_expectation=json_expectation, type_expectation=type_expectations) + validate_field( + response=response, + json_expectation=json_expectation, + type_expectation=type_expectations, + ) return if isinstance(response, list): - assert len(response) == len(json_expectation), "Length mismatch, expected: {0}, Actual: {1}".format( + assert len(response) == len( + json_expectation + ), "Length mismatch, expected: {0}, Actual: {1}".format( len(response), len(json_expectation) ) content_expectation = type_expectations @@ -108,7 +132,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e content_expectation = type_expectations[1] for idx, item in enumerate(response): validate_response( - response=item, json_expectation=json_expectation[idx], type_expectations=content_expectation[idx] + response=item, + json_expectation=json_expectation[idx], + type_expectations=content_expectation[idx], ) else: response_json = response @@ -116,7 +142,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e response_json = response.dict(by_alias=True) for key, value in json_expectation.items(): - assert key in response_json, "Field {0} not found within the response object: {1}".format( + assert ( + key in response_json + ), "Field {0} not found within the response object: {1}".format( key, response_json ) @@ -128,11 +156,19 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e # Otherwise, we're just validating a single field that's a pydantic model. if isinstance(value, dict) and not isinstance(type_expectation, tuple): validate_response( - response=response_json[key], json_expectation=value, type_expectations=type_expectation + response=response_json[key], + json_expectation=value, + type_expectations=type_expectation, ) else: - validate_field(response=response_json[key], json_expectation=value, type_expectation=type_expectation) + validate_field( + response=response_json[key], + json_expectation=value, + type_expectation=type_expectation, + ) # Ensure there are no additional fields here either del response_json[key] - assert len(response_json) == 0, "Additional fields found, expected None: {0}".format(response_json) + assert ( + len(response_json) == 0 + ), "Additional fields found, expected None: {0}".format(response_json) diff --git a/seed/python-sdk/api-wide-base-path/tests/utils/assets/models/__init__.py b/seed/python-sdk/api-wide-base-path/tests/utils/assets/models/__init__.py index 2cf01263529..3a1c852e71e 100644 --- a/seed/python-sdk/api-wide-base-path/tests/utils/assets/models/__init__.py +++ b/seed/python-sdk/api-wide-base-path/tests/utils/assets/models/__init__.py @@ -5,7 +5,7 @@ from .circle import CircleParams from .object_with_defaults import ObjectWithDefaultsParams from .object_with_optional_field import ObjectWithOptionalFieldParams -from .shape import Shape_CircleParams, Shape_SquareParams, ShapeParams +from .shape import ShapeParams, Shape_CircleParams, Shape_SquareParams from .square import SquareParams from .undiscriminated_shape import UndiscriminatedShapeParams diff --git a/seed/python-sdk/api-wide-base-path/tests/utils/assets/models/circle.py b/seed/python-sdk/api-wide-base-path/tests/utils/assets/models/circle.py index af7a1bf8a8e..253f12d38b3 100644 --- a/seed/python-sdk/api-wide-base-path/tests/utils/assets/models/circle.py +++ b/seed/python-sdk/api-wide-base-path/tests/utils/assets/models/circle.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class CircleParams(typing_extensions.TypedDict): - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] diff --git a/seed/python-sdk/api-wide-base-path/tests/utils/assets/models/object_with_optional_field.py b/seed/python-sdk/api-wide-base-path/tests/utils/assets/models/object_with_optional_field.py index 3ad93d5f305..ebe7dc80547 100644 --- a/seed/python-sdk/api-wide-base-path/tests/utils/assets/models/object_with_optional_field.py +++ b/seed/python-sdk/api-wide-base-path/tests/utils/assets/models/object_with_optional_field.py @@ -7,8 +7,8 @@ import uuid import typing_extensions -from seed.core.serialization import FieldMetadata +from seed.core.serialization import FieldMetadata from .color import Color from .shape import ShapeParams from .undiscriminated_shape import UndiscriminatedShapeParams @@ -18,16 +18,30 @@ class ObjectWithOptionalFieldParams(typing_extensions.TypedDict): literal: typing.Literal["lit_one"] string: typing_extensions.NotRequired[str] integer: typing_extensions.NotRequired[int] - long_: typing_extensions.NotRequired[typing_extensions.Annotated[int, FieldMetadata(alias="long")]] + long_: typing_extensions.NotRequired[ + typing_extensions.Annotated[int, FieldMetadata(alias="long")] + ] double: typing_extensions.NotRequired[float] - bool_: typing_extensions.NotRequired[typing_extensions.Annotated[bool, FieldMetadata(alias="bool")]] + bool_: typing_extensions.NotRequired[ + typing_extensions.Annotated[bool, FieldMetadata(alias="bool")] + ] datetime: typing_extensions.NotRequired[dt.datetime] date: typing_extensions.NotRequired[dt.date] - uuid_: typing_extensions.NotRequired[typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")]] - base_64: typing_extensions.NotRequired[typing_extensions.Annotated[str, FieldMetadata(alias="base64")]] - list_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")]] - set_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")]] - map_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")]] + uuid_: typing_extensions.NotRequired[ + typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")] + ] + base_64: typing_extensions.NotRequired[ + typing_extensions.Annotated[str, FieldMetadata(alias="base64")] + ] + list_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")] + ] + set_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")] + ] + map_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")] + ] enum: typing_extensions.NotRequired[Color] union: typing_extensions.NotRequired[ShapeParams] second_union: typing_extensions.NotRequired[ShapeParams] diff --git a/seed/python-sdk/api-wide-base-path/tests/utils/assets/models/shape.py b/seed/python-sdk/api-wide-base-path/tests/utils/assets/models/shape.py index 2c33c877951..816ffc51bdc 100644 --- a/seed/python-sdk/api-wide-base-path/tests/utils/assets/models/shape.py +++ b/seed/python-sdk/api-wide-base-path/tests/utils/assets/models/shape.py @@ -7,6 +7,7 @@ import typing import typing_extensions + from seed.core.serialization import FieldMetadata @@ -15,13 +16,21 @@ class Base(typing_extensions.TypedDict): class Shape_CircleParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["circle"], FieldMetadata(alias="shapeType")] - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["circle"], FieldMetadata(alias="shapeType") + ] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] class Shape_SquareParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["square"], FieldMetadata(alias="shapeType")] - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["square"], FieldMetadata(alias="shapeType") + ] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] ShapeParams = typing.Union[Shape_CircleParams, Shape_SquareParams] diff --git a/seed/python-sdk/api-wide-base-path/tests/utils/assets/models/square.py b/seed/python-sdk/api-wide-base-path/tests/utils/assets/models/square.py index b9b7dd319bc..bcf08a723c5 100644 --- a/seed/python-sdk/api-wide-base-path/tests/utils/assets/models/square.py +++ b/seed/python-sdk/api-wide-base-path/tests/utils/assets/models/square.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class SquareParams(typing_extensions.TypedDict): - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] diff --git a/seed/python-sdk/api-wide-base-path/tests/utils/test_http_client.py b/seed/python-sdk/api-wide-base-path/tests/utils/test_http_client.py index edd11ca7afb..f5a874a75f3 100644 --- a/seed/python-sdk/api-wide-base-path/tests/utils/test_http_client.py +++ b/seed/python-sdk/api-wide-base-path/tests/utils/test_http_client.py @@ -9,12 +9,17 @@ def get_request_options() -> RequestOptions: def test_get_json_request_body() -> None: - json_body, data_body = get_request_body(json={"hello": "world"}, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json={"hello": "world"}, data=None, request_options=None, omit=None + ) assert json_body == {"hello": "world"} assert data_body is None json_body_extras, data_body_extras = get_request_body( - json={"goodbye": "world"}, data=None, request_options=get_request_options(), omit=None + json={"goodbye": "world"}, + data=None, + request_options=get_request_options(), + omit=None, ) assert json_body_extras == {"goodbye": "world", "see you": "later"} @@ -22,12 +27,17 @@ def test_get_json_request_body() -> None: def test_get_files_request_body() -> None: - json_body, data_body = get_request_body(json=None, data={"hello": "world"}, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data={"hello": "world"}, request_options=None, omit=None + ) assert data_body == {"hello": "world"} assert json_body is None json_body_extras, data_body_extras = get_request_body( - json=None, data={"goodbye": "world"}, request_options=get_request_options(), omit=None + json=None, + data={"goodbye": "world"}, + request_options=get_request_options(), + omit=None, ) assert data_body_extras == {"goodbye": "world", "see you": "later"} @@ -35,7 +45,9 @@ def test_get_files_request_body() -> None: def test_get_none_request_body() -> None: - json_body, data_body = get_request_body(json=None, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data=None, request_options=None, omit=None + ) assert data_body is None assert json_body is None diff --git a/seed/python-sdk/api-wide-base-path/tests/utils/test_query_encoding.py b/seed/python-sdk/api-wide-base-path/tests/utils/test_query_encoding.py index 247e1551b46..fbc8f402167 100644 --- a/seed/python-sdk/api-wide-base-path/tests/utils/test_query_encoding.py +++ b/seed/python-sdk/api-wide-base-path/tests/utils/test_query_encoding.py @@ -4,9 +4,15 @@ def test_query_encoding() -> None: - assert encode_query({"hello world": "hello world"}) == {"hello world": "hello world"} - assert encode_query({"hello_world": {"hello": "world"}}) == {"hello_world[hello]": "world"} - assert encode_query({"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"}) == { + assert encode_query({"hello world": "hello world"}) == { + "hello world": "hello world" + } + assert encode_query({"hello_world": {"hello": "world"}}) == { + "hello_world[hello]": "world" + } + assert encode_query( + {"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"} + ) == { "hello_world[hello][world]": "today", "hello_world[test]": "this", "hi": "there", diff --git a/seed/python-sdk/api-wide-base-path/tests/utils/test_serialization.py b/seed/python-sdk/api-wide-base-path/tests/utils/test_serialization.py index 58b1ed66e6d..5ca956916dd 100644 --- a/seed/python-sdk/api-wide-base-path/tests/utils/test_serialization.py +++ b/seed/python-sdk/api-wide-base-path/tests/utils/test_serialization.py @@ -1,10 +1,12 @@ # This file was auto-generated by Fern from our API Definition. -from typing import Any, List +from typing import List, Any -from seed.core.serialization import convert_and_respect_annotation_metadata +from seed.core.serialization import ( + convert_and_respect_annotation_metadata, +) +from .assets.models import ShapeParams, ObjectWithOptionalFieldParams -from .assets.models import ObjectWithOptionalFieldParams, ShapeParams UNION_TEST: ShapeParams = {"radius_measurement": 1.0, "shape_type": "circle", "id": "1"} UNION_TEST_CONVERTED = {"shapeType": "circle", "radiusMeasurement": 1.0, "id": "1"} @@ -18,20 +20,54 @@ def test_convert_and_respect_annotation_metadata() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) - assert converted == {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"} + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) + assert converted == { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + } def test_convert_and_respect_annotation_metadata_in_list() -> None: data: List[ObjectWithOptionalFieldParams] = [ - {"string": "string", "long_": 12345, "bool_": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long_": 67890, "list_": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long_": 12345, + "bool_": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long_": 67890, + "list_": [], + "literal": "lit_one", + "any": "any", + }, ] - converted = convert_and_respect_annotation_metadata(object_=data, annotation=List[ObjectWithOptionalFieldParams]) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=List[ObjectWithOptionalFieldParams] + ) assert converted == [ - {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long": 67890, "list": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long": 67890, + "list": [], + "literal": "lit_one", + "any": "any", + }, ] @@ -43,7 +79,9 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) assert converted == { "string": "string", @@ -55,12 +93,16 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: def test_convert_and_respect_annotation_metadata_in_union() -> None: - converted = convert_and_respect_annotation_metadata(object_=UNION_TEST, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=UNION_TEST, annotation=ShapeParams + ) assert converted == UNION_TEST_CONVERTED def test_convert_and_respect_annotation_metadata_with_empty_object() -> None: data: Any = {} - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ShapeParams + ) assert converted == data diff --git a/seed/python-sdk/audiences/pyproject.toml b/seed/python-sdk/audiences/pyproject.toml index bf8b414880e..c1865d0deb8 100644 --- a/seed/python-sdk/audiences/pyproject.toml +++ b/seed/python-sdk/audiences/pyproject.toml @@ -43,6 +43,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/python-sdk/audiences/src/seed/client.py b/seed/python-sdk/audiences/src/seed/client.py index ce1411e2e44..66dfe7bb29e 100644 --- a/seed/python-sdk/audiences/src/seed/client.py +++ b/seed/python-sdk/audiences/src/seed/client.py @@ -1,12 +1,13 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from .folder_a.client import AsyncFolderAClient, FolderAClient -from .foo.client import AsyncFooClient, FooClient +from .core.client_wrapper import SyncClientWrapper +from .folder_a.client import FolderAClient +from .foo.client import FooClient +from .core.client_wrapper import AsyncClientWrapper +from .folder_a.client import AsyncFolderAClient +from .foo.client import AsyncFooClient class SeedAudiences: @@ -42,14 +43,18 @@ def __init__( base_url: str, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.Client] = None + httpx_client: typing.Optional[httpx.Client] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = SyncClientWrapper( base_url=base_url, httpx_client=httpx_client if httpx_client is not None - else httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.Client( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.Client(timeout=_defaulted_timeout), timeout=_defaulted_timeout, @@ -91,14 +96,18 @@ def __init__( base_url: str, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.AsyncClient] = None + httpx_client: typing.Optional[httpx.AsyncClient] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = AsyncClientWrapper( base_url=base_url, httpx_client=httpx_client if httpx_client is not None - else httpx.AsyncClient(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.AsyncClient( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.AsyncClient(timeout=_defaulted_timeout), timeout=_defaulted_timeout, diff --git a/seed/python-sdk/audiences/src/seed/core/api_error.py b/seed/python-sdk/audiences/src/seed/core/api_error.py index 2e9fc5431cd..da734b58068 100644 --- a/seed/python-sdk/audiences/src/seed/core/api_error.py +++ b/seed/python-sdk/audiences/src/seed/core/api_error.py @@ -7,7 +7,9 @@ class ApiError(Exception): status_code: typing.Optional[int] body: typing.Any - def __init__(self, *, status_code: typing.Optional[int] = None, body: typing.Any = None): + def __init__( + self, *, status_code: typing.Optional[int] = None, body: typing.Any = None + ): self.status_code = status_code self.body = body diff --git a/seed/python-sdk/audiences/src/seed/core/client_wrapper.py b/seed/python-sdk/audiences/src/seed/core/client_wrapper.py index 1bc956666ce..fd874c4395b 100644 --- a/seed/python-sdk/audiences/src/seed/core/client_wrapper.py +++ b/seed/python-sdk/audiences/src/seed/core/client_wrapper.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .http_client import AsyncHttpClient, HttpClient +from .http_client import HttpClient +from .http_client import AsyncHttpClient class BaseClientWrapper: @@ -28,7 +27,13 @@ def get_timeout(self) -> typing.Optional[float]: class SyncClientWrapper(BaseClientWrapper): - def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, httpx_client: httpx.Client): + def __init__( + self, + *, + base_url: str, + timeout: typing.Optional[float] = None, + httpx_client: httpx.Client, + ): super().__init__(base_url=base_url, timeout=timeout) self.httpx_client = HttpClient( httpx_client=httpx_client, @@ -39,7 +44,13 @@ def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, htt class AsyncClientWrapper(BaseClientWrapper): - def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, httpx_client: httpx.AsyncClient): + def __init__( + self, + *, + base_url: str, + timeout: typing.Optional[float] = None, + httpx_client: httpx.AsyncClient, + ): super().__init__(base_url=base_url, timeout=timeout) self.httpx_client = AsyncHttpClient( httpx_client=httpx_client, diff --git a/seed/python-sdk/audiences/src/seed/core/datetime_utils.py b/seed/python-sdk/audiences/src/seed/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/python-sdk/audiences/src/seed/core/datetime_utils.py +++ b/seed/python-sdk/audiences/src/seed/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/python-sdk/audiences/src/seed/core/file.py b/seed/python-sdk/audiences/src/seed/core/file.py index cb0d40bbbf3..6e0f92bfcb1 100644 --- a/seed/python-sdk/audiences/src/seed/core/file.py +++ b/seed/python-sdk/audiences/src/seed/core/file.py @@ -13,12 +13,17 @@ # (filename, file (or bytes), content_type) typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str]], # (filename, file (or bytes), content_type, headers) - typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str], typing.Mapping[str, str]], + typing.Tuple[ + typing.Optional[str], + FileContent, + typing.Optional[str], + typing.Mapping[str, str], + ], ] def convert_file_dict_to_httpx_tuples( - d: typing.Dict[str, typing.Union[File, typing.List[File]]] + d: typing.Dict[str, typing.Union[File, typing.List[File]]], ) -> typing.List[typing.Tuple[str, File]]: """ The format we use is a list of tuples, where the first element is the diff --git a/seed/python-sdk/audiences/src/seed/core/http_client.py b/seed/python-sdk/audiences/src/seed/core/http_client.py index 9333d8a7f15..091f71bc185 100644 --- a/seed/python-sdk/audiences/src/seed/core/http_client.py +++ b/seed/python-sdk/audiences/src/seed/core/http_client.py @@ -77,7 +77,9 @@ def _retry_timeout(response: httpx.Response, retries: int) -> float: return retry_after # Apply exponential backoff, capped at MAX_RETRY_DELAY_SECONDS. - retry_delay = min(INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS) + retry_delay = min( + INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS + ) # Add a randomness / jitter to the retry delay to avoid overwhelming the server with retries. timeout = retry_delay * (1 - 0.25 * random()) @@ -90,7 +92,8 @@ def _should_retry(response: httpx.Response) -> bool: def remove_omit_from_dict( - original: typing.Dict[str, typing.Optional[typing.Any]], omit: typing.Optional[typing.Any] + original: typing.Dict[str, typing.Optional[typing.Any]], + omit: typing.Optional[typing.Any], ) -> typing.Dict[str, typing.Any]: if omit is None: return original @@ -108,7 +111,8 @@ def maybe_filter_request_body( ) -> typing.Optional[typing.Any]: if data is None: return ( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else None ) @@ -118,7 +122,8 @@ def maybe_filter_request_body( data_content = { **(jsonable_encoder(remove_omit_from_dict(data, omit))), # type: ignore **( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else {} ), @@ -162,7 +167,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url def request( @@ -174,8 +181,12 @@ def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -184,11 +195,14 @@ def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) response = self.httpx_client.request( method=method, @@ -198,7 +212,11 @@ def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -209,7 +227,10 @@ def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -222,11 +243,15 @@ def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: time.sleep(_retry_timeout(response=response, retries=retries)) @@ -256,8 +281,12 @@ def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -266,11 +295,14 @@ def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) with self.httpx_client.stream( method=method, @@ -280,7 +312,11 @@ def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -291,7 +327,9 @@ def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -304,7 +342,9 @@ def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream @@ -327,7 +367,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url async def request( @@ -339,8 +381,12 @@ async def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -349,11 +395,14 @@ async def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) # Add the input to each of these and do None-safety checks response = await self.httpx_client.request( @@ -364,7 +413,11 @@ async def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -375,7 +428,10 @@ async def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -388,11 +444,15 @@ async def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: await asyncio.sleep(_retry_timeout(response=response, retries=retries)) @@ -421,8 +481,12 @@ async def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -431,11 +495,14 @@ async def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) async with self.httpx_client.stream( method=method, @@ -445,7 +512,11 @@ async def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -456,7 +527,9 @@ async def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -469,7 +542,9 @@ async def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream diff --git a/seed/python-sdk/audiences/src/seed/core/jsonable_encoder.py b/seed/python-sdk/audiences/src/seed/core/jsonable_encoder.py index d3fd328fd41..12a8b52fc22 100644 --- a/seed/python-sdk/audiences/src/seed/core/jsonable_encoder.py +++ b/seed/python-sdk/audiences/src/seed/core/jsonable_encoder.py @@ -19,13 +19,19 @@ import pydantic from .datetime_utils import serialize_datetime -from .pydantic_utilities import IS_PYDANTIC_V2, encode_by_type, to_jsonable_with_fallback +from .pydantic_utilities import ( + IS_PYDANTIC_V2, + encode_by_type, + to_jsonable_with_fallback, +) SetIntStr = Set[Union[int, str]] DictIntStrAny = Dict[Union[int, str], Any] -def jsonable_encoder(obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None) -> Any: +def jsonable_encoder( + obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None +) -> Any: custom_encoder = custom_encoder or {} if custom_encoder: if type(obj) in custom_encoder: diff --git a/seed/python-sdk/audiences/src/seed/core/pydantic_utilities.py b/seed/python-sdk/audiences/src/seed/core/pydantic_utilities.py index 170a563d6eb..c63935c32a2 100644 --- a/seed/python-sdk/audiences/src/seed/core/pydantic_utilities.py +++ b/seed/python-sdk/audiences/src/seed/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) # type: ignore # Pydantic v1 diff --git a/seed/python-sdk/audiences/src/seed/core/query_encoder.py b/seed/python-sdk/audiences/src/seed/core/query_encoder.py index 24076d72ee9..7cb98f52cd7 100644 --- a/seed/python-sdk/audiences/src/seed/core/query_encoder.py +++ b/seed/python-sdk/audiences/src/seed/core/query_encoder.py @@ -7,7 +7,9 @@ # Flattens dicts to be of the form {"key[subkey][subkey2]": value} where value is not a dict -def traverse_query_dict(dict_flat: Dict[str, Any], key_prefix: Optional[str] = None) -> Dict[str, Any]: +def traverse_query_dict( + dict_flat: Dict[str, Any], key_prefix: Optional[str] = None +) -> Dict[str, Any]: result = {} for k, v in dict_flat.items(): key = f"{key_prefix}[{k}]" if key_prefix is not None else k @@ -30,4 +32,8 @@ def single_query_encoder(query_key: str, query_value: Any) -> Dict[str, Any]: def encode_query(query: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: - return dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) if query is not None else None + return ( + dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) + if query is not None + else None + ) diff --git a/seed/python-sdk/audiences/src/seed/core/serialization.py b/seed/python-sdk/audiences/src/seed/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/python-sdk/audiences/src/seed/core/serialization.py +++ b/seed/python-sdk/audiences/src/seed/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/python-sdk/audiences/src/seed/folder_a/client.py b/seed/python-sdk/audiences/src/seed/folder_a/client.py index e8c2bd50bee..57900c44b72 100644 --- a/seed/python-sdk/audiences/src/seed/folder_a/client.py +++ b/seed/python-sdk/audiences/src/seed/folder_a/client.py @@ -1,7 +1,9 @@ # This file was auto-generated by Fern from our API Definition. -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from .service.client import AsyncServiceClient, ServiceClient +from ..core.client_wrapper import SyncClientWrapper +from .service.client import ServiceClient +from ..core.client_wrapper import AsyncClientWrapper +from .service.client import AsyncServiceClient class FolderAClient: diff --git a/seed/python-sdk/audiences/src/seed/folder_a/service/client.py b/seed/python-sdk/audiences/src/seed/folder_a/service/client.py index 83a45982ea5..3ef9e9fd386 100644 --- a/seed/python-sdk/audiences/src/seed/folder_a/service/client.py +++ b/seed/python-sdk/audiences/src/seed/folder_a/service/client.py @@ -1,20 +1,22 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.client_wrapper import SyncClientWrapper import typing -from json.decoder import JSONDecodeError - -from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ...core.pydantic_utilities import parse_obj_as from ...core.request_options import RequestOptions from .types.response import Response +from ...core.pydantic_utilities import parse_obj_as +from json.decoder import JSONDecodeError +from ...core.api_error import ApiError +from ...core.client_wrapper import AsyncClientWrapper class ServiceClient: def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper - def get_direct_thread(self, *, request_options: typing.Optional[RequestOptions] = None) -> Response: + def get_direct_thread( + self, *, request_options: typing.Optional[RequestOptions] = None + ) -> Response: """ Parameters ---------- @@ -34,10 +36,15 @@ def get_direct_thread(self, *, request_options: typing.Optional[RequestOptions] ) client.folder_a.service.get_direct_thread() """ - _response = self._client_wrapper.httpx_client.request(method="GET", request_options=request_options) + _response = self._client_wrapper.httpx_client.request( + method="GET", + request_options=request_options, + ) try: if 200 <= _response.status_code < 300: - return typing.cast(Response, parse_obj_as(type_=Response, object_=_response.json())) # type: ignore + return typing.cast( + Response, parse_obj_as(type_=Response, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -48,7 +55,9 @@ class AsyncServiceClient: def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper - async def get_direct_thread(self, *, request_options: typing.Optional[RequestOptions] = None) -> Response: + async def get_direct_thread( + self, *, request_options: typing.Optional[RequestOptions] = None + ) -> Response: """ Parameters ---------- @@ -76,10 +85,15 @@ async def main() -> None: asyncio.run(main()) """ - _response = await self._client_wrapper.httpx_client.request(method="GET", request_options=request_options) + _response = await self._client_wrapper.httpx_client.request( + method="GET", + request_options=request_options, + ) try: if 200 <= _response.status_code < 300: - return typing.cast(Response, parse_obj_as(type_=Response, object_=_response.json())) # type: ignore + return typing.cast( + Response, parse_obj_as(type_=Response, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/audiences/src/seed/folder_a/service/types/response.py b/seed/python-sdk/audiences/src/seed/folder_a/service/types/response.py index f1b8bdf2660..6baf09c622f 100644 --- a/seed/python-sdk/audiences/src/seed/folder_a/service/types/response.py +++ b/seed/python-sdk/audiences/src/seed/folder_a/service/types/response.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from ....folder_b.common.types.foo import Foo +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import pydantic class Response(UniversalBaseModel): foo: typing.Optional[Foo] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/audiences/src/seed/folder_b/common/types/foo.py b/seed/python-sdk/audiences/src/seed/folder_b/common/types/foo.py index 77cbe294201..acb64200dcc 100644 --- a/seed/python-sdk/audiences/src/seed/folder_b/common/types/foo.py +++ b/seed/python-sdk/audiences/src/seed/folder_b/common/types/foo.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from ....folder_c.common.types.foo import Foo as folder_c_common_types_foo_Foo +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import pydantic class Foo(UniversalBaseModel): foo: typing.Optional[folder_c_common_types_foo_Foo] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/audiences/src/seed/folder_c/common/types/foo.py b/seed/python-sdk/audiences/src/seed/folder_c/common/types/foo.py index f4a501ac76b..865161ba037 100644 --- a/seed/python-sdk/audiences/src/seed/folder_c/common/types/foo.py +++ b/seed/python-sdk/audiences/src/seed/folder_c/common/types/foo.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. -import typing +from ....core.pydantic_utilities import UniversalBaseModel import uuid - +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class Foo(UniversalBaseModel): bar_property: uuid.UUID if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/audiences/src/seed/foo/client.py b/seed/python-sdk/audiences/src/seed/foo/client.py index c186a54b68d..dd3a52be599 100644 --- a/seed/python-sdk/audiences/src/seed/foo/client.py +++ b/seed/python-sdk/audiences/src/seed/foo/client.py @@ -1,14 +1,14 @@ # This file was auto-generated by Fern from our API Definition. import typing -from json.decoder import JSONDecodeError - -from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.pydantic_utilities import parse_obj_as +from ..core.client_wrapper import SyncClientWrapper +from .types.optional_string import OptionalString from ..core.request_options import RequestOptions from .types.importing_type import ImportingType -from .types.optional_string import OptionalString +from ..core.pydantic_utilities import parse_obj_as +from json.decoder import JSONDecodeError +from ..core.api_error import ApiError +from ..core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -24,7 +24,7 @@ def find( optional_string: OptionalString, public_property: typing.Optional[str] = OMIT, private_property: typing.Optional[int] = OMIT, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> ImportingType: """ Parameters @@ -57,14 +57,22 @@ def find( """ _response = self._client_wrapper.httpx_client.request( method="POST", - params={"optionalString": optional_string}, - json={"publicProperty": public_property, "privateProperty": private_property}, + params={ + "optionalString": optional_string, + }, + json={ + "publicProperty": public_property, + "privateProperty": private_property, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ImportingType, parse_obj_as(type_=ImportingType, object_=_response.json())) # type: ignore + return typing.cast( + ImportingType, + parse_obj_as(type_=ImportingType, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -81,7 +89,7 @@ async def find( optional_string: OptionalString, public_property: typing.Optional[str] = OMIT, private_property: typing.Optional[int] = OMIT, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> ImportingType: """ Parameters @@ -122,14 +130,22 @@ async def main() -> None: """ _response = await self._client_wrapper.httpx_client.request( method="POST", - params={"optionalString": optional_string}, - json={"publicProperty": public_property, "privateProperty": private_property}, + params={ + "optionalString": optional_string, + }, + json={ + "publicProperty": public_property, + "privateProperty": private_property, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ImportingType, parse_obj_as(type_=ImportingType, object_=_response.json())) # type: ignore + return typing.cast( + ImportingType, + parse_obj_as(type_=ImportingType, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/audiences/src/seed/foo/types/filtered_type.py b/seed/python-sdk/audiences/src/seed/foo/types/filtered_type.py index 067cf0fd7e4..ffd8bc55906 100644 --- a/seed/python-sdk/audiences/src/seed/foo/types/filtered_type.py +++ b/seed/python-sdk/audiences/src/seed/foo/types/filtered_type.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel import typing - +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class FilteredType(UniversalBaseModel): public_property: typing.Optional[str] = None private_property: int if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/audiences/src/seed/foo/types/importing_type.py b/seed/python-sdk/audiences/src/seed/foo/types/importing_type.py index 431e9b6e9c1..fee33ffdd6c 100644 --- a/seed/python-sdk/audiences/src/seed/foo/types/importing_type.py +++ b/seed/python-sdk/audiences/src/seed/foo/types/importing_type.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ...commons.types.imported import Imported +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...commons.types.imported import Imported -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class ImportingType(UniversalBaseModel): imported: Imported if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/audiences/src/seed/version.py b/seed/python-sdk/audiences/src/seed/version.py index f772c83b9ad..782dd0e9785 100644 --- a/seed/python-sdk/audiences/src/seed/version.py +++ b/seed/python-sdk/audiences/src/seed/version.py @@ -1,4 +1,3 @@ - from importlib import metadata __version__ = metadata.version("fern_audiences") diff --git a/seed/python-sdk/audiences/tests/conftest.py b/seed/python-sdk/audiences/tests/conftest.py index 1f849400c6d..b66d7e4ef42 100644 --- a/seed/python-sdk/audiences/tests/conftest.py +++ b/seed/python-sdk/audiences/tests/conftest.py @@ -1,9 +1,9 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedAudiences import os - import pytest -from seed import AsyncSeedAudiences, SeedAudiences +from seed import AsyncSeedAudiences @pytest.fixture diff --git a/seed/python-sdk/audiences/tests/custom/test_client.py b/seed/python-sdk/audiences/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/python-sdk/audiences/tests/custom/test_client.py +++ b/seed/python-sdk/audiences/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/python-sdk/audiences/tests/folder_a/test_service.py b/seed/python-sdk/audiences/tests/folder_a/test_service.py index ec1dee5f273..3e4f7824f4e 100644 --- a/seed/python-sdk/audiences/tests/folder_a/test_service.py +++ b/seed/python-sdk/audiences/tests/folder_a/test_service.py @@ -1,13 +1,14 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedAudiences +from seed import AsyncSeedAudiences import typing - -from seed import AsyncSeedAudiences, SeedAudiences - from ..utilities import validate_response -async def test_get_direct_thread(client: SeedAudiences, async_client: AsyncSeedAudiences) -> None: +async def test_get_direct_thread( + client: SeedAudiences, async_client: AsyncSeedAudiences +) -> None: expected_response: typing.Any = {"foo": {}} expected_types: typing.Any = {"foo": {}} response = client.folder_a.service.get_direct_thread() diff --git a/seed/python-sdk/audiences/tests/test_foo.py b/seed/python-sdk/audiences/tests/test_foo.py index 641495f20b7..b8fee8dfd79 100644 --- a/seed/python-sdk/audiences/tests/test_foo.py +++ b/seed/python-sdk/audiences/tests/test_foo.py @@ -1,17 +1,20 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedAudiences +from seed import AsyncSeedAudiences import typing - -from seed import AsyncSeedAudiences, SeedAudiences - from .utilities import validate_response async def test_find(client: SeedAudiences, async_client: AsyncSeedAudiences) -> None: expected_response: typing.Any = {"imported": "string"} expected_types: typing.Any = {"imported": None} - response = client.foo.find(optional_string="string", public_property="string", private_property=1) + response = client.foo.find( + optional_string="string", public_property="string", private_property=1 + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.foo.find(optional_string="string", public_property="string", private_property=1) + async_response = await async_client.foo.find( + optional_string="string", public_property="string", private_property=1 + ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/audiences/tests/utilities.py b/seed/python-sdk/audiences/tests/utilities.py index 13da208eb3a..e8f4472564c 100644 --- a/seed/python-sdk/audiences/tests/utilities.py +++ b/seed/python-sdk/audiences/tests/utilities.py @@ -3,11 +3,14 @@ import typing import uuid -import pydantic from dateutil import parser +import pydantic + -def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> typing.Any: +def cast_field( + json_expectation: typing.Any, type_expectation: typing.Any +) -> typing.Any: # Cast these specific types which come through as string and expect our # models to cast to the correct type. if type_expectation == "uuid": @@ -25,7 +28,9 @@ def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> ty return json_expectation -def validate_field(response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any) -> None: +def validate_field( + response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectation == "no_validate": return @@ -44,7 +49,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(entry_expectation, dict): is_container_of_complex_type = True validate_response( - response=response[idx], json_expectation=ex, type_expectations=entry_expectation + response=response[idx], + json_expectation=ex, + type_expectations=entry_expectation, ) else: cast_json_expectation.append(cast_field(ex, entry_expectation)) @@ -56,7 +63,10 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # if any of the values of the set have a type_expectation of a dict, we're assuming it's a pydantic # model and keeping it a list. if container_expectation != "set" or not any( - map(lambda value: isinstance(value, dict), list(contents_expectation.values())) + map( + lambda value: isinstance(value, dict), + list(contents_expectation.values()), + ) ): json_expectation = cast_field(json_expectation, container_expectation) elif isinstance(type_expectation, tuple): @@ -65,9 +75,15 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(contents_expectation, dict): json_expectation = { cast_field( - key, contents_expectation.get(idx)[0] if contents_expectation.get(idx) is not None else None # type: ignore + key, + contents_expectation.get(idx)[0] + if contents_expectation.get(idx) is not None + else None, # type: ignore ): cast_field( - value, contents_expectation.get(idx)[1] if contents_expectation.get(idx) is not None else None # type: ignore + value, + contents_expectation.get(idx)[1] + if contents_expectation.get(idx) is not None + else None, # type: ignore ) for idx, (key, value) in enumerate(json_expectation.items()) } @@ -86,7 +102,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # Arg type_expectations is a deeply nested structure that matches the response, but with the values replaced with the expected types -def validate_response(response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any) -> None: +def validate_response( + response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectations == "no_validate": return @@ -96,11 +114,17 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e and not isinstance(response, dict) and not issubclass(type(response), pydantic.BaseModel) ): - validate_field(response=response, json_expectation=json_expectation, type_expectation=type_expectations) + validate_field( + response=response, + json_expectation=json_expectation, + type_expectation=type_expectations, + ) return if isinstance(response, list): - assert len(response) == len(json_expectation), "Length mismatch, expected: {0}, Actual: {1}".format( + assert len(response) == len( + json_expectation + ), "Length mismatch, expected: {0}, Actual: {1}".format( len(response), len(json_expectation) ) content_expectation = type_expectations @@ -108,7 +132,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e content_expectation = type_expectations[1] for idx, item in enumerate(response): validate_response( - response=item, json_expectation=json_expectation[idx], type_expectations=content_expectation[idx] + response=item, + json_expectation=json_expectation[idx], + type_expectations=content_expectation[idx], ) else: response_json = response @@ -116,7 +142,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e response_json = response.dict(by_alias=True) for key, value in json_expectation.items(): - assert key in response_json, "Field {0} not found within the response object: {1}".format( + assert ( + key in response_json + ), "Field {0} not found within the response object: {1}".format( key, response_json ) @@ -128,11 +156,19 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e # Otherwise, we're just validating a single field that's a pydantic model. if isinstance(value, dict) and not isinstance(type_expectation, tuple): validate_response( - response=response_json[key], json_expectation=value, type_expectations=type_expectation + response=response_json[key], + json_expectation=value, + type_expectations=type_expectation, ) else: - validate_field(response=response_json[key], json_expectation=value, type_expectation=type_expectation) + validate_field( + response=response_json[key], + json_expectation=value, + type_expectation=type_expectation, + ) # Ensure there are no additional fields here either del response_json[key] - assert len(response_json) == 0, "Additional fields found, expected None: {0}".format(response_json) + assert ( + len(response_json) == 0 + ), "Additional fields found, expected None: {0}".format(response_json) diff --git a/seed/python-sdk/audiences/tests/utils/assets/models/__init__.py b/seed/python-sdk/audiences/tests/utils/assets/models/__init__.py index 2cf01263529..3a1c852e71e 100644 --- a/seed/python-sdk/audiences/tests/utils/assets/models/__init__.py +++ b/seed/python-sdk/audiences/tests/utils/assets/models/__init__.py @@ -5,7 +5,7 @@ from .circle import CircleParams from .object_with_defaults import ObjectWithDefaultsParams from .object_with_optional_field import ObjectWithOptionalFieldParams -from .shape import Shape_CircleParams, Shape_SquareParams, ShapeParams +from .shape import ShapeParams, Shape_CircleParams, Shape_SquareParams from .square import SquareParams from .undiscriminated_shape import UndiscriminatedShapeParams diff --git a/seed/python-sdk/audiences/tests/utils/assets/models/circle.py b/seed/python-sdk/audiences/tests/utils/assets/models/circle.py index af7a1bf8a8e..253f12d38b3 100644 --- a/seed/python-sdk/audiences/tests/utils/assets/models/circle.py +++ b/seed/python-sdk/audiences/tests/utils/assets/models/circle.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class CircleParams(typing_extensions.TypedDict): - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] diff --git a/seed/python-sdk/audiences/tests/utils/assets/models/object_with_optional_field.py b/seed/python-sdk/audiences/tests/utils/assets/models/object_with_optional_field.py index 3ad93d5f305..ebe7dc80547 100644 --- a/seed/python-sdk/audiences/tests/utils/assets/models/object_with_optional_field.py +++ b/seed/python-sdk/audiences/tests/utils/assets/models/object_with_optional_field.py @@ -7,8 +7,8 @@ import uuid import typing_extensions -from seed.core.serialization import FieldMetadata +from seed.core.serialization import FieldMetadata from .color import Color from .shape import ShapeParams from .undiscriminated_shape import UndiscriminatedShapeParams @@ -18,16 +18,30 @@ class ObjectWithOptionalFieldParams(typing_extensions.TypedDict): literal: typing.Literal["lit_one"] string: typing_extensions.NotRequired[str] integer: typing_extensions.NotRequired[int] - long_: typing_extensions.NotRequired[typing_extensions.Annotated[int, FieldMetadata(alias="long")]] + long_: typing_extensions.NotRequired[ + typing_extensions.Annotated[int, FieldMetadata(alias="long")] + ] double: typing_extensions.NotRequired[float] - bool_: typing_extensions.NotRequired[typing_extensions.Annotated[bool, FieldMetadata(alias="bool")]] + bool_: typing_extensions.NotRequired[ + typing_extensions.Annotated[bool, FieldMetadata(alias="bool")] + ] datetime: typing_extensions.NotRequired[dt.datetime] date: typing_extensions.NotRequired[dt.date] - uuid_: typing_extensions.NotRequired[typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")]] - base_64: typing_extensions.NotRequired[typing_extensions.Annotated[str, FieldMetadata(alias="base64")]] - list_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")]] - set_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")]] - map_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")]] + uuid_: typing_extensions.NotRequired[ + typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")] + ] + base_64: typing_extensions.NotRequired[ + typing_extensions.Annotated[str, FieldMetadata(alias="base64")] + ] + list_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")] + ] + set_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")] + ] + map_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")] + ] enum: typing_extensions.NotRequired[Color] union: typing_extensions.NotRequired[ShapeParams] second_union: typing_extensions.NotRequired[ShapeParams] diff --git a/seed/python-sdk/audiences/tests/utils/assets/models/shape.py b/seed/python-sdk/audiences/tests/utils/assets/models/shape.py index 2c33c877951..816ffc51bdc 100644 --- a/seed/python-sdk/audiences/tests/utils/assets/models/shape.py +++ b/seed/python-sdk/audiences/tests/utils/assets/models/shape.py @@ -7,6 +7,7 @@ import typing import typing_extensions + from seed.core.serialization import FieldMetadata @@ -15,13 +16,21 @@ class Base(typing_extensions.TypedDict): class Shape_CircleParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["circle"], FieldMetadata(alias="shapeType")] - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["circle"], FieldMetadata(alias="shapeType") + ] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] class Shape_SquareParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["square"], FieldMetadata(alias="shapeType")] - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["square"], FieldMetadata(alias="shapeType") + ] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] ShapeParams = typing.Union[Shape_CircleParams, Shape_SquareParams] diff --git a/seed/python-sdk/audiences/tests/utils/assets/models/square.py b/seed/python-sdk/audiences/tests/utils/assets/models/square.py index b9b7dd319bc..bcf08a723c5 100644 --- a/seed/python-sdk/audiences/tests/utils/assets/models/square.py +++ b/seed/python-sdk/audiences/tests/utils/assets/models/square.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class SquareParams(typing_extensions.TypedDict): - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] diff --git a/seed/python-sdk/audiences/tests/utils/test_http_client.py b/seed/python-sdk/audiences/tests/utils/test_http_client.py index edd11ca7afb..f5a874a75f3 100644 --- a/seed/python-sdk/audiences/tests/utils/test_http_client.py +++ b/seed/python-sdk/audiences/tests/utils/test_http_client.py @@ -9,12 +9,17 @@ def get_request_options() -> RequestOptions: def test_get_json_request_body() -> None: - json_body, data_body = get_request_body(json={"hello": "world"}, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json={"hello": "world"}, data=None, request_options=None, omit=None + ) assert json_body == {"hello": "world"} assert data_body is None json_body_extras, data_body_extras = get_request_body( - json={"goodbye": "world"}, data=None, request_options=get_request_options(), omit=None + json={"goodbye": "world"}, + data=None, + request_options=get_request_options(), + omit=None, ) assert json_body_extras == {"goodbye": "world", "see you": "later"} @@ -22,12 +27,17 @@ def test_get_json_request_body() -> None: def test_get_files_request_body() -> None: - json_body, data_body = get_request_body(json=None, data={"hello": "world"}, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data={"hello": "world"}, request_options=None, omit=None + ) assert data_body == {"hello": "world"} assert json_body is None json_body_extras, data_body_extras = get_request_body( - json=None, data={"goodbye": "world"}, request_options=get_request_options(), omit=None + json=None, + data={"goodbye": "world"}, + request_options=get_request_options(), + omit=None, ) assert data_body_extras == {"goodbye": "world", "see you": "later"} @@ -35,7 +45,9 @@ def test_get_files_request_body() -> None: def test_get_none_request_body() -> None: - json_body, data_body = get_request_body(json=None, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data=None, request_options=None, omit=None + ) assert data_body is None assert json_body is None diff --git a/seed/python-sdk/audiences/tests/utils/test_query_encoding.py b/seed/python-sdk/audiences/tests/utils/test_query_encoding.py index 247e1551b46..fbc8f402167 100644 --- a/seed/python-sdk/audiences/tests/utils/test_query_encoding.py +++ b/seed/python-sdk/audiences/tests/utils/test_query_encoding.py @@ -4,9 +4,15 @@ def test_query_encoding() -> None: - assert encode_query({"hello world": "hello world"}) == {"hello world": "hello world"} - assert encode_query({"hello_world": {"hello": "world"}}) == {"hello_world[hello]": "world"} - assert encode_query({"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"}) == { + assert encode_query({"hello world": "hello world"}) == { + "hello world": "hello world" + } + assert encode_query({"hello_world": {"hello": "world"}}) == { + "hello_world[hello]": "world" + } + assert encode_query( + {"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"} + ) == { "hello_world[hello][world]": "today", "hello_world[test]": "this", "hi": "there", diff --git a/seed/python-sdk/audiences/tests/utils/test_serialization.py b/seed/python-sdk/audiences/tests/utils/test_serialization.py index 58b1ed66e6d..5ca956916dd 100644 --- a/seed/python-sdk/audiences/tests/utils/test_serialization.py +++ b/seed/python-sdk/audiences/tests/utils/test_serialization.py @@ -1,10 +1,12 @@ # This file was auto-generated by Fern from our API Definition. -from typing import Any, List +from typing import List, Any -from seed.core.serialization import convert_and_respect_annotation_metadata +from seed.core.serialization import ( + convert_and_respect_annotation_metadata, +) +from .assets.models import ShapeParams, ObjectWithOptionalFieldParams -from .assets.models import ObjectWithOptionalFieldParams, ShapeParams UNION_TEST: ShapeParams = {"radius_measurement": 1.0, "shape_type": "circle", "id": "1"} UNION_TEST_CONVERTED = {"shapeType": "circle", "radiusMeasurement": 1.0, "id": "1"} @@ -18,20 +20,54 @@ def test_convert_and_respect_annotation_metadata() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) - assert converted == {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"} + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) + assert converted == { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + } def test_convert_and_respect_annotation_metadata_in_list() -> None: data: List[ObjectWithOptionalFieldParams] = [ - {"string": "string", "long_": 12345, "bool_": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long_": 67890, "list_": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long_": 12345, + "bool_": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long_": 67890, + "list_": [], + "literal": "lit_one", + "any": "any", + }, ] - converted = convert_and_respect_annotation_metadata(object_=data, annotation=List[ObjectWithOptionalFieldParams]) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=List[ObjectWithOptionalFieldParams] + ) assert converted == [ - {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long": 67890, "list": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long": 67890, + "list": [], + "literal": "lit_one", + "any": "any", + }, ] @@ -43,7 +79,9 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) assert converted == { "string": "string", @@ -55,12 +93,16 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: def test_convert_and_respect_annotation_metadata_in_union() -> None: - converted = convert_and_respect_annotation_metadata(object_=UNION_TEST, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=UNION_TEST, annotation=ShapeParams + ) assert converted == UNION_TEST_CONVERTED def test_convert_and_respect_annotation_metadata_with_empty_object() -> None: data: Any = {} - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ShapeParams + ) assert converted == data diff --git a/seed/python-sdk/auth-environment-variables/pyproject.toml b/seed/python-sdk/auth-environment-variables/pyproject.toml index b9cd4726260..da4ac8b61da 100644 --- a/seed/python-sdk/auth-environment-variables/pyproject.toml +++ b/seed/python-sdk/auth-environment-variables/pyproject.toml @@ -43,6 +43,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/python-sdk/auth-environment-variables/src/seed/__init__.py b/seed/python-sdk/auth-environment-variables/src/seed/__init__.py index fb04a2268bd..6f99aca563a 100644 --- a/seed/python-sdk/auth-environment-variables/src/seed/__init__.py +++ b/seed/python-sdk/auth-environment-variables/src/seed/__init__.py @@ -4,4 +4,9 @@ from .client import AsyncSeedAuthEnvironmentVariables, SeedAuthEnvironmentVariables from .version import __version__ -__all__ = ["AsyncSeedAuthEnvironmentVariables", "SeedAuthEnvironmentVariables", "__version__", "service"] +__all__ = [ + "AsyncSeedAuthEnvironmentVariables", + "SeedAuthEnvironmentVariables", + "__version__", + "service", +] diff --git a/seed/python-sdk/auth-environment-variables/src/seed/client.py b/seed/python-sdk/auth-environment-variables/src/seed/client.py index 31117dd937d..67e916bab94 100644 --- a/seed/python-sdk/auth-environment-variables/src/seed/client.py +++ b/seed/python-sdk/auth-environment-variables/src/seed/client.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. -import os import typing - +import os import httpx - from .core.api_error import ApiError -from .core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from .service.client import AsyncServiceClient, ServiceClient +from .core.client_wrapper import SyncClientWrapper +from .service.client import ServiceClient +from .core.client_wrapper import AsyncClientWrapper +from .service.client import AsyncServiceClient class SeedAuthEnvironmentVariables: @@ -49,22 +49,28 @@ def __init__( api_key: typing.Optional[str] = os.getenv("FERN_API_KEY"), timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.Client] = None + httpx_client: typing.Optional[httpx.Client] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) if x_another_header is None: raise ApiError( body="The client must be instantiated be either passing in x_another_header or setting ANOTHER_ENV_VAR" ) if api_key is None: - raise ApiError(body="The client must be instantiated be either passing in api_key or setting FERN_API_KEY") + raise ApiError( + body="The client must be instantiated be either passing in api_key or setting FERN_API_KEY" + ) self._client_wrapper = SyncClientWrapper( base_url=base_url, x_another_header=x_another_header, api_key=api_key, httpx_client=httpx_client if httpx_client is not None - else httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.Client( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.Client(timeout=_defaulted_timeout), timeout=_defaulted_timeout, @@ -111,22 +117,28 @@ def __init__( api_key: typing.Optional[str] = os.getenv("FERN_API_KEY"), timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.AsyncClient] = None + httpx_client: typing.Optional[httpx.AsyncClient] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) if x_another_header is None: raise ApiError( body="The client must be instantiated be either passing in x_another_header or setting ANOTHER_ENV_VAR" ) if api_key is None: - raise ApiError(body="The client must be instantiated be either passing in api_key or setting FERN_API_KEY") + raise ApiError( + body="The client must be instantiated be either passing in api_key or setting FERN_API_KEY" + ) self._client_wrapper = AsyncClientWrapper( base_url=base_url, x_another_header=x_another_header, api_key=api_key, httpx_client=httpx_client if httpx_client is not None - else httpx.AsyncClient(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.AsyncClient( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.AsyncClient(timeout=_defaulted_timeout), timeout=_defaulted_timeout, diff --git a/seed/python-sdk/auth-environment-variables/src/seed/core/api_error.py b/seed/python-sdk/auth-environment-variables/src/seed/core/api_error.py index 2e9fc5431cd..da734b58068 100644 --- a/seed/python-sdk/auth-environment-variables/src/seed/core/api_error.py +++ b/seed/python-sdk/auth-environment-variables/src/seed/core/api_error.py @@ -7,7 +7,9 @@ class ApiError(Exception): status_code: typing.Optional[int] body: typing.Any - def __init__(self, *, status_code: typing.Optional[int] = None, body: typing.Any = None): + def __init__( + self, *, status_code: typing.Optional[int] = None, body: typing.Any = None + ): self.status_code = status_code self.body = body diff --git a/seed/python-sdk/auth-environment-variables/src/seed/core/client_wrapper.py b/seed/python-sdk/auth-environment-variables/src/seed/core/client_wrapper.py index d06badb6789..a7bcefb2c99 100644 --- a/seed/python-sdk/auth-environment-variables/src/seed/core/client_wrapper.py +++ b/seed/python-sdk/auth-environment-variables/src/seed/core/client_wrapper.py @@ -1,14 +1,20 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .http_client import AsyncHttpClient, HttpClient +from .http_client import HttpClient +from .http_client import AsyncHttpClient class BaseClientWrapper: - def __init__(self, *, x_another_header: str, api_key: str, base_url: str, timeout: typing.Optional[float] = None): + def __init__( + self, + *, + x_another_header: str, + api_key: str, + base_url: str, + timeout: typing.Optional[float] = None, + ): self._x_another_header = x_another_header self.api_key = api_key self._base_url = base_url @@ -39,9 +45,14 @@ def __init__( api_key: str, base_url: str, timeout: typing.Optional[float] = None, - httpx_client: httpx.Client + httpx_client: httpx.Client, ): - super().__init__(x_another_header=x_another_header, api_key=api_key, base_url=base_url, timeout=timeout) + super().__init__( + x_another_header=x_another_header, + api_key=api_key, + base_url=base_url, + timeout=timeout, + ) self.httpx_client = HttpClient( httpx_client=httpx_client, base_headers=self.get_headers(), @@ -58,9 +69,14 @@ def __init__( api_key: str, base_url: str, timeout: typing.Optional[float] = None, - httpx_client: httpx.AsyncClient + httpx_client: httpx.AsyncClient, ): - super().__init__(x_another_header=x_another_header, api_key=api_key, base_url=base_url, timeout=timeout) + super().__init__( + x_another_header=x_another_header, + api_key=api_key, + base_url=base_url, + timeout=timeout, + ) self.httpx_client = AsyncHttpClient( httpx_client=httpx_client, base_headers=self.get_headers(), diff --git a/seed/python-sdk/auth-environment-variables/src/seed/core/datetime_utils.py b/seed/python-sdk/auth-environment-variables/src/seed/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/python-sdk/auth-environment-variables/src/seed/core/datetime_utils.py +++ b/seed/python-sdk/auth-environment-variables/src/seed/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/python-sdk/auth-environment-variables/src/seed/core/file.py b/seed/python-sdk/auth-environment-variables/src/seed/core/file.py index cb0d40bbbf3..6e0f92bfcb1 100644 --- a/seed/python-sdk/auth-environment-variables/src/seed/core/file.py +++ b/seed/python-sdk/auth-environment-variables/src/seed/core/file.py @@ -13,12 +13,17 @@ # (filename, file (or bytes), content_type) typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str]], # (filename, file (or bytes), content_type, headers) - typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str], typing.Mapping[str, str]], + typing.Tuple[ + typing.Optional[str], + FileContent, + typing.Optional[str], + typing.Mapping[str, str], + ], ] def convert_file_dict_to_httpx_tuples( - d: typing.Dict[str, typing.Union[File, typing.List[File]]] + d: typing.Dict[str, typing.Union[File, typing.List[File]]], ) -> typing.List[typing.Tuple[str, File]]: """ The format we use is a list of tuples, where the first element is the diff --git a/seed/python-sdk/auth-environment-variables/src/seed/core/http_client.py b/seed/python-sdk/auth-environment-variables/src/seed/core/http_client.py index 9333d8a7f15..091f71bc185 100644 --- a/seed/python-sdk/auth-environment-variables/src/seed/core/http_client.py +++ b/seed/python-sdk/auth-environment-variables/src/seed/core/http_client.py @@ -77,7 +77,9 @@ def _retry_timeout(response: httpx.Response, retries: int) -> float: return retry_after # Apply exponential backoff, capped at MAX_RETRY_DELAY_SECONDS. - retry_delay = min(INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS) + retry_delay = min( + INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS + ) # Add a randomness / jitter to the retry delay to avoid overwhelming the server with retries. timeout = retry_delay * (1 - 0.25 * random()) @@ -90,7 +92,8 @@ def _should_retry(response: httpx.Response) -> bool: def remove_omit_from_dict( - original: typing.Dict[str, typing.Optional[typing.Any]], omit: typing.Optional[typing.Any] + original: typing.Dict[str, typing.Optional[typing.Any]], + omit: typing.Optional[typing.Any], ) -> typing.Dict[str, typing.Any]: if omit is None: return original @@ -108,7 +111,8 @@ def maybe_filter_request_body( ) -> typing.Optional[typing.Any]: if data is None: return ( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else None ) @@ -118,7 +122,8 @@ def maybe_filter_request_body( data_content = { **(jsonable_encoder(remove_omit_from_dict(data, omit))), # type: ignore **( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else {} ), @@ -162,7 +167,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url def request( @@ -174,8 +181,12 @@ def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -184,11 +195,14 @@ def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) response = self.httpx_client.request( method=method, @@ -198,7 +212,11 @@ def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -209,7 +227,10 @@ def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -222,11 +243,15 @@ def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: time.sleep(_retry_timeout(response=response, retries=retries)) @@ -256,8 +281,12 @@ def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -266,11 +295,14 @@ def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) with self.httpx_client.stream( method=method, @@ -280,7 +312,11 @@ def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -291,7 +327,9 @@ def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -304,7 +342,9 @@ def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream @@ -327,7 +367,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url async def request( @@ -339,8 +381,12 @@ async def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -349,11 +395,14 @@ async def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) # Add the input to each of these and do None-safety checks response = await self.httpx_client.request( @@ -364,7 +413,11 @@ async def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -375,7 +428,10 @@ async def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -388,11 +444,15 @@ async def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: await asyncio.sleep(_retry_timeout(response=response, retries=retries)) @@ -421,8 +481,12 @@ async def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -431,11 +495,14 @@ async def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) async with self.httpx_client.stream( method=method, @@ -445,7 +512,11 @@ async def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -456,7 +527,9 @@ async def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -469,7 +542,9 @@ async def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream diff --git a/seed/python-sdk/auth-environment-variables/src/seed/core/jsonable_encoder.py b/seed/python-sdk/auth-environment-variables/src/seed/core/jsonable_encoder.py index d3fd328fd41..12a8b52fc22 100644 --- a/seed/python-sdk/auth-environment-variables/src/seed/core/jsonable_encoder.py +++ b/seed/python-sdk/auth-environment-variables/src/seed/core/jsonable_encoder.py @@ -19,13 +19,19 @@ import pydantic from .datetime_utils import serialize_datetime -from .pydantic_utilities import IS_PYDANTIC_V2, encode_by_type, to_jsonable_with_fallback +from .pydantic_utilities import ( + IS_PYDANTIC_V2, + encode_by_type, + to_jsonable_with_fallback, +) SetIntStr = Set[Union[int, str]] DictIntStrAny = Dict[Union[int, str], Any] -def jsonable_encoder(obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None) -> Any: +def jsonable_encoder( + obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None +) -> Any: custom_encoder = custom_encoder or {} if custom_encoder: if type(obj) in custom_encoder: diff --git a/seed/python-sdk/auth-environment-variables/src/seed/core/pydantic_utilities.py b/seed/python-sdk/auth-environment-variables/src/seed/core/pydantic_utilities.py index 170a563d6eb..c63935c32a2 100644 --- a/seed/python-sdk/auth-environment-variables/src/seed/core/pydantic_utilities.py +++ b/seed/python-sdk/auth-environment-variables/src/seed/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) # type: ignore # Pydantic v1 diff --git a/seed/python-sdk/auth-environment-variables/src/seed/core/query_encoder.py b/seed/python-sdk/auth-environment-variables/src/seed/core/query_encoder.py index 24076d72ee9..7cb98f52cd7 100644 --- a/seed/python-sdk/auth-environment-variables/src/seed/core/query_encoder.py +++ b/seed/python-sdk/auth-environment-variables/src/seed/core/query_encoder.py @@ -7,7 +7,9 @@ # Flattens dicts to be of the form {"key[subkey][subkey2]": value} where value is not a dict -def traverse_query_dict(dict_flat: Dict[str, Any], key_prefix: Optional[str] = None) -> Dict[str, Any]: +def traverse_query_dict( + dict_flat: Dict[str, Any], key_prefix: Optional[str] = None +) -> Dict[str, Any]: result = {} for k, v in dict_flat.items(): key = f"{key_prefix}[{k}]" if key_prefix is not None else k @@ -30,4 +32,8 @@ def single_query_encoder(query_key: str, query_value: Any) -> Dict[str, Any]: def encode_query(query: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: - return dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) if query is not None else None + return ( + dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) + if query is not None + else None + ) diff --git a/seed/python-sdk/auth-environment-variables/src/seed/core/serialization.py b/seed/python-sdk/auth-environment-variables/src/seed/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/python-sdk/auth-environment-variables/src/seed/core/serialization.py +++ b/seed/python-sdk/auth-environment-variables/src/seed/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/python-sdk/auth-environment-variables/src/seed/service/client.py b/seed/python-sdk/auth-environment-variables/src/seed/service/client.py index d409123a6b0..0c056151574 100644 --- a/seed/python-sdk/auth-environment-variables/src/seed/service/client.py +++ b/seed/python-sdk/auth-environment-variables/src/seed/service/client.py @@ -1,20 +1,22 @@ # This file was auto-generated by Fern from our API Definition. -import os +from ..core.client_wrapper import SyncClientWrapper import typing +from ..core.request_options import RequestOptions +from ..core.pydantic_utilities import parse_obj_as from json.decoder import JSONDecodeError - from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.pydantic_utilities import parse_obj_as -from ..core.request_options import RequestOptions +import os +from ..core.client_wrapper import AsyncClientWrapper class ServiceClient: def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper - def get_with_api_key(self, *, request_options: typing.Optional[RequestOptions] = None) -> str: + def get_with_api_key( + self, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ GET request with custom api key @@ -38,10 +40,16 @@ def get_with_api_key(self, *, request_options: typing.Optional[RequestOptions] = ) client.service.get_with_api_key() """ - _response = self._client_wrapper.httpx_client.request("apiKey", method="GET", request_options=request_options) + _response = self._client_wrapper.httpx_client.request( + "apiKey", + method="GET", + request_options=request_options, + ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -51,7 +59,7 @@ def get_with_header( self, *, x_endpoint_header: typing.Optional[str] = os.getenv("MY_HEADER_ENV"), - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> str: """ GET request with custom api key @@ -84,12 +92,18 @@ def get_with_header( _response = self._client_wrapper.httpx_client.request( "apiKeyInHeader", method="GET", - headers={"X-Endpoint-Header": str(x_endpoint_header) if x_endpoint_header is not None else None}, + headers={ + "X-Endpoint-Header": str(x_endpoint_header) + if x_endpoint_header is not None + else None, + }, request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -100,7 +114,9 @@ class AsyncServiceClient: def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper - async def get_with_api_key(self, *, request_options: typing.Optional[RequestOptions] = None) -> str: + async def get_with_api_key( + self, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ GET request with custom api key @@ -133,11 +149,15 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "apiKey", method="GET", request_options=request_options + "apiKey", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -147,7 +167,7 @@ async def get_with_header( self, *, x_endpoint_header: typing.Optional[str] = os.getenv("MY_HEADER_ENV"), - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> str: """ GET request with custom api key @@ -188,12 +208,18 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( "apiKeyInHeader", method="GET", - headers={"X-Endpoint-Header": str(x_endpoint_header) if x_endpoint_header is not None else None}, + headers={ + "X-Endpoint-Header": str(x_endpoint_header) + if x_endpoint_header is not None + else None, + }, request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/auth-environment-variables/src/seed/version.py b/seed/python-sdk/auth-environment-variables/src/seed/version.py index de468edb967..8fb694fbf89 100644 --- a/seed/python-sdk/auth-environment-variables/src/seed/version.py +++ b/seed/python-sdk/auth-environment-variables/src/seed/version.py @@ -1,4 +1,3 @@ - from importlib import metadata __version__ = metadata.version("fern_auth-environment-variables") diff --git a/seed/python-sdk/auth-environment-variables/tests/conftest.py b/seed/python-sdk/auth-environment-variables/tests/conftest.py index 69d898e5884..8722c153011 100644 --- a/seed/python-sdk/auth-environment-variables/tests/conftest.py +++ b/seed/python-sdk/auth-environment-variables/tests/conftest.py @@ -1,9 +1,9 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedAuthEnvironmentVariables import os - import pytest -from seed import AsyncSeedAuthEnvironmentVariables, SeedAuthEnvironmentVariables +from seed import AsyncSeedAuthEnvironmentVariables @pytest.fixture diff --git a/seed/python-sdk/auth-environment-variables/tests/custom/test_client.py b/seed/python-sdk/auth-environment-variables/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/python-sdk/auth-environment-variables/tests/custom/test_client.py +++ b/seed/python-sdk/auth-environment-variables/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/python-sdk/auth-environment-variables/tests/test_service.py b/seed/python-sdk/auth-environment-variables/tests/test_service.py index 7dee7abb26b..b1af98cf288 100644 --- a/seed/python-sdk/auth-environment-variables/tests/test_service.py +++ b/seed/python-sdk/auth-environment-variables/tests/test_service.py @@ -1,14 +1,14 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedAuthEnvironmentVariables +from seed import AsyncSeedAuthEnvironmentVariables import typing - -from seed import AsyncSeedAuthEnvironmentVariables, SeedAuthEnvironmentVariables - from .utilities import validate_response async def test_get_with_api_key( - client: SeedAuthEnvironmentVariables, async_client: AsyncSeedAuthEnvironmentVariables + client: SeedAuthEnvironmentVariables, + async_client: AsyncSeedAuthEnvironmentVariables, ) -> None: expected_response: typing.Any = "string" expected_types: typing.Any = None @@ -20,12 +20,15 @@ async def test_get_with_api_key( async def test_get_with_header( - client: SeedAuthEnvironmentVariables, async_client: AsyncSeedAuthEnvironmentVariables + client: SeedAuthEnvironmentVariables, + async_client: AsyncSeedAuthEnvironmentVariables, ) -> None: expected_response: typing.Any = "string" expected_types: typing.Any = None response = client.service.get_with_header(x_endpoint_header="string") validate_response(response, expected_response, expected_types) - async_response = await async_client.service.get_with_header(x_endpoint_header="string") + async_response = await async_client.service.get_with_header( + x_endpoint_header="string" + ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/auth-environment-variables/tests/utilities.py b/seed/python-sdk/auth-environment-variables/tests/utilities.py index 13da208eb3a..e8f4472564c 100644 --- a/seed/python-sdk/auth-environment-variables/tests/utilities.py +++ b/seed/python-sdk/auth-environment-variables/tests/utilities.py @@ -3,11 +3,14 @@ import typing import uuid -import pydantic from dateutil import parser +import pydantic + -def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> typing.Any: +def cast_field( + json_expectation: typing.Any, type_expectation: typing.Any +) -> typing.Any: # Cast these specific types which come through as string and expect our # models to cast to the correct type. if type_expectation == "uuid": @@ -25,7 +28,9 @@ def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> ty return json_expectation -def validate_field(response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any) -> None: +def validate_field( + response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectation == "no_validate": return @@ -44,7 +49,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(entry_expectation, dict): is_container_of_complex_type = True validate_response( - response=response[idx], json_expectation=ex, type_expectations=entry_expectation + response=response[idx], + json_expectation=ex, + type_expectations=entry_expectation, ) else: cast_json_expectation.append(cast_field(ex, entry_expectation)) @@ -56,7 +63,10 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # if any of the values of the set have a type_expectation of a dict, we're assuming it's a pydantic # model and keeping it a list. if container_expectation != "set" or not any( - map(lambda value: isinstance(value, dict), list(contents_expectation.values())) + map( + lambda value: isinstance(value, dict), + list(contents_expectation.values()), + ) ): json_expectation = cast_field(json_expectation, container_expectation) elif isinstance(type_expectation, tuple): @@ -65,9 +75,15 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(contents_expectation, dict): json_expectation = { cast_field( - key, contents_expectation.get(idx)[0] if contents_expectation.get(idx) is not None else None # type: ignore + key, + contents_expectation.get(idx)[0] + if contents_expectation.get(idx) is not None + else None, # type: ignore ): cast_field( - value, contents_expectation.get(idx)[1] if contents_expectation.get(idx) is not None else None # type: ignore + value, + contents_expectation.get(idx)[1] + if contents_expectation.get(idx) is not None + else None, # type: ignore ) for idx, (key, value) in enumerate(json_expectation.items()) } @@ -86,7 +102,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # Arg type_expectations is a deeply nested structure that matches the response, but with the values replaced with the expected types -def validate_response(response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any) -> None: +def validate_response( + response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectations == "no_validate": return @@ -96,11 +114,17 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e and not isinstance(response, dict) and not issubclass(type(response), pydantic.BaseModel) ): - validate_field(response=response, json_expectation=json_expectation, type_expectation=type_expectations) + validate_field( + response=response, + json_expectation=json_expectation, + type_expectation=type_expectations, + ) return if isinstance(response, list): - assert len(response) == len(json_expectation), "Length mismatch, expected: {0}, Actual: {1}".format( + assert len(response) == len( + json_expectation + ), "Length mismatch, expected: {0}, Actual: {1}".format( len(response), len(json_expectation) ) content_expectation = type_expectations @@ -108,7 +132,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e content_expectation = type_expectations[1] for idx, item in enumerate(response): validate_response( - response=item, json_expectation=json_expectation[idx], type_expectations=content_expectation[idx] + response=item, + json_expectation=json_expectation[idx], + type_expectations=content_expectation[idx], ) else: response_json = response @@ -116,7 +142,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e response_json = response.dict(by_alias=True) for key, value in json_expectation.items(): - assert key in response_json, "Field {0} not found within the response object: {1}".format( + assert ( + key in response_json + ), "Field {0} not found within the response object: {1}".format( key, response_json ) @@ -128,11 +156,19 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e # Otherwise, we're just validating a single field that's a pydantic model. if isinstance(value, dict) and not isinstance(type_expectation, tuple): validate_response( - response=response_json[key], json_expectation=value, type_expectations=type_expectation + response=response_json[key], + json_expectation=value, + type_expectations=type_expectation, ) else: - validate_field(response=response_json[key], json_expectation=value, type_expectation=type_expectation) + validate_field( + response=response_json[key], + json_expectation=value, + type_expectation=type_expectation, + ) # Ensure there are no additional fields here either del response_json[key] - assert len(response_json) == 0, "Additional fields found, expected None: {0}".format(response_json) + assert ( + len(response_json) == 0 + ), "Additional fields found, expected None: {0}".format(response_json) diff --git a/seed/python-sdk/auth-environment-variables/tests/utils/assets/models/__init__.py b/seed/python-sdk/auth-environment-variables/tests/utils/assets/models/__init__.py index 2cf01263529..3a1c852e71e 100644 --- a/seed/python-sdk/auth-environment-variables/tests/utils/assets/models/__init__.py +++ b/seed/python-sdk/auth-environment-variables/tests/utils/assets/models/__init__.py @@ -5,7 +5,7 @@ from .circle import CircleParams from .object_with_defaults import ObjectWithDefaultsParams from .object_with_optional_field import ObjectWithOptionalFieldParams -from .shape import Shape_CircleParams, Shape_SquareParams, ShapeParams +from .shape import ShapeParams, Shape_CircleParams, Shape_SquareParams from .square import SquareParams from .undiscriminated_shape import UndiscriminatedShapeParams diff --git a/seed/python-sdk/auth-environment-variables/tests/utils/assets/models/circle.py b/seed/python-sdk/auth-environment-variables/tests/utils/assets/models/circle.py index af7a1bf8a8e..253f12d38b3 100644 --- a/seed/python-sdk/auth-environment-variables/tests/utils/assets/models/circle.py +++ b/seed/python-sdk/auth-environment-variables/tests/utils/assets/models/circle.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class CircleParams(typing_extensions.TypedDict): - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] diff --git a/seed/python-sdk/auth-environment-variables/tests/utils/assets/models/object_with_optional_field.py b/seed/python-sdk/auth-environment-variables/tests/utils/assets/models/object_with_optional_field.py index 3ad93d5f305..ebe7dc80547 100644 --- a/seed/python-sdk/auth-environment-variables/tests/utils/assets/models/object_with_optional_field.py +++ b/seed/python-sdk/auth-environment-variables/tests/utils/assets/models/object_with_optional_field.py @@ -7,8 +7,8 @@ import uuid import typing_extensions -from seed.core.serialization import FieldMetadata +from seed.core.serialization import FieldMetadata from .color import Color from .shape import ShapeParams from .undiscriminated_shape import UndiscriminatedShapeParams @@ -18,16 +18,30 @@ class ObjectWithOptionalFieldParams(typing_extensions.TypedDict): literal: typing.Literal["lit_one"] string: typing_extensions.NotRequired[str] integer: typing_extensions.NotRequired[int] - long_: typing_extensions.NotRequired[typing_extensions.Annotated[int, FieldMetadata(alias="long")]] + long_: typing_extensions.NotRequired[ + typing_extensions.Annotated[int, FieldMetadata(alias="long")] + ] double: typing_extensions.NotRequired[float] - bool_: typing_extensions.NotRequired[typing_extensions.Annotated[bool, FieldMetadata(alias="bool")]] + bool_: typing_extensions.NotRequired[ + typing_extensions.Annotated[bool, FieldMetadata(alias="bool")] + ] datetime: typing_extensions.NotRequired[dt.datetime] date: typing_extensions.NotRequired[dt.date] - uuid_: typing_extensions.NotRequired[typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")]] - base_64: typing_extensions.NotRequired[typing_extensions.Annotated[str, FieldMetadata(alias="base64")]] - list_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")]] - set_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")]] - map_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")]] + uuid_: typing_extensions.NotRequired[ + typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")] + ] + base_64: typing_extensions.NotRequired[ + typing_extensions.Annotated[str, FieldMetadata(alias="base64")] + ] + list_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")] + ] + set_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")] + ] + map_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")] + ] enum: typing_extensions.NotRequired[Color] union: typing_extensions.NotRequired[ShapeParams] second_union: typing_extensions.NotRequired[ShapeParams] diff --git a/seed/python-sdk/auth-environment-variables/tests/utils/assets/models/shape.py b/seed/python-sdk/auth-environment-variables/tests/utils/assets/models/shape.py index 2c33c877951..816ffc51bdc 100644 --- a/seed/python-sdk/auth-environment-variables/tests/utils/assets/models/shape.py +++ b/seed/python-sdk/auth-environment-variables/tests/utils/assets/models/shape.py @@ -7,6 +7,7 @@ import typing import typing_extensions + from seed.core.serialization import FieldMetadata @@ -15,13 +16,21 @@ class Base(typing_extensions.TypedDict): class Shape_CircleParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["circle"], FieldMetadata(alias="shapeType")] - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["circle"], FieldMetadata(alias="shapeType") + ] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] class Shape_SquareParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["square"], FieldMetadata(alias="shapeType")] - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["square"], FieldMetadata(alias="shapeType") + ] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] ShapeParams = typing.Union[Shape_CircleParams, Shape_SquareParams] diff --git a/seed/python-sdk/auth-environment-variables/tests/utils/assets/models/square.py b/seed/python-sdk/auth-environment-variables/tests/utils/assets/models/square.py index b9b7dd319bc..bcf08a723c5 100644 --- a/seed/python-sdk/auth-environment-variables/tests/utils/assets/models/square.py +++ b/seed/python-sdk/auth-environment-variables/tests/utils/assets/models/square.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class SquareParams(typing_extensions.TypedDict): - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] diff --git a/seed/python-sdk/auth-environment-variables/tests/utils/test_http_client.py b/seed/python-sdk/auth-environment-variables/tests/utils/test_http_client.py index edd11ca7afb..f5a874a75f3 100644 --- a/seed/python-sdk/auth-environment-variables/tests/utils/test_http_client.py +++ b/seed/python-sdk/auth-environment-variables/tests/utils/test_http_client.py @@ -9,12 +9,17 @@ def get_request_options() -> RequestOptions: def test_get_json_request_body() -> None: - json_body, data_body = get_request_body(json={"hello": "world"}, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json={"hello": "world"}, data=None, request_options=None, omit=None + ) assert json_body == {"hello": "world"} assert data_body is None json_body_extras, data_body_extras = get_request_body( - json={"goodbye": "world"}, data=None, request_options=get_request_options(), omit=None + json={"goodbye": "world"}, + data=None, + request_options=get_request_options(), + omit=None, ) assert json_body_extras == {"goodbye": "world", "see you": "later"} @@ -22,12 +27,17 @@ def test_get_json_request_body() -> None: def test_get_files_request_body() -> None: - json_body, data_body = get_request_body(json=None, data={"hello": "world"}, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data={"hello": "world"}, request_options=None, omit=None + ) assert data_body == {"hello": "world"} assert json_body is None json_body_extras, data_body_extras = get_request_body( - json=None, data={"goodbye": "world"}, request_options=get_request_options(), omit=None + json=None, + data={"goodbye": "world"}, + request_options=get_request_options(), + omit=None, ) assert data_body_extras == {"goodbye": "world", "see you": "later"} @@ -35,7 +45,9 @@ def test_get_files_request_body() -> None: def test_get_none_request_body() -> None: - json_body, data_body = get_request_body(json=None, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data=None, request_options=None, omit=None + ) assert data_body is None assert json_body is None diff --git a/seed/python-sdk/auth-environment-variables/tests/utils/test_query_encoding.py b/seed/python-sdk/auth-environment-variables/tests/utils/test_query_encoding.py index 247e1551b46..fbc8f402167 100644 --- a/seed/python-sdk/auth-environment-variables/tests/utils/test_query_encoding.py +++ b/seed/python-sdk/auth-environment-variables/tests/utils/test_query_encoding.py @@ -4,9 +4,15 @@ def test_query_encoding() -> None: - assert encode_query({"hello world": "hello world"}) == {"hello world": "hello world"} - assert encode_query({"hello_world": {"hello": "world"}}) == {"hello_world[hello]": "world"} - assert encode_query({"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"}) == { + assert encode_query({"hello world": "hello world"}) == { + "hello world": "hello world" + } + assert encode_query({"hello_world": {"hello": "world"}}) == { + "hello_world[hello]": "world" + } + assert encode_query( + {"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"} + ) == { "hello_world[hello][world]": "today", "hello_world[test]": "this", "hi": "there", diff --git a/seed/python-sdk/auth-environment-variables/tests/utils/test_serialization.py b/seed/python-sdk/auth-environment-variables/tests/utils/test_serialization.py index 58b1ed66e6d..5ca956916dd 100644 --- a/seed/python-sdk/auth-environment-variables/tests/utils/test_serialization.py +++ b/seed/python-sdk/auth-environment-variables/tests/utils/test_serialization.py @@ -1,10 +1,12 @@ # This file was auto-generated by Fern from our API Definition. -from typing import Any, List +from typing import List, Any -from seed.core.serialization import convert_and_respect_annotation_metadata +from seed.core.serialization import ( + convert_and_respect_annotation_metadata, +) +from .assets.models import ShapeParams, ObjectWithOptionalFieldParams -from .assets.models import ObjectWithOptionalFieldParams, ShapeParams UNION_TEST: ShapeParams = {"radius_measurement": 1.0, "shape_type": "circle", "id": "1"} UNION_TEST_CONVERTED = {"shapeType": "circle", "radiusMeasurement": 1.0, "id": "1"} @@ -18,20 +20,54 @@ def test_convert_and_respect_annotation_metadata() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) - assert converted == {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"} + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) + assert converted == { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + } def test_convert_and_respect_annotation_metadata_in_list() -> None: data: List[ObjectWithOptionalFieldParams] = [ - {"string": "string", "long_": 12345, "bool_": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long_": 67890, "list_": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long_": 12345, + "bool_": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long_": 67890, + "list_": [], + "literal": "lit_one", + "any": "any", + }, ] - converted = convert_and_respect_annotation_metadata(object_=data, annotation=List[ObjectWithOptionalFieldParams]) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=List[ObjectWithOptionalFieldParams] + ) assert converted == [ - {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long": 67890, "list": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long": 67890, + "list": [], + "literal": "lit_one", + "any": "any", + }, ] @@ -43,7 +79,9 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) assert converted == { "string": "string", @@ -55,12 +93,16 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: def test_convert_and_respect_annotation_metadata_in_union() -> None: - converted = convert_and_respect_annotation_metadata(object_=UNION_TEST, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=UNION_TEST, annotation=ShapeParams + ) assert converted == UNION_TEST_CONVERTED def test_convert_and_respect_annotation_metadata_with_empty_object() -> None: data: Any = {} - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ShapeParams + ) assert converted == data diff --git a/seed/python-sdk/basic-auth-environment-variables/pyproject.toml b/seed/python-sdk/basic-auth-environment-variables/pyproject.toml index e728d89b3cc..c1b0c19e5aa 100644 --- a/seed/python-sdk/basic-auth-environment-variables/pyproject.toml +++ b/seed/python-sdk/basic-auth-environment-variables/pyproject.toml @@ -43,6 +43,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/python-sdk/basic-auth-environment-variables/src/seed/__init__.py b/seed/python-sdk/basic-auth-environment-variables/src/seed/__init__.py index b2b6199dcdd..22bcd789782 100644 --- a/seed/python-sdk/basic-auth-environment-variables/src/seed/__init__.py +++ b/seed/python-sdk/basic-auth-environment-variables/src/seed/__init__.py @@ -2,7 +2,10 @@ from .errors import BadRequest, UnauthorizedRequest, UnauthorizedRequestErrorBody from . import basic_auth, errors -from .client import AsyncSeedBasicAuthEnvironmentVariables, SeedBasicAuthEnvironmentVariables +from .client import ( + AsyncSeedBasicAuthEnvironmentVariables, + SeedBasicAuthEnvironmentVariables, +) from .version import __version__ __all__ = [ diff --git a/seed/python-sdk/basic-auth-environment-variables/src/seed/basic_auth/client.py b/seed/python-sdk/basic-auth-environment-variables/src/seed/basic_auth/client.py index a30f034ec4f..a8a175690fb 100644 --- a/seed/python-sdk/basic-auth-environment-variables/src/seed/basic_auth/client.py +++ b/seed/python-sdk/basic-auth-environment-variables/src/seed/basic_auth/client.py @@ -1,15 +1,15 @@ # This file was auto-generated by Fern from our API Definition. import typing -from json.decoder import JSONDecodeError - -from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.pydantic_utilities import parse_obj_as +from ..core.client_wrapper import SyncClientWrapper from ..core.request_options import RequestOptions -from ..errors.errors.bad_request import BadRequest +from ..core.pydantic_utilities import parse_obj_as from ..errors.errors.unauthorized_request import UnauthorizedRequest from ..errors.types.unauthorized_request_error_body import UnauthorizedRequestErrorBody +from json.decoder import JSONDecodeError +from ..core.api_error import ApiError +from ..errors.errors.bad_request import BadRequest +from ..core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -19,7 +19,9 @@ class BasicAuthClient: def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper - def get_with_basic_auth(self, *, request_options: typing.Optional[RequestOptions] = None) -> bool: + def get_with_basic_auth( + self, *, request_options: typing.Optional[RequestOptions] = None + ) -> bool: """ GET request with basic auth scheme @@ -44,14 +46,23 @@ def get_with_basic_auth(self, *, request_options: typing.Optional[RequestOptions client.basic_auth.get_with_basic_auth() """ _response = self._client_wrapper.httpx_client.request( - "basic-auth", method="GET", request_options=request_options + "basic-auth", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore if _response.status_code == 401: raise UnauthorizedRequest( - typing.cast(UnauthorizedRequestErrorBody, parse_obj_as(type_=UnauthorizedRequestErrorBody, object_=_response.json())) # type: ignore + typing.cast( + UnauthorizedRequestErrorBody, + parse_obj_as( + type_=UnauthorizedRequestErrorBody, object_=_response.json() + ), + ) # type: ignore ) _response_json = _response.json() except JSONDecodeError: @@ -59,7 +70,10 @@ def get_with_basic_auth(self, *, request_options: typing.Optional[RequestOptions raise ApiError(status_code=_response.status_code, body=_response_json) def post_with_basic_auth( - self, *, request: typing.Any, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Any, + request_options: typing.Optional[RequestOptions] = None, ) -> bool: """ POST request with basic auth scheme @@ -89,14 +103,25 @@ def post_with_basic_auth( ) """ _response = self._client_wrapper.httpx_client.request( - "basic-auth", method="POST", json=request, request_options=request_options, omit=OMIT + "basic-auth", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore if _response.status_code == 401: raise UnauthorizedRequest( - typing.cast(UnauthorizedRequestErrorBody, parse_obj_as(type_=UnauthorizedRequestErrorBody, object_=_response.json())) # type: ignore + typing.cast( + UnauthorizedRequestErrorBody, + parse_obj_as( + type_=UnauthorizedRequestErrorBody, object_=_response.json() + ), + ) # type: ignore ) if _response.status_code == 400: raise BadRequest() @@ -110,7 +135,9 @@ class AsyncBasicAuthClient: def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper - async def get_with_basic_auth(self, *, request_options: typing.Optional[RequestOptions] = None) -> bool: + async def get_with_basic_auth( + self, *, request_options: typing.Optional[RequestOptions] = None + ) -> bool: """ GET request with basic auth scheme @@ -143,14 +170,23 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "basic-auth", method="GET", request_options=request_options + "basic-auth", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore if _response.status_code == 401: raise UnauthorizedRequest( - typing.cast(UnauthorizedRequestErrorBody, parse_obj_as(type_=UnauthorizedRequestErrorBody, object_=_response.json())) # type: ignore + typing.cast( + UnauthorizedRequestErrorBody, + parse_obj_as( + type_=UnauthorizedRequestErrorBody, object_=_response.json() + ), + ) # type: ignore ) _response_json = _response.json() except JSONDecodeError: @@ -158,7 +194,10 @@ async def main() -> None: raise ApiError(status_code=_response.status_code, body=_response_json) async def post_with_basic_auth( - self, *, request: typing.Any, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Any, + request_options: typing.Optional[RequestOptions] = None, ) -> bool: """ POST request with basic auth scheme @@ -196,14 +235,25 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "basic-auth", method="POST", json=request, request_options=request_options, omit=OMIT + "basic-auth", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore if _response.status_code == 401: raise UnauthorizedRequest( - typing.cast(UnauthorizedRequestErrorBody, parse_obj_as(type_=UnauthorizedRequestErrorBody, object_=_response.json())) # type: ignore + typing.cast( + UnauthorizedRequestErrorBody, + parse_obj_as( + type_=UnauthorizedRequestErrorBody, object_=_response.json() + ), + ) # type: ignore ) if _response.status_code == 400: raise BadRequest() diff --git a/seed/python-sdk/basic-auth-environment-variables/src/seed/client.py b/seed/python-sdk/basic-auth-environment-variables/src/seed/client.py index 26884b8b01f..8a1a33933b0 100644 --- a/seed/python-sdk/basic-auth-environment-variables/src/seed/client.py +++ b/seed/python-sdk/basic-auth-environment-variables/src/seed/client.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. -import os import typing - +import os import httpx - -from .basic_auth.client import AsyncBasicAuthClient, BasicAuthClient from .core.api_error import ApiError -from .core.client_wrapper import AsyncClientWrapper, SyncClientWrapper +from .core.client_wrapper import SyncClientWrapper +from .basic_auth.client import BasicAuthClient +from .core.client_wrapper import AsyncClientWrapper +from .basic_auth.client import AsyncBasicAuthClient class SeedBasicAuthEnvironmentVariables: @@ -45,24 +45,36 @@ def __init__( self, *, base_url: str, - username: typing.Optional[typing.Union[str, typing.Callable[[], str]]] = os.getenv("USERNAME"), - password: typing.Optional[typing.Union[str, typing.Callable[[], str]]] = os.getenv("PASSWORD"), + username: typing.Optional[ + typing.Union[str, typing.Callable[[], str]] + ] = os.getenv("USERNAME"), + password: typing.Optional[ + typing.Union[str, typing.Callable[[], str]] + ] = os.getenv("PASSWORD"), timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.Client] = None + httpx_client: typing.Optional[httpx.Client] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) if username is None: - raise ApiError(body="The client must be instantiated be either passing in username or setting USERNAME") + raise ApiError( + body="The client must be instantiated be either passing in username or setting USERNAME" + ) if password is None: - raise ApiError(body="The client must be instantiated be either passing in password or setting PASSWORD") + raise ApiError( + body="The client must be instantiated be either passing in password or setting PASSWORD" + ) self._client_wrapper = SyncClientWrapper( base_url=base_url, username=username, password=password, httpx_client=httpx_client if httpx_client is not None - else httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.Client( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.Client(timeout=_defaulted_timeout), timeout=_defaulted_timeout, @@ -105,24 +117,36 @@ def __init__( self, *, base_url: str, - username: typing.Optional[typing.Union[str, typing.Callable[[], str]]] = os.getenv("USERNAME"), - password: typing.Optional[typing.Union[str, typing.Callable[[], str]]] = os.getenv("PASSWORD"), + username: typing.Optional[ + typing.Union[str, typing.Callable[[], str]] + ] = os.getenv("USERNAME"), + password: typing.Optional[ + typing.Union[str, typing.Callable[[], str]] + ] = os.getenv("PASSWORD"), timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.AsyncClient] = None + httpx_client: typing.Optional[httpx.AsyncClient] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) if username is None: - raise ApiError(body="The client must be instantiated be either passing in username or setting USERNAME") + raise ApiError( + body="The client must be instantiated be either passing in username or setting USERNAME" + ) if password is None: - raise ApiError(body="The client must be instantiated be either passing in password or setting PASSWORD") + raise ApiError( + body="The client must be instantiated be either passing in password or setting PASSWORD" + ) self._client_wrapper = AsyncClientWrapper( base_url=base_url, username=username, password=password, httpx_client=httpx_client if httpx_client is not None - else httpx.AsyncClient(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.AsyncClient( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.AsyncClient(timeout=_defaulted_timeout), timeout=_defaulted_timeout, diff --git a/seed/python-sdk/basic-auth-environment-variables/src/seed/core/api_error.py b/seed/python-sdk/basic-auth-environment-variables/src/seed/core/api_error.py index 2e9fc5431cd..da734b58068 100644 --- a/seed/python-sdk/basic-auth-environment-variables/src/seed/core/api_error.py +++ b/seed/python-sdk/basic-auth-environment-variables/src/seed/core/api_error.py @@ -7,7 +7,9 @@ class ApiError(Exception): status_code: typing.Optional[int] body: typing.Any - def __init__(self, *, status_code: typing.Optional[int] = None, body: typing.Any = None): + def __init__( + self, *, status_code: typing.Optional[int] = None, body: typing.Any = None + ): self.status_code = status_code self.body = body diff --git a/seed/python-sdk/basic-auth-environment-variables/src/seed/core/client_wrapper.py b/seed/python-sdk/basic-auth-environment-variables/src/seed/core/client_wrapper.py index b130e981786..dadbb18ce98 100644 --- a/seed/python-sdk/basic-auth-environment-variables/src/seed/core/client_wrapper.py +++ b/seed/python-sdk/basic-auth-environment-variables/src/seed/core/client_wrapper.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .http_client import AsyncHttpClient, HttpClient +from .http_client import HttpClient +from .http_client import AsyncHttpClient class BaseClientWrapper: @@ -14,7 +13,7 @@ def __init__( username: typing.Union[str, typing.Callable[[], str]], password: typing.Union[str, typing.Callable[[], str]], base_url: str, - timeout: typing.Optional[float] = None + timeout: typing.Optional[float] = None, ): self._username = username self._password = password @@ -27,7 +26,9 @@ def get_headers(self) -> typing.Dict[str, str]: "X-Fern-SDK-Name": "fern_basic-auth-environment-variables", "X-Fern-SDK-Version": "0.0.1", } - headers["Authorization"] = httpx.BasicAuth(self._get_username(), self._get_password())._auth_header + headers["Authorization"] = httpx.BasicAuth( + self._get_username(), self._get_password() + )._auth_header return headers def _get_username(self) -> str: @@ -57,9 +58,11 @@ def __init__( password: typing.Union[str, typing.Callable[[], str]], base_url: str, timeout: typing.Optional[float] = None, - httpx_client: httpx.Client + httpx_client: httpx.Client, ): - super().__init__(username=username, password=password, base_url=base_url, timeout=timeout) + super().__init__( + username=username, password=password, base_url=base_url, timeout=timeout + ) self.httpx_client = HttpClient( httpx_client=httpx_client, base_headers=self.get_headers(), @@ -76,9 +79,11 @@ def __init__( password: typing.Union[str, typing.Callable[[], str]], base_url: str, timeout: typing.Optional[float] = None, - httpx_client: httpx.AsyncClient + httpx_client: httpx.AsyncClient, ): - super().__init__(username=username, password=password, base_url=base_url, timeout=timeout) + super().__init__( + username=username, password=password, base_url=base_url, timeout=timeout + ) self.httpx_client = AsyncHttpClient( httpx_client=httpx_client, base_headers=self.get_headers(), diff --git a/seed/python-sdk/basic-auth-environment-variables/src/seed/core/datetime_utils.py b/seed/python-sdk/basic-auth-environment-variables/src/seed/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/python-sdk/basic-auth-environment-variables/src/seed/core/datetime_utils.py +++ b/seed/python-sdk/basic-auth-environment-variables/src/seed/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/python-sdk/basic-auth-environment-variables/src/seed/core/file.py b/seed/python-sdk/basic-auth-environment-variables/src/seed/core/file.py index cb0d40bbbf3..6e0f92bfcb1 100644 --- a/seed/python-sdk/basic-auth-environment-variables/src/seed/core/file.py +++ b/seed/python-sdk/basic-auth-environment-variables/src/seed/core/file.py @@ -13,12 +13,17 @@ # (filename, file (or bytes), content_type) typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str]], # (filename, file (or bytes), content_type, headers) - typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str], typing.Mapping[str, str]], + typing.Tuple[ + typing.Optional[str], + FileContent, + typing.Optional[str], + typing.Mapping[str, str], + ], ] def convert_file_dict_to_httpx_tuples( - d: typing.Dict[str, typing.Union[File, typing.List[File]]] + d: typing.Dict[str, typing.Union[File, typing.List[File]]], ) -> typing.List[typing.Tuple[str, File]]: """ The format we use is a list of tuples, where the first element is the diff --git a/seed/python-sdk/basic-auth-environment-variables/src/seed/core/http_client.py b/seed/python-sdk/basic-auth-environment-variables/src/seed/core/http_client.py index 9333d8a7f15..091f71bc185 100644 --- a/seed/python-sdk/basic-auth-environment-variables/src/seed/core/http_client.py +++ b/seed/python-sdk/basic-auth-environment-variables/src/seed/core/http_client.py @@ -77,7 +77,9 @@ def _retry_timeout(response: httpx.Response, retries: int) -> float: return retry_after # Apply exponential backoff, capped at MAX_RETRY_DELAY_SECONDS. - retry_delay = min(INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS) + retry_delay = min( + INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS + ) # Add a randomness / jitter to the retry delay to avoid overwhelming the server with retries. timeout = retry_delay * (1 - 0.25 * random()) @@ -90,7 +92,8 @@ def _should_retry(response: httpx.Response) -> bool: def remove_omit_from_dict( - original: typing.Dict[str, typing.Optional[typing.Any]], omit: typing.Optional[typing.Any] + original: typing.Dict[str, typing.Optional[typing.Any]], + omit: typing.Optional[typing.Any], ) -> typing.Dict[str, typing.Any]: if omit is None: return original @@ -108,7 +111,8 @@ def maybe_filter_request_body( ) -> typing.Optional[typing.Any]: if data is None: return ( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else None ) @@ -118,7 +122,8 @@ def maybe_filter_request_body( data_content = { **(jsonable_encoder(remove_omit_from_dict(data, omit))), # type: ignore **( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else {} ), @@ -162,7 +167,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url def request( @@ -174,8 +181,12 @@ def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -184,11 +195,14 @@ def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) response = self.httpx_client.request( method=method, @@ -198,7 +212,11 @@ def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -209,7 +227,10 @@ def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -222,11 +243,15 @@ def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: time.sleep(_retry_timeout(response=response, retries=retries)) @@ -256,8 +281,12 @@ def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -266,11 +295,14 @@ def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) with self.httpx_client.stream( method=method, @@ -280,7 +312,11 @@ def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -291,7 +327,9 @@ def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -304,7 +342,9 @@ def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream @@ -327,7 +367,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url async def request( @@ -339,8 +381,12 @@ async def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -349,11 +395,14 @@ async def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) # Add the input to each of these and do None-safety checks response = await self.httpx_client.request( @@ -364,7 +413,11 @@ async def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -375,7 +428,10 @@ async def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -388,11 +444,15 @@ async def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: await asyncio.sleep(_retry_timeout(response=response, retries=retries)) @@ -421,8 +481,12 @@ async def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -431,11 +495,14 @@ async def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) async with self.httpx_client.stream( method=method, @@ -445,7 +512,11 @@ async def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -456,7 +527,9 @@ async def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -469,7 +542,9 @@ async def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream diff --git a/seed/python-sdk/basic-auth-environment-variables/src/seed/core/jsonable_encoder.py b/seed/python-sdk/basic-auth-environment-variables/src/seed/core/jsonable_encoder.py index d3fd328fd41..12a8b52fc22 100644 --- a/seed/python-sdk/basic-auth-environment-variables/src/seed/core/jsonable_encoder.py +++ b/seed/python-sdk/basic-auth-environment-variables/src/seed/core/jsonable_encoder.py @@ -19,13 +19,19 @@ import pydantic from .datetime_utils import serialize_datetime -from .pydantic_utilities import IS_PYDANTIC_V2, encode_by_type, to_jsonable_with_fallback +from .pydantic_utilities import ( + IS_PYDANTIC_V2, + encode_by_type, + to_jsonable_with_fallback, +) SetIntStr = Set[Union[int, str]] DictIntStrAny = Dict[Union[int, str], Any] -def jsonable_encoder(obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None) -> Any: +def jsonable_encoder( + obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None +) -> Any: custom_encoder = custom_encoder or {} if custom_encoder: if type(obj) in custom_encoder: diff --git a/seed/python-sdk/basic-auth-environment-variables/src/seed/core/pydantic_utilities.py b/seed/python-sdk/basic-auth-environment-variables/src/seed/core/pydantic_utilities.py index 170a563d6eb..c63935c32a2 100644 --- a/seed/python-sdk/basic-auth-environment-variables/src/seed/core/pydantic_utilities.py +++ b/seed/python-sdk/basic-auth-environment-variables/src/seed/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) # type: ignore # Pydantic v1 diff --git a/seed/python-sdk/basic-auth-environment-variables/src/seed/core/query_encoder.py b/seed/python-sdk/basic-auth-environment-variables/src/seed/core/query_encoder.py index 24076d72ee9..7cb98f52cd7 100644 --- a/seed/python-sdk/basic-auth-environment-variables/src/seed/core/query_encoder.py +++ b/seed/python-sdk/basic-auth-environment-variables/src/seed/core/query_encoder.py @@ -7,7 +7,9 @@ # Flattens dicts to be of the form {"key[subkey][subkey2]": value} where value is not a dict -def traverse_query_dict(dict_flat: Dict[str, Any], key_prefix: Optional[str] = None) -> Dict[str, Any]: +def traverse_query_dict( + dict_flat: Dict[str, Any], key_prefix: Optional[str] = None +) -> Dict[str, Any]: result = {} for k, v in dict_flat.items(): key = f"{key_prefix}[{k}]" if key_prefix is not None else k @@ -30,4 +32,8 @@ def single_query_encoder(query_key: str, query_value: Any) -> Dict[str, Any]: def encode_query(query: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: - return dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) if query is not None else None + return ( + dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) + if query is not None + else None + ) diff --git a/seed/python-sdk/basic-auth-environment-variables/src/seed/core/serialization.py b/seed/python-sdk/basic-auth-environment-variables/src/seed/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/python-sdk/basic-auth-environment-variables/src/seed/core/serialization.py +++ b/seed/python-sdk/basic-auth-environment-variables/src/seed/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/python-sdk/basic-auth-environment-variables/src/seed/errors/types/unauthorized_request_error_body.py b/seed/python-sdk/basic-auth-environment-variables/src/seed/errors/types/unauthorized_request_error_body.py index 2a84d1263c6..4e83edd5002 100644 --- a/seed/python-sdk/basic-auth-environment-variables/src/seed/errors/types/unauthorized_request_error_body.py +++ b/seed/python-sdk/basic-auth-environment-variables/src/seed/errors/types/unauthorized_request_error_body.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class UnauthorizedRequestErrorBody(UniversalBaseModel): message: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/basic-auth-environment-variables/src/seed/version.py b/seed/python-sdk/basic-auth-environment-variables/src/seed/version.py index 2c3a7e6074d..c06e0d7d48c 100644 --- a/seed/python-sdk/basic-auth-environment-variables/src/seed/version.py +++ b/seed/python-sdk/basic-auth-environment-variables/src/seed/version.py @@ -1,4 +1,3 @@ - from importlib import metadata __version__ = metadata.version("fern_basic-auth-environment-variables") diff --git a/seed/python-sdk/basic-auth-environment-variables/tests/conftest.py b/seed/python-sdk/basic-auth-environment-variables/tests/conftest.py index 70e8b829c35..21d22c38055 100644 --- a/seed/python-sdk/basic-auth-environment-variables/tests/conftest.py +++ b/seed/python-sdk/basic-auth-environment-variables/tests/conftest.py @@ -1,9 +1,9 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedBasicAuthEnvironmentVariables import os - import pytest -from seed import AsyncSeedBasicAuthEnvironmentVariables, SeedBasicAuthEnvironmentVariables +from seed import AsyncSeedBasicAuthEnvironmentVariables @pytest.fixture diff --git a/seed/python-sdk/basic-auth-environment-variables/tests/custom/test_client.py b/seed/python-sdk/basic-auth-environment-variables/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/python-sdk/basic-auth-environment-variables/tests/custom/test_client.py +++ b/seed/python-sdk/basic-auth-environment-variables/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/python-sdk/basic-auth-environment-variables/tests/test_basic_auth.py b/seed/python-sdk/basic-auth-environment-variables/tests/test_basic_auth.py index 7626f48178c..cdd1221ab13 100644 --- a/seed/python-sdk/basic-auth-environment-variables/tests/test_basic_auth.py +++ b/seed/python-sdk/basic-auth-environment-variables/tests/test_basic_auth.py @@ -1,14 +1,14 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedBasicAuthEnvironmentVariables +from seed import AsyncSeedBasicAuthEnvironmentVariables import typing - -from seed import AsyncSeedBasicAuthEnvironmentVariables, SeedBasicAuthEnvironmentVariables - from .utilities import validate_response async def test_get_with_basic_auth( - client: SeedBasicAuthEnvironmentVariables, async_client: AsyncSeedBasicAuthEnvironmentVariables + client: SeedBasicAuthEnvironmentVariables, + async_client: AsyncSeedBasicAuthEnvironmentVariables, ) -> None: expected_response: typing.Any = True expected_types: typing.Any = None @@ -20,12 +20,15 @@ async def test_get_with_basic_auth( async def test_post_with_basic_auth( - client: SeedBasicAuthEnvironmentVariables, async_client: AsyncSeedBasicAuthEnvironmentVariables + client: SeedBasicAuthEnvironmentVariables, + async_client: AsyncSeedBasicAuthEnvironmentVariables, ) -> None: expected_response: typing.Any = True expected_types: typing.Any = None response = client.basic_auth.post_with_basic_auth(request={"key": "value"}) validate_response(response, expected_response, expected_types) - async_response = await async_client.basic_auth.post_with_basic_auth(request={"key": "value"}) + async_response = await async_client.basic_auth.post_with_basic_auth( + request={"key": "value"} + ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/basic-auth-environment-variables/tests/utilities.py b/seed/python-sdk/basic-auth-environment-variables/tests/utilities.py index 13da208eb3a..e8f4472564c 100644 --- a/seed/python-sdk/basic-auth-environment-variables/tests/utilities.py +++ b/seed/python-sdk/basic-auth-environment-variables/tests/utilities.py @@ -3,11 +3,14 @@ import typing import uuid -import pydantic from dateutil import parser +import pydantic + -def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> typing.Any: +def cast_field( + json_expectation: typing.Any, type_expectation: typing.Any +) -> typing.Any: # Cast these specific types which come through as string and expect our # models to cast to the correct type. if type_expectation == "uuid": @@ -25,7 +28,9 @@ def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> ty return json_expectation -def validate_field(response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any) -> None: +def validate_field( + response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectation == "no_validate": return @@ -44,7 +49,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(entry_expectation, dict): is_container_of_complex_type = True validate_response( - response=response[idx], json_expectation=ex, type_expectations=entry_expectation + response=response[idx], + json_expectation=ex, + type_expectations=entry_expectation, ) else: cast_json_expectation.append(cast_field(ex, entry_expectation)) @@ -56,7 +63,10 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # if any of the values of the set have a type_expectation of a dict, we're assuming it's a pydantic # model and keeping it a list. if container_expectation != "set" or not any( - map(lambda value: isinstance(value, dict), list(contents_expectation.values())) + map( + lambda value: isinstance(value, dict), + list(contents_expectation.values()), + ) ): json_expectation = cast_field(json_expectation, container_expectation) elif isinstance(type_expectation, tuple): @@ -65,9 +75,15 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(contents_expectation, dict): json_expectation = { cast_field( - key, contents_expectation.get(idx)[0] if contents_expectation.get(idx) is not None else None # type: ignore + key, + contents_expectation.get(idx)[0] + if contents_expectation.get(idx) is not None + else None, # type: ignore ): cast_field( - value, contents_expectation.get(idx)[1] if contents_expectation.get(idx) is not None else None # type: ignore + value, + contents_expectation.get(idx)[1] + if contents_expectation.get(idx) is not None + else None, # type: ignore ) for idx, (key, value) in enumerate(json_expectation.items()) } @@ -86,7 +102,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # Arg type_expectations is a deeply nested structure that matches the response, but with the values replaced with the expected types -def validate_response(response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any) -> None: +def validate_response( + response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectations == "no_validate": return @@ -96,11 +114,17 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e and not isinstance(response, dict) and not issubclass(type(response), pydantic.BaseModel) ): - validate_field(response=response, json_expectation=json_expectation, type_expectation=type_expectations) + validate_field( + response=response, + json_expectation=json_expectation, + type_expectation=type_expectations, + ) return if isinstance(response, list): - assert len(response) == len(json_expectation), "Length mismatch, expected: {0}, Actual: {1}".format( + assert len(response) == len( + json_expectation + ), "Length mismatch, expected: {0}, Actual: {1}".format( len(response), len(json_expectation) ) content_expectation = type_expectations @@ -108,7 +132,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e content_expectation = type_expectations[1] for idx, item in enumerate(response): validate_response( - response=item, json_expectation=json_expectation[idx], type_expectations=content_expectation[idx] + response=item, + json_expectation=json_expectation[idx], + type_expectations=content_expectation[idx], ) else: response_json = response @@ -116,7 +142,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e response_json = response.dict(by_alias=True) for key, value in json_expectation.items(): - assert key in response_json, "Field {0} not found within the response object: {1}".format( + assert ( + key in response_json + ), "Field {0} not found within the response object: {1}".format( key, response_json ) @@ -128,11 +156,19 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e # Otherwise, we're just validating a single field that's a pydantic model. if isinstance(value, dict) and not isinstance(type_expectation, tuple): validate_response( - response=response_json[key], json_expectation=value, type_expectations=type_expectation + response=response_json[key], + json_expectation=value, + type_expectations=type_expectation, ) else: - validate_field(response=response_json[key], json_expectation=value, type_expectation=type_expectation) + validate_field( + response=response_json[key], + json_expectation=value, + type_expectation=type_expectation, + ) # Ensure there are no additional fields here either del response_json[key] - assert len(response_json) == 0, "Additional fields found, expected None: {0}".format(response_json) + assert ( + len(response_json) == 0 + ), "Additional fields found, expected None: {0}".format(response_json) diff --git a/seed/python-sdk/basic-auth-environment-variables/tests/utils/assets/models/__init__.py b/seed/python-sdk/basic-auth-environment-variables/tests/utils/assets/models/__init__.py index 2cf01263529..3a1c852e71e 100644 --- a/seed/python-sdk/basic-auth-environment-variables/tests/utils/assets/models/__init__.py +++ b/seed/python-sdk/basic-auth-environment-variables/tests/utils/assets/models/__init__.py @@ -5,7 +5,7 @@ from .circle import CircleParams from .object_with_defaults import ObjectWithDefaultsParams from .object_with_optional_field import ObjectWithOptionalFieldParams -from .shape import Shape_CircleParams, Shape_SquareParams, ShapeParams +from .shape import ShapeParams, Shape_CircleParams, Shape_SquareParams from .square import SquareParams from .undiscriminated_shape import UndiscriminatedShapeParams diff --git a/seed/python-sdk/basic-auth-environment-variables/tests/utils/assets/models/circle.py b/seed/python-sdk/basic-auth-environment-variables/tests/utils/assets/models/circle.py index af7a1bf8a8e..253f12d38b3 100644 --- a/seed/python-sdk/basic-auth-environment-variables/tests/utils/assets/models/circle.py +++ b/seed/python-sdk/basic-auth-environment-variables/tests/utils/assets/models/circle.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class CircleParams(typing_extensions.TypedDict): - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] diff --git a/seed/python-sdk/basic-auth-environment-variables/tests/utils/assets/models/object_with_optional_field.py b/seed/python-sdk/basic-auth-environment-variables/tests/utils/assets/models/object_with_optional_field.py index 3ad93d5f305..ebe7dc80547 100644 --- a/seed/python-sdk/basic-auth-environment-variables/tests/utils/assets/models/object_with_optional_field.py +++ b/seed/python-sdk/basic-auth-environment-variables/tests/utils/assets/models/object_with_optional_field.py @@ -7,8 +7,8 @@ import uuid import typing_extensions -from seed.core.serialization import FieldMetadata +from seed.core.serialization import FieldMetadata from .color import Color from .shape import ShapeParams from .undiscriminated_shape import UndiscriminatedShapeParams @@ -18,16 +18,30 @@ class ObjectWithOptionalFieldParams(typing_extensions.TypedDict): literal: typing.Literal["lit_one"] string: typing_extensions.NotRequired[str] integer: typing_extensions.NotRequired[int] - long_: typing_extensions.NotRequired[typing_extensions.Annotated[int, FieldMetadata(alias="long")]] + long_: typing_extensions.NotRequired[ + typing_extensions.Annotated[int, FieldMetadata(alias="long")] + ] double: typing_extensions.NotRequired[float] - bool_: typing_extensions.NotRequired[typing_extensions.Annotated[bool, FieldMetadata(alias="bool")]] + bool_: typing_extensions.NotRequired[ + typing_extensions.Annotated[bool, FieldMetadata(alias="bool")] + ] datetime: typing_extensions.NotRequired[dt.datetime] date: typing_extensions.NotRequired[dt.date] - uuid_: typing_extensions.NotRequired[typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")]] - base_64: typing_extensions.NotRequired[typing_extensions.Annotated[str, FieldMetadata(alias="base64")]] - list_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")]] - set_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")]] - map_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")]] + uuid_: typing_extensions.NotRequired[ + typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")] + ] + base_64: typing_extensions.NotRequired[ + typing_extensions.Annotated[str, FieldMetadata(alias="base64")] + ] + list_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")] + ] + set_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")] + ] + map_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")] + ] enum: typing_extensions.NotRequired[Color] union: typing_extensions.NotRequired[ShapeParams] second_union: typing_extensions.NotRequired[ShapeParams] diff --git a/seed/python-sdk/basic-auth-environment-variables/tests/utils/assets/models/shape.py b/seed/python-sdk/basic-auth-environment-variables/tests/utils/assets/models/shape.py index 2c33c877951..816ffc51bdc 100644 --- a/seed/python-sdk/basic-auth-environment-variables/tests/utils/assets/models/shape.py +++ b/seed/python-sdk/basic-auth-environment-variables/tests/utils/assets/models/shape.py @@ -7,6 +7,7 @@ import typing import typing_extensions + from seed.core.serialization import FieldMetadata @@ -15,13 +16,21 @@ class Base(typing_extensions.TypedDict): class Shape_CircleParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["circle"], FieldMetadata(alias="shapeType")] - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["circle"], FieldMetadata(alias="shapeType") + ] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] class Shape_SquareParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["square"], FieldMetadata(alias="shapeType")] - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["square"], FieldMetadata(alias="shapeType") + ] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] ShapeParams = typing.Union[Shape_CircleParams, Shape_SquareParams] diff --git a/seed/python-sdk/basic-auth-environment-variables/tests/utils/assets/models/square.py b/seed/python-sdk/basic-auth-environment-variables/tests/utils/assets/models/square.py index b9b7dd319bc..bcf08a723c5 100644 --- a/seed/python-sdk/basic-auth-environment-variables/tests/utils/assets/models/square.py +++ b/seed/python-sdk/basic-auth-environment-variables/tests/utils/assets/models/square.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class SquareParams(typing_extensions.TypedDict): - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] diff --git a/seed/python-sdk/basic-auth-environment-variables/tests/utils/test_http_client.py b/seed/python-sdk/basic-auth-environment-variables/tests/utils/test_http_client.py index edd11ca7afb..f5a874a75f3 100644 --- a/seed/python-sdk/basic-auth-environment-variables/tests/utils/test_http_client.py +++ b/seed/python-sdk/basic-auth-environment-variables/tests/utils/test_http_client.py @@ -9,12 +9,17 @@ def get_request_options() -> RequestOptions: def test_get_json_request_body() -> None: - json_body, data_body = get_request_body(json={"hello": "world"}, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json={"hello": "world"}, data=None, request_options=None, omit=None + ) assert json_body == {"hello": "world"} assert data_body is None json_body_extras, data_body_extras = get_request_body( - json={"goodbye": "world"}, data=None, request_options=get_request_options(), omit=None + json={"goodbye": "world"}, + data=None, + request_options=get_request_options(), + omit=None, ) assert json_body_extras == {"goodbye": "world", "see you": "later"} @@ -22,12 +27,17 @@ def test_get_json_request_body() -> None: def test_get_files_request_body() -> None: - json_body, data_body = get_request_body(json=None, data={"hello": "world"}, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data={"hello": "world"}, request_options=None, omit=None + ) assert data_body == {"hello": "world"} assert json_body is None json_body_extras, data_body_extras = get_request_body( - json=None, data={"goodbye": "world"}, request_options=get_request_options(), omit=None + json=None, + data={"goodbye": "world"}, + request_options=get_request_options(), + omit=None, ) assert data_body_extras == {"goodbye": "world", "see you": "later"} @@ -35,7 +45,9 @@ def test_get_files_request_body() -> None: def test_get_none_request_body() -> None: - json_body, data_body = get_request_body(json=None, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data=None, request_options=None, omit=None + ) assert data_body is None assert json_body is None diff --git a/seed/python-sdk/basic-auth-environment-variables/tests/utils/test_query_encoding.py b/seed/python-sdk/basic-auth-environment-variables/tests/utils/test_query_encoding.py index 247e1551b46..fbc8f402167 100644 --- a/seed/python-sdk/basic-auth-environment-variables/tests/utils/test_query_encoding.py +++ b/seed/python-sdk/basic-auth-environment-variables/tests/utils/test_query_encoding.py @@ -4,9 +4,15 @@ def test_query_encoding() -> None: - assert encode_query({"hello world": "hello world"}) == {"hello world": "hello world"} - assert encode_query({"hello_world": {"hello": "world"}}) == {"hello_world[hello]": "world"} - assert encode_query({"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"}) == { + assert encode_query({"hello world": "hello world"}) == { + "hello world": "hello world" + } + assert encode_query({"hello_world": {"hello": "world"}}) == { + "hello_world[hello]": "world" + } + assert encode_query( + {"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"} + ) == { "hello_world[hello][world]": "today", "hello_world[test]": "this", "hi": "there", diff --git a/seed/python-sdk/basic-auth-environment-variables/tests/utils/test_serialization.py b/seed/python-sdk/basic-auth-environment-variables/tests/utils/test_serialization.py index 58b1ed66e6d..5ca956916dd 100644 --- a/seed/python-sdk/basic-auth-environment-variables/tests/utils/test_serialization.py +++ b/seed/python-sdk/basic-auth-environment-variables/tests/utils/test_serialization.py @@ -1,10 +1,12 @@ # This file was auto-generated by Fern from our API Definition. -from typing import Any, List +from typing import List, Any -from seed.core.serialization import convert_and_respect_annotation_metadata +from seed.core.serialization import ( + convert_and_respect_annotation_metadata, +) +from .assets.models import ShapeParams, ObjectWithOptionalFieldParams -from .assets.models import ObjectWithOptionalFieldParams, ShapeParams UNION_TEST: ShapeParams = {"radius_measurement": 1.0, "shape_type": "circle", "id": "1"} UNION_TEST_CONVERTED = {"shapeType": "circle", "radiusMeasurement": 1.0, "id": "1"} @@ -18,20 +20,54 @@ def test_convert_and_respect_annotation_metadata() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) - assert converted == {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"} + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) + assert converted == { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + } def test_convert_and_respect_annotation_metadata_in_list() -> None: data: List[ObjectWithOptionalFieldParams] = [ - {"string": "string", "long_": 12345, "bool_": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long_": 67890, "list_": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long_": 12345, + "bool_": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long_": 67890, + "list_": [], + "literal": "lit_one", + "any": "any", + }, ] - converted = convert_and_respect_annotation_metadata(object_=data, annotation=List[ObjectWithOptionalFieldParams]) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=List[ObjectWithOptionalFieldParams] + ) assert converted == [ - {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long": 67890, "list": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long": 67890, + "list": [], + "literal": "lit_one", + "any": "any", + }, ] @@ -43,7 +79,9 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) assert converted == { "string": "string", @@ -55,12 +93,16 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: def test_convert_and_respect_annotation_metadata_in_union() -> None: - converted = convert_and_respect_annotation_metadata(object_=UNION_TEST, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=UNION_TEST, annotation=ShapeParams + ) assert converted == UNION_TEST_CONVERTED def test_convert_and_respect_annotation_metadata_with_empty_object() -> None: data: Any = {} - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ShapeParams + ) assert converted == data diff --git a/seed/python-sdk/basic-auth/pyproject.toml b/seed/python-sdk/basic-auth/pyproject.toml index 667496b380b..41913f2e5de 100644 --- a/seed/python-sdk/basic-auth/pyproject.toml +++ b/seed/python-sdk/basic-auth/pyproject.toml @@ -43,6 +43,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/python-sdk/basic-auth/src/seed/basic_auth/client.py b/seed/python-sdk/basic-auth/src/seed/basic_auth/client.py index 49db4ba1538..c77442d3270 100644 --- a/seed/python-sdk/basic-auth/src/seed/basic_auth/client.py +++ b/seed/python-sdk/basic-auth/src/seed/basic_auth/client.py @@ -1,15 +1,15 @@ # This file was auto-generated by Fern from our API Definition. import typing -from json.decoder import JSONDecodeError - -from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.pydantic_utilities import parse_obj_as +from ..core.client_wrapper import SyncClientWrapper from ..core.request_options import RequestOptions -from ..errors.errors.bad_request import BadRequest +from ..core.pydantic_utilities import parse_obj_as from ..errors.errors.unauthorized_request import UnauthorizedRequest from ..errors.types.unauthorized_request_error_body import UnauthorizedRequestErrorBody +from json.decoder import JSONDecodeError +from ..core.api_error import ApiError +from ..errors.errors.bad_request import BadRequest +from ..core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -19,7 +19,9 @@ class BasicAuthClient: def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper - def get_with_basic_auth(self, *, request_options: typing.Optional[RequestOptions] = None) -> bool: + def get_with_basic_auth( + self, *, request_options: typing.Optional[RequestOptions] = None + ) -> bool: """ GET request with basic auth scheme @@ -44,14 +46,23 @@ def get_with_basic_auth(self, *, request_options: typing.Optional[RequestOptions client.basic_auth.get_with_basic_auth() """ _response = self._client_wrapper.httpx_client.request( - "basic-auth", method="GET", request_options=request_options + "basic-auth", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore if _response.status_code == 401: raise UnauthorizedRequest( - typing.cast(UnauthorizedRequestErrorBody, parse_obj_as(type_=UnauthorizedRequestErrorBody, object_=_response.json())) # type: ignore + typing.cast( + UnauthorizedRequestErrorBody, + parse_obj_as( + type_=UnauthorizedRequestErrorBody, object_=_response.json() + ), + ) # type: ignore ) _response_json = _response.json() except JSONDecodeError: @@ -59,7 +70,10 @@ def get_with_basic_auth(self, *, request_options: typing.Optional[RequestOptions raise ApiError(status_code=_response.status_code, body=_response_json) def post_with_basic_auth( - self, *, request: typing.Any, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Any, + request_options: typing.Optional[RequestOptions] = None, ) -> bool: """ POST request with basic auth scheme @@ -89,14 +103,25 @@ def post_with_basic_auth( ) """ _response = self._client_wrapper.httpx_client.request( - "basic-auth", method="POST", json=request, request_options=request_options, omit=OMIT + "basic-auth", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore if _response.status_code == 401: raise UnauthorizedRequest( - typing.cast(UnauthorizedRequestErrorBody, parse_obj_as(type_=UnauthorizedRequestErrorBody, object_=_response.json())) # type: ignore + typing.cast( + UnauthorizedRequestErrorBody, + parse_obj_as( + type_=UnauthorizedRequestErrorBody, object_=_response.json() + ), + ) # type: ignore ) if _response.status_code == 400: raise BadRequest() @@ -110,7 +135,9 @@ class AsyncBasicAuthClient: def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper - async def get_with_basic_auth(self, *, request_options: typing.Optional[RequestOptions] = None) -> bool: + async def get_with_basic_auth( + self, *, request_options: typing.Optional[RequestOptions] = None + ) -> bool: """ GET request with basic auth scheme @@ -143,14 +170,23 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "basic-auth", method="GET", request_options=request_options + "basic-auth", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore if _response.status_code == 401: raise UnauthorizedRequest( - typing.cast(UnauthorizedRequestErrorBody, parse_obj_as(type_=UnauthorizedRequestErrorBody, object_=_response.json())) # type: ignore + typing.cast( + UnauthorizedRequestErrorBody, + parse_obj_as( + type_=UnauthorizedRequestErrorBody, object_=_response.json() + ), + ) # type: ignore ) _response_json = _response.json() except JSONDecodeError: @@ -158,7 +194,10 @@ async def main() -> None: raise ApiError(status_code=_response.status_code, body=_response_json) async def post_with_basic_auth( - self, *, request: typing.Any, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Any, + request_options: typing.Optional[RequestOptions] = None, ) -> bool: """ POST request with basic auth scheme @@ -196,14 +235,25 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "basic-auth", method="POST", json=request, request_options=request_options, omit=OMIT + "basic-auth", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore if _response.status_code == 401: raise UnauthorizedRequest( - typing.cast(UnauthorizedRequestErrorBody, parse_obj_as(type_=UnauthorizedRequestErrorBody, object_=_response.json())) # type: ignore + typing.cast( + UnauthorizedRequestErrorBody, + parse_obj_as( + type_=UnauthorizedRequestErrorBody, object_=_response.json() + ), + ) # type: ignore ) if _response.status_code == 400: raise BadRequest() diff --git a/seed/python-sdk/basic-auth/src/seed/client.py b/seed/python-sdk/basic-auth/src/seed/client.py index d056bda48a8..cde2bfa80da 100644 --- a/seed/python-sdk/basic-auth/src/seed/client.py +++ b/seed/python-sdk/basic-auth/src/seed/client.py @@ -1,11 +1,11 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .basic_auth.client import AsyncBasicAuthClient, BasicAuthClient -from .core.client_wrapper import AsyncClientWrapper, SyncClientWrapper +from .core.client_wrapper import SyncClientWrapper +from .basic_auth.client import BasicAuthClient +from .core.client_wrapper import AsyncClientWrapper +from .basic_auth.client import AsyncBasicAuthClient class SeedBasicAuth: @@ -47,16 +47,20 @@ def __init__( password: typing.Union[str, typing.Callable[[], str]], timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.Client] = None + httpx_client: typing.Optional[httpx.Client] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = SyncClientWrapper( base_url=base_url, username=username, password=password, httpx_client=httpx_client if httpx_client is not None - else httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.Client( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.Client(timeout=_defaulted_timeout), timeout=_defaulted_timeout, @@ -103,16 +107,20 @@ def __init__( password: typing.Union[str, typing.Callable[[], str]], timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.AsyncClient] = None + httpx_client: typing.Optional[httpx.AsyncClient] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = AsyncClientWrapper( base_url=base_url, username=username, password=password, httpx_client=httpx_client if httpx_client is not None - else httpx.AsyncClient(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.AsyncClient( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.AsyncClient(timeout=_defaulted_timeout), timeout=_defaulted_timeout, diff --git a/seed/python-sdk/basic-auth/src/seed/core/api_error.py b/seed/python-sdk/basic-auth/src/seed/core/api_error.py index 2e9fc5431cd..da734b58068 100644 --- a/seed/python-sdk/basic-auth/src/seed/core/api_error.py +++ b/seed/python-sdk/basic-auth/src/seed/core/api_error.py @@ -7,7 +7,9 @@ class ApiError(Exception): status_code: typing.Optional[int] body: typing.Any - def __init__(self, *, status_code: typing.Optional[int] = None, body: typing.Any = None): + def __init__( + self, *, status_code: typing.Optional[int] = None, body: typing.Any = None + ): self.status_code = status_code self.body = body diff --git a/seed/python-sdk/basic-auth/src/seed/core/client_wrapper.py b/seed/python-sdk/basic-auth/src/seed/core/client_wrapper.py index e68b473e099..0da1fd6151f 100644 --- a/seed/python-sdk/basic-auth/src/seed/core/client_wrapper.py +++ b/seed/python-sdk/basic-auth/src/seed/core/client_wrapper.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .http_client import AsyncHttpClient, HttpClient +from .http_client import HttpClient +from .http_client import AsyncHttpClient class BaseClientWrapper: @@ -14,7 +13,7 @@ def __init__( username: typing.Union[str, typing.Callable[[], str]], password: typing.Union[str, typing.Callable[[], str]], base_url: str, - timeout: typing.Optional[float] = None + timeout: typing.Optional[float] = None, ): self._username = username self._password = password @@ -27,7 +26,9 @@ def get_headers(self) -> typing.Dict[str, str]: "X-Fern-SDK-Name": "fern_basic-auth", "X-Fern-SDK-Version": "0.0.1", } - headers["Authorization"] = httpx.BasicAuth(self._get_username(), self._get_password())._auth_header + headers["Authorization"] = httpx.BasicAuth( + self._get_username(), self._get_password() + )._auth_header return headers def _get_username(self) -> str: @@ -57,9 +58,11 @@ def __init__( password: typing.Union[str, typing.Callable[[], str]], base_url: str, timeout: typing.Optional[float] = None, - httpx_client: httpx.Client + httpx_client: httpx.Client, ): - super().__init__(username=username, password=password, base_url=base_url, timeout=timeout) + super().__init__( + username=username, password=password, base_url=base_url, timeout=timeout + ) self.httpx_client = HttpClient( httpx_client=httpx_client, base_headers=self.get_headers(), @@ -76,9 +79,11 @@ def __init__( password: typing.Union[str, typing.Callable[[], str]], base_url: str, timeout: typing.Optional[float] = None, - httpx_client: httpx.AsyncClient + httpx_client: httpx.AsyncClient, ): - super().__init__(username=username, password=password, base_url=base_url, timeout=timeout) + super().__init__( + username=username, password=password, base_url=base_url, timeout=timeout + ) self.httpx_client = AsyncHttpClient( httpx_client=httpx_client, base_headers=self.get_headers(), diff --git a/seed/python-sdk/basic-auth/src/seed/core/datetime_utils.py b/seed/python-sdk/basic-auth/src/seed/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/python-sdk/basic-auth/src/seed/core/datetime_utils.py +++ b/seed/python-sdk/basic-auth/src/seed/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/python-sdk/basic-auth/src/seed/core/file.py b/seed/python-sdk/basic-auth/src/seed/core/file.py index cb0d40bbbf3..6e0f92bfcb1 100644 --- a/seed/python-sdk/basic-auth/src/seed/core/file.py +++ b/seed/python-sdk/basic-auth/src/seed/core/file.py @@ -13,12 +13,17 @@ # (filename, file (or bytes), content_type) typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str]], # (filename, file (or bytes), content_type, headers) - typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str], typing.Mapping[str, str]], + typing.Tuple[ + typing.Optional[str], + FileContent, + typing.Optional[str], + typing.Mapping[str, str], + ], ] def convert_file_dict_to_httpx_tuples( - d: typing.Dict[str, typing.Union[File, typing.List[File]]] + d: typing.Dict[str, typing.Union[File, typing.List[File]]], ) -> typing.List[typing.Tuple[str, File]]: """ The format we use is a list of tuples, where the first element is the diff --git a/seed/python-sdk/basic-auth/src/seed/core/http_client.py b/seed/python-sdk/basic-auth/src/seed/core/http_client.py index 9333d8a7f15..091f71bc185 100644 --- a/seed/python-sdk/basic-auth/src/seed/core/http_client.py +++ b/seed/python-sdk/basic-auth/src/seed/core/http_client.py @@ -77,7 +77,9 @@ def _retry_timeout(response: httpx.Response, retries: int) -> float: return retry_after # Apply exponential backoff, capped at MAX_RETRY_DELAY_SECONDS. - retry_delay = min(INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS) + retry_delay = min( + INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS + ) # Add a randomness / jitter to the retry delay to avoid overwhelming the server with retries. timeout = retry_delay * (1 - 0.25 * random()) @@ -90,7 +92,8 @@ def _should_retry(response: httpx.Response) -> bool: def remove_omit_from_dict( - original: typing.Dict[str, typing.Optional[typing.Any]], omit: typing.Optional[typing.Any] + original: typing.Dict[str, typing.Optional[typing.Any]], + omit: typing.Optional[typing.Any], ) -> typing.Dict[str, typing.Any]: if omit is None: return original @@ -108,7 +111,8 @@ def maybe_filter_request_body( ) -> typing.Optional[typing.Any]: if data is None: return ( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else None ) @@ -118,7 +122,8 @@ def maybe_filter_request_body( data_content = { **(jsonable_encoder(remove_omit_from_dict(data, omit))), # type: ignore **( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else {} ), @@ -162,7 +167,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url def request( @@ -174,8 +181,12 @@ def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -184,11 +195,14 @@ def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) response = self.httpx_client.request( method=method, @@ -198,7 +212,11 @@ def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -209,7 +227,10 @@ def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -222,11 +243,15 @@ def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: time.sleep(_retry_timeout(response=response, retries=retries)) @@ -256,8 +281,12 @@ def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -266,11 +295,14 @@ def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) with self.httpx_client.stream( method=method, @@ -280,7 +312,11 @@ def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -291,7 +327,9 @@ def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -304,7 +342,9 @@ def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream @@ -327,7 +367,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url async def request( @@ -339,8 +381,12 @@ async def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -349,11 +395,14 @@ async def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) # Add the input to each of these and do None-safety checks response = await self.httpx_client.request( @@ -364,7 +413,11 @@ async def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -375,7 +428,10 @@ async def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -388,11 +444,15 @@ async def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: await asyncio.sleep(_retry_timeout(response=response, retries=retries)) @@ -421,8 +481,12 @@ async def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -431,11 +495,14 @@ async def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) async with self.httpx_client.stream( method=method, @@ -445,7 +512,11 @@ async def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -456,7 +527,9 @@ async def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -469,7 +542,9 @@ async def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream diff --git a/seed/python-sdk/basic-auth/src/seed/core/jsonable_encoder.py b/seed/python-sdk/basic-auth/src/seed/core/jsonable_encoder.py index d3fd328fd41..12a8b52fc22 100644 --- a/seed/python-sdk/basic-auth/src/seed/core/jsonable_encoder.py +++ b/seed/python-sdk/basic-auth/src/seed/core/jsonable_encoder.py @@ -19,13 +19,19 @@ import pydantic from .datetime_utils import serialize_datetime -from .pydantic_utilities import IS_PYDANTIC_V2, encode_by_type, to_jsonable_with_fallback +from .pydantic_utilities import ( + IS_PYDANTIC_V2, + encode_by_type, + to_jsonable_with_fallback, +) SetIntStr = Set[Union[int, str]] DictIntStrAny = Dict[Union[int, str], Any] -def jsonable_encoder(obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None) -> Any: +def jsonable_encoder( + obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None +) -> Any: custom_encoder = custom_encoder or {} if custom_encoder: if type(obj) in custom_encoder: diff --git a/seed/python-sdk/basic-auth/src/seed/core/pydantic_utilities.py b/seed/python-sdk/basic-auth/src/seed/core/pydantic_utilities.py index 170a563d6eb..c63935c32a2 100644 --- a/seed/python-sdk/basic-auth/src/seed/core/pydantic_utilities.py +++ b/seed/python-sdk/basic-auth/src/seed/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) # type: ignore # Pydantic v1 diff --git a/seed/python-sdk/basic-auth/src/seed/core/query_encoder.py b/seed/python-sdk/basic-auth/src/seed/core/query_encoder.py index 24076d72ee9..7cb98f52cd7 100644 --- a/seed/python-sdk/basic-auth/src/seed/core/query_encoder.py +++ b/seed/python-sdk/basic-auth/src/seed/core/query_encoder.py @@ -7,7 +7,9 @@ # Flattens dicts to be of the form {"key[subkey][subkey2]": value} where value is not a dict -def traverse_query_dict(dict_flat: Dict[str, Any], key_prefix: Optional[str] = None) -> Dict[str, Any]: +def traverse_query_dict( + dict_flat: Dict[str, Any], key_prefix: Optional[str] = None +) -> Dict[str, Any]: result = {} for k, v in dict_flat.items(): key = f"{key_prefix}[{k}]" if key_prefix is not None else k @@ -30,4 +32,8 @@ def single_query_encoder(query_key: str, query_value: Any) -> Dict[str, Any]: def encode_query(query: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: - return dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) if query is not None else None + return ( + dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) + if query is not None + else None + ) diff --git a/seed/python-sdk/basic-auth/src/seed/core/serialization.py b/seed/python-sdk/basic-auth/src/seed/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/python-sdk/basic-auth/src/seed/core/serialization.py +++ b/seed/python-sdk/basic-auth/src/seed/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/python-sdk/basic-auth/src/seed/errors/types/unauthorized_request_error_body.py b/seed/python-sdk/basic-auth/src/seed/errors/types/unauthorized_request_error_body.py index 2a84d1263c6..4e83edd5002 100644 --- a/seed/python-sdk/basic-auth/src/seed/errors/types/unauthorized_request_error_body.py +++ b/seed/python-sdk/basic-auth/src/seed/errors/types/unauthorized_request_error_body.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class UnauthorizedRequestErrorBody(UniversalBaseModel): message: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/basic-auth/src/seed/version.py b/seed/python-sdk/basic-auth/src/seed/version.py index 249ce3e1205..fc884b76fa7 100644 --- a/seed/python-sdk/basic-auth/src/seed/version.py +++ b/seed/python-sdk/basic-auth/src/seed/version.py @@ -1,4 +1,3 @@ - from importlib import metadata __version__ = metadata.version("fern_basic-auth") diff --git a/seed/python-sdk/basic-auth/tests/conftest.py b/seed/python-sdk/basic-auth/tests/conftest.py index 087860c2536..cb96f0c34c9 100644 --- a/seed/python-sdk/basic-auth/tests/conftest.py +++ b/seed/python-sdk/basic-auth/tests/conftest.py @@ -1,9 +1,9 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedBasicAuth import os - import pytest -from seed import AsyncSeedBasicAuth, SeedBasicAuth +from seed import AsyncSeedBasicAuth @pytest.fixture diff --git a/seed/python-sdk/basic-auth/tests/custom/test_client.py b/seed/python-sdk/basic-auth/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/python-sdk/basic-auth/tests/custom/test_client.py +++ b/seed/python-sdk/basic-auth/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/python-sdk/basic-auth/tests/test_basic_auth.py b/seed/python-sdk/basic-auth/tests/test_basic_auth.py index c0213b6e72e..bcdd4b6ce88 100644 --- a/seed/python-sdk/basic-auth/tests/test_basic_auth.py +++ b/seed/python-sdk/basic-auth/tests/test_basic_auth.py @@ -1,13 +1,14 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedBasicAuth +from seed import AsyncSeedBasicAuth import typing - -from seed import AsyncSeedBasicAuth, SeedBasicAuth - from .utilities import validate_response -async def test_get_with_basic_auth(client: SeedBasicAuth, async_client: AsyncSeedBasicAuth) -> None: +async def test_get_with_basic_auth( + client: SeedBasicAuth, async_client: AsyncSeedBasicAuth +) -> None: expected_response: typing.Any = True expected_types: typing.Any = None response = client.basic_auth.get_with_basic_auth() @@ -17,11 +18,15 @@ async def test_get_with_basic_auth(client: SeedBasicAuth, async_client: AsyncSee validate_response(async_response, expected_response, expected_types) -async def test_post_with_basic_auth(client: SeedBasicAuth, async_client: AsyncSeedBasicAuth) -> None: +async def test_post_with_basic_auth( + client: SeedBasicAuth, async_client: AsyncSeedBasicAuth +) -> None: expected_response: typing.Any = True expected_types: typing.Any = None response = client.basic_auth.post_with_basic_auth(request={"key": "value"}) validate_response(response, expected_response, expected_types) - async_response = await async_client.basic_auth.post_with_basic_auth(request={"key": "value"}) + async_response = await async_client.basic_auth.post_with_basic_auth( + request={"key": "value"} + ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/basic-auth/tests/utilities.py b/seed/python-sdk/basic-auth/tests/utilities.py index 13da208eb3a..e8f4472564c 100644 --- a/seed/python-sdk/basic-auth/tests/utilities.py +++ b/seed/python-sdk/basic-auth/tests/utilities.py @@ -3,11 +3,14 @@ import typing import uuid -import pydantic from dateutil import parser +import pydantic + -def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> typing.Any: +def cast_field( + json_expectation: typing.Any, type_expectation: typing.Any +) -> typing.Any: # Cast these specific types which come through as string and expect our # models to cast to the correct type. if type_expectation == "uuid": @@ -25,7 +28,9 @@ def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> ty return json_expectation -def validate_field(response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any) -> None: +def validate_field( + response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectation == "no_validate": return @@ -44,7 +49,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(entry_expectation, dict): is_container_of_complex_type = True validate_response( - response=response[idx], json_expectation=ex, type_expectations=entry_expectation + response=response[idx], + json_expectation=ex, + type_expectations=entry_expectation, ) else: cast_json_expectation.append(cast_field(ex, entry_expectation)) @@ -56,7 +63,10 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # if any of the values of the set have a type_expectation of a dict, we're assuming it's a pydantic # model and keeping it a list. if container_expectation != "set" or not any( - map(lambda value: isinstance(value, dict), list(contents_expectation.values())) + map( + lambda value: isinstance(value, dict), + list(contents_expectation.values()), + ) ): json_expectation = cast_field(json_expectation, container_expectation) elif isinstance(type_expectation, tuple): @@ -65,9 +75,15 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(contents_expectation, dict): json_expectation = { cast_field( - key, contents_expectation.get(idx)[0] if contents_expectation.get(idx) is not None else None # type: ignore + key, + contents_expectation.get(idx)[0] + if contents_expectation.get(idx) is not None + else None, # type: ignore ): cast_field( - value, contents_expectation.get(idx)[1] if contents_expectation.get(idx) is not None else None # type: ignore + value, + contents_expectation.get(idx)[1] + if contents_expectation.get(idx) is not None + else None, # type: ignore ) for idx, (key, value) in enumerate(json_expectation.items()) } @@ -86,7 +102,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # Arg type_expectations is a deeply nested structure that matches the response, but with the values replaced with the expected types -def validate_response(response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any) -> None: +def validate_response( + response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectations == "no_validate": return @@ -96,11 +114,17 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e and not isinstance(response, dict) and not issubclass(type(response), pydantic.BaseModel) ): - validate_field(response=response, json_expectation=json_expectation, type_expectation=type_expectations) + validate_field( + response=response, + json_expectation=json_expectation, + type_expectation=type_expectations, + ) return if isinstance(response, list): - assert len(response) == len(json_expectation), "Length mismatch, expected: {0}, Actual: {1}".format( + assert len(response) == len( + json_expectation + ), "Length mismatch, expected: {0}, Actual: {1}".format( len(response), len(json_expectation) ) content_expectation = type_expectations @@ -108,7 +132,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e content_expectation = type_expectations[1] for idx, item in enumerate(response): validate_response( - response=item, json_expectation=json_expectation[idx], type_expectations=content_expectation[idx] + response=item, + json_expectation=json_expectation[idx], + type_expectations=content_expectation[idx], ) else: response_json = response @@ -116,7 +142,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e response_json = response.dict(by_alias=True) for key, value in json_expectation.items(): - assert key in response_json, "Field {0} not found within the response object: {1}".format( + assert ( + key in response_json + ), "Field {0} not found within the response object: {1}".format( key, response_json ) @@ -128,11 +156,19 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e # Otherwise, we're just validating a single field that's a pydantic model. if isinstance(value, dict) and not isinstance(type_expectation, tuple): validate_response( - response=response_json[key], json_expectation=value, type_expectations=type_expectation + response=response_json[key], + json_expectation=value, + type_expectations=type_expectation, ) else: - validate_field(response=response_json[key], json_expectation=value, type_expectation=type_expectation) + validate_field( + response=response_json[key], + json_expectation=value, + type_expectation=type_expectation, + ) # Ensure there are no additional fields here either del response_json[key] - assert len(response_json) == 0, "Additional fields found, expected None: {0}".format(response_json) + assert ( + len(response_json) == 0 + ), "Additional fields found, expected None: {0}".format(response_json) diff --git a/seed/python-sdk/basic-auth/tests/utils/assets/models/__init__.py b/seed/python-sdk/basic-auth/tests/utils/assets/models/__init__.py index 2cf01263529..3a1c852e71e 100644 --- a/seed/python-sdk/basic-auth/tests/utils/assets/models/__init__.py +++ b/seed/python-sdk/basic-auth/tests/utils/assets/models/__init__.py @@ -5,7 +5,7 @@ from .circle import CircleParams from .object_with_defaults import ObjectWithDefaultsParams from .object_with_optional_field import ObjectWithOptionalFieldParams -from .shape import Shape_CircleParams, Shape_SquareParams, ShapeParams +from .shape import ShapeParams, Shape_CircleParams, Shape_SquareParams from .square import SquareParams from .undiscriminated_shape import UndiscriminatedShapeParams diff --git a/seed/python-sdk/basic-auth/tests/utils/assets/models/circle.py b/seed/python-sdk/basic-auth/tests/utils/assets/models/circle.py index af7a1bf8a8e..253f12d38b3 100644 --- a/seed/python-sdk/basic-auth/tests/utils/assets/models/circle.py +++ b/seed/python-sdk/basic-auth/tests/utils/assets/models/circle.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class CircleParams(typing_extensions.TypedDict): - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] diff --git a/seed/python-sdk/basic-auth/tests/utils/assets/models/object_with_optional_field.py b/seed/python-sdk/basic-auth/tests/utils/assets/models/object_with_optional_field.py index 3ad93d5f305..ebe7dc80547 100644 --- a/seed/python-sdk/basic-auth/tests/utils/assets/models/object_with_optional_field.py +++ b/seed/python-sdk/basic-auth/tests/utils/assets/models/object_with_optional_field.py @@ -7,8 +7,8 @@ import uuid import typing_extensions -from seed.core.serialization import FieldMetadata +from seed.core.serialization import FieldMetadata from .color import Color from .shape import ShapeParams from .undiscriminated_shape import UndiscriminatedShapeParams @@ -18,16 +18,30 @@ class ObjectWithOptionalFieldParams(typing_extensions.TypedDict): literal: typing.Literal["lit_one"] string: typing_extensions.NotRequired[str] integer: typing_extensions.NotRequired[int] - long_: typing_extensions.NotRequired[typing_extensions.Annotated[int, FieldMetadata(alias="long")]] + long_: typing_extensions.NotRequired[ + typing_extensions.Annotated[int, FieldMetadata(alias="long")] + ] double: typing_extensions.NotRequired[float] - bool_: typing_extensions.NotRequired[typing_extensions.Annotated[bool, FieldMetadata(alias="bool")]] + bool_: typing_extensions.NotRequired[ + typing_extensions.Annotated[bool, FieldMetadata(alias="bool")] + ] datetime: typing_extensions.NotRequired[dt.datetime] date: typing_extensions.NotRequired[dt.date] - uuid_: typing_extensions.NotRequired[typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")]] - base_64: typing_extensions.NotRequired[typing_extensions.Annotated[str, FieldMetadata(alias="base64")]] - list_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")]] - set_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")]] - map_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")]] + uuid_: typing_extensions.NotRequired[ + typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")] + ] + base_64: typing_extensions.NotRequired[ + typing_extensions.Annotated[str, FieldMetadata(alias="base64")] + ] + list_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")] + ] + set_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")] + ] + map_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")] + ] enum: typing_extensions.NotRequired[Color] union: typing_extensions.NotRequired[ShapeParams] second_union: typing_extensions.NotRequired[ShapeParams] diff --git a/seed/python-sdk/basic-auth/tests/utils/assets/models/shape.py b/seed/python-sdk/basic-auth/tests/utils/assets/models/shape.py index 2c33c877951..816ffc51bdc 100644 --- a/seed/python-sdk/basic-auth/tests/utils/assets/models/shape.py +++ b/seed/python-sdk/basic-auth/tests/utils/assets/models/shape.py @@ -7,6 +7,7 @@ import typing import typing_extensions + from seed.core.serialization import FieldMetadata @@ -15,13 +16,21 @@ class Base(typing_extensions.TypedDict): class Shape_CircleParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["circle"], FieldMetadata(alias="shapeType")] - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["circle"], FieldMetadata(alias="shapeType") + ] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] class Shape_SquareParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["square"], FieldMetadata(alias="shapeType")] - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["square"], FieldMetadata(alias="shapeType") + ] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] ShapeParams = typing.Union[Shape_CircleParams, Shape_SquareParams] diff --git a/seed/python-sdk/basic-auth/tests/utils/assets/models/square.py b/seed/python-sdk/basic-auth/tests/utils/assets/models/square.py index b9b7dd319bc..bcf08a723c5 100644 --- a/seed/python-sdk/basic-auth/tests/utils/assets/models/square.py +++ b/seed/python-sdk/basic-auth/tests/utils/assets/models/square.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class SquareParams(typing_extensions.TypedDict): - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] diff --git a/seed/python-sdk/basic-auth/tests/utils/test_http_client.py b/seed/python-sdk/basic-auth/tests/utils/test_http_client.py index edd11ca7afb..f5a874a75f3 100644 --- a/seed/python-sdk/basic-auth/tests/utils/test_http_client.py +++ b/seed/python-sdk/basic-auth/tests/utils/test_http_client.py @@ -9,12 +9,17 @@ def get_request_options() -> RequestOptions: def test_get_json_request_body() -> None: - json_body, data_body = get_request_body(json={"hello": "world"}, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json={"hello": "world"}, data=None, request_options=None, omit=None + ) assert json_body == {"hello": "world"} assert data_body is None json_body_extras, data_body_extras = get_request_body( - json={"goodbye": "world"}, data=None, request_options=get_request_options(), omit=None + json={"goodbye": "world"}, + data=None, + request_options=get_request_options(), + omit=None, ) assert json_body_extras == {"goodbye": "world", "see you": "later"} @@ -22,12 +27,17 @@ def test_get_json_request_body() -> None: def test_get_files_request_body() -> None: - json_body, data_body = get_request_body(json=None, data={"hello": "world"}, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data={"hello": "world"}, request_options=None, omit=None + ) assert data_body == {"hello": "world"} assert json_body is None json_body_extras, data_body_extras = get_request_body( - json=None, data={"goodbye": "world"}, request_options=get_request_options(), omit=None + json=None, + data={"goodbye": "world"}, + request_options=get_request_options(), + omit=None, ) assert data_body_extras == {"goodbye": "world", "see you": "later"} @@ -35,7 +45,9 @@ def test_get_files_request_body() -> None: def test_get_none_request_body() -> None: - json_body, data_body = get_request_body(json=None, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data=None, request_options=None, omit=None + ) assert data_body is None assert json_body is None diff --git a/seed/python-sdk/basic-auth/tests/utils/test_query_encoding.py b/seed/python-sdk/basic-auth/tests/utils/test_query_encoding.py index 247e1551b46..fbc8f402167 100644 --- a/seed/python-sdk/basic-auth/tests/utils/test_query_encoding.py +++ b/seed/python-sdk/basic-auth/tests/utils/test_query_encoding.py @@ -4,9 +4,15 @@ def test_query_encoding() -> None: - assert encode_query({"hello world": "hello world"}) == {"hello world": "hello world"} - assert encode_query({"hello_world": {"hello": "world"}}) == {"hello_world[hello]": "world"} - assert encode_query({"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"}) == { + assert encode_query({"hello world": "hello world"}) == { + "hello world": "hello world" + } + assert encode_query({"hello_world": {"hello": "world"}}) == { + "hello_world[hello]": "world" + } + assert encode_query( + {"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"} + ) == { "hello_world[hello][world]": "today", "hello_world[test]": "this", "hi": "there", diff --git a/seed/python-sdk/basic-auth/tests/utils/test_serialization.py b/seed/python-sdk/basic-auth/tests/utils/test_serialization.py index 58b1ed66e6d..5ca956916dd 100644 --- a/seed/python-sdk/basic-auth/tests/utils/test_serialization.py +++ b/seed/python-sdk/basic-auth/tests/utils/test_serialization.py @@ -1,10 +1,12 @@ # This file was auto-generated by Fern from our API Definition. -from typing import Any, List +from typing import List, Any -from seed.core.serialization import convert_and_respect_annotation_metadata +from seed.core.serialization import ( + convert_and_respect_annotation_metadata, +) +from .assets.models import ShapeParams, ObjectWithOptionalFieldParams -from .assets.models import ObjectWithOptionalFieldParams, ShapeParams UNION_TEST: ShapeParams = {"radius_measurement": 1.0, "shape_type": "circle", "id": "1"} UNION_TEST_CONVERTED = {"shapeType": "circle", "radiusMeasurement": 1.0, "id": "1"} @@ -18,20 +20,54 @@ def test_convert_and_respect_annotation_metadata() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) - assert converted == {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"} + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) + assert converted == { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + } def test_convert_and_respect_annotation_metadata_in_list() -> None: data: List[ObjectWithOptionalFieldParams] = [ - {"string": "string", "long_": 12345, "bool_": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long_": 67890, "list_": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long_": 12345, + "bool_": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long_": 67890, + "list_": [], + "literal": "lit_one", + "any": "any", + }, ] - converted = convert_and_respect_annotation_metadata(object_=data, annotation=List[ObjectWithOptionalFieldParams]) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=List[ObjectWithOptionalFieldParams] + ) assert converted == [ - {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long": 67890, "list": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long": 67890, + "list": [], + "literal": "lit_one", + "any": "any", + }, ] @@ -43,7 +79,9 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) assert converted == { "string": "string", @@ -55,12 +93,16 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: def test_convert_and_respect_annotation_metadata_in_union() -> None: - converted = convert_and_respect_annotation_metadata(object_=UNION_TEST, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=UNION_TEST, annotation=ShapeParams + ) assert converted == UNION_TEST_CONVERTED def test_convert_and_respect_annotation_metadata_with_empty_object() -> None: data: Any = {} - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ShapeParams + ) assert converted == data diff --git a/seed/python-sdk/bearer-token-environment-variable/pyproject.toml b/seed/python-sdk/bearer-token-environment-variable/pyproject.toml index 66a7e5bbf07..1d3af3266e5 100644 --- a/seed/python-sdk/bearer-token-environment-variable/pyproject.toml +++ b/seed/python-sdk/bearer-token-environment-variable/pyproject.toml @@ -43,6 +43,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/python-sdk/bearer-token-environment-variable/src/seed/__init__.py b/seed/python-sdk/bearer-token-environment-variable/src/seed/__init__.py index 5bfe6c26953..da1d9d527d6 100644 --- a/seed/python-sdk/bearer-token-environment-variable/src/seed/__init__.py +++ b/seed/python-sdk/bearer-token-environment-variable/src/seed/__init__.py @@ -1,7 +1,15 @@ # This file was auto-generated by Fern from our API Definition. from . import service -from .client import AsyncSeedBearerTokenEnvironmentVariable, SeedBearerTokenEnvironmentVariable +from .client import ( + AsyncSeedBearerTokenEnvironmentVariable, + SeedBearerTokenEnvironmentVariable, +) from .version import __version__ -__all__ = ["AsyncSeedBearerTokenEnvironmentVariable", "SeedBearerTokenEnvironmentVariable", "__version__", "service"] +__all__ = [ + "AsyncSeedBearerTokenEnvironmentVariable", + "SeedBearerTokenEnvironmentVariable", + "__version__", + "service", +] diff --git a/seed/python-sdk/bearer-token-environment-variable/src/seed/client.py b/seed/python-sdk/bearer-token-environment-variable/src/seed/client.py index 43abf6a0c89..b9cf4260e79 100644 --- a/seed/python-sdk/bearer-token-environment-variable/src/seed/client.py +++ b/seed/python-sdk/bearer-token-environment-variable/src/seed/client.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. -import os import typing - +import os import httpx - from .core.api_error import ApiError -from .core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from .service.client import AsyncServiceClient, ServiceClient +from .core.client_wrapper import SyncClientWrapper +from .service.client import ServiceClient +from .core.client_wrapper import AsyncClientWrapper +from .service.client import AsyncServiceClient class SeedBearerTokenEnvironmentVariable: @@ -43,12 +43,16 @@ def __init__( self, *, base_url: str, - api_key: typing.Optional[typing.Union[str, typing.Callable[[], str]]] = os.getenv("COURIER_API_KEY"), + api_key: typing.Optional[ + typing.Union[str, typing.Callable[[], str]] + ] = os.getenv("COURIER_API_KEY"), timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.Client] = None + httpx_client: typing.Optional[httpx.Client] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) if api_key is None: raise ApiError( body="The client must be instantiated be either passing in api_key or setting COURIER_API_KEY" @@ -58,7 +62,9 @@ def __init__( api_key=api_key, httpx_client=httpx_client if httpx_client is not None - else httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.Client( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.Client(timeout=_defaulted_timeout), timeout=_defaulted_timeout, @@ -99,12 +105,16 @@ def __init__( self, *, base_url: str, - api_key: typing.Optional[typing.Union[str, typing.Callable[[], str]]] = os.getenv("COURIER_API_KEY"), + api_key: typing.Optional[ + typing.Union[str, typing.Callable[[], str]] + ] = os.getenv("COURIER_API_KEY"), timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.AsyncClient] = None + httpx_client: typing.Optional[httpx.AsyncClient] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) if api_key is None: raise ApiError( body="The client must be instantiated be either passing in api_key or setting COURIER_API_KEY" @@ -114,7 +124,9 @@ def __init__( api_key=api_key, httpx_client=httpx_client if httpx_client is not None - else httpx.AsyncClient(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.AsyncClient( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.AsyncClient(timeout=_defaulted_timeout), timeout=_defaulted_timeout, diff --git a/seed/python-sdk/bearer-token-environment-variable/src/seed/core/api_error.py b/seed/python-sdk/bearer-token-environment-variable/src/seed/core/api_error.py index 2e9fc5431cd..da734b58068 100644 --- a/seed/python-sdk/bearer-token-environment-variable/src/seed/core/api_error.py +++ b/seed/python-sdk/bearer-token-environment-variable/src/seed/core/api_error.py @@ -7,7 +7,9 @@ class ApiError(Exception): status_code: typing.Optional[int] body: typing.Any - def __init__(self, *, status_code: typing.Optional[int] = None, body: typing.Any = None): + def __init__( + self, *, status_code: typing.Optional[int] = None, body: typing.Any = None + ): self.status_code = status_code self.body = body diff --git a/seed/python-sdk/bearer-token-environment-variable/src/seed/core/client_wrapper.py b/seed/python-sdk/bearer-token-environment-variable/src/seed/core/client_wrapper.py index 838cf4dde93..8efea0917cf 100644 --- a/seed/python-sdk/bearer-token-environment-variable/src/seed/core/client_wrapper.py +++ b/seed/python-sdk/bearer-token-environment-variable/src/seed/core/client_wrapper.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .http_client import AsyncHttpClient, HttpClient +from .http_client import HttpClient +from .http_client import AsyncHttpClient class BaseClientWrapper: diff --git a/seed/python-sdk/bearer-token-environment-variable/src/seed/core/datetime_utils.py b/seed/python-sdk/bearer-token-environment-variable/src/seed/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/python-sdk/bearer-token-environment-variable/src/seed/core/datetime_utils.py +++ b/seed/python-sdk/bearer-token-environment-variable/src/seed/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/python-sdk/bearer-token-environment-variable/src/seed/core/file.py b/seed/python-sdk/bearer-token-environment-variable/src/seed/core/file.py index cb0d40bbbf3..6e0f92bfcb1 100644 --- a/seed/python-sdk/bearer-token-environment-variable/src/seed/core/file.py +++ b/seed/python-sdk/bearer-token-environment-variable/src/seed/core/file.py @@ -13,12 +13,17 @@ # (filename, file (or bytes), content_type) typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str]], # (filename, file (or bytes), content_type, headers) - typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str], typing.Mapping[str, str]], + typing.Tuple[ + typing.Optional[str], + FileContent, + typing.Optional[str], + typing.Mapping[str, str], + ], ] def convert_file_dict_to_httpx_tuples( - d: typing.Dict[str, typing.Union[File, typing.List[File]]] + d: typing.Dict[str, typing.Union[File, typing.List[File]]], ) -> typing.List[typing.Tuple[str, File]]: """ The format we use is a list of tuples, where the first element is the diff --git a/seed/python-sdk/bearer-token-environment-variable/src/seed/core/http_client.py b/seed/python-sdk/bearer-token-environment-variable/src/seed/core/http_client.py index 9333d8a7f15..091f71bc185 100644 --- a/seed/python-sdk/bearer-token-environment-variable/src/seed/core/http_client.py +++ b/seed/python-sdk/bearer-token-environment-variable/src/seed/core/http_client.py @@ -77,7 +77,9 @@ def _retry_timeout(response: httpx.Response, retries: int) -> float: return retry_after # Apply exponential backoff, capped at MAX_RETRY_DELAY_SECONDS. - retry_delay = min(INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS) + retry_delay = min( + INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS + ) # Add a randomness / jitter to the retry delay to avoid overwhelming the server with retries. timeout = retry_delay * (1 - 0.25 * random()) @@ -90,7 +92,8 @@ def _should_retry(response: httpx.Response) -> bool: def remove_omit_from_dict( - original: typing.Dict[str, typing.Optional[typing.Any]], omit: typing.Optional[typing.Any] + original: typing.Dict[str, typing.Optional[typing.Any]], + omit: typing.Optional[typing.Any], ) -> typing.Dict[str, typing.Any]: if omit is None: return original @@ -108,7 +111,8 @@ def maybe_filter_request_body( ) -> typing.Optional[typing.Any]: if data is None: return ( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else None ) @@ -118,7 +122,8 @@ def maybe_filter_request_body( data_content = { **(jsonable_encoder(remove_omit_from_dict(data, omit))), # type: ignore **( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else {} ), @@ -162,7 +167,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url def request( @@ -174,8 +181,12 @@ def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -184,11 +195,14 @@ def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) response = self.httpx_client.request( method=method, @@ -198,7 +212,11 @@ def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -209,7 +227,10 @@ def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -222,11 +243,15 @@ def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: time.sleep(_retry_timeout(response=response, retries=retries)) @@ -256,8 +281,12 @@ def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -266,11 +295,14 @@ def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) with self.httpx_client.stream( method=method, @@ -280,7 +312,11 @@ def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -291,7 +327,9 @@ def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -304,7 +342,9 @@ def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream @@ -327,7 +367,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url async def request( @@ -339,8 +381,12 @@ async def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -349,11 +395,14 @@ async def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) # Add the input to each of these and do None-safety checks response = await self.httpx_client.request( @@ -364,7 +413,11 @@ async def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -375,7 +428,10 @@ async def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -388,11 +444,15 @@ async def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: await asyncio.sleep(_retry_timeout(response=response, retries=retries)) @@ -421,8 +481,12 @@ async def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -431,11 +495,14 @@ async def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) async with self.httpx_client.stream( method=method, @@ -445,7 +512,11 @@ async def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -456,7 +527,9 @@ async def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -469,7 +542,9 @@ async def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream diff --git a/seed/python-sdk/bearer-token-environment-variable/src/seed/core/jsonable_encoder.py b/seed/python-sdk/bearer-token-environment-variable/src/seed/core/jsonable_encoder.py index d3fd328fd41..12a8b52fc22 100644 --- a/seed/python-sdk/bearer-token-environment-variable/src/seed/core/jsonable_encoder.py +++ b/seed/python-sdk/bearer-token-environment-variable/src/seed/core/jsonable_encoder.py @@ -19,13 +19,19 @@ import pydantic from .datetime_utils import serialize_datetime -from .pydantic_utilities import IS_PYDANTIC_V2, encode_by_type, to_jsonable_with_fallback +from .pydantic_utilities import ( + IS_PYDANTIC_V2, + encode_by_type, + to_jsonable_with_fallback, +) SetIntStr = Set[Union[int, str]] DictIntStrAny = Dict[Union[int, str], Any] -def jsonable_encoder(obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None) -> Any: +def jsonable_encoder( + obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None +) -> Any: custom_encoder = custom_encoder or {} if custom_encoder: if type(obj) in custom_encoder: diff --git a/seed/python-sdk/bearer-token-environment-variable/src/seed/core/pydantic_utilities.py b/seed/python-sdk/bearer-token-environment-variable/src/seed/core/pydantic_utilities.py index 170a563d6eb..c63935c32a2 100644 --- a/seed/python-sdk/bearer-token-environment-variable/src/seed/core/pydantic_utilities.py +++ b/seed/python-sdk/bearer-token-environment-variable/src/seed/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) # type: ignore # Pydantic v1 diff --git a/seed/python-sdk/bearer-token-environment-variable/src/seed/core/query_encoder.py b/seed/python-sdk/bearer-token-environment-variable/src/seed/core/query_encoder.py index 24076d72ee9..7cb98f52cd7 100644 --- a/seed/python-sdk/bearer-token-environment-variable/src/seed/core/query_encoder.py +++ b/seed/python-sdk/bearer-token-environment-variable/src/seed/core/query_encoder.py @@ -7,7 +7,9 @@ # Flattens dicts to be of the form {"key[subkey][subkey2]": value} where value is not a dict -def traverse_query_dict(dict_flat: Dict[str, Any], key_prefix: Optional[str] = None) -> Dict[str, Any]: +def traverse_query_dict( + dict_flat: Dict[str, Any], key_prefix: Optional[str] = None +) -> Dict[str, Any]: result = {} for k, v in dict_flat.items(): key = f"{key_prefix}[{k}]" if key_prefix is not None else k @@ -30,4 +32,8 @@ def single_query_encoder(query_key: str, query_value: Any) -> Dict[str, Any]: def encode_query(query: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: - return dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) if query is not None else None + return ( + dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) + if query is not None + else None + ) diff --git a/seed/python-sdk/bearer-token-environment-variable/src/seed/core/serialization.py b/seed/python-sdk/bearer-token-environment-variable/src/seed/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/python-sdk/bearer-token-environment-variable/src/seed/core/serialization.py +++ b/seed/python-sdk/bearer-token-environment-variable/src/seed/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/python-sdk/bearer-token-environment-variable/src/seed/service/client.py b/seed/python-sdk/bearer-token-environment-variable/src/seed/service/client.py index 68aa64a2ad6..3eabf1d8112 100644 --- a/seed/python-sdk/bearer-token-environment-variable/src/seed/service/client.py +++ b/seed/python-sdk/bearer-token-environment-variable/src/seed/service/client.py @@ -1,19 +1,21 @@ # This file was auto-generated by Fern from our API Definition. +from ..core.client_wrapper import SyncClientWrapper import typing +from ..core.request_options import RequestOptions +from ..core.pydantic_utilities import parse_obj_as from json.decoder import JSONDecodeError - from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.pydantic_utilities import parse_obj_as -from ..core.request_options import RequestOptions +from ..core.client_wrapper import AsyncClientWrapper class ServiceClient: def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper - def get_with_bearer_token(self, *, request_options: typing.Optional[RequestOptions] = None) -> str: + def get_with_bearer_token( + self, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ GET request with custom api key @@ -36,10 +38,16 @@ def get_with_bearer_token(self, *, request_options: typing.Optional[RequestOptio ) client.service.get_with_bearer_token() """ - _response = self._client_wrapper.httpx_client.request("apiKey", method="GET", request_options=request_options) + _response = self._client_wrapper.httpx_client.request( + "apiKey", + method="GET", + request_options=request_options, + ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -50,7 +58,9 @@ class AsyncServiceClient: def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper - async def get_with_bearer_token(self, *, request_options: typing.Optional[RequestOptions] = None) -> str: + async def get_with_bearer_token( + self, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ GET request with custom api key @@ -82,11 +92,15 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "apiKey", method="GET", request_options=request_options + "apiKey", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/bearer-token-environment-variable/src/seed/version.py b/seed/python-sdk/bearer-token-environment-variable/src/seed/version.py index e7ed6c87a97..7b69835e1fa 100644 --- a/seed/python-sdk/bearer-token-environment-variable/src/seed/version.py +++ b/seed/python-sdk/bearer-token-environment-variable/src/seed/version.py @@ -1,4 +1,3 @@ - from importlib import metadata __version__ = metadata.version("fern_bearer-token-environment-variable") diff --git a/seed/python-sdk/bearer-token-environment-variable/tests/conftest.py b/seed/python-sdk/bearer-token-environment-variable/tests/conftest.py index 8eb8bb57d15..ddb078e404b 100644 --- a/seed/python-sdk/bearer-token-environment-variable/tests/conftest.py +++ b/seed/python-sdk/bearer-token-environment-variable/tests/conftest.py @@ -1,20 +1,22 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedBearerTokenEnvironmentVariable import os - import pytest -from seed import AsyncSeedBearerTokenEnvironmentVariable, SeedBearerTokenEnvironmentVariable +from seed import AsyncSeedBearerTokenEnvironmentVariable @pytest.fixture def client() -> SeedBearerTokenEnvironmentVariable: return SeedBearerTokenEnvironmentVariable( - api_key=os.getenv("ENV_API_KEY", "api_key"), base_url=os.getenv("TESTS_BASE_URL", "base_url") + api_key=os.getenv("ENV_API_KEY", "api_key"), + base_url=os.getenv("TESTS_BASE_URL", "base_url"), ) @pytest.fixture def async_client() -> AsyncSeedBearerTokenEnvironmentVariable: return AsyncSeedBearerTokenEnvironmentVariable( - api_key=os.getenv("ENV_API_KEY", "api_key"), base_url=os.getenv("TESTS_BASE_URL", "base_url") + api_key=os.getenv("ENV_API_KEY", "api_key"), + base_url=os.getenv("TESTS_BASE_URL", "base_url"), ) diff --git a/seed/python-sdk/bearer-token-environment-variable/tests/custom/test_client.py b/seed/python-sdk/bearer-token-environment-variable/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/python-sdk/bearer-token-environment-variable/tests/custom/test_client.py +++ b/seed/python-sdk/bearer-token-environment-variable/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/python-sdk/bearer-token-environment-variable/tests/test_service.py b/seed/python-sdk/bearer-token-environment-variable/tests/test_service.py index d6dcab557f4..5e6b451a9b0 100644 --- a/seed/python-sdk/bearer-token-environment-variable/tests/test_service.py +++ b/seed/python-sdk/bearer-token-environment-variable/tests/test_service.py @@ -1,14 +1,14 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedBearerTokenEnvironmentVariable +from seed import AsyncSeedBearerTokenEnvironmentVariable import typing - -from seed import AsyncSeedBearerTokenEnvironmentVariable, SeedBearerTokenEnvironmentVariable - from .utilities import validate_response async def test_get_with_bearer_token( - client: SeedBearerTokenEnvironmentVariable, async_client: AsyncSeedBearerTokenEnvironmentVariable + client: SeedBearerTokenEnvironmentVariable, + async_client: AsyncSeedBearerTokenEnvironmentVariable, ) -> None: expected_response: typing.Any = "string" expected_types: typing.Any = None diff --git a/seed/python-sdk/bearer-token-environment-variable/tests/utilities.py b/seed/python-sdk/bearer-token-environment-variable/tests/utilities.py index 13da208eb3a..e8f4472564c 100644 --- a/seed/python-sdk/bearer-token-environment-variable/tests/utilities.py +++ b/seed/python-sdk/bearer-token-environment-variable/tests/utilities.py @@ -3,11 +3,14 @@ import typing import uuid -import pydantic from dateutil import parser +import pydantic + -def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> typing.Any: +def cast_field( + json_expectation: typing.Any, type_expectation: typing.Any +) -> typing.Any: # Cast these specific types which come through as string and expect our # models to cast to the correct type. if type_expectation == "uuid": @@ -25,7 +28,9 @@ def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> ty return json_expectation -def validate_field(response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any) -> None: +def validate_field( + response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectation == "no_validate": return @@ -44,7 +49,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(entry_expectation, dict): is_container_of_complex_type = True validate_response( - response=response[idx], json_expectation=ex, type_expectations=entry_expectation + response=response[idx], + json_expectation=ex, + type_expectations=entry_expectation, ) else: cast_json_expectation.append(cast_field(ex, entry_expectation)) @@ -56,7 +63,10 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # if any of the values of the set have a type_expectation of a dict, we're assuming it's a pydantic # model and keeping it a list. if container_expectation != "set" or not any( - map(lambda value: isinstance(value, dict), list(contents_expectation.values())) + map( + lambda value: isinstance(value, dict), + list(contents_expectation.values()), + ) ): json_expectation = cast_field(json_expectation, container_expectation) elif isinstance(type_expectation, tuple): @@ -65,9 +75,15 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(contents_expectation, dict): json_expectation = { cast_field( - key, contents_expectation.get(idx)[0] if contents_expectation.get(idx) is not None else None # type: ignore + key, + contents_expectation.get(idx)[0] + if contents_expectation.get(idx) is not None + else None, # type: ignore ): cast_field( - value, contents_expectation.get(idx)[1] if contents_expectation.get(idx) is not None else None # type: ignore + value, + contents_expectation.get(idx)[1] + if contents_expectation.get(idx) is not None + else None, # type: ignore ) for idx, (key, value) in enumerate(json_expectation.items()) } @@ -86,7 +102,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # Arg type_expectations is a deeply nested structure that matches the response, but with the values replaced with the expected types -def validate_response(response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any) -> None: +def validate_response( + response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectations == "no_validate": return @@ -96,11 +114,17 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e and not isinstance(response, dict) and not issubclass(type(response), pydantic.BaseModel) ): - validate_field(response=response, json_expectation=json_expectation, type_expectation=type_expectations) + validate_field( + response=response, + json_expectation=json_expectation, + type_expectation=type_expectations, + ) return if isinstance(response, list): - assert len(response) == len(json_expectation), "Length mismatch, expected: {0}, Actual: {1}".format( + assert len(response) == len( + json_expectation + ), "Length mismatch, expected: {0}, Actual: {1}".format( len(response), len(json_expectation) ) content_expectation = type_expectations @@ -108,7 +132,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e content_expectation = type_expectations[1] for idx, item in enumerate(response): validate_response( - response=item, json_expectation=json_expectation[idx], type_expectations=content_expectation[idx] + response=item, + json_expectation=json_expectation[idx], + type_expectations=content_expectation[idx], ) else: response_json = response @@ -116,7 +142,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e response_json = response.dict(by_alias=True) for key, value in json_expectation.items(): - assert key in response_json, "Field {0} not found within the response object: {1}".format( + assert ( + key in response_json + ), "Field {0} not found within the response object: {1}".format( key, response_json ) @@ -128,11 +156,19 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e # Otherwise, we're just validating a single field that's a pydantic model. if isinstance(value, dict) and not isinstance(type_expectation, tuple): validate_response( - response=response_json[key], json_expectation=value, type_expectations=type_expectation + response=response_json[key], + json_expectation=value, + type_expectations=type_expectation, ) else: - validate_field(response=response_json[key], json_expectation=value, type_expectation=type_expectation) + validate_field( + response=response_json[key], + json_expectation=value, + type_expectation=type_expectation, + ) # Ensure there are no additional fields here either del response_json[key] - assert len(response_json) == 0, "Additional fields found, expected None: {0}".format(response_json) + assert ( + len(response_json) == 0 + ), "Additional fields found, expected None: {0}".format(response_json) diff --git a/seed/python-sdk/bearer-token-environment-variable/tests/utils/assets/models/__init__.py b/seed/python-sdk/bearer-token-environment-variable/tests/utils/assets/models/__init__.py index 2cf01263529..3a1c852e71e 100644 --- a/seed/python-sdk/bearer-token-environment-variable/tests/utils/assets/models/__init__.py +++ b/seed/python-sdk/bearer-token-environment-variable/tests/utils/assets/models/__init__.py @@ -5,7 +5,7 @@ from .circle import CircleParams from .object_with_defaults import ObjectWithDefaultsParams from .object_with_optional_field import ObjectWithOptionalFieldParams -from .shape import Shape_CircleParams, Shape_SquareParams, ShapeParams +from .shape import ShapeParams, Shape_CircleParams, Shape_SquareParams from .square import SquareParams from .undiscriminated_shape import UndiscriminatedShapeParams diff --git a/seed/python-sdk/bearer-token-environment-variable/tests/utils/assets/models/circle.py b/seed/python-sdk/bearer-token-environment-variable/tests/utils/assets/models/circle.py index af7a1bf8a8e..253f12d38b3 100644 --- a/seed/python-sdk/bearer-token-environment-variable/tests/utils/assets/models/circle.py +++ b/seed/python-sdk/bearer-token-environment-variable/tests/utils/assets/models/circle.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class CircleParams(typing_extensions.TypedDict): - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] diff --git a/seed/python-sdk/bearer-token-environment-variable/tests/utils/assets/models/object_with_optional_field.py b/seed/python-sdk/bearer-token-environment-variable/tests/utils/assets/models/object_with_optional_field.py index 3ad93d5f305..ebe7dc80547 100644 --- a/seed/python-sdk/bearer-token-environment-variable/tests/utils/assets/models/object_with_optional_field.py +++ b/seed/python-sdk/bearer-token-environment-variable/tests/utils/assets/models/object_with_optional_field.py @@ -7,8 +7,8 @@ import uuid import typing_extensions -from seed.core.serialization import FieldMetadata +from seed.core.serialization import FieldMetadata from .color import Color from .shape import ShapeParams from .undiscriminated_shape import UndiscriminatedShapeParams @@ -18,16 +18,30 @@ class ObjectWithOptionalFieldParams(typing_extensions.TypedDict): literal: typing.Literal["lit_one"] string: typing_extensions.NotRequired[str] integer: typing_extensions.NotRequired[int] - long_: typing_extensions.NotRequired[typing_extensions.Annotated[int, FieldMetadata(alias="long")]] + long_: typing_extensions.NotRequired[ + typing_extensions.Annotated[int, FieldMetadata(alias="long")] + ] double: typing_extensions.NotRequired[float] - bool_: typing_extensions.NotRequired[typing_extensions.Annotated[bool, FieldMetadata(alias="bool")]] + bool_: typing_extensions.NotRequired[ + typing_extensions.Annotated[bool, FieldMetadata(alias="bool")] + ] datetime: typing_extensions.NotRequired[dt.datetime] date: typing_extensions.NotRequired[dt.date] - uuid_: typing_extensions.NotRequired[typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")]] - base_64: typing_extensions.NotRequired[typing_extensions.Annotated[str, FieldMetadata(alias="base64")]] - list_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")]] - set_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")]] - map_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")]] + uuid_: typing_extensions.NotRequired[ + typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")] + ] + base_64: typing_extensions.NotRequired[ + typing_extensions.Annotated[str, FieldMetadata(alias="base64")] + ] + list_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")] + ] + set_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")] + ] + map_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")] + ] enum: typing_extensions.NotRequired[Color] union: typing_extensions.NotRequired[ShapeParams] second_union: typing_extensions.NotRequired[ShapeParams] diff --git a/seed/python-sdk/bearer-token-environment-variable/tests/utils/assets/models/shape.py b/seed/python-sdk/bearer-token-environment-variable/tests/utils/assets/models/shape.py index 2c33c877951..816ffc51bdc 100644 --- a/seed/python-sdk/bearer-token-environment-variable/tests/utils/assets/models/shape.py +++ b/seed/python-sdk/bearer-token-environment-variable/tests/utils/assets/models/shape.py @@ -7,6 +7,7 @@ import typing import typing_extensions + from seed.core.serialization import FieldMetadata @@ -15,13 +16,21 @@ class Base(typing_extensions.TypedDict): class Shape_CircleParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["circle"], FieldMetadata(alias="shapeType")] - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["circle"], FieldMetadata(alias="shapeType") + ] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] class Shape_SquareParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["square"], FieldMetadata(alias="shapeType")] - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["square"], FieldMetadata(alias="shapeType") + ] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] ShapeParams = typing.Union[Shape_CircleParams, Shape_SquareParams] diff --git a/seed/python-sdk/bearer-token-environment-variable/tests/utils/assets/models/square.py b/seed/python-sdk/bearer-token-environment-variable/tests/utils/assets/models/square.py index b9b7dd319bc..bcf08a723c5 100644 --- a/seed/python-sdk/bearer-token-environment-variable/tests/utils/assets/models/square.py +++ b/seed/python-sdk/bearer-token-environment-variable/tests/utils/assets/models/square.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class SquareParams(typing_extensions.TypedDict): - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] diff --git a/seed/python-sdk/bearer-token-environment-variable/tests/utils/test_http_client.py b/seed/python-sdk/bearer-token-environment-variable/tests/utils/test_http_client.py index edd11ca7afb..f5a874a75f3 100644 --- a/seed/python-sdk/bearer-token-environment-variable/tests/utils/test_http_client.py +++ b/seed/python-sdk/bearer-token-environment-variable/tests/utils/test_http_client.py @@ -9,12 +9,17 @@ def get_request_options() -> RequestOptions: def test_get_json_request_body() -> None: - json_body, data_body = get_request_body(json={"hello": "world"}, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json={"hello": "world"}, data=None, request_options=None, omit=None + ) assert json_body == {"hello": "world"} assert data_body is None json_body_extras, data_body_extras = get_request_body( - json={"goodbye": "world"}, data=None, request_options=get_request_options(), omit=None + json={"goodbye": "world"}, + data=None, + request_options=get_request_options(), + omit=None, ) assert json_body_extras == {"goodbye": "world", "see you": "later"} @@ -22,12 +27,17 @@ def test_get_json_request_body() -> None: def test_get_files_request_body() -> None: - json_body, data_body = get_request_body(json=None, data={"hello": "world"}, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data={"hello": "world"}, request_options=None, omit=None + ) assert data_body == {"hello": "world"} assert json_body is None json_body_extras, data_body_extras = get_request_body( - json=None, data={"goodbye": "world"}, request_options=get_request_options(), omit=None + json=None, + data={"goodbye": "world"}, + request_options=get_request_options(), + omit=None, ) assert data_body_extras == {"goodbye": "world", "see you": "later"} @@ -35,7 +45,9 @@ def test_get_files_request_body() -> None: def test_get_none_request_body() -> None: - json_body, data_body = get_request_body(json=None, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data=None, request_options=None, omit=None + ) assert data_body is None assert json_body is None diff --git a/seed/python-sdk/bearer-token-environment-variable/tests/utils/test_query_encoding.py b/seed/python-sdk/bearer-token-environment-variable/tests/utils/test_query_encoding.py index 247e1551b46..fbc8f402167 100644 --- a/seed/python-sdk/bearer-token-environment-variable/tests/utils/test_query_encoding.py +++ b/seed/python-sdk/bearer-token-environment-variable/tests/utils/test_query_encoding.py @@ -4,9 +4,15 @@ def test_query_encoding() -> None: - assert encode_query({"hello world": "hello world"}) == {"hello world": "hello world"} - assert encode_query({"hello_world": {"hello": "world"}}) == {"hello_world[hello]": "world"} - assert encode_query({"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"}) == { + assert encode_query({"hello world": "hello world"}) == { + "hello world": "hello world" + } + assert encode_query({"hello_world": {"hello": "world"}}) == { + "hello_world[hello]": "world" + } + assert encode_query( + {"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"} + ) == { "hello_world[hello][world]": "today", "hello_world[test]": "this", "hi": "there", diff --git a/seed/python-sdk/bearer-token-environment-variable/tests/utils/test_serialization.py b/seed/python-sdk/bearer-token-environment-variable/tests/utils/test_serialization.py index 58b1ed66e6d..5ca956916dd 100644 --- a/seed/python-sdk/bearer-token-environment-variable/tests/utils/test_serialization.py +++ b/seed/python-sdk/bearer-token-environment-variable/tests/utils/test_serialization.py @@ -1,10 +1,12 @@ # This file was auto-generated by Fern from our API Definition. -from typing import Any, List +from typing import List, Any -from seed.core.serialization import convert_and_respect_annotation_metadata +from seed.core.serialization import ( + convert_and_respect_annotation_metadata, +) +from .assets.models import ShapeParams, ObjectWithOptionalFieldParams -from .assets.models import ObjectWithOptionalFieldParams, ShapeParams UNION_TEST: ShapeParams = {"radius_measurement": 1.0, "shape_type": "circle", "id": "1"} UNION_TEST_CONVERTED = {"shapeType": "circle", "radiusMeasurement": 1.0, "id": "1"} @@ -18,20 +20,54 @@ def test_convert_and_respect_annotation_metadata() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) - assert converted == {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"} + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) + assert converted == { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + } def test_convert_and_respect_annotation_metadata_in_list() -> None: data: List[ObjectWithOptionalFieldParams] = [ - {"string": "string", "long_": 12345, "bool_": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long_": 67890, "list_": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long_": 12345, + "bool_": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long_": 67890, + "list_": [], + "literal": "lit_one", + "any": "any", + }, ] - converted = convert_and_respect_annotation_metadata(object_=data, annotation=List[ObjectWithOptionalFieldParams]) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=List[ObjectWithOptionalFieldParams] + ) assert converted == [ - {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long": 67890, "list": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long": 67890, + "list": [], + "literal": "lit_one", + "any": "any", + }, ] @@ -43,7 +79,9 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) assert converted == { "string": "string", @@ -55,12 +93,16 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: def test_convert_and_respect_annotation_metadata_in_union() -> None: - converted = convert_and_respect_annotation_metadata(object_=UNION_TEST, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=UNION_TEST, annotation=ShapeParams + ) assert converted == UNION_TEST_CONVERTED def test_convert_and_respect_annotation_metadata_with_empty_object() -> None: data: Any = {} - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ShapeParams + ) assert converted == data diff --git a/seed/python-sdk/bytes/pyproject.toml b/seed/python-sdk/bytes/pyproject.toml index ba449f11ce8..0ce2ad9291d 100644 --- a/seed/python-sdk/bytes/pyproject.toml +++ b/seed/python-sdk/bytes/pyproject.toml @@ -43,6 +43,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/python-sdk/bytes/src/seed/client.py b/seed/python-sdk/bytes/src/seed/client.py index ab3639a240a..e3ed277dd15 100644 --- a/seed/python-sdk/bytes/src/seed/client.py +++ b/seed/python-sdk/bytes/src/seed/client.py @@ -1,11 +1,11 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from .service.client import AsyncServiceClient, ServiceClient +from .core.client_wrapper import SyncClientWrapper +from .service.client import ServiceClient +from .core.client_wrapper import AsyncClientWrapper +from .service.client import AsyncServiceClient class SeedBytes: @@ -41,14 +41,18 @@ def __init__( base_url: str, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.Client] = None + httpx_client: typing.Optional[httpx.Client] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = SyncClientWrapper( base_url=base_url, httpx_client=httpx_client if httpx_client is not None - else httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.Client( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.Client(timeout=_defaulted_timeout), timeout=_defaulted_timeout, @@ -89,14 +93,18 @@ def __init__( base_url: str, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.AsyncClient] = None + httpx_client: typing.Optional[httpx.AsyncClient] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = AsyncClientWrapper( base_url=base_url, httpx_client=httpx_client if httpx_client is not None - else httpx.AsyncClient(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.AsyncClient( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.AsyncClient(timeout=_defaulted_timeout), timeout=_defaulted_timeout, diff --git a/seed/python-sdk/bytes/src/seed/core/api_error.py b/seed/python-sdk/bytes/src/seed/core/api_error.py index 2e9fc5431cd..da734b58068 100644 --- a/seed/python-sdk/bytes/src/seed/core/api_error.py +++ b/seed/python-sdk/bytes/src/seed/core/api_error.py @@ -7,7 +7,9 @@ class ApiError(Exception): status_code: typing.Optional[int] body: typing.Any - def __init__(self, *, status_code: typing.Optional[int] = None, body: typing.Any = None): + def __init__( + self, *, status_code: typing.Optional[int] = None, body: typing.Any = None + ): self.status_code = status_code self.body = body diff --git a/seed/python-sdk/bytes/src/seed/core/client_wrapper.py b/seed/python-sdk/bytes/src/seed/core/client_wrapper.py index 4ffcdbdeb95..c986f9a529a 100644 --- a/seed/python-sdk/bytes/src/seed/core/client_wrapper.py +++ b/seed/python-sdk/bytes/src/seed/core/client_wrapper.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .http_client import AsyncHttpClient, HttpClient +from .http_client import HttpClient +from .http_client import AsyncHttpClient class BaseClientWrapper: @@ -28,7 +27,13 @@ def get_timeout(self) -> typing.Optional[float]: class SyncClientWrapper(BaseClientWrapper): - def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, httpx_client: httpx.Client): + def __init__( + self, + *, + base_url: str, + timeout: typing.Optional[float] = None, + httpx_client: httpx.Client, + ): super().__init__(base_url=base_url, timeout=timeout) self.httpx_client = HttpClient( httpx_client=httpx_client, @@ -39,7 +44,13 @@ def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, htt class AsyncClientWrapper(BaseClientWrapper): - def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, httpx_client: httpx.AsyncClient): + def __init__( + self, + *, + base_url: str, + timeout: typing.Optional[float] = None, + httpx_client: httpx.AsyncClient, + ): super().__init__(base_url=base_url, timeout=timeout) self.httpx_client = AsyncHttpClient( httpx_client=httpx_client, diff --git a/seed/python-sdk/bytes/src/seed/core/datetime_utils.py b/seed/python-sdk/bytes/src/seed/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/python-sdk/bytes/src/seed/core/datetime_utils.py +++ b/seed/python-sdk/bytes/src/seed/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/python-sdk/bytes/src/seed/core/file.py b/seed/python-sdk/bytes/src/seed/core/file.py index cb0d40bbbf3..6e0f92bfcb1 100644 --- a/seed/python-sdk/bytes/src/seed/core/file.py +++ b/seed/python-sdk/bytes/src/seed/core/file.py @@ -13,12 +13,17 @@ # (filename, file (or bytes), content_type) typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str]], # (filename, file (or bytes), content_type, headers) - typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str], typing.Mapping[str, str]], + typing.Tuple[ + typing.Optional[str], + FileContent, + typing.Optional[str], + typing.Mapping[str, str], + ], ] def convert_file_dict_to_httpx_tuples( - d: typing.Dict[str, typing.Union[File, typing.List[File]]] + d: typing.Dict[str, typing.Union[File, typing.List[File]]], ) -> typing.List[typing.Tuple[str, File]]: """ The format we use is a list of tuples, where the first element is the diff --git a/seed/python-sdk/bytes/src/seed/core/http_client.py b/seed/python-sdk/bytes/src/seed/core/http_client.py index 9333d8a7f15..091f71bc185 100644 --- a/seed/python-sdk/bytes/src/seed/core/http_client.py +++ b/seed/python-sdk/bytes/src/seed/core/http_client.py @@ -77,7 +77,9 @@ def _retry_timeout(response: httpx.Response, retries: int) -> float: return retry_after # Apply exponential backoff, capped at MAX_RETRY_DELAY_SECONDS. - retry_delay = min(INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS) + retry_delay = min( + INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS + ) # Add a randomness / jitter to the retry delay to avoid overwhelming the server with retries. timeout = retry_delay * (1 - 0.25 * random()) @@ -90,7 +92,8 @@ def _should_retry(response: httpx.Response) -> bool: def remove_omit_from_dict( - original: typing.Dict[str, typing.Optional[typing.Any]], omit: typing.Optional[typing.Any] + original: typing.Dict[str, typing.Optional[typing.Any]], + omit: typing.Optional[typing.Any], ) -> typing.Dict[str, typing.Any]: if omit is None: return original @@ -108,7 +111,8 @@ def maybe_filter_request_body( ) -> typing.Optional[typing.Any]: if data is None: return ( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else None ) @@ -118,7 +122,8 @@ def maybe_filter_request_body( data_content = { **(jsonable_encoder(remove_omit_from_dict(data, omit))), # type: ignore **( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else {} ), @@ -162,7 +167,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url def request( @@ -174,8 +181,12 @@ def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -184,11 +195,14 @@ def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) response = self.httpx_client.request( method=method, @@ -198,7 +212,11 @@ def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -209,7 +227,10 @@ def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -222,11 +243,15 @@ def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: time.sleep(_retry_timeout(response=response, retries=retries)) @@ -256,8 +281,12 @@ def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -266,11 +295,14 @@ def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) with self.httpx_client.stream( method=method, @@ -280,7 +312,11 @@ def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -291,7 +327,9 @@ def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -304,7 +342,9 @@ def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream @@ -327,7 +367,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url async def request( @@ -339,8 +381,12 @@ async def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -349,11 +395,14 @@ async def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) # Add the input to each of these and do None-safety checks response = await self.httpx_client.request( @@ -364,7 +413,11 @@ async def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -375,7 +428,10 @@ async def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -388,11 +444,15 @@ async def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: await asyncio.sleep(_retry_timeout(response=response, retries=retries)) @@ -421,8 +481,12 @@ async def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -431,11 +495,14 @@ async def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) async with self.httpx_client.stream( method=method, @@ -445,7 +512,11 @@ async def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -456,7 +527,9 @@ async def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -469,7 +542,9 @@ async def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream diff --git a/seed/python-sdk/bytes/src/seed/core/jsonable_encoder.py b/seed/python-sdk/bytes/src/seed/core/jsonable_encoder.py index d3fd328fd41..12a8b52fc22 100644 --- a/seed/python-sdk/bytes/src/seed/core/jsonable_encoder.py +++ b/seed/python-sdk/bytes/src/seed/core/jsonable_encoder.py @@ -19,13 +19,19 @@ import pydantic from .datetime_utils import serialize_datetime -from .pydantic_utilities import IS_PYDANTIC_V2, encode_by_type, to_jsonable_with_fallback +from .pydantic_utilities import ( + IS_PYDANTIC_V2, + encode_by_type, + to_jsonable_with_fallback, +) SetIntStr = Set[Union[int, str]] DictIntStrAny = Dict[Union[int, str], Any] -def jsonable_encoder(obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None) -> Any: +def jsonable_encoder( + obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None +) -> Any: custom_encoder = custom_encoder or {} if custom_encoder: if type(obj) in custom_encoder: diff --git a/seed/python-sdk/bytes/src/seed/core/pydantic_utilities.py b/seed/python-sdk/bytes/src/seed/core/pydantic_utilities.py index 170a563d6eb..c63935c32a2 100644 --- a/seed/python-sdk/bytes/src/seed/core/pydantic_utilities.py +++ b/seed/python-sdk/bytes/src/seed/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) # type: ignore # Pydantic v1 diff --git a/seed/python-sdk/bytes/src/seed/core/query_encoder.py b/seed/python-sdk/bytes/src/seed/core/query_encoder.py index 24076d72ee9..7cb98f52cd7 100644 --- a/seed/python-sdk/bytes/src/seed/core/query_encoder.py +++ b/seed/python-sdk/bytes/src/seed/core/query_encoder.py @@ -7,7 +7,9 @@ # Flattens dicts to be of the form {"key[subkey][subkey2]": value} where value is not a dict -def traverse_query_dict(dict_flat: Dict[str, Any], key_prefix: Optional[str] = None) -> Dict[str, Any]: +def traverse_query_dict( + dict_flat: Dict[str, Any], key_prefix: Optional[str] = None +) -> Dict[str, Any]: result = {} for k, v in dict_flat.items(): key = f"{key_prefix}[{k}]" if key_prefix is not None else k @@ -30,4 +32,8 @@ def single_query_encoder(query_key: str, query_value: Any) -> Dict[str, Any]: def encode_query(query: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: - return dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) if query is not None else None + return ( + dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) + if query is not None + else None + ) diff --git a/seed/python-sdk/bytes/src/seed/core/serialization.py b/seed/python-sdk/bytes/src/seed/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/python-sdk/bytes/src/seed/core/serialization.py +++ b/seed/python-sdk/bytes/src/seed/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/python-sdk/bytes/src/seed/service/client.py b/seed/python-sdk/bytes/src/seed/service/client.py index 34ff215752c..3b9ae9b3f10 100644 --- a/seed/python-sdk/bytes/src/seed/service/client.py +++ b/seed/python-sdk/bytes/src/seed/service/client.py @@ -1,11 +1,11 @@ # This file was auto-generated by Fern from our API Definition. import typing +from ..core.client_wrapper import SyncClientWrapper +from ..core.request_options import RequestOptions from json.decoder import JSONDecodeError - from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.request_options import RequestOptions +from ..core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -18,8 +18,10 @@ def __init__(self, *, client_wrapper: SyncClientWrapper): def upload( self, *, - request: typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]], - request_options: typing.Optional[RequestOptions] = None + request: typing.Union[ + bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes] + ], + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ Parameters @@ -43,7 +45,11 @@ def upload( client.service.upload() """ _response = self._client_wrapper.httpx_client.request( - "upload-content", method="POST", content=request, request_options=request_options, omit=OMIT + "upload-content", + method="POST", + content=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: @@ -61,8 +67,10 @@ def __init__(self, *, client_wrapper: AsyncClientWrapper): async def upload( self, *, - request: typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]], - request_options: typing.Optional[RequestOptions] = None + request: typing.Union[ + bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes] + ], + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ Parameters @@ -94,7 +102,11 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "upload-content", method="POST", content=request, request_options=request_options, omit=OMIT + "upload-content", + method="POST", + content=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: diff --git a/seed/python-sdk/bytes/src/seed/version.py b/seed/python-sdk/bytes/src/seed/version.py index 62034cb9f65..3e52ff3bc15 100644 --- a/seed/python-sdk/bytes/src/seed/version.py +++ b/seed/python-sdk/bytes/src/seed/version.py @@ -1,4 +1,3 @@ - from importlib import metadata __version__ = metadata.version("fern_bytes") diff --git a/seed/python-sdk/bytes/tests/conftest.py b/seed/python-sdk/bytes/tests/conftest.py index c5042bf7e44..4bcb5f3e9a9 100644 --- a/seed/python-sdk/bytes/tests/conftest.py +++ b/seed/python-sdk/bytes/tests/conftest.py @@ -1,9 +1,9 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedBytes import os - import pytest -from seed import AsyncSeedBytes, SeedBytes +from seed import AsyncSeedBytes @pytest.fixture diff --git a/seed/python-sdk/bytes/tests/custom/test_client.py b/seed/python-sdk/bytes/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/python-sdk/bytes/tests/custom/test_client.py +++ b/seed/python-sdk/bytes/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/python-sdk/bytes/tests/utilities.py b/seed/python-sdk/bytes/tests/utilities.py index 13da208eb3a..e8f4472564c 100644 --- a/seed/python-sdk/bytes/tests/utilities.py +++ b/seed/python-sdk/bytes/tests/utilities.py @@ -3,11 +3,14 @@ import typing import uuid -import pydantic from dateutil import parser +import pydantic + -def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> typing.Any: +def cast_field( + json_expectation: typing.Any, type_expectation: typing.Any +) -> typing.Any: # Cast these specific types which come through as string and expect our # models to cast to the correct type. if type_expectation == "uuid": @@ -25,7 +28,9 @@ def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> ty return json_expectation -def validate_field(response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any) -> None: +def validate_field( + response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectation == "no_validate": return @@ -44,7 +49,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(entry_expectation, dict): is_container_of_complex_type = True validate_response( - response=response[idx], json_expectation=ex, type_expectations=entry_expectation + response=response[idx], + json_expectation=ex, + type_expectations=entry_expectation, ) else: cast_json_expectation.append(cast_field(ex, entry_expectation)) @@ -56,7 +63,10 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # if any of the values of the set have a type_expectation of a dict, we're assuming it's a pydantic # model and keeping it a list. if container_expectation != "set" or not any( - map(lambda value: isinstance(value, dict), list(contents_expectation.values())) + map( + lambda value: isinstance(value, dict), + list(contents_expectation.values()), + ) ): json_expectation = cast_field(json_expectation, container_expectation) elif isinstance(type_expectation, tuple): @@ -65,9 +75,15 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(contents_expectation, dict): json_expectation = { cast_field( - key, contents_expectation.get(idx)[0] if contents_expectation.get(idx) is not None else None # type: ignore + key, + contents_expectation.get(idx)[0] + if contents_expectation.get(idx) is not None + else None, # type: ignore ): cast_field( - value, contents_expectation.get(idx)[1] if contents_expectation.get(idx) is not None else None # type: ignore + value, + contents_expectation.get(idx)[1] + if contents_expectation.get(idx) is not None + else None, # type: ignore ) for idx, (key, value) in enumerate(json_expectation.items()) } @@ -86,7 +102,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # Arg type_expectations is a deeply nested structure that matches the response, but with the values replaced with the expected types -def validate_response(response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any) -> None: +def validate_response( + response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectations == "no_validate": return @@ -96,11 +114,17 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e and not isinstance(response, dict) and not issubclass(type(response), pydantic.BaseModel) ): - validate_field(response=response, json_expectation=json_expectation, type_expectation=type_expectations) + validate_field( + response=response, + json_expectation=json_expectation, + type_expectation=type_expectations, + ) return if isinstance(response, list): - assert len(response) == len(json_expectation), "Length mismatch, expected: {0}, Actual: {1}".format( + assert len(response) == len( + json_expectation + ), "Length mismatch, expected: {0}, Actual: {1}".format( len(response), len(json_expectation) ) content_expectation = type_expectations @@ -108,7 +132,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e content_expectation = type_expectations[1] for idx, item in enumerate(response): validate_response( - response=item, json_expectation=json_expectation[idx], type_expectations=content_expectation[idx] + response=item, + json_expectation=json_expectation[idx], + type_expectations=content_expectation[idx], ) else: response_json = response @@ -116,7 +142,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e response_json = response.dict(by_alias=True) for key, value in json_expectation.items(): - assert key in response_json, "Field {0} not found within the response object: {1}".format( + assert ( + key in response_json + ), "Field {0} not found within the response object: {1}".format( key, response_json ) @@ -128,11 +156,19 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e # Otherwise, we're just validating a single field that's a pydantic model. if isinstance(value, dict) and not isinstance(type_expectation, tuple): validate_response( - response=response_json[key], json_expectation=value, type_expectations=type_expectation + response=response_json[key], + json_expectation=value, + type_expectations=type_expectation, ) else: - validate_field(response=response_json[key], json_expectation=value, type_expectation=type_expectation) + validate_field( + response=response_json[key], + json_expectation=value, + type_expectation=type_expectation, + ) # Ensure there are no additional fields here either del response_json[key] - assert len(response_json) == 0, "Additional fields found, expected None: {0}".format(response_json) + assert ( + len(response_json) == 0 + ), "Additional fields found, expected None: {0}".format(response_json) diff --git a/seed/python-sdk/bytes/tests/utils/assets/models/__init__.py b/seed/python-sdk/bytes/tests/utils/assets/models/__init__.py index 2cf01263529..3a1c852e71e 100644 --- a/seed/python-sdk/bytes/tests/utils/assets/models/__init__.py +++ b/seed/python-sdk/bytes/tests/utils/assets/models/__init__.py @@ -5,7 +5,7 @@ from .circle import CircleParams from .object_with_defaults import ObjectWithDefaultsParams from .object_with_optional_field import ObjectWithOptionalFieldParams -from .shape import Shape_CircleParams, Shape_SquareParams, ShapeParams +from .shape import ShapeParams, Shape_CircleParams, Shape_SquareParams from .square import SquareParams from .undiscriminated_shape import UndiscriminatedShapeParams diff --git a/seed/python-sdk/bytes/tests/utils/assets/models/circle.py b/seed/python-sdk/bytes/tests/utils/assets/models/circle.py index af7a1bf8a8e..253f12d38b3 100644 --- a/seed/python-sdk/bytes/tests/utils/assets/models/circle.py +++ b/seed/python-sdk/bytes/tests/utils/assets/models/circle.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class CircleParams(typing_extensions.TypedDict): - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] diff --git a/seed/python-sdk/bytes/tests/utils/assets/models/object_with_optional_field.py b/seed/python-sdk/bytes/tests/utils/assets/models/object_with_optional_field.py index 3ad93d5f305..ebe7dc80547 100644 --- a/seed/python-sdk/bytes/tests/utils/assets/models/object_with_optional_field.py +++ b/seed/python-sdk/bytes/tests/utils/assets/models/object_with_optional_field.py @@ -7,8 +7,8 @@ import uuid import typing_extensions -from seed.core.serialization import FieldMetadata +from seed.core.serialization import FieldMetadata from .color import Color from .shape import ShapeParams from .undiscriminated_shape import UndiscriminatedShapeParams @@ -18,16 +18,30 @@ class ObjectWithOptionalFieldParams(typing_extensions.TypedDict): literal: typing.Literal["lit_one"] string: typing_extensions.NotRequired[str] integer: typing_extensions.NotRequired[int] - long_: typing_extensions.NotRequired[typing_extensions.Annotated[int, FieldMetadata(alias="long")]] + long_: typing_extensions.NotRequired[ + typing_extensions.Annotated[int, FieldMetadata(alias="long")] + ] double: typing_extensions.NotRequired[float] - bool_: typing_extensions.NotRequired[typing_extensions.Annotated[bool, FieldMetadata(alias="bool")]] + bool_: typing_extensions.NotRequired[ + typing_extensions.Annotated[bool, FieldMetadata(alias="bool")] + ] datetime: typing_extensions.NotRequired[dt.datetime] date: typing_extensions.NotRequired[dt.date] - uuid_: typing_extensions.NotRequired[typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")]] - base_64: typing_extensions.NotRequired[typing_extensions.Annotated[str, FieldMetadata(alias="base64")]] - list_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")]] - set_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")]] - map_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")]] + uuid_: typing_extensions.NotRequired[ + typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")] + ] + base_64: typing_extensions.NotRequired[ + typing_extensions.Annotated[str, FieldMetadata(alias="base64")] + ] + list_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")] + ] + set_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")] + ] + map_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")] + ] enum: typing_extensions.NotRequired[Color] union: typing_extensions.NotRequired[ShapeParams] second_union: typing_extensions.NotRequired[ShapeParams] diff --git a/seed/python-sdk/bytes/tests/utils/assets/models/shape.py b/seed/python-sdk/bytes/tests/utils/assets/models/shape.py index 2c33c877951..816ffc51bdc 100644 --- a/seed/python-sdk/bytes/tests/utils/assets/models/shape.py +++ b/seed/python-sdk/bytes/tests/utils/assets/models/shape.py @@ -7,6 +7,7 @@ import typing import typing_extensions + from seed.core.serialization import FieldMetadata @@ -15,13 +16,21 @@ class Base(typing_extensions.TypedDict): class Shape_CircleParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["circle"], FieldMetadata(alias="shapeType")] - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["circle"], FieldMetadata(alias="shapeType") + ] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] class Shape_SquareParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["square"], FieldMetadata(alias="shapeType")] - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["square"], FieldMetadata(alias="shapeType") + ] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] ShapeParams = typing.Union[Shape_CircleParams, Shape_SquareParams] diff --git a/seed/python-sdk/bytes/tests/utils/assets/models/square.py b/seed/python-sdk/bytes/tests/utils/assets/models/square.py index b9b7dd319bc..bcf08a723c5 100644 --- a/seed/python-sdk/bytes/tests/utils/assets/models/square.py +++ b/seed/python-sdk/bytes/tests/utils/assets/models/square.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class SquareParams(typing_extensions.TypedDict): - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] diff --git a/seed/python-sdk/bytes/tests/utils/test_http_client.py b/seed/python-sdk/bytes/tests/utils/test_http_client.py index edd11ca7afb..f5a874a75f3 100644 --- a/seed/python-sdk/bytes/tests/utils/test_http_client.py +++ b/seed/python-sdk/bytes/tests/utils/test_http_client.py @@ -9,12 +9,17 @@ def get_request_options() -> RequestOptions: def test_get_json_request_body() -> None: - json_body, data_body = get_request_body(json={"hello": "world"}, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json={"hello": "world"}, data=None, request_options=None, omit=None + ) assert json_body == {"hello": "world"} assert data_body is None json_body_extras, data_body_extras = get_request_body( - json={"goodbye": "world"}, data=None, request_options=get_request_options(), omit=None + json={"goodbye": "world"}, + data=None, + request_options=get_request_options(), + omit=None, ) assert json_body_extras == {"goodbye": "world", "see you": "later"} @@ -22,12 +27,17 @@ def test_get_json_request_body() -> None: def test_get_files_request_body() -> None: - json_body, data_body = get_request_body(json=None, data={"hello": "world"}, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data={"hello": "world"}, request_options=None, omit=None + ) assert data_body == {"hello": "world"} assert json_body is None json_body_extras, data_body_extras = get_request_body( - json=None, data={"goodbye": "world"}, request_options=get_request_options(), omit=None + json=None, + data={"goodbye": "world"}, + request_options=get_request_options(), + omit=None, ) assert data_body_extras == {"goodbye": "world", "see you": "later"} @@ -35,7 +45,9 @@ def test_get_files_request_body() -> None: def test_get_none_request_body() -> None: - json_body, data_body = get_request_body(json=None, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data=None, request_options=None, omit=None + ) assert data_body is None assert json_body is None diff --git a/seed/python-sdk/bytes/tests/utils/test_query_encoding.py b/seed/python-sdk/bytes/tests/utils/test_query_encoding.py index 247e1551b46..fbc8f402167 100644 --- a/seed/python-sdk/bytes/tests/utils/test_query_encoding.py +++ b/seed/python-sdk/bytes/tests/utils/test_query_encoding.py @@ -4,9 +4,15 @@ def test_query_encoding() -> None: - assert encode_query({"hello world": "hello world"}) == {"hello world": "hello world"} - assert encode_query({"hello_world": {"hello": "world"}}) == {"hello_world[hello]": "world"} - assert encode_query({"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"}) == { + assert encode_query({"hello world": "hello world"}) == { + "hello world": "hello world" + } + assert encode_query({"hello_world": {"hello": "world"}}) == { + "hello_world[hello]": "world" + } + assert encode_query( + {"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"} + ) == { "hello_world[hello][world]": "today", "hello_world[test]": "this", "hi": "there", diff --git a/seed/python-sdk/bytes/tests/utils/test_serialization.py b/seed/python-sdk/bytes/tests/utils/test_serialization.py index 58b1ed66e6d..5ca956916dd 100644 --- a/seed/python-sdk/bytes/tests/utils/test_serialization.py +++ b/seed/python-sdk/bytes/tests/utils/test_serialization.py @@ -1,10 +1,12 @@ # This file was auto-generated by Fern from our API Definition. -from typing import Any, List +from typing import List, Any -from seed.core.serialization import convert_and_respect_annotation_metadata +from seed.core.serialization import ( + convert_and_respect_annotation_metadata, +) +from .assets.models import ShapeParams, ObjectWithOptionalFieldParams -from .assets.models import ObjectWithOptionalFieldParams, ShapeParams UNION_TEST: ShapeParams = {"radius_measurement": 1.0, "shape_type": "circle", "id": "1"} UNION_TEST_CONVERTED = {"shapeType": "circle", "radiusMeasurement": 1.0, "id": "1"} @@ -18,20 +20,54 @@ def test_convert_and_respect_annotation_metadata() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) - assert converted == {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"} + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) + assert converted == { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + } def test_convert_and_respect_annotation_metadata_in_list() -> None: data: List[ObjectWithOptionalFieldParams] = [ - {"string": "string", "long_": 12345, "bool_": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long_": 67890, "list_": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long_": 12345, + "bool_": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long_": 67890, + "list_": [], + "literal": "lit_one", + "any": "any", + }, ] - converted = convert_and_respect_annotation_metadata(object_=data, annotation=List[ObjectWithOptionalFieldParams]) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=List[ObjectWithOptionalFieldParams] + ) assert converted == [ - {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long": 67890, "list": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long": 67890, + "list": [], + "literal": "lit_one", + "any": "any", + }, ] @@ -43,7 +79,9 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) assert converted == { "string": "string", @@ -55,12 +93,16 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: def test_convert_and_respect_annotation_metadata_in_union() -> None: - converted = convert_and_respect_annotation_metadata(object_=UNION_TEST, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=UNION_TEST, annotation=ShapeParams + ) assert converted == UNION_TEST_CONVERTED def test_convert_and_respect_annotation_metadata_with_empty_object() -> None: data: Any = {} - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ShapeParams + ) assert converted == data diff --git a/seed/python-sdk/circular-references-advanced/pyproject.toml b/seed/python-sdk/circular-references-advanced/pyproject.toml index 26212bc16ba..8f4fb035ae4 100644 --- a/seed/python-sdk/circular-references-advanced/pyproject.toml +++ b/seed/python-sdk/circular-references-advanced/pyproject.toml @@ -43,6 +43,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/python-sdk/circular-references-advanced/src/seed/a/types/a.py b/seed/python-sdk/circular-references-advanced/src/seed/a/types/a.py index 1333d010963..d5352cca952 100644 --- a/seed/python-sdk/circular-references-advanced/src/seed/a/types/a.py +++ b/seed/python-sdk/circular-references-advanced/src/seed/a/types/a.py @@ -1,16 +1,16 @@ # This file was auto-generated by Fern from our API Definition. +from ...types.root_type import RootType +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2 -from ...types.root_type import RootType - class A(RootType): if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/circular-references-advanced/src/seed/ast/types/__init__.py b/seed/python-sdk/circular-references-advanced/src/seed/ast/types/__init__.py index 036ab4a59d4..a884e3ead85 100644 --- a/seed/python-sdk/circular-references-advanced/src/seed/ast/types/__init__.py +++ b/seed/python-sdk/circular-references-advanced/src/seed/ast/types/__init__.py @@ -1,8 +1,17 @@ # This file was auto-generated by Fern from our API Definition. -from .container_value import ContainerValue, ContainerValue_List, ContainerValue_Optional +from .container_value import ( + ContainerValue, + ContainerValue_List, + ContainerValue_Optional, +) from .field_name import FieldName -from .field_value import FieldValue, FieldValue_ContainerValue, FieldValue_ObjectValue, FieldValue_PrimitiveValue +from .field_value import ( + FieldValue, + FieldValue_ContainerValue, + FieldValue_ObjectValue, + FieldValue_PrimitiveValue, +) from .object_field_value import ObjectFieldValue from .object_value import ObjectValue from .primitive_value import PrimitiveValue diff --git a/seed/python-sdk/circular-references-advanced/src/seed/ast/types/container_value.py b/seed/python-sdk/circular-references-advanced/src/seed/ast/types/container_value.py index eb0977022bb..a29a9c7bff3 100644 --- a/seed/python-sdk/circular-references-advanced/src/seed/ast/types/container_value.py +++ b/seed/python-sdk/circular-references-advanced/src/seed/ast/types/container_value.py @@ -1,14 +1,13 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ...core.pydantic_utilities import UniversalBaseModel import typing - +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel, update_forward_refs from .object_value import ObjectValue from .primitive_value import PrimitiveValue +from ...core.pydantic_utilities import update_forward_refs class ContainerValue_List(UniversalBaseModel): @@ -16,7 +15,9 @@ class ContainerValue_List(UniversalBaseModel): type: typing.Literal["list"] = "list" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + frozen=True + ) # type: ignore # Pydantic v2 else: class Config: @@ -29,7 +30,9 @@ class ContainerValue_Optional(UniversalBaseModel): type: typing.Literal["optional"] = "optional" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/circular-references-advanced/src/seed/ast/types/field_value.py b/seed/python-sdk/circular-references-advanced/src/seed/ast/types/field_value.py index 1e1ce6a3bcb..865121656b6 100644 --- a/seed/python-sdk/circular-references-advanced/src/seed/ast/types/field_value.py +++ b/seed/python-sdk/circular-references-advanced/src/seed/ast/types/field_value.py @@ -1,13 +1,12 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ...core.pydantic_utilities import UniversalBaseModel +from .primitive_value import PrimitiveValue import typing - +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel, update_forward_refs -from .primitive_value import PrimitiveValue +from ...core.pydantic_utilities import update_forward_refs class FieldValue_PrimitiveValue(UniversalBaseModel): @@ -15,7 +14,9 @@ class FieldValue_PrimitiveValue(UniversalBaseModel): type: typing.Literal["primitive_value"] = "primitive_value" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + frozen=True + ) # type: ignore # Pydantic v2 else: class Config: @@ -27,7 +28,9 @@ class FieldValue_ObjectValue(UniversalBaseModel): type: typing.Literal["object_value"] = "object_value" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: @@ -41,7 +44,9 @@ class FieldValue_ContainerValue(UniversalBaseModel): type: typing.Literal["container_value"] = "container_value" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + frozen=True + ) # type: ignore # Pydantic v2 else: class Config: @@ -49,7 +54,9 @@ class Config: smart_union = True -FieldValue = typing.Union[FieldValue_PrimitiveValue, FieldValue_ObjectValue, FieldValue_ContainerValue] +FieldValue = typing.Union[ + FieldValue_PrimitiveValue, FieldValue_ObjectValue, FieldValue_ContainerValue +] from .container_value import ContainerValue # noqa: E402 update_forward_refs(FieldValue_ContainerValue, ContainerValue=ContainerValue) diff --git a/seed/python-sdk/circular-references-advanced/src/seed/ast/types/object_field_value.py b/seed/python-sdk/circular-references-advanced/src/seed/ast/types/object_field_value.py index 78f893cefab..0beb0a470a6 100644 --- a/seed/python-sdk/circular-references-advanced/src/seed/ast/types/object_field_value.py +++ b/seed/python-sdk/circular-references-advanced/src/seed/ast/types/object_field_value.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ...core.pydantic_utilities import UniversalBaseModel from .field_name import FieldName from .field_value import FieldValue +from ...core.pydantic_utilities import IS_PYDANTIC_V2 +import typing +import pydantic class ObjectFieldValue(UniversalBaseModel): @@ -18,7 +17,9 @@ class ObjectFieldValue(UniversalBaseModel): value: FieldValue if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/circular-references-advanced/src/seed/ast/types/object_value.py b/seed/python-sdk/circular-references-advanced/src/seed/ast/types/object_value.py index 07b7f2038c9..47b3da57340 100644 --- a/seed/python-sdk/circular-references-advanced/src/seed/ast/types/object_value.py +++ b/seed/python-sdk/circular-references-advanced/src/seed/ast/types/object_value.py @@ -1,15 +1,16 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class ObjectValue(UniversalBaseModel): if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/circular-references-advanced/src/seed/client.py b/seed/python-sdk/circular-references-advanced/src/seed/client.py index c1e3be6d4d3..6940f7b8880 100644 --- a/seed/python-sdk/circular-references-advanced/src/seed/client.py +++ b/seed/python-sdk/circular-references-advanced/src/seed/client.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .core.client_wrapper import AsyncClientWrapper, SyncClientWrapper +from .core.client_wrapper import SyncClientWrapper +from .core.client_wrapper import AsyncClientWrapper class SeedApi: @@ -40,14 +39,18 @@ def __init__( base_url: str, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.Client] = None + httpx_client: typing.Optional[httpx.Client] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = SyncClientWrapper( base_url=base_url, httpx_client=httpx_client if httpx_client is not None - else httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.Client( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.Client(timeout=_defaulted_timeout), timeout=_defaulted_timeout, @@ -87,14 +90,18 @@ def __init__( base_url: str, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.AsyncClient] = None + httpx_client: typing.Optional[httpx.AsyncClient] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = AsyncClientWrapper( base_url=base_url, httpx_client=httpx_client if httpx_client is not None - else httpx.AsyncClient(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.AsyncClient( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.AsyncClient(timeout=_defaulted_timeout), timeout=_defaulted_timeout, diff --git a/seed/python-sdk/circular-references-advanced/src/seed/core/api_error.py b/seed/python-sdk/circular-references-advanced/src/seed/core/api_error.py index 2e9fc5431cd..da734b58068 100644 --- a/seed/python-sdk/circular-references-advanced/src/seed/core/api_error.py +++ b/seed/python-sdk/circular-references-advanced/src/seed/core/api_error.py @@ -7,7 +7,9 @@ class ApiError(Exception): status_code: typing.Optional[int] body: typing.Any - def __init__(self, *, status_code: typing.Optional[int] = None, body: typing.Any = None): + def __init__( + self, *, status_code: typing.Optional[int] = None, body: typing.Any = None + ): self.status_code = status_code self.body = body diff --git a/seed/python-sdk/circular-references-advanced/src/seed/core/client_wrapper.py b/seed/python-sdk/circular-references-advanced/src/seed/core/client_wrapper.py index b7b94cab9e9..581ca2a793d 100644 --- a/seed/python-sdk/circular-references-advanced/src/seed/core/client_wrapper.py +++ b/seed/python-sdk/circular-references-advanced/src/seed/core/client_wrapper.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .http_client import AsyncHttpClient, HttpClient +from .http_client import HttpClient +from .http_client import AsyncHttpClient class BaseClientWrapper: @@ -28,7 +27,13 @@ def get_timeout(self) -> typing.Optional[float]: class SyncClientWrapper(BaseClientWrapper): - def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, httpx_client: httpx.Client): + def __init__( + self, + *, + base_url: str, + timeout: typing.Optional[float] = None, + httpx_client: httpx.Client, + ): super().__init__(base_url=base_url, timeout=timeout) self.httpx_client = HttpClient( httpx_client=httpx_client, @@ -39,7 +44,13 @@ def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, htt class AsyncClientWrapper(BaseClientWrapper): - def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, httpx_client: httpx.AsyncClient): + def __init__( + self, + *, + base_url: str, + timeout: typing.Optional[float] = None, + httpx_client: httpx.AsyncClient, + ): super().__init__(base_url=base_url, timeout=timeout) self.httpx_client = AsyncHttpClient( httpx_client=httpx_client, diff --git a/seed/python-sdk/circular-references-advanced/src/seed/core/datetime_utils.py b/seed/python-sdk/circular-references-advanced/src/seed/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/python-sdk/circular-references-advanced/src/seed/core/datetime_utils.py +++ b/seed/python-sdk/circular-references-advanced/src/seed/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/python-sdk/circular-references-advanced/src/seed/core/file.py b/seed/python-sdk/circular-references-advanced/src/seed/core/file.py index cb0d40bbbf3..6e0f92bfcb1 100644 --- a/seed/python-sdk/circular-references-advanced/src/seed/core/file.py +++ b/seed/python-sdk/circular-references-advanced/src/seed/core/file.py @@ -13,12 +13,17 @@ # (filename, file (or bytes), content_type) typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str]], # (filename, file (or bytes), content_type, headers) - typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str], typing.Mapping[str, str]], + typing.Tuple[ + typing.Optional[str], + FileContent, + typing.Optional[str], + typing.Mapping[str, str], + ], ] def convert_file_dict_to_httpx_tuples( - d: typing.Dict[str, typing.Union[File, typing.List[File]]] + d: typing.Dict[str, typing.Union[File, typing.List[File]]], ) -> typing.List[typing.Tuple[str, File]]: """ The format we use is a list of tuples, where the first element is the diff --git a/seed/python-sdk/circular-references-advanced/src/seed/core/http_client.py b/seed/python-sdk/circular-references-advanced/src/seed/core/http_client.py index 9333d8a7f15..091f71bc185 100644 --- a/seed/python-sdk/circular-references-advanced/src/seed/core/http_client.py +++ b/seed/python-sdk/circular-references-advanced/src/seed/core/http_client.py @@ -77,7 +77,9 @@ def _retry_timeout(response: httpx.Response, retries: int) -> float: return retry_after # Apply exponential backoff, capped at MAX_RETRY_DELAY_SECONDS. - retry_delay = min(INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS) + retry_delay = min( + INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS + ) # Add a randomness / jitter to the retry delay to avoid overwhelming the server with retries. timeout = retry_delay * (1 - 0.25 * random()) @@ -90,7 +92,8 @@ def _should_retry(response: httpx.Response) -> bool: def remove_omit_from_dict( - original: typing.Dict[str, typing.Optional[typing.Any]], omit: typing.Optional[typing.Any] + original: typing.Dict[str, typing.Optional[typing.Any]], + omit: typing.Optional[typing.Any], ) -> typing.Dict[str, typing.Any]: if omit is None: return original @@ -108,7 +111,8 @@ def maybe_filter_request_body( ) -> typing.Optional[typing.Any]: if data is None: return ( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else None ) @@ -118,7 +122,8 @@ def maybe_filter_request_body( data_content = { **(jsonable_encoder(remove_omit_from_dict(data, omit))), # type: ignore **( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else {} ), @@ -162,7 +167,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url def request( @@ -174,8 +181,12 @@ def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -184,11 +195,14 @@ def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) response = self.httpx_client.request( method=method, @@ -198,7 +212,11 @@ def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -209,7 +227,10 @@ def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -222,11 +243,15 @@ def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: time.sleep(_retry_timeout(response=response, retries=retries)) @@ -256,8 +281,12 @@ def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -266,11 +295,14 @@ def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) with self.httpx_client.stream( method=method, @@ -280,7 +312,11 @@ def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -291,7 +327,9 @@ def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -304,7 +342,9 @@ def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream @@ -327,7 +367,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url async def request( @@ -339,8 +381,12 @@ async def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -349,11 +395,14 @@ async def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) # Add the input to each of these and do None-safety checks response = await self.httpx_client.request( @@ -364,7 +413,11 @@ async def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -375,7 +428,10 @@ async def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -388,11 +444,15 @@ async def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: await asyncio.sleep(_retry_timeout(response=response, retries=retries)) @@ -421,8 +481,12 @@ async def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -431,11 +495,14 @@ async def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) async with self.httpx_client.stream( method=method, @@ -445,7 +512,11 @@ async def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -456,7 +527,9 @@ async def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -469,7 +542,9 @@ async def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream diff --git a/seed/python-sdk/circular-references-advanced/src/seed/core/jsonable_encoder.py b/seed/python-sdk/circular-references-advanced/src/seed/core/jsonable_encoder.py index d3fd328fd41..12a8b52fc22 100644 --- a/seed/python-sdk/circular-references-advanced/src/seed/core/jsonable_encoder.py +++ b/seed/python-sdk/circular-references-advanced/src/seed/core/jsonable_encoder.py @@ -19,13 +19,19 @@ import pydantic from .datetime_utils import serialize_datetime -from .pydantic_utilities import IS_PYDANTIC_V2, encode_by_type, to_jsonable_with_fallback +from .pydantic_utilities import ( + IS_PYDANTIC_V2, + encode_by_type, + to_jsonable_with_fallback, +) SetIntStr = Set[Union[int, str]] DictIntStrAny = Dict[Union[int, str], Any] -def jsonable_encoder(obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None) -> Any: +def jsonable_encoder( + obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None +) -> Any: custom_encoder = custom_encoder or {} if custom_encoder: if type(obj) in custom_encoder: diff --git a/seed/python-sdk/circular-references-advanced/src/seed/core/pydantic_utilities.py b/seed/python-sdk/circular-references-advanced/src/seed/core/pydantic_utilities.py index 170a563d6eb..c63935c32a2 100644 --- a/seed/python-sdk/circular-references-advanced/src/seed/core/pydantic_utilities.py +++ b/seed/python-sdk/circular-references-advanced/src/seed/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) # type: ignore # Pydantic v1 diff --git a/seed/python-sdk/circular-references-advanced/src/seed/core/query_encoder.py b/seed/python-sdk/circular-references-advanced/src/seed/core/query_encoder.py index 24076d72ee9..7cb98f52cd7 100644 --- a/seed/python-sdk/circular-references-advanced/src/seed/core/query_encoder.py +++ b/seed/python-sdk/circular-references-advanced/src/seed/core/query_encoder.py @@ -7,7 +7,9 @@ # Flattens dicts to be of the form {"key[subkey][subkey2]": value} where value is not a dict -def traverse_query_dict(dict_flat: Dict[str, Any], key_prefix: Optional[str] = None) -> Dict[str, Any]: +def traverse_query_dict( + dict_flat: Dict[str, Any], key_prefix: Optional[str] = None +) -> Dict[str, Any]: result = {} for k, v in dict_flat.items(): key = f"{key_prefix}[{k}]" if key_prefix is not None else k @@ -30,4 +32,8 @@ def single_query_encoder(query_key: str, query_value: Any) -> Dict[str, Any]: def encode_query(query: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: - return dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) if query is not None else None + return ( + dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) + if query is not None + else None + ) diff --git a/seed/python-sdk/circular-references-advanced/src/seed/core/serialization.py b/seed/python-sdk/circular-references-advanced/src/seed/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/python-sdk/circular-references-advanced/src/seed/core/serialization.py +++ b/seed/python-sdk/circular-references-advanced/src/seed/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/python-sdk/circular-references-advanced/src/seed/types/importing_a.py b/seed/python-sdk/circular-references-advanced/src/seed/types/importing_a.py index 9d97e997eb6..f4ca1e67ffb 100644 --- a/seed/python-sdk/circular-references-advanced/src/seed/types/importing_a.py +++ b/seed/python-sdk/circular-references-advanced/src/seed/types/importing_a.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from ..core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - from ..a.types.a import A -from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ..core.pydantic_utilities import IS_PYDANTIC_V2 +import pydantic class ImportingA(UniversalBaseModel): a: typing.Optional[A] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/circular-references-advanced/src/seed/types/root_type.py b/seed/python-sdk/circular-references-advanced/src/seed/types/root_type.py index 7fbb44001a6..972cd0aae3a 100644 --- a/seed/python-sdk/circular-references-advanced/src/seed/types/root_type.py +++ b/seed/python-sdk/circular-references-advanced/src/seed/types/root_type.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ..core.pydantic_utilities import UniversalBaseModel +from ..core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class RootType(UniversalBaseModel): s: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/circular-references-advanced/src/seed/version.py b/seed/python-sdk/circular-references-advanced/src/seed/version.py index 030d15b3c74..8bceace9866 100644 --- a/seed/python-sdk/circular-references-advanced/src/seed/version.py +++ b/seed/python-sdk/circular-references-advanced/src/seed/version.py @@ -1,4 +1,3 @@ - from importlib import metadata __version__ = metadata.version("fern_circular-references-advanced") diff --git a/seed/python-sdk/circular-references-advanced/tests/conftest.py b/seed/python-sdk/circular-references-advanced/tests/conftest.py index c39a48a47ef..f92e935f947 100644 --- a/seed/python-sdk/circular-references-advanced/tests/conftest.py +++ b/seed/python-sdk/circular-references-advanced/tests/conftest.py @@ -1,9 +1,9 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedApi import os - import pytest -from seed import AsyncSeedApi, SeedApi +from seed import AsyncSeedApi @pytest.fixture diff --git a/seed/python-sdk/circular-references-advanced/tests/custom/test_client.py b/seed/python-sdk/circular-references-advanced/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/python-sdk/circular-references-advanced/tests/custom/test_client.py +++ b/seed/python-sdk/circular-references-advanced/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/python-sdk/circular-references-advanced/tests/utilities.py b/seed/python-sdk/circular-references-advanced/tests/utilities.py index 13da208eb3a..e8f4472564c 100644 --- a/seed/python-sdk/circular-references-advanced/tests/utilities.py +++ b/seed/python-sdk/circular-references-advanced/tests/utilities.py @@ -3,11 +3,14 @@ import typing import uuid -import pydantic from dateutil import parser +import pydantic + -def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> typing.Any: +def cast_field( + json_expectation: typing.Any, type_expectation: typing.Any +) -> typing.Any: # Cast these specific types which come through as string and expect our # models to cast to the correct type. if type_expectation == "uuid": @@ -25,7 +28,9 @@ def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> ty return json_expectation -def validate_field(response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any) -> None: +def validate_field( + response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectation == "no_validate": return @@ -44,7 +49,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(entry_expectation, dict): is_container_of_complex_type = True validate_response( - response=response[idx], json_expectation=ex, type_expectations=entry_expectation + response=response[idx], + json_expectation=ex, + type_expectations=entry_expectation, ) else: cast_json_expectation.append(cast_field(ex, entry_expectation)) @@ -56,7 +63,10 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # if any of the values of the set have a type_expectation of a dict, we're assuming it's a pydantic # model and keeping it a list. if container_expectation != "set" or not any( - map(lambda value: isinstance(value, dict), list(contents_expectation.values())) + map( + lambda value: isinstance(value, dict), + list(contents_expectation.values()), + ) ): json_expectation = cast_field(json_expectation, container_expectation) elif isinstance(type_expectation, tuple): @@ -65,9 +75,15 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(contents_expectation, dict): json_expectation = { cast_field( - key, contents_expectation.get(idx)[0] if contents_expectation.get(idx) is not None else None # type: ignore + key, + contents_expectation.get(idx)[0] + if contents_expectation.get(idx) is not None + else None, # type: ignore ): cast_field( - value, contents_expectation.get(idx)[1] if contents_expectation.get(idx) is not None else None # type: ignore + value, + contents_expectation.get(idx)[1] + if contents_expectation.get(idx) is not None + else None, # type: ignore ) for idx, (key, value) in enumerate(json_expectation.items()) } @@ -86,7 +102,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # Arg type_expectations is a deeply nested structure that matches the response, but with the values replaced with the expected types -def validate_response(response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any) -> None: +def validate_response( + response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectations == "no_validate": return @@ -96,11 +114,17 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e and not isinstance(response, dict) and not issubclass(type(response), pydantic.BaseModel) ): - validate_field(response=response, json_expectation=json_expectation, type_expectation=type_expectations) + validate_field( + response=response, + json_expectation=json_expectation, + type_expectation=type_expectations, + ) return if isinstance(response, list): - assert len(response) == len(json_expectation), "Length mismatch, expected: {0}, Actual: {1}".format( + assert len(response) == len( + json_expectation + ), "Length mismatch, expected: {0}, Actual: {1}".format( len(response), len(json_expectation) ) content_expectation = type_expectations @@ -108,7 +132,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e content_expectation = type_expectations[1] for idx, item in enumerate(response): validate_response( - response=item, json_expectation=json_expectation[idx], type_expectations=content_expectation[idx] + response=item, + json_expectation=json_expectation[idx], + type_expectations=content_expectation[idx], ) else: response_json = response @@ -116,7 +142,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e response_json = response.dict(by_alias=True) for key, value in json_expectation.items(): - assert key in response_json, "Field {0} not found within the response object: {1}".format( + assert ( + key in response_json + ), "Field {0} not found within the response object: {1}".format( key, response_json ) @@ -128,11 +156,19 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e # Otherwise, we're just validating a single field that's a pydantic model. if isinstance(value, dict) and not isinstance(type_expectation, tuple): validate_response( - response=response_json[key], json_expectation=value, type_expectations=type_expectation + response=response_json[key], + json_expectation=value, + type_expectations=type_expectation, ) else: - validate_field(response=response_json[key], json_expectation=value, type_expectation=type_expectation) + validate_field( + response=response_json[key], + json_expectation=value, + type_expectation=type_expectation, + ) # Ensure there are no additional fields here either del response_json[key] - assert len(response_json) == 0, "Additional fields found, expected None: {0}".format(response_json) + assert ( + len(response_json) == 0 + ), "Additional fields found, expected None: {0}".format(response_json) diff --git a/seed/python-sdk/circular-references-advanced/tests/utils/assets/models/__init__.py b/seed/python-sdk/circular-references-advanced/tests/utils/assets/models/__init__.py index 2cf01263529..3a1c852e71e 100644 --- a/seed/python-sdk/circular-references-advanced/tests/utils/assets/models/__init__.py +++ b/seed/python-sdk/circular-references-advanced/tests/utils/assets/models/__init__.py @@ -5,7 +5,7 @@ from .circle import CircleParams from .object_with_defaults import ObjectWithDefaultsParams from .object_with_optional_field import ObjectWithOptionalFieldParams -from .shape import Shape_CircleParams, Shape_SquareParams, ShapeParams +from .shape import ShapeParams, Shape_CircleParams, Shape_SquareParams from .square import SquareParams from .undiscriminated_shape import UndiscriminatedShapeParams diff --git a/seed/python-sdk/circular-references-advanced/tests/utils/assets/models/circle.py b/seed/python-sdk/circular-references-advanced/tests/utils/assets/models/circle.py index af7a1bf8a8e..253f12d38b3 100644 --- a/seed/python-sdk/circular-references-advanced/tests/utils/assets/models/circle.py +++ b/seed/python-sdk/circular-references-advanced/tests/utils/assets/models/circle.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class CircleParams(typing_extensions.TypedDict): - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] diff --git a/seed/python-sdk/circular-references-advanced/tests/utils/assets/models/object_with_optional_field.py b/seed/python-sdk/circular-references-advanced/tests/utils/assets/models/object_with_optional_field.py index 3ad93d5f305..ebe7dc80547 100644 --- a/seed/python-sdk/circular-references-advanced/tests/utils/assets/models/object_with_optional_field.py +++ b/seed/python-sdk/circular-references-advanced/tests/utils/assets/models/object_with_optional_field.py @@ -7,8 +7,8 @@ import uuid import typing_extensions -from seed.core.serialization import FieldMetadata +from seed.core.serialization import FieldMetadata from .color import Color from .shape import ShapeParams from .undiscriminated_shape import UndiscriminatedShapeParams @@ -18,16 +18,30 @@ class ObjectWithOptionalFieldParams(typing_extensions.TypedDict): literal: typing.Literal["lit_one"] string: typing_extensions.NotRequired[str] integer: typing_extensions.NotRequired[int] - long_: typing_extensions.NotRequired[typing_extensions.Annotated[int, FieldMetadata(alias="long")]] + long_: typing_extensions.NotRequired[ + typing_extensions.Annotated[int, FieldMetadata(alias="long")] + ] double: typing_extensions.NotRequired[float] - bool_: typing_extensions.NotRequired[typing_extensions.Annotated[bool, FieldMetadata(alias="bool")]] + bool_: typing_extensions.NotRequired[ + typing_extensions.Annotated[bool, FieldMetadata(alias="bool")] + ] datetime: typing_extensions.NotRequired[dt.datetime] date: typing_extensions.NotRequired[dt.date] - uuid_: typing_extensions.NotRequired[typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")]] - base_64: typing_extensions.NotRequired[typing_extensions.Annotated[str, FieldMetadata(alias="base64")]] - list_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")]] - set_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")]] - map_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")]] + uuid_: typing_extensions.NotRequired[ + typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")] + ] + base_64: typing_extensions.NotRequired[ + typing_extensions.Annotated[str, FieldMetadata(alias="base64")] + ] + list_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")] + ] + set_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")] + ] + map_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")] + ] enum: typing_extensions.NotRequired[Color] union: typing_extensions.NotRequired[ShapeParams] second_union: typing_extensions.NotRequired[ShapeParams] diff --git a/seed/python-sdk/circular-references-advanced/tests/utils/assets/models/shape.py b/seed/python-sdk/circular-references-advanced/tests/utils/assets/models/shape.py index 2c33c877951..816ffc51bdc 100644 --- a/seed/python-sdk/circular-references-advanced/tests/utils/assets/models/shape.py +++ b/seed/python-sdk/circular-references-advanced/tests/utils/assets/models/shape.py @@ -7,6 +7,7 @@ import typing import typing_extensions + from seed.core.serialization import FieldMetadata @@ -15,13 +16,21 @@ class Base(typing_extensions.TypedDict): class Shape_CircleParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["circle"], FieldMetadata(alias="shapeType")] - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["circle"], FieldMetadata(alias="shapeType") + ] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] class Shape_SquareParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["square"], FieldMetadata(alias="shapeType")] - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["square"], FieldMetadata(alias="shapeType") + ] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] ShapeParams = typing.Union[Shape_CircleParams, Shape_SquareParams] diff --git a/seed/python-sdk/circular-references-advanced/tests/utils/assets/models/square.py b/seed/python-sdk/circular-references-advanced/tests/utils/assets/models/square.py index b9b7dd319bc..bcf08a723c5 100644 --- a/seed/python-sdk/circular-references-advanced/tests/utils/assets/models/square.py +++ b/seed/python-sdk/circular-references-advanced/tests/utils/assets/models/square.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class SquareParams(typing_extensions.TypedDict): - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] diff --git a/seed/python-sdk/circular-references-advanced/tests/utils/test_http_client.py b/seed/python-sdk/circular-references-advanced/tests/utils/test_http_client.py index edd11ca7afb..f5a874a75f3 100644 --- a/seed/python-sdk/circular-references-advanced/tests/utils/test_http_client.py +++ b/seed/python-sdk/circular-references-advanced/tests/utils/test_http_client.py @@ -9,12 +9,17 @@ def get_request_options() -> RequestOptions: def test_get_json_request_body() -> None: - json_body, data_body = get_request_body(json={"hello": "world"}, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json={"hello": "world"}, data=None, request_options=None, omit=None + ) assert json_body == {"hello": "world"} assert data_body is None json_body_extras, data_body_extras = get_request_body( - json={"goodbye": "world"}, data=None, request_options=get_request_options(), omit=None + json={"goodbye": "world"}, + data=None, + request_options=get_request_options(), + omit=None, ) assert json_body_extras == {"goodbye": "world", "see you": "later"} @@ -22,12 +27,17 @@ def test_get_json_request_body() -> None: def test_get_files_request_body() -> None: - json_body, data_body = get_request_body(json=None, data={"hello": "world"}, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data={"hello": "world"}, request_options=None, omit=None + ) assert data_body == {"hello": "world"} assert json_body is None json_body_extras, data_body_extras = get_request_body( - json=None, data={"goodbye": "world"}, request_options=get_request_options(), omit=None + json=None, + data={"goodbye": "world"}, + request_options=get_request_options(), + omit=None, ) assert data_body_extras == {"goodbye": "world", "see you": "later"} @@ -35,7 +45,9 @@ def test_get_files_request_body() -> None: def test_get_none_request_body() -> None: - json_body, data_body = get_request_body(json=None, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data=None, request_options=None, omit=None + ) assert data_body is None assert json_body is None diff --git a/seed/python-sdk/circular-references-advanced/tests/utils/test_query_encoding.py b/seed/python-sdk/circular-references-advanced/tests/utils/test_query_encoding.py index 247e1551b46..fbc8f402167 100644 --- a/seed/python-sdk/circular-references-advanced/tests/utils/test_query_encoding.py +++ b/seed/python-sdk/circular-references-advanced/tests/utils/test_query_encoding.py @@ -4,9 +4,15 @@ def test_query_encoding() -> None: - assert encode_query({"hello world": "hello world"}) == {"hello world": "hello world"} - assert encode_query({"hello_world": {"hello": "world"}}) == {"hello_world[hello]": "world"} - assert encode_query({"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"}) == { + assert encode_query({"hello world": "hello world"}) == { + "hello world": "hello world" + } + assert encode_query({"hello_world": {"hello": "world"}}) == { + "hello_world[hello]": "world" + } + assert encode_query( + {"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"} + ) == { "hello_world[hello][world]": "today", "hello_world[test]": "this", "hi": "there", diff --git a/seed/python-sdk/circular-references-advanced/tests/utils/test_serialization.py b/seed/python-sdk/circular-references-advanced/tests/utils/test_serialization.py index 58b1ed66e6d..5ca956916dd 100644 --- a/seed/python-sdk/circular-references-advanced/tests/utils/test_serialization.py +++ b/seed/python-sdk/circular-references-advanced/tests/utils/test_serialization.py @@ -1,10 +1,12 @@ # This file was auto-generated by Fern from our API Definition. -from typing import Any, List +from typing import List, Any -from seed.core.serialization import convert_and_respect_annotation_metadata +from seed.core.serialization import ( + convert_and_respect_annotation_metadata, +) +from .assets.models import ShapeParams, ObjectWithOptionalFieldParams -from .assets.models import ObjectWithOptionalFieldParams, ShapeParams UNION_TEST: ShapeParams = {"radius_measurement": 1.0, "shape_type": "circle", "id": "1"} UNION_TEST_CONVERTED = {"shapeType": "circle", "radiusMeasurement": 1.0, "id": "1"} @@ -18,20 +20,54 @@ def test_convert_and_respect_annotation_metadata() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) - assert converted == {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"} + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) + assert converted == { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + } def test_convert_and_respect_annotation_metadata_in_list() -> None: data: List[ObjectWithOptionalFieldParams] = [ - {"string": "string", "long_": 12345, "bool_": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long_": 67890, "list_": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long_": 12345, + "bool_": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long_": 67890, + "list_": [], + "literal": "lit_one", + "any": "any", + }, ] - converted = convert_and_respect_annotation_metadata(object_=data, annotation=List[ObjectWithOptionalFieldParams]) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=List[ObjectWithOptionalFieldParams] + ) assert converted == [ - {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long": 67890, "list": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long": 67890, + "list": [], + "literal": "lit_one", + "any": "any", + }, ] @@ -43,7 +79,9 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) assert converted == { "string": "string", @@ -55,12 +93,16 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: def test_convert_and_respect_annotation_metadata_in_union() -> None: - converted = convert_and_respect_annotation_metadata(object_=UNION_TEST, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=UNION_TEST, annotation=ShapeParams + ) assert converted == UNION_TEST_CONVERTED def test_convert_and_respect_annotation_metadata_with_empty_object() -> None: data: Any = {} - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ShapeParams + ) assert converted == data diff --git a/seed/python-sdk/circular-references/pyproject.toml b/seed/python-sdk/circular-references/pyproject.toml index f1638c2b9fb..6319de4f5a2 100644 --- a/seed/python-sdk/circular-references/pyproject.toml +++ b/seed/python-sdk/circular-references/pyproject.toml @@ -43,6 +43,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/python-sdk/circular-references/src/seed/a/types/a.py b/seed/python-sdk/circular-references/src/seed/a/types/a.py index 1333d010963..d5352cca952 100644 --- a/seed/python-sdk/circular-references/src/seed/a/types/a.py +++ b/seed/python-sdk/circular-references/src/seed/a/types/a.py @@ -1,16 +1,16 @@ # This file was auto-generated by Fern from our API Definition. +from ...types.root_type import RootType +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2 -from ...types.root_type import RootType - class A(RootType): if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/circular-references/src/seed/ast/types/__init__.py b/seed/python-sdk/circular-references/src/seed/ast/types/__init__.py index a820a4eea37..10dd40bdd5b 100644 --- a/seed/python-sdk/circular-references/src/seed/ast/types/__init__.py +++ b/seed/python-sdk/circular-references/src/seed/ast/types/__init__.py @@ -1,7 +1,16 @@ # This file was auto-generated by Fern from our API Definition. -from .container_value import ContainerValue, ContainerValue_List, ContainerValue_Optional -from .field_value import FieldValue, FieldValue_ContainerValue, FieldValue_ObjectValue, FieldValue_PrimitiveValue +from .container_value import ( + ContainerValue, + ContainerValue_List, + ContainerValue_Optional, +) +from .field_value import ( + FieldValue, + FieldValue_ContainerValue, + FieldValue_ObjectValue, + FieldValue_PrimitiveValue, +) from .object_value import ObjectValue from .primitive_value import PrimitiveValue diff --git a/seed/python-sdk/circular-references/src/seed/ast/types/container_value.py b/seed/python-sdk/circular-references/src/seed/ast/types/container_value.py index eb0977022bb..a29a9c7bff3 100644 --- a/seed/python-sdk/circular-references/src/seed/ast/types/container_value.py +++ b/seed/python-sdk/circular-references/src/seed/ast/types/container_value.py @@ -1,14 +1,13 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ...core.pydantic_utilities import UniversalBaseModel import typing - +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel, update_forward_refs from .object_value import ObjectValue from .primitive_value import PrimitiveValue +from ...core.pydantic_utilities import update_forward_refs class ContainerValue_List(UniversalBaseModel): @@ -16,7 +15,9 @@ class ContainerValue_List(UniversalBaseModel): type: typing.Literal["list"] = "list" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + frozen=True + ) # type: ignore # Pydantic v2 else: class Config: @@ -29,7 +30,9 @@ class ContainerValue_Optional(UniversalBaseModel): type: typing.Literal["optional"] = "optional" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/circular-references/src/seed/ast/types/field_value.py b/seed/python-sdk/circular-references/src/seed/ast/types/field_value.py index 1e1ce6a3bcb..865121656b6 100644 --- a/seed/python-sdk/circular-references/src/seed/ast/types/field_value.py +++ b/seed/python-sdk/circular-references/src/seed/ast/types/field_value.py @@ -1,13 +1,12 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ...core.pydantic_utilities import UniversalBaseModel +from .primitive_value import PrimitiveValue import typing - +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel, update_forward_refs -from .primitive_value import PrimitiveValue +from ...core.pydantic_utilities import update_forward_refs class FieldValue_PrimitiveValue(UniversalBaseModel): @@ -15,7 +14,9 @@ class FieldValue_PrimitiveValue(UniversalBaseModel): type: typing.Literal["primitive_value"] = "primitive_value" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + frozen=True + ) # type: ignore # Pydantic v2 else: class Config: @@ -27,7 +28,9 @@ class FieldValue_ObjectValue(UniversalBaseModel): type: typing.Literal["object_value"] = "object_value" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: @@ -41,7 +44,9 @@ class FieldValue_ContainerValue(UniversalBaseModel): type: typing.Literal["container_value"] = "container_value" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + frozen=True + ) # type: ignore # Pydantic v2 else: class Config: @@ -49,7 +54,9 @@ class Config: smart_union = True -FieldValue = typing.Union[FieldValue_PrimitiveValue, FieldValue_ObjectValue, FieldValue_ContainerValue] +FieldValue = typing.Union[ + FieldValue_PrimitiveValue, FieldValue_ObjectValue, FieldValue_ContainerValue +] from .container_value import ContainerValue # noqa: E402 update_forward_refs(FieldValue_ContainerValue, ContainerValue=ContainerValue) diff --git a/seed/python-sdk/circular-references/src/seed/ast/types/object_value.py b/seed/python-sdk/circular-references/src/seed/ast/types/object_value.py index 07b7f2038c9..47b3da57340 100644 --- a/seed/python-sdk/circular-references/src/seed/ast/types/object_value.py +++ b/seed/python-sdk/circular-references/src/seed/ast/types/object_value.py @@ -1,15 +1,16 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class ObjectValue(UniversalBaseModel): if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/circular-references/src/seed/client.py b/seed/python-sdk/circular-references/src/seed/client.py index c1e3be6d4d3..6940f7b8880 100644 --- a/seed/python-sdk/circular-references/src/seed/client.py +++ b/seed/python-sdk/circular-references/src/seed/client.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .core.client_wrapper import AsyncClientWrapper, SyncClientWrapper +from .core.client_wrapper import SyncClientWrapper +from .core.client_wrapper import AsyncClientWrapper class SeedApi: @@ -40,14 +39,18 @@ def __init__( base_url: str, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.Client] = None + httpx_client: typing.Optional[httpx.Client] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = SyncClientWrapper( base_url=base_url, httpx_client=httpx_client if httpx_client is not None - else httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.Client( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.Client(timeout=_defaulted_timeout), timeout=_defaulted_timeout, @@ -87,14 +90,18 @@ def __init__( base_url: str, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.AsyncClient] = None + httpx_client: typing.Optional[httpx.AsyncClient] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = AsyncClientWrapper( base_url=base_url, httpx_client=httpx_client if httpx_client is not None - else httpx.AsyncClient(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.AsyncClient( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.AsyncClient(timeout=_defaulted_timeout), timeout=_defaulted_timeout, diff --git a/seed/python-sdk/circular-references/src/seed/core/api_error.py b/seed/python-sdk/circular-references/src/seed/core/api_error.py index 2e9fc5431cd..da734b58068 100644 --- a/seed/python-sdk/circular-references/src/seed/core/api_error.py +++ b/seed/python-sdk/circular-references/src/seed/core/api_error.py @@ -7,7 +7,9 @@ class ApiError(Exception): status_code: typing.Optional[int] body: typing.Any - def __init__(self, *, status_code: typing.Optional[int] = None, body: typing.Any = None): + def __init__( + self, *, status_code: typing.Optional[int] = None, body: typing.Any = None + ): self.status_code = status_code self.body = body diff --git a/seed/python-sdk/circular-references/src/seed/core/client_wrapper.py b/seed/python-sdk/circular-references/src/seed/core/client_wrapper.py index f6aeb28ed8d..4bc693a73ca 100644 --- a/seed/python-sdk/circular-references/src/seed/core/client_wrapper.py +++ b/seed/python-sdk/circular-references/src/seed/core/client_wrapper.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .http_client import AsyncHttpClient, HttpClient +from .http_client import HttpClient +from .http_client import AsyncHttpClient class BaseClientWrapper: @@ -28,7 +27,13 @@ def get_timeout(self) -> typing.Optional[float]: class SyncClientWrapper(BaseClientWrapper): - def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, httpx_client: httpx.Client): + def __init__( + self, + *, + base_url: str, + timeout: typing.Optional[float] = None, + httpx_client: httpx.Client, + ): super().__init__(base_url=base_url, timeout=timeout) self.httpx_client = HttpClient( httpx_client=httpx_client, @@ -39,7 +44,13 @@ def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, htt class AsyncClientWrapper(BaseClientWrapper): - def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, httpx_client: httpx.AsyncClient): + def __init__( + self, + *, + base_url: str, + timeout: typing.Optional[float] = None, + httpx_client: httpx.AsyncClient, + ): super().__init__(base_url=base_url, timeout=timeout) self.httpx_client = AsyncHttpClient( httpx_client=httpx_client, diff --git a/seed/python-sdk/circular-references/src/seed/core/datetime_utils.py b/seed/python-sdk/circular-references/src/seed/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/python-sdk/circular-references/src/seed/core/datetime_utils.py +++ b/seed/python-sdk/circular-references/src/seed/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/python-sdk/circular-references/src/seed/core/file.py b/seed/python-sdk/circular-references/src/seed/core/file.py index cb0d40bbbf3..6e0f92bfcb1 100644 --- a/seed/python-sdk/circular-references/src/seed/core/file.py +++ b/seed/python-sdk/circular-references/src/seed/core/file.py @@ -13,12 +13,17 @@ # (filename, file (or bytes), content_type) typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str]], # (filename, file (or bytes), content_type, headers) - typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str], typing.Mapping[str, str]], + typing.Tuple[ + typing.Optional[str], + FileContent, + typing.Optional[str], + typing.Mapping[str, str], + ], ] def convert_file_dict_to_httpx_tuples( - d: typing.Dict[str, typing.Union[File, typing.List[File]]] + d: typing.Dict[str, typing.Union[File, typing.List[File]]], ) -> typing.List[typing.Tuple[str, File]]: """ The format we use is a list of tuples, where the first element is the diff --git a/seed/python-sdk/circular-references/src/seed/core/http_client.py b/seed/python-sdk/circular-references/src/seed/core/http_client.py index 9333d8a7f15..091f71bc185 100644 --- a/seed/python-sdk/circular-references/src/seed/core/http_client.py +++ b/seed/python-sdk/circular-references/src/seed/core/http_client.py @@ -77,7 +77,9 @@ def _retry_timeout(response: httpx.Response, retries: int) -> float: return retry_after # Apply exponential backoff, capped at MAX_RETRY_DELAY_SECONDS. - retry_delay = min(INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS) + retry_delay = min( + INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS + ) # Add a randomness / jitter to the retry delay to avoid overwhelming the server with retries. timeout = retry_delay * (1 - 0.25 * random()) @@ -90,7 +92,8 @@ def _should_retry(response: httpx.Response) -> bool: def remove_omit_from_dict( - original: typing.Dict[str, typing.Optional[typing.Any]], omit: typing.Optional[typing.Any] + original: typing.Dict[str, typing.Optional[typing.Any]], + omit: typing.Optional[typing.Any], ) -> typing.Dict[str, typing.Any]: if omit is None: return original @@ -108,7 +111,8 @@ def maybe_filter_request_body( ) -> typing.Optional[typing.Any]: if data is None: return ( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else None ) @@ -118,7 +122,8 @@ def maybe_filter_request_body( data_content = { **(jsonable_encoder(remove_omit_from_dict(data, omit))), # type: ignore **( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else {} ), @@ -162,7 +167,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url def request( @@ -174,8 +181,12 @@ def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -184,11 +195,14 @@ def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) response = self.httpx_client.request( method=method, @@ -198,7 +212,11 @@ def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -209,7 +227,10 @@ def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -222,11 +243,15 @@ def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: time.sleep(_retry_timeout(response=response, retries=retries)) @@ -256,8 +281,12 @@ def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -266,11 +295,14 @@ def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) with self.httpx_client.stream( method=method, @@ -280,7 +312,11 @@ def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -291,7 +327,9 @@ def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -304,7 +342,9 @@ def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream @@ -327,7 +367,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url async def request( @@ -339,8 +381,12 @@ async def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -349,11 +395,14 @@ async def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) # Add the input to each of these and do None-safety checks response = await self.httpx_client.request( @@ -364,7 +413,11 @@ async def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -375,7 +428,10 @@ async def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -388,11 +444,15 @@ async def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: await asyncio.sleep(_retry_timeout(response=response, retries=retries)) @@ -421,8 +481,12 @@ async def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -431,11 +495,14 @@ async def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) async with self.httpx_client.stream( method=method, @@ -445,7 +512,11 @@ async def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -456,7 +527,9 @@ async def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -469,7 +542,9 @@ async def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream diff --git a/seed/python-sdk/circular-references/src/seed/core/jsonable_encoder.py b/seed/python-sdk/circular-references/src/seed/core/jsonable_encoder.py index d3fd328fd41..12a8b52fc22 100644 --- a/seed/python-sdk/circular-references/src/seed/core/jsonable_encoder.py +++ b/seed/python-sdk/circular-references/src/seed/core/jsonable_encoder.py @@ -19,13 +19,19 @@ import pydantic from .datetime_utils import serialize_datetime -from .pydantic_utilities import IS_PYDANTIC_V2, encode_by_type, to_jsonable_with_fallback +from .pydantic_utilities import ( + IS_PYDANTIC_V2, + encode_by_type, + to_jsonable_with_fallback, +) SetIntStr = Set[Union[int, str]] DictIntStrAny = Dict[Union[int, str], Any] -def jsonable_encoder(obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None) -> Any: +def jsonable_encoder( + obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None +) -> Any: custom_encoder = custom_encoder or {} if custom_encoder: if type(obj) in custom_encoder: diff --git a/seed/python-sdk/circular-references/src/seed/core/pydantic_utilities.py b/seed/python-sdk/circular-references/src/seed/core/pydantic_utilities.py index 170a563d6eb..c63935c32a2 100644 --- a/seed/python-sdk/circular-references/src/seed/core/pydantic_utilities.py +++ b/seed/python-sdk/circular-references/src/seed/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) # type: ignore # Pydantic v1 diff --git a/seed/python-sdk/circular-references/src/seed/core/query_encoder.py b/seed/python-sdk/circular-references/src/seed/core/query_encoder.py index 24076d72ee9..7cb98f52cd7 100644 --- a/seed/python-sdk/circular-references/src/seed/core/query_encoder.py +++ b/seed/python-sdk/circular-references/src/seed/core/query_encoder.py @@ -7,7 +7,9 @@ # Flattens dicts to be of the form {"key[subkey][subkey2]": value} where value is not a dict -def traverse_query_dict(dict_flat: Dict[str, Any], key_prefix: Optional[str] = None) -> Dict[str, Any]: +def traverse_query_dict( + dict_flat: Dict[str, Any], key_prefix: Optional[str] = None +) -> Dict[str, Any]: result = {} for k, v in dict_flat.items(): key = f"{key_prefix}[{k}]" if key_prefix is not None else k @@ -30,4 +32,8 @@ def single_query_encoder(query_key: str, query_value: Any) -> Dict[str, Any]: def encode_query(query: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: - return dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) if query is not None else None + return ( + dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) + if query is not None + else None + ) diff --git a/seed/python-sdk/circular-references/src/seed/core/serialization.py b/seed/python-sdk/circular-references/src/seed/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/python-sdk/circular-references/src/seed/core/serialization.py +++ b/seed/python-sdk/circular-references/src/seed/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/python-sdk/circular-references/src/seed/types/importing_a.py b/seed/python-sdk/circular-references/src/seed/types/importing_a.py index 9d97e997eb6..f4ca1e67ffb 100644 --- a/seed/python-sdk/circular-references/src/seed/types/importing_a.py +++ b/seed/python-sdk/circular-references/src/seed/types/importing_a.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from ..core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - from ..a.types.a import A -from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ..core.pydantic_utilities import IS_PYDANTIC_V2 +import pydantic class ImportingA(UniversalBaseModel): a: typing.Optional[A] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/circular-references/src/seed/types/root_type.py b/seed/python-sdk/circular-references/src/seed/types/root_type.py index 7fbb44001a6..972cd0aae3a 100644 --- a/seed/python-sdk/circular-references/src/seed/types/root_type.py +++ b/seed/python-sdk/circular-references/src/seed/types/root_type.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ..core.pydantic_utilities import UniversalBaseModel +from ..core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class RootType(UniversalBaseModel): s: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/circular-references/src/seed/version.py b/seed/python-sdk/circular-references/src/seed/version.py index 3a12073d406..ba33e102b5e 100644 --- a/seed/python-sdk/circular-references/src/seed/version.py +++ b/seed/python-sdk/circular-references/src/seed/version.py @@ -1,4 +1,3 @@ - from importlib import metadata __version__ = metadata.version("fern_circular-references") diff --git a/seed/python-sdk/circular-references/tests/conftest.py b/seed/python-sdk/circular-references/tests/conftest.py index c39a48a47ef..f92e935f947 100644 --- a/seed/python-sdk/circular-references/tests/conftest.py +++ b/seed/python-sdk/circular-references/tests/conftest.py @@ -1,9 +1,9 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedApi import os - import pytest -from seed import AsyncSeedApi, SeedApi +from seed import AsyncSeedApi @pytest.fixture diff --git a/seed/python-sdk/circular-references/tests/custom/test_client.py b/seed/python-sdk/circular-references/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/python-sdk/circular-references/tests/custom/test_client.py +++ b/seed/python-sdk/circular-references/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/python-sdk/circular-references/tests/utilities.py b/seed/python-sdk/circular-references/tests/utilities.py index 13da208eb3a..e8f4472564c 100644 --- a/seed/python-sdk/circular-references/tests/utilities.py +++ b/seed/python-sdk/circular-references/tests/utilities.py @@ -3,11 +3,14 @@ import typing import uuid -import pydantic from dateutil import parser +import pydantic + -def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> typing.Any: +def cast_field( + json_expectation: typing.Any, type_expectation: typing.Any +) -> typing.Any: # Cast these specific types which come through as string and expect our # models to cast to the correct type. if type_expectation == "uuid": @@ -25,7 +28,9 @@ def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> ty return json_expectation -def validate_field(response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any) -> None: +def validate_field( + response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectation == "no_validate": return @@ -44,7 +49,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(entry_expectation, dict): is_container_of_complex_type = True validate_response( - response=response[idx], json_expectation=ex, type_expectations=entry_expectation + response=response[idx], + json_expectation=ex, + type_expectations=entry_expectation, ) else: cast_json_expectation.append(cast_field(ex, entry_expectation)) @@ -56,7 +63,10 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # if any of the values of the set have a type_expectation of a dict, we're assuming it's a pydantic # model and keeping it a list. if container_expectation != "set" or not any( - map(lambda value: isinstance(value, dict), list(contents_expectation.values())) + map( + lambda value: isinstance(value, dict), + list(contents_expectation.values()), + ) ): json_expectation = cast_field(json_expectation, container_expectation) elif isinstance(type_expectation, tuple): @@ -65,9 +75,15 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(contents_expectation, dict): json_expectation = { cast_field( - key, contents_expectation.get(idx)[0] if contents_expectation.get(idx) is not None else None # type: ignore + key, + contents_expectation.get(idx)[0] + if contents_expectation.get(idx) is not None + else None, # type: ignore ): cast_field( - value, contents_expectation.get(idx)[1] if contents_expectation.get(idx) is not None else None # type: ignore + value, + contents_expectation.get(idx)[1] + if contents_expectation.get(idx) is not None + else None, # type: ignore ) for idx, (key, value) in enumerate(json_expectation.items()) } @@ -86,7 +102,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # Arg type_expectations is a deeply nested structure that matches the response, but with the values replaced with the expected types -def validate_response(response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any) -> None: +def validate_response( + response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectations == "no_validate": return @@ -96,11 +114,17 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e and not isinstance(response, dict) and not issubclass(type(response), pydantic.BaseModel) ): - validate_field(response=response, json_expectation=json_expectation, type_expectation=type_expectations) + validate_field( + response=response, + json_expectation=json_expectation, + type_expectation=type_expectations, + ) return if isinstance(response, list): - assert len(response) == len(json_expectation), "Length mismatch, expected: {0}, Actual: {1}".format( + assert len(response) == len( + json_expectation + ), "Length mismatch, expected: {0}, Actual: {1}".format( len(response), len(json_expectation) ) content_expectation = type_expectations @@ -108,7 +132,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e content_expectation = type_expectations[1] for idx, item in enumerate(response): validate_response( - response=item, json_expectation=json_expectation[idx], type_expectations=content_expectation[idx] + response=item, + json_expectation=json_expectation[idx], + type_expectations=content_expectation[idx], ) else: response_json = response @@ -116,7 +142,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e response_json = response.dict(by_alias=True) for key, value in json_expectation.items(): - assert key in response_json, "Field {0} not found within the response object: {1}".format( + assert ( + key in response_json + ), "Field {0} not found within the response object: {1}".format( key, response_json ) @@ -128,11 +156,19 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e # Otherwise, we're just validating a single field that's a pydantic model. if isinstance(value, dict) and not isinstance(type_expectation, tuple): validate_response( - response=response_json[key], json_expectation=value, type_expectations=type_expectation + response=response_json[key], + json_expectation=value, + type_expectations=type_expectation, ) else: - validate_field(response=response_json[key], json_expectation=value, type_expectation=type_expectation) + validate_field( + response=response_json[key], + json_expectation=value, + type_expectation=type_expectation, + ) # Ensure there are no additional fields here either del response_json[key] - assert len(response_json) == 0, "Additional fields found, expected None: {0}".format(response_json) + assert ( + len(response_json) == 0 + ), "Additional fields found, expected None: {0}".format(response_json) diff --git a/seed/python-sdk/circular-references/tests/utils/assets/models/__init__.py b/seed/python-sdk/circular-references/tests/utils/assets/models/__init__.py index 2cf01263529..3a1c852e71e 100644 --- a/seed/python-sdk/circular-references/tests/utils/assets/models/__init__.py +++ b/seed/python-sdk/circular-references/tests/utils/assets/models/__init__.py @@ -5,7 +5,7 @@ from .circle import CircleParams from .object_with_defaults import ObjectWithDefaultsParams from .object_with_optional_field import ObjectWithOptionalFieldParams -from .shape import Shape_CircleParams, Shape_SquareParams, ShapeParams +from .shape import ShapeParams, Shape_CircleParams, Shape_SquareParams from .square import SquareParams from .undiscriminated_shape import UndiscriminatedShapeParams diff --git a/seed/python-sdk/circular-references/tests/utils/assets/models/circle.py b/seed/python-sdk/circular-references/tests/utils/assets/models/circle.py index af7a1bf8a8e..253f12d38b3 100644 --- a/seed/python-sdk/circular-references/tests/utils/assets/models/circle.py +++ b/seed/python-sdk/circular-references/tests/utils/assets/models/circle.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class CircleParams(typing_extensions.TypedDict): - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] diff --git a/seed/python-sdk/circular-references/tests/utils/assets/models/object_with_optional_field.py b/seed/python-sdk/circular-references/tests/utils/assets/models/object_with_optional_field.py index 3ad93d5f305..ebe7dc80547 100644 --- a/seed/python-sdk/circular-references/tests/utils/assets/models/object_with_optional_field.py +++ b/seed/python-sdk/circular-references/tests/utils/assets/models/object_with_optional_field.py @@ -7,8 +7,8 @@ import uuid import typing_extensions -from seed.core.serialization import FieldMetadata +from seed.core.serialization import FieldMetadata from .color import Color from .shape import ShapeParams from .undiscriminated_shape import UndiscriminatedShapeParams @@ -18,16 +18,30 @@ class ObjectWithOptionalFieldParams(typing_extensions.TypedDict): literal: typing.Literal["lit_one"] string: typing_extensions.NotRequired[str] integer: typing_extensions.NotRequired[int] - long_: typing_extensions.NotRequired[typing_extensions.Annotated[int, FieldMetadata(alias="long")]] + long_: typing_extensions.NotRequired[ + typing_extensions.Annotated[int, FieldMetadata(alias="long")] + ] double: typing_extensions.NotRequired[float] - bool_: typing_extensions.NotRequired[typing_extensions.Annotated[bool, FieldMetadata(alias="bool")]] + bool_: typing_extensions.NotRequired[ + typing_extensions.Annotated[bool, FieldMetadata(alias="bool")] + ] datetime: typing_extensions.NotRequired[dt.datetime] date: typing_extensions.NotRequired[dt.date] - uuid_: typing_extensions.NotRequired[typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")]] - base_64: typing_extensions.NotRequired[typing_extensions.Annotated[str, FieldMetadata(alias="base64")]] - list_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")]] - set_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")]] - map_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")]] + uuid_: typing_extensions.NotRequired[ + typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")] + ] + base_64: typing_extensions.NotRequired[ + typing_extensions.Annotated[str, FieldMetadata(alias="base64")] + ] + list_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")] + ] + set_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")] + ] + map_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")] + ] enum: typing_extensions.NotRequired[Color] union: typing_extensions.NotRequired[ShapeParams] second_union: typing_extensions.NotRequired[ShapeParams] diff --git a/seed/python-sdk/circular-references/tests/utils/assets/models/shape.py b/seed/python-sdk/circular-references/tests/utils/assets/models/shape.py index 2c33c877951..816ffc51bdc 100644 --- a/seed/python-sdk/circular-references/tests/utils/assets/models/shape.py +++ b/seed/python-sdk/circular-references/tests/utils/assets/models/shape.py @@ -7,6 +7,7 @@ import typing import typing_extensions + from seed.core.serialization import FieldMetadata @@ -15,13 +16,21 @@ class Base(typing_extensions.TypedDict): class Shape_CircleParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["circle"], FieldMetadata(alias="shapeType")] - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["circle"], FieldMetadata(alias="shapeType") + ] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] class Shape_SquareParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["square"], FieldMetadata(alias="shapeType")] - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["square"], FieldMetadata(alias="shapeType") + ] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] ShapeParams = typing.Union[Shape_CircleParams, Shape_SquareParams] diff --git a/seed/python-sdk/circular-references/tests/utils/assets/models/square.py b/seed/python-sdk/circular-references/tests/utils/assets/models/square.py index b9b7dd319bc..bcf08a723c5 100644 --- a/seed/python-sdk/circular-references/tests/utils/assets/models/square.py +++ b/seed/python-sdk/circular-references/tests/utils/assets/models/square.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class SquareParams(typing_extensions.TypedDict): - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] diff --git a/seed/python-sdk/circular-references/tests/utils/test_http_client.py b/seed/python-sdk/circular-references/tests/utils/test_http_client.py index edd11ca7afb..f5a874a75f3 100644 --- a/seed/python-sdk/circular-references/tests/utils/test_http_client.py +++ b/seed/python-sdk/circular-references/tests/utils/test_http_client.py @@ -9,12 +9,17 @@ def get_request_options() -> RequestOptions: def test_get_json_request_body() -> None: - json_body, data_body = get_request_body(json={"hello": "world"}, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json={"hello": "world"}, data=None, request_options=None, omit=None + ) assert json_body == {"hello": "world"} assert data_body is None json_body_extras, data_body_extras = get_request_body( - json={"goodbye": "world"}, data=None, request_options=get_request_options(), omit=None + json={"goodbye": "world"}, + data=None, + request_options=get_request_options(), + omit=None, ) assert json_body_extras == {"goodbye": "world", "see you": "later"} @@ -22,12 +27,17 @@ def test_get_json_request_body() -> None: def test_get_files_request_body() -> None: - json_body, data_body = get_request_body(json=None, data={"hello": "world"}, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data={"hello": "world"}, request_options=None, omit=None + ) assert data_body == {"hello": "world"} assert json_body is None json_body_extras, data_body_extras = get_request_body( - json=None, data={"goodbye": "world"}, request_options=get_request_options(), omit=None + json=None, + data={"goodbye": "world"}, + request_options=get_request_options(), + omit=None, ) assert data_body_extras == {"goodbye": "world", "see you": "later"} @@ -35,7 +45,9 @@ def test_get_files_request_body() -> None: def test_get_none_request_body() -> None: - json_body, data_body = get_request_body(json=None, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data=None, request_options=None, omit=None + ) assert data_body is None assert json_body is None diff --git a/seed/python-sdk/circular-references/tests/utils/test_query_encoding.py b/seed/python-sdk/circular-references/tests/utils/test_query_encoding.py index 247e1551b46..fbc8f402167 100644 --- a/seed/python-sdk/circular-references/tests/utils/test_query_encoding.py +++ b/seed/python-sdk/circular-references/tests/utils/test_query_encoding.py @@ -4,9 +4,15 @@ def test_query_encoding() -> None: - assert encode_query({"hello world": "hello world"}) == {"hello world": "hello world"} - assert encode_query({"hello_world": {"hello": "world"}}) == {"hello_world[hello]": "world"} - assert encode_query({"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"}) == { + assert encode_query({"hello world": "hello world"}) == { + "hello world": "hello world" + } + assert encode_query({"hello_world": {"hello": "world"}}) == { + "hello_world[hello]": "world" + } + assert encode_query( + {"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"} + ) == { "hello_world[hello][world]": "today", "hello_world[test]": "this", "hi": "there", diff --git a/seed/python-sdk/circular-references/tests/utils/test_serialization.py b/seed/python-sdk/circular-references/tests/utils/test_serialization.py index 58b1ed66e6d..5ca956916dd 100644 --- a/seed/python-sdk/circular-references/tests/utils/test_serialization.py +++ b/seed/python-sdk/circular-references/tests/utils/test_serialization.py @@ -1,10 +1,12 @@ # This file was auto-generated by Fern from our API Definition. -from typing import Any, List +from typing import List, Any -from seed.core.serialization import convert_and_respect_annotation_metadata +from seed.core.serialization import ( + convert_and_respect_annotation_metadata, +) +from .assets.models import ShapeParams, ObjectWithOptionalFieldParams -from .assets.models import ObjectWithOptionalFieldParams, ShapeParams UNION_TEST: ShapeParams = {"radius_measurement": 1.0, "shape_type": "circle", "id": "1"} UNION_TEST_CONVERTED = {"shapeType": "circle", "radiusMeasurement": 1.0, "id": "1"} @@ -18,20 +20,54 @@ def test_convert_and_respect_annotation_metadata() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) - assert converted == {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"} + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) + assert converted == { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + } def test_convert_and_respect_annotation_metadata_in_list() -> None: data: List[ObjectWithOptionalFieldParams] = [ - {"string": "string", "long_": 12345, "bool_": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long_": 67890, "list_": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long_": 12345, + "bool_": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long_": 67890, + "list_": [], + "literal": "lit_one", + "any": "any", + }, ] - converted = convert_and_respect_annotation_metadata(object_=data, annotation=List[ObjectWithOptionalFieldParams]) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=List[ObjectWithOptionalFieldParams] + ) assert converted == [ - {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long": 67890, "list": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long": 67890, + "list": [], + "literal": "lit_one", + "any": "any", + }, ] @@ -43,7 +79,9 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) assert converted == { "string": "string", @@ -55,12 +93,16 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: def test_convert_and_respect_annotation_metadata_in_union() -> None: - converted = convert_and_respect_annotation_metadata(object_=UNION_TEST, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=UNION_TEST, annotation=ShapeParams + ) assert converted == UNION_TEST_CONVERTED def test_convert_and_respect_annotation_metadata_with_empty_object() -> None: data: Any = {} - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ShapeParams + ) assert converted == data diff --git a/seed/python-sdk/code-samples/pyproject.toml b/seed/python-sdk/code-samples/pyproject.toml index 92ac37495d1..36fdfd15cd7 100644 --- a/seed/python-sdk/code-samples/pyproject.toml +++ b/seed/python-sdk/code-samples/pyproject.toml @@ -43,6 +43,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/python-sdk/code-samples/src/seed/__init__.py b/seed/python-sdk/code-samples/src/seed/__init__.py index 5edcddde3b6..b5fdd48cda9 100644 --- a/seed/python-sdk/code-samples/src/seed/__init__.py +++ b/seed/python-sdk/code-samples/src/seed/__init__.py @@ -5,4 +5,10 @@ from .service import MyResponse from .version import __version__ -__all__ = ["AsyncSeedCodeSamples", "MyResponse", "SeedCodeSamples", "__version__", "service"] +__all__ = [ + "AsyncSeedCodeSamples", + "MyResponse", + "SeedCodeSamples", + "__version__", + "service", +] diff --git a/seed/python-sdk/code-samples/src/seed/client.py b/seed/python-sdk/code-samples/src/seed/client.py index cdc29bb1cd2..9a9df3d813b 100644 --- a/seed/python-sdk/code-samples/src/seed/client.py +++ b/seed/python-sdk/code-samples/src/seed/client.py @@ -1,11 +1,11 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from .service.client import AsyncServiceClient, ServiceClient +from .core.client_wrapper import SyncClientWrapper +from .service.client import ServiceClient +from .core.client_wrapper import AsyncClientWrapper +from .service.client import AsyncServiceClient class SeedCodeSamples: @@ -41,14 +41,18 @@ def __init__( base_url: str, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.Client] = None + httpx_client: typing.Optional[httpx.Client] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = SyncClientWrapper( base_url=base_url, httpx_client=httpx_client if httpx_client is not None - else httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.Client( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.Client(timeout=_defaulted_timeout), timeout=_defaulted_timeout, @@ -89,14 +93,18 @@ def __init__( base_url: str, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.AsyncClient] = None + httpx_client: typing.Optional[httpx.AsyncClient] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = AsyncClientWrapper( base_url=base_url, httpx_client=httpx_client if httpx_client is not None - else httpx.AsyncClient(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.AsyncClient( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.AsyncClient(timeout=_defaulted_timeout), timeout=_defaulted_timeout, diff --git a/seed/python-sdk/code-samples/src/seed/core/api_error.py b/seed/python-sdk/code-samples/src/seed/core/api_error.py index 2e9fc5431cd..da734b58068 100644 --- a/seed/python-sdk/code-samples/src/seed/core/api_error.py +++ b/seed/python-sdk/code-samples/src/seed/core/api_error.py @@ -7,7 +7,9 @@ class ApiError(Exception): status_code: typing.Optional[int] body: typing.Any - def __init__(self, *, status_code: typing.Optional[int] = None, body: typing.Any = None): + def __init__( + self, *, status_code: typing.Optional[int] = None, body: typing.Any = None + ): self.status_code = status_code self.body = body diff --git a/seed/python-sdk/code-samples/src/seed/core/client_wrapper.py b/seed/python-sdk/code-samples/src/seed/core/client_wrapper.py index 67034f9dae1..eb2a99b3969 100644 --- a/seed/python-sdk/code-samples/src/seed/core/client_wrapper.py +++ b/seed/python-sdk/code-samples/src/seed/core/client_wrapper.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .http_client import AsyncHttpClient, HttpClient +from .http_client import HttpClient +from .http_client import AsyncHttpClient class BaseClientWrapper: @@ -28,7 +27,13 @@ def get_timeout(self) -> typing.Optional[float]: class SyncClientWrapper(BaseClientWrapper): - def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, httpx_client: httpx.Client): + def __init__( + self, + *, + base_url: str, + timeout: typing.Optional[float] = None, + httpx_client: httpx.Client, + ): super().__init__(base_url=base_url, timeout=timeout) self.httpx_client = HttpClient( httpx_client=httpx_client, @@ -39,7 +44,13 @@ def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, htt class AsyncClientWrapper(BaseClientWrapper): - def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, httpx_client: httpx.AsyncClient): + def __init__( + self, + *, + base_url: str, + timeout: typing.Optional[float] = None, + httpx_client: httpx.AsyncClient, + ): super().__init__(base_url=base_url, timeout=timeout) self.httpx_client = AsyncHttpClient( httpx_client=httpx_client, diff --git a/seed/python-sdk/code-samples/src/seed/core/datetime_utils.py b/seed/python-sdk/code-samples/src/seed/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/python-sdk/code-samples/src/seed/core/datetime_utils.py +++ b/seed/python-sdk/code-samples/src/seed/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/python-sdk/code-samples/src/seed/core/file.py b/seed/python-sdk/code-samples/src/seed/core/file.py index cb0d40bbbf3..6e0f92bfcb1 100644 --- a/seed/python-sdk/code-samples/src/seed/core/file.py +++ b/seed/python-sdk/code-samples/src/seed/core/file.py @@ -13,12 +13,17 @@ # (filename, file (or bytes), content_type) typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str]], # (filename, file (or bytes), content_type, headers) - typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str], typing.Mapping[str, str]], + typing.Tuple[ + typing.Optional[str], + FileContent, + typing.Optional[str], + typing.Mapping[str, str], + ], ] def convert_file_dict_to_httpx_tuples( - d: typing.Dict[str, typing.Union[File, typing.List[File]]] + d: typing.Dict[str, typing.Union[File, typing.List[File]]], ) -> typing.List[typing.Tuple[str, File]]: """ The format we use is a list of tuples, where the first element is the diff --git a/seed/python-sdk/code-samples/src/seed/core/http_client.py b/seed/python-sdk/code-samples/src/seed/core/http_client.py index 9333d8a7f15..091f71bc185 100644 --- a/seed/python-sdk/code-samples/src/seed/core/http_client.py +++ b/seed/python-sdk/code-samples/src/seed/core/http_client.py @@ -77,7 +77,9 @@ def _retry_timeout(response: httpx.Response, retries: int) -> float: return retry_after # Apply exponential backoff, capped at MAX_RETRY_DELAY_SECONDS. - retry_delay = min(INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS) + retry_delay = min( + INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS + ) # Add a randomness / jitter to the retry delay to avoid overwhelming the server with retries. timeout = retry_delay * (1 - 0.25 * random()) @@ -90,7 +92,8 @@ def _should_retry(response: httpx.Response) -> bool: def remove_omit_from_dict( - original: typing.Dict[str, typing.Optional[typing.Any]], omit: typing.Optional[typing.Any] + original: typing.Dict[str, typing.Optional[typing.Any]], + omit: typing.Optional[typing.Any], ) -> typing.Dict[str, typing.Any]: if omit is None: return original @@ -108,7 +111,8 @@ def maybe_filter_request_body( ) -> typing.Optional[typing.Any]: if data is None: return ( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else None ) @@ -118,7 +122,8 @@ def maybe_filter_request_body( data_content = { **(jsonable_encoder(remove_omit_from_dict(data, omit))), # type: ignore **( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else {} ), @@ -162,7 +167,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url def request( @@ -174,8 +181,12 @@ def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -184,11 +195,14 @@ def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) response = self.httpx_client.request( method=method, @@ -198,7 +212,11 @@ def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -209,7 +227,10 @@ def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -222,11 +243,15 @@ def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: time.sleep(_retry_timeout(response=response, retries=retries)) @@ -256,8 +281,12 @@ def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -266,11 +295,14 @@ def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) with self.httpx_client.stream( method=method, @@ -280,7 +312,11 @@ def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -291,7 +327,9 @@ def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -304,7 +342,9 @@ def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream @@ -327,7 +367,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url async def request( @@ -339,8 +381,12 @@ async def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -349,11 +395,14 @@ async def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) # Add the input to each of these and do None-safety checks response = await self.httpx_client.request( @@ -364,7 +413,11 @@ async def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -375,7 +428,10 @@ async def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -388,11 +444,15 @@ async def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: await asyncio.sleep(_retry_timeout(response=response, retries=retries)) @@ -421,8 +481,12 @@ async def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -431,11 +495,14 @@ async def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) async with self.httpx_client.stream( method=method, @@ -445,7 +512,11 @@ async def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -456,7 +527,9 @@ async def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -469,7 +542,9 @@ async def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream diff --git a/seed/python-sdk/code-samples/src/seed/core/jsonable_encoder.py b/seed/python-sdk/code-samples/src/seed/core/jsonable_encoder.py index d3fd328fd41..12a8b52fc22 100644 --- a/seed/python-sdk/code-samples/src/seed/core/jsonable_encoder.py +++ b/seed/python-sdk/code-samples/src/seed/core/jsonable_encoder.py @@ -19,13 +19,19 @@ import pydantic from .datetime_utils import serialize_datetime -from .pydantic_utilities import IS_PYDANTIC_V2, encode_by_type, to_jsonable_with_fallback +from .pydantic_utilities import ( + IS_PYDANTIC_V2, + encode_by_type, + to_jsonable_with_fallback, +) SetIntStr = Set[Union[int, str]] DictIntStrAny = Dict[Union[int, str], Any] -def jsonable_encoder(obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None) -> Any: +def jsonable_encoder( + obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None +) -> Any: custom_encoder = custom_encoder or {} if custom_encoder: if type(obj) in custom_encoder: diff --git a/seed/python-sdk/code-samples/src/seed/core/pydantic_utilities.py b/seed/python-sdk/code-samples/src/seed/core/pydantic_utilities.py index 170a563d6eb..c63935c32a2 100644 --- a/seed/python-sdk/code-samples/src/seed/core/pydantic_utilities.py +++ b/seed/python-sdk/code-samples/src/seed/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) # type: ignore # Pydantic v1 diff --git a/seed/python-sdk/code-samples/src/seed/core/query_encoder.py b/seed/python-sdk/code-samples/src/seed/core/query_encoder.py index 24076d72ee9..7cb98f52cd7 100644 --- a/seed/python-sdk/code-samples/src/seed/core/query_encoder.py +++ b/seed/python-sdk/code-samples/src/seed/core/query_encoder.py @@ -7,7 +7,9 @@ # Flattens dicts to be of the form {"key[subkey][subkey2]": value} where value is not a dict -def traverse_query_dict(dict_flat: Dict[str, Any], key_prefix: Optional[str] = None) -> Dict[str, Any]: +def traverse_query_dict( + dict_flat: Dict[str, Any], key_prefix: Optional[str] = None +) -> Dict[str, Any]: result = {} for k, v in dict_flat.items(): key = f"{key_prefix}[{k}]" if key_prefix is not None else k @@ -30,4 +32,8 @@ def single_query_encoder(query_key: str, query_value: Any) -> Dict[str, Any]: def encode_query(query: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: - return dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) if query is not None else None + return ( + dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) + if query is not None + else None + ) diff --git a/seed/python-sdk/code-samples/src/seed/core/serialization.py b/seed/python-sdk/code-samples/src/seed/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/python-sdk/code-samples/src/seed/core/serialization.py +++ b/seed/python-sdk/code-samples/src/seed/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/python-sdk/code-samples/src/seed/service/client.py b/seed/python-sdk/code-samples/src/seed/service/client.py index 9cd76b7912d..a94b2b04940 100644 --- a/seed/python-sdk/code-samples/src/seed/service/client.py +++ b/seed/python-sdk/code-samples/src/seed/service/client.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. import typing -from json.decoder import JSONDecodeError - -from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.pydantic_utilities import parse_obj_as +from ..core.client_wrapper import SyncClientWrapper from ..core.request_options import RequestOptions from .types.my_response import MyResponse +from ..core.pydantic_utilities import parse_obj_as +from json.decoder import JSONDecodeError +from ..core.api_error import ApiError +from ..core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -17,7 +17,12 @@ class ServiceClient: def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper - def hello(self, *, num_events: int, request_options: typing.Optional[RequestOptions] = None) -> MyResponse: + def hello( + self, + *, + num_events: int, + request_options: typing.Optional[RequestOptions] = None, + ) -> MyResponse: """ Parameters ---------- @@ -42,11 +47,19 @@ def hello(self, *, num_events: int, request_options: typing.Optional[RequestOpti ) """ _response = self._client_wrapper.httpx_client.request( - "hello", method="POST", json={"num_events": num_events}, request_options=request_options, omit=OMIT + "hello", + method="POST", + json={ + "num_events": num_events, + }, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(MyResponse, parse_obj_as(type_=MyResponse, object_=_response.json())) # type: ignore + return typing.cast( + MyResponse, parse_obj_as(type_=MyResponse, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -57,7 +70,12 @@ class AsyncServiceClient: def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper - async def hello(self, *, num_events: int, request_options: typing.Optional[RequestOptions] = None) -> MyResponse: + async def hello( + self, + *, + num_events: int, + request_options: typing.Optional[RequestOptions] = None, + ) -> MyResponse: """ Parameters ---------- @@ -90,11 +108,19 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "hello", method="POST", json={"num_events": num_events}, request_options=request_options, omit=OMIT + "hello", + method="POST", + json={ + "num_events": num_events, + }, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(MyResponse, parse_obj_as(type_=MyResponse, object_=_response.json())) # type: ignore + return typing.cast( + MyResponse, parse_obj_as(type_=MyResponse, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/code-samples/src/seed/service/types/my_response.py b/seed/python-sdk/code-samples/src/seed/service/types/my_response.py index 92cab02e52f..baac61e4505 100644 --- a/seed/python-sdk/code-samples/src/seed/service/types/my_response.py +++ b/seed/python-sdk/code-samples/src/seed/service/types/my_response.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel import typing - +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class MyResponse(UniversalBaseModel): id: str name: typing.Optional[str] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/code-samples/src/seed/version.py b/seed/python-sdk/code-samples/src/seed/version.py index 87aca90e9c8..335235a2762 100644 --- a/seed/python-sdk/code-samples/src/seed/version.py +++ b/seed/python-sdk/code-samples/src/seed/version.py @@ -1,4 +1,3 @@ - from importlib import metadata __version__ = metadata.version("fern_code-samples") diff --git a/seed/python-sdk/code-samples/tests/conftest.py b/seed/python-sdk/code-samples/tests/conftest.py index e6ed2d55754..3f5bc3ae304 100644 --- a/seed/python-sdk/code-samples/tests/conftest.py +++ b/seed/python-sdk/code-samples/tests/conftest.py @@ -1,9 +1,9 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedCodeSamples import os - import pytest -from seed import AsyncSeedCodeSamples, SeedCodeSamples +from seed import AsyncSeedCodeSamples @pytest.fixture diff --git a/seed/python-sdk/code-samples/tests/custom/test_client.py b/seed/python-sdk/code-samples/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/python-sdk/code-samples/tests/custom/test_client.py +++ b/seed/python-sdk/code-samples/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/python-sdk/code-samples/tests/test_service.py b/seed/python-sdk/code-samples/tests/test_service.py index a504e2dd670..35a5072c6a0 100644 --- a/seed/python-sdk/code-samples/tests/test_service.py +++ b/seed/python-sdk/code-samples/tests/test_service.py @@ -1,13 +1,14 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedCodeSamples +from seed import AsyncSeedCodeSamples import typing - -from seed import AsyncSeedCodeSamples, SeedCodeSamples - from .utilities import validate_response -async def test_hello(client: SeedCodeSamples, async_client: AsyncSeedCodeSamples) -> None: +async def test_hello( + client: SeedCodeSamples, async_client: AsyncSeedCodeSamples +) -> None: expected_response: typing.Any = {"id": "123", "name": "hello"} expected_types: typing.Any = {"id": None, "name": None} response = client.service.hello(num_events=5) diff --git a/seed/python-sdk/code-samples/tests/utilities.py b/seed/python-sdk/code-samples/tests/utilities.py index 13da208eb3a..e8f4472564c 100644 --- a/seed/python-sdk/code-samples/tests/utilities.py +++ b/seed/python-sdk/code-samples/tests/utilities.py @@ -3,11 +3,14 @@ import typing import uuid -import pydantic from dateutil import parser +import pydantic + -def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> typing.Any: +def cast_field( + json_expectation: typing.Any, type_expectation: typing.Any +) -> typing.Any: # Cast these specific types which come through as string and expect our # models to cast to the correct type. if type_expectation == "uuid": @@ -25,7 +28,9 @@ def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> ty return json_expectation -def validate_field(response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any) -> None: +def validate_field( + response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectation == "no_validate": return @@ -44,7 +49,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(entry_expectation, dict): is_container_of_complex_type = True validate_response( - response=response[idx], json_expectation=ex, type_expectations=entry_expectation + response=response[idx], + json_expectation=ex, + type_expectations=entry_expectation, ) else: cast_json_expectation.append(cast_field(ex, entry_expectation)) @@ -56,7 +63,10 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # if any of the values of the set have a type_expectation of a dict, we're assuming it's a pydantic # model and keeping it a list. if container_expectation != "set" or not any( - map(lambda value: isinstance(value, dict), list(contents_expectation.values())) + map( + lambda value: isinstance(value, dict), + list(contents_expectation.values()), + ) ): json_expectation = cast_field(json_expectation, container_expectation) elif isinstance(type_expectation, tuple): @@ -65,9 +75,15 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(contents_expectation, dict): json_expectation = { cast_field( - key, contents_expectation.get(idx)[0] if contents_expectation.get(idx) is not None else None # type: ignore + key, + contents_expectation.get(idx)[0] + if contents_expectation.get(idx) is not None + else None, # type: ignore ): cast_field( - value, contents_expectation.get(idx)[1] if contents_expectation.get(idx) is not None else None # type: ignore + value, + contents_expectation.get(idx)[1] + if contents_expectation.get(idx) is not None + else None, # type: ignore ) for idx, (key, value) in enumerate(json_expectation.items()) } @@ -86,7 +102,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # Arg type_expectations is a deeply nested structure that matches the response, but with the values replaced with the expected types -def validate_response(response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any) -> None: +def validate_response( + response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectations == "no_validate": return @@ -96,11 +114,17 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e and not isinstance(response, dict) and not issubclass(type(response), pydantic.BaseModel) ): - validate_field(response=response, json_expectation=json_expectation, type_expectation=type_expectations) + validate_field( + response=response, + json_expectation=json_expectation, + type_expectation=type_expectations, + ) return if isinstance(response, list): - assert len(response) == len(json_expectation), "Length mismatch, expected: {0}, Actual: {1}".format( + assert len(response) == len( + json_expectation + ), "Length mismatch, expected: {0}, Actual: {1}".format( len(response), len(json_expectation) ) content_expectation = type_expectations @@ -108,7 +132,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e content_expectation = type_expectations[1] for idx, item in enumerate(response): validate_response( - response=item, json_expectation=json_expectation[idx], type_expectations=content_expectation[idx] + response=item, + json_expectation=json_expectation[idx], + type_expectations=content_expectation[idx], ) else: response_json = response @@ -116,7 +142,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e response_json = response.dict(by_alias=True) for key, value in json_expectation.items(): - assert key in response_json, "Field {0} not found within the response object: {1}".format( + assert ( + key in response_json + ), "Field {0} not found within the response object: {1}".format( key, response_json ) @@ -128,11 +156,19 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e # Otherwise, we're just validating a single field that's a pydantic model. if isinstance(value, dict) and not isinstance(type_expectation, tuple): validate_response( - response=response_json[key], json_expectation=value, type_expectations=type_expectation + response=response_json[key], + json_expectation=value, + type_expectations=type_expectation, ) else: - validate_field(response=response_json[key], json_expectation=value, type_expectation=type_expectation) + validate_field( + response=response_json[key], + json_expectation=value, + type_expectation=type_expectation, + ) # Ensure there are no additional fields here either del response_json[key] - assert len(response_json) == 0, "Additional fields found, expected None: {0}".format(response_json) + assert ( + len(response_json) == 0 + ), "Additional fields found, expected None: {0}".format(response_json) diff --git a/seed/python-sdk/code-samples/tests/utils/assets/models/__init__.py b/seed/python-sdk/code-samples/tests/utils/assets/models/__init__.py index 2cf01263529..3a1c852e71e 100644 --- a/seed/python-sdk/code-samples/tests/utils/assets/models/__init__.py +++ b/seed/python-sdk/code-samples/tests/utils/assets/models/__init__.py @@ -5,7 +5,7 @@ from .circle import CircleParams from .object_with_defaults import ObjectWithDefaultsParams from .object_with_optional_field import ObjectWithOptionalFieldParams -from .shape import Shape_CircleParams, Shape_SquareParams, ShapeParams +from .shape import ShapeParams, Shape_CircleParams, Shape_SquareParams from .square import SquareParams from .undiscriminated_shape import UndiscriminatedShapeParams diff --git a/seed/python-sdk/code-samples/tests/utils/assets/models/circle.py b/seed/python-sdk/code-samples/tests/utils/assets/models/circle.py index af7a1bf8a8e..253f12d38b3 100644 --- a/seed/python-sdk/code-samples/tests/utils/assets/models/circle.py +++ b/seed/python-sdk/code-samples/tests/utils/assets/models/circle.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class CircleParams(typing_extensions.TypedDict): - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] diff --git a/seed/python-sdk/code-samples/tests/utils/assets/models/object_with_optional_field.py b/seed/python-sdk/code-samples/tests/utils/assets/models/object_with_optional_field.py index 3ad93d5f305..ebe7dc80547 100644 --- a/seed/python-sdk/code-samples/tests/utils/assets/models/object_with_optional_field.py +++ b/seed/python-sdk/code-samples/tests/utils/assets/models/object_with_optional_field.py @@ -7,8 +7,8 @@ import uuid import typing_extensions -from seed.core.serialization import FieldMetadata +from seed.core.serialization import FieldMetadata from .color import Color from .shape import ShapeParams from .undiscriminated_shape import UndiscriminatedShapeParams @@ -18,16 +18,30 @@ class ObjectWithOptionalFieldParams(typing_extensions.TypedDict): literal: typing.Literal["lit_one"] string: typing_extensions.NotRequired[str] integer: typing_extensions.NotRequired[int] - long_: typing_extensions.NotRequired[typing_extensions.Annotated[int, FieldMetadata(alias="long")]] + long_: typing_extensions.NotRequired[ + typing_extensions.Annotated[int, FieldMetadata(alias="long")] + ] double: typing_extensions.NotRequired[float] - bool_: typing_extensions.NotRequired[typing_extensions.Annotated[bool, FieldMetadata(alias="bool")]] + bool_: typing_extensions.NotRequired[ + typing_extensions.Annotated[bool, FieldMetadata(alias="bool")] + ] datetime: typing_extensions.NotRequired[dt.datetime] date: typing_extensions.NotRequired[dt.date] - uuid_: typing_extensions.NotRequired[typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")]] - base_64: typing_extensions.NotRequired[typing_extensions.Annotated[str, FieldMetadata(alias="base64")]] - list_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")]] - set_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")]] - map_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")]] + uuid_: typing_extensions.NotRequired[ + typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")] + ] + base_64: typing_extensions.NotRequired[ + typing_extensions.Annotated[str, FieldMetadata(alias="base64")] + ] + list_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")] + ] + set_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")] + ] + map_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")] + ] enum: typing_extensions.NotRequired[Color] union: typing_extensions.NotRequired[ShapeParams] second_union: typing_extensions.NotRequired[ShapeParams] diff --git a/seed/python-sdk/code-samples/tests/utils/assets/models/shape.py b/seed/python-sdk/code-samples/tests/utils/assets/models/shape.py index 2c33c877951..816ffc51bdc 100644 --- a/seed/python-sdk/code-samples/tests/utils/assets/models/shape.py +++ b/seed/python-sdk/code-samples/tests/utils/assets/models/shape.py @@ -7,6 +7,7 @@ import typing import typing_extensions + from seed.core.serialization import FieldMetadata @@ -15,13 +16,21 @@ class Base(typing_extensions.TypedDict): class Shape_CircleParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["circle"], FieldMetadata(alias="shapeType")] - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["circle"], FieldMetadata(alias="shapeType") + ] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] class Shape_SquareParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["square"], FieldMetadata(alias="shapeType")] - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["square"], FieldMetadata(alias="shapeType") + ] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] ShapeParams = typing.Union[Shape_CircleParams, Shape_SquareParams] diff --git a/seed/python-sdk/code-samples/tests/utils/assets/models/square.py b/seed/python-sdk/code-samples/tests/utils/assets/models/square.py index b9b7dd319bc..bcf08a723c5 100644 --- a/seed/python-sdk/code-samples/tests/utils/assets/models/square.py +++ b/seed/python-sdk/code-samples/tests/utils/assets/models/square.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class SquareParams(typing_extensions.TypedDict): - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] diff --git a/seed/python-sdk/code-samples/tests/utils/test_http_client.py b/seed/python-sdk/code-samples/tests/utils/test_http_client.py index edd11ca7afb..f5a874a75f3 100644 --- a/seed/python-sdk/code-samples/tests/utils/test_http_client.py +++ b/seed/python-sdk/code-samples/tests/utils/test_http_client.py @@ -9,12 +9,17 @@ def get_request_options() -> RequestOptions: def test_get_json_request_body() -> None: - json_body, data_body = get_request_body(json={"hello": "world"}, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json={"hello": "world"}, data=None, request_options=None, omit=None + ) assert json_body == {"hello": "world"} assert data_body is None json_body_extras, data_body_extras = get_request_body( - json={"goodbye": "world"}, data=None, request_options=get_request_options(), omit=None + json={"goodbye": "world"}, + data=None, + request_options=get_request_options(), + omit=None, ) assert json_body_extras == {"goodbye": "world", "see you": "later"} @@ -22,12 +27,17 @@ def test_get_json_request_body() -> None: def test_get_files_request_body() -> None: - json_body, data_body = get_request_body(json=None, data={"hello": "world"}, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data={"hello": "world"}, request_options=None, omit=None + ) assert data_body == {"hello": "world"} assert json_body is None json_body_extras, data_body_extras = get_request_body( - json=None, data={"goodbye": "world"}, request_options=get_request_options(), omit=None + json=None, + data={"goodbye": "world"}, + request_options=get_request_options(), + omit=None, ) assert data_body_extras == {"goodbye": "world", "see you": "later"} @@ -35,7 +45,9 @@ def test_get_files_request_body() -> None: def test_get_none_request_body() -> None: - json_body, data_body = get_request_body(json=None, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data=None, request_options=None, omit=None + ) assert data_body is None assert json_body is None diff --git a/seed/python-sdk/code-samples/tests/utils/test_query_encoding.py b/seed/python-sdk/code-samples/tests/utils/test_query_encoding.py index 247e1551b46..fbc8f402167 100644 --- a/seed/python-sdk/code-samples/tests/utils/test_query_encoding.py +++ b/seed/python-sdk/code-samples/tests/utils/test_query_encoding.py @@ -4,9 +4,15 @@ def test_query_encoding() -> None: - assert encode_query({"hello world": "hello world"}) == {"hello world": "hello world"} - assert encode_query({"hello_world": {"hello": "world"}}) == {"hello_world[hello]": "world"} - assert encode_query({"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"}) == { + assert encode_query({"hello world": "hello world"}) == { + "hello world": "hello world" + } + assert encode_query({"hello_world": {"hello": "world"}}) == { + "hello_world[hello]": "world" + } + assert encode_query( + {"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"} + ) == { "hello_world[hello][world]": "today", "hello_world[test]": "this", "hi": "there", diff --git a/seed/python-sdk/code-samples/tests/utils/test_serialization.py b/seed/python-sdk/code-samples/tests/utils/test_serialization.py index 58b1ed66e6d..5ca956916dd 100644 --- a/seed/python-sdk/code-samples/tests/utils/test_serialization.py +++ b/seed/python-sdk/code-samples/tests/utils/test_serialization.py @@ -1,10 +1,12 @@ # This file was auto-generated by Fern from our API Definition. -from typing import Any, List +from typing import List, Any -from seed.core.serialization import convert_and_respect_annotation_metadata +from seed.core.serialization import ( + convert_and_respect_annotation_metadata, +) +from .assets.models import ShapeParams, ObjectWithOptionalFieldParams -from .assets.models import ObjectWithOptionalFieldParams, ShapeParams UNION_TEST: ShapeParams = {"radius_measurement": 1.0, "shape_type": "circle", "id": "1"} UNION_TEST_CONVERTED = {"shapeType": "circle", "radiusMeasurement": 1.0, "id": "1"} @@ -18,20 +20,54 @@ def test_convert_and_respect_annotation_metadata() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) - assert converted == {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"} + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) + assert converted == { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + } def test_convert_and_respect_annotation_metadata_in_list() -> None: data: List[ObjectWithOptionalFieldParams] = [ - {"string": "string", "long_": 12345, "bool_": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long_": 67890, "list_": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long_": 12345, + "bool_": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long_": 67890, + "list_": [], + "literal": "lit_one", + "any": "any", + }, ] - converted = convert_and_respect_annotation_metadata(object_=data, annotation=List[ObjectWithOptionalFieldParams]) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=List[ObjectWithOptionalFieldParams] + ) assert converted == [ - {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long": 67890, "list": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long": 67890, + "list": [], + "literal": "lit_one", + "any": "any", + }, ] @@ -43,7 +79,9 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) assert converted == { "string": "string", @@ -55,12 +93,16 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: def test_convert_and_respect_annotation_metadata_in_union() -> None: - converted = convert_and_respect_annotation_metadata(object_=UNION_TEST, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=UNION_TEST, annotation=ShapeParams + ) assert converted == UNION_TEST_CONVERTED def test_convert_and_respect_annotation_metadata_with_empty_object() -> None: data: Any = {} - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ShapeParams + ) assert converted == data diff --git a/seed/python-sdk/custom-auth/pyproject.toml b/seed/python-sdk/custom-auth/pyproject.toml index d11b527e9e1..ad551be8b77 100644 --- a/seed/python-sdk/custom-auth/pyproject.toml +++ b/seed/python-sdk/custom-auth/pyproject.toml @@ -43,6 +43,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/python-sdk/custom-auth/src/seed/client.py b/seed/python-sdk/custom-auth/src/seed/client.py index 657c4faf1dd..81ed3c44e7a 100644 --- a/seed/python-sdk/custom-auth/src/seed/client.py +++ b/seed/python-sdk/custom-auth/src/seed/client.py @@ -1,11 +1,11 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from .custom_auth.client import AsyncCustomAuthClient, CustomAuthClient +from .core.client_wrapper import SyncClientWrapper +from .custom_auth.client import CustomAuthClient +from .core.client_wrapper import AsyncClientWrapper +from .custom_auth.client import AsyncCustomAuthClient class SeedCustomAuth: @@ -44,15 +44,19 @@ def __init__( custom_auth_scheme: str, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.Client] = None + httpx_client: typing.Optional[httpx.Client] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = SyncClientWrapper( base_url=base_url, custom_auth_scheme=custom_auth_scheme, httpx_client=httpx_client if httpx_client is not None - else httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.Client( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.Client(timeout=_defaulted_timeout), timeout=_defaulted_timeout, @@ -96,15 +100,19 @@ def __init__( custom_auth_scheme: str, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.AsyncClient] = None + httpx_client: typing.Optional[httpx.AsyncClient] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = AsyncClientWrapper( base_url=base_url, custom_auth_scheme=custom_auth_scheme, httpx_client=httpx_client if httpx_client is not None - else httpx.AsyncClient(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.AsyncClient( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.AsyncClient(timeout=_defaulted_timeout), timeout=_defaulted_timeout, diff --git a/seed/python-sdk/custom-auth/src/seed/core/api_error.py b/seed/python-sdk/custom-auth/src/seed/core/api_error.py index 2e9fc5431cd..da734b58068 100644 --- a/seed/python-sdk/custom-auth/src/seed/core/api_error.py +++ b/seed/python-sdk/custom-auth/src/seed/core/api_error.py @@ -7,7 +7,9 @@ class ApiError(Exception): status_code: typing.Optional[int] body: typing.Any - def __init__(self, *, status_code: typing.Optional[int] = None, body: typing.Any = None): + def __init__( + self, *, status_code: typing.Optional[int] = None, body: typing.Any = None + ): self.status_code = status_code self.body = body diff --git a/seed/python-sdk/custom-auth/src/seed/core/client_wrapper.py b/seed/python-sdk/custom-auth/src/seed/core/client_wrapper.py index 5e1e31c5b32..c9a156a7edb 100644 --- a/seed/python-sdk/custom-auth/src/seed/core/client_wrapper.py +++ b/seed/python-sdk/custom-auth/src/seed/core/client_wrapper.py @@ -1,14 +1,19 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .http_client import AsyncHttpClient, HttpClient +from .http_client import HttpClient +from .http_client import AsyncHttpClient class BaseClientWrapper: - def __init__(self, *, custom_auth_scheme: str, base_url: str, timeout: typing.Optional[float] = None): + def __init__( + self, + *, + custom_auth_scheme: str, + base_url: str, + timeout: typing.Optional[float] = None, + ): self.custom_auth_scheme = custom_auth_scheme self._base_url = base_url self._timeout = timeout @@ -36,9 +41,11 @@ def __init__( custom_auth_scheme: str, base_url: str, timeout: typing.Optional[float] = None, - httpx_client: httpx.Client + httpx_client: httpx.Client, ): - super().__init__(custom_auth_scheme=custom_auth_scheme, base_url=base_url, timeout=timeout) + super().__init__( + custom_auth_scheme=custom_auth_scheme, base_url=base_url, timeout=timeout + ) self.httpx_client = HttpClient( httpx_client=httpx_client, base_headers=self.get_headers(), @@ -54,9 +61,11 @@ def __init__( custom_auth_scheme: str, base_url: str, timeout: typing.Optional[float] = None, - httpx_client: httpx.AsyncClient + httpx_client: httpx.AsyncClient, ): - super().__init__(custom_auth_scheme=custom_auth_scheme, base_url=base_url, timeout=timeout) + super().__init__( + custom_auth_scheme=custom_auth_scheme, base_url=base_url, timeout=timeout + ) self.httpx_client = AsyncHttpClient( httpx_client=httpx_client, base_headers=self.get_headers(), diff --git a/seed/python-sdk/custom-auth/src/seed/core/datetime_utils.py b/seed/python-sdk/custom-auth/src/seed/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/python-sdk/custom-auth/src/seed/core/datetime_utils.py +++ b/seed/python-sdk/custom-auth/src/seed/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/python-sdk/custom-auth/src/seed/core/file.py b/seed/python-sdk/custom-auth/src/seed/core/file.py index cb0d40bbbf3..6e0f92bfcb1 100644 --- a/seed/python-sdk/custom-auth/src/seed/core/file.py +++ b/seed/python-sdk/custom-auth/src/seed/core/file.py @@ -13,12 +13,17 @@ # (filename, file (or bytes), content_type) typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str]], # (filename, file (or bytes), content_type, headers) - typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str], typing.Mapping[str, str]], + typing.Tuple[ + typing.Optional[str], + FileContent, + typing.Optional[str], + typing.Mapping[str, str], + ], ] def convert_file_dict_to_httpx_tuples( - d: typing.Dict[str, typing.Union[File, typing.List[File]]] + d: typing.Dict[str, typing.Union[File, typing.List[File]]], ) -> typing.List[typing.Tuple[str, File]]: """ The format we use is a list of tuples, where the first element is the diff --git a/seed/python-sdk/custom-auth/src/seed/core/http_client.py b/seed/python-sdk/custom-auth/src/seed/core/http_client.py index 9333d8a7f15..091f71bc185 100644 --- a/seed/python-sdk/custom-auth/src/seed/core/http_client.py +++ b/seed/python-sdk/custom-auth/src/seed/core/http_client.py @@ -77,7 +77,9 @@ def _retry_timeout(response: httpx.Response, retries: int) -> float: return retry_after # Apply exponential backoff, capped at MAX_RETRY_DELAY_SECONDS. - retry_delay = min(INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS) + retry_delay = min( + INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS + ) # Add a randomness / jitter to the retry delay to avoid overwhelming the server with retries. timeout = retry_delay * (1 - 0.25 * random()) @@ -90,7 +92,8 @@ def _should_retry(response: httpx.Response) -> bool: def remove_omit_from_dict( - original: typing.Dict[str, typing.Optional[typing.Any]], omit: typing.Optional[typing.Any] + original: typing.Dict[str, typing.Optional[typing.Any]], + omit: typing.Optional[typing.Any], ) -> typing.Dict[str, typing.Any]: if omit is None: return original @@ -108,7 +111,8 @@ def maybe_filter_request_body( ) -> typing.Optional[typing.Any]: if data is None: return ( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else None ) @@ -118,7 +122,8 @@ def maybe_filter_request_body( data_content = { **(jsonable_encoder(remove_omit_from_dict(data, omit))), # type: ignore **( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else {} ), @@ -162,7 +167,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url def request( @@ -174,8 +181,12 @@ def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -184,11 +195,14 @@ def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) response = self.httpx_client.request( method=method, @@ -198,7 +212,11 @@ def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -209,7 +227,10 @@ def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -222,11 +243,15 @@ def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: time.sleep(_retry_timeout(response=response, retries=retries)) @@ -256,8 +281,12 @@ def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -266,11 +295,14 @@ def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) with self.httpx_client.stream( method=method, @@ -280,7 +312,11 @@ def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -291,7 +327,9 @@ def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -304,7 +342,9 @@ def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream @@ -327,7 +367,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url async def request( @@ -339,8 +381,12 @@ async def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -349,11 +395,14 @@ async def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) # Add the input to each of these and do None-safety checks response = await self.httpx_client.request( @@ -364,7 +413,11 @@ async def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -375,7 +428,10 @@ async def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -388,11 +444,15 @@ async def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: await asyncio.sleep(_retry_timeout(response=response, retries=retries)) @@ -421,8 +481,12 @@ async def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -431,11 +495,14 @@ async def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) async with self.httpx_client.stream( method=method, @@ -445,7 +512,11 @@ async def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -456,7 +527,9 @@ async def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -469,7 +542,9 @@ async def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream diff --git a/seed/python-sdk/custom-auth/src/seed/core/jsonable_encoder.py b/seed/python-sdk/custom-auth/src/seed/core/jsonable_encoder.py index d3fd328fd41..12a8b52fc22 100644 --- a/seed/python-sdk/custom-auth/src/seed/core/jsonable_encoder.py +++ b/seed/python-sdk/custom-auth/src/seed/core/jsonable_encoder.py @@ -19,13 +19,19 @@ import pydantic from .datetime_utils import serialize_datetime -from .pydantic_utilities import IS_PYDANTIC_V2, encode_by_type, to_jsonable_with_fallback +from .pydantic_utilities import ( + IS_PYDANTIC_V2, + encode_by_type, + to_jsonable_with_fallback, +) SetIntStr = Set[Union[int, str]] DictIntStrAny = Dict[Union[int, str], Any] -def jsonable_encoder(obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None) -> Any: +def jsonable_encoder( + obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None +) -> Any: custom_encoder = custom_encoder or {} if custom_encoder: if type(obj) in custom_encoder: diff --git a/seed/python-sdk/custom-auth/src/seed/core/pydantic_utilities.py b/seed/python-sdk/custom-auth/src/seed/core/pydantic_utilities.py index 170a563d6eb..c63935c32a2 100644 --- a/seed/python-sdk/custom-auth/src/seed/core/pydantic_utilities.py +++ b/seed/python-sdk/custom-auth/src/seed/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) # type: ignore # Pydantic v1 diff --git a/seed/python-sdk/custom-auth/src/seed/core/query_encoder.py b/seed/python-sdk/custom-auth/src/seed/core/query_encoder.py index 24076d72ee9..7cb98f52cd7 100644 --- a/seed/python-sdk/custom-auth/src/seed/core/query_encoder.py +++ b/seed/python-sdk/custom-auth/src/seed/core/query_encoder.py @@ -7,7 +7,9 @@ # Flattens dicts to be of the form {"key[subkey][subkey2]": value} where value is not a dict -def traverse_query_dict(dict_flat: Dict[str, Any], key_prefix: Optional[str] = None) -> Dict[str, Any]: +def traverse_query_dict( + dict_flat: Dict[str, Any], key_prefix: Optional[str] = None +) -> Dict[str, Any]: result = {} for k, v in dict_flat.items(): key = f"{key_prefix}[{k}]" if key_prefix is not None else k @@ -30,4 +32,8 @@ def single_query_encoder(query_key: str, query_value: Any) -> Dict[str, Any]: def encode_query(query: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: - return dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) if query is not None else None + return ( + dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) + if query is not None + else None + ) diff --git a/seed/python-sdk/custom-auth/src/seed/core/serialization.py b/seed/python-sdk/custom-auth/src/seed/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/python-sdk/custom-auth/src/seed/core/serialization.py +++ b/seed/python-sdk/custom-auth/src/seed/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/python-sdk/custom-auth/src/seed/custom_auth/client.py b/seed/python-sdk/custom-auth/src/seed/custom_auth/client.py index 65b6effd37d..76f39a87f66 100644 --- a/seed/python-sdk/custom-auth/src/seed/custom_auth/client.py +++ b/seed/python-sdk/custom-auth/src/seed/custom_auth/client.py @@ -1,15 +1,15 @@ # This file was auto-generated by Fern from our API Definition. import typing -from json.decoder import JSONDecodeError - -from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.pydantic_utilities import parse_obj_as +from ..core.client_wrapper import SyncClientWrapper from ..core.request_options import RequestOptions -from ..errors.errors.bad_request import BadRequest +from ..core.pydantic_utilities import parse_obj_as from ..errors.errors.unauthorized_request import UnauthorizedRequest from ..errors.types.unauthorized_request_error_body import UnauthorizedRequestErrorBody +from json.decoder import JSONDecodeError +from ..core.api_error import ApiError +from ..errors.errors.bad_request import BadRequest +from ..core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -19,7 +19,9 @@ class CustomAuthClient: def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper - def get_with_custom_auth(self, *, request_options: typing.Optional[RequestOptions] = None) -> bool: + def get_with_custom_auth( + self, *, request_options: typing.Optional[RequestOptions] = None + ) -> bool: """ GET request with custom auth scheme @@ -43,14 +45,23 @@ def get_with_custom_auth(self, *, request_options: typing.Optional[RequestOption client.custom_auth.get_with_custom_auth() """ _response = self._client_wrapper.httpx_client.request( - "custom-auth", method="GET", request_options=request_options + "custom-auth", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore if _response.status_code == 401: raise UnauthorizedRequest( - typing.cast(UnauthorizedRequestErrorBody, parse_obj_as(type_=UnauthorizedRequestErrorBody, object_=_response.json())) # type: ignore + typing.cast( + UnauthorizedRequestErrorBody, + parse_obj_as( + type_=UnauthorizedRequestErrorBody, object_=_response.json() + ), + ) # type: ignore ) _response_json = _response.json() except JSONDecodeError: @@ -58,7 +69,10 @@ def get_with_custom_auth(self, *, request_options: typing.Optional[RequestOption raise ApiError(status_code=_response.status_code, body=_response_json) def post_with_custom_auth( - self, *, request: typing.Any, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Any, + request_options: typing.Optional[RequestOptions] = None, ) -> bool: """ POST request with custom auth scheme @@ -87,14 +101,25 @@ def post_with_custom_auth( ) """ _response = self._client_wrapper.httpx_client.request( - "custom-auth", method="POST", json=request, request_options=request_options, omit=OMIT + "custom-auth", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore if _response.status_code == 401: raise UnauthorizedRequest( - typing.cast(UnauthorizedRequestErrorBody, parse_obj_as(type_=UnauthorizedRequestErrorBody, object_=_response.json())) # type: ignore + typing.cast( + UnauthorizedRequestErrorBody, + parse_obj_as( + type_=UnauthorizedRequestErrorBody, object_=_response.json() + ), + ) # type: ignore ) if _response.status_code == 400: raise BadRequest() @@ -108,7 +133,9 @@ class AsyncCustomAuthClient: def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper - async def get_with_custom_auth(self, *, request_options: typing.Optional[RequestOptions] = None) -> bool: + async def get_with_custom_auth( + self, *, request_options: typing.Optional[RequestOptions] = None + ) -> bool: """ GET request with custom auth scheme @@ -140,14 +167,23 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "custom-auth", method="GET", request_options=request_options + "custom-auth", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore if _response.status_code == 401: raise UnauthorizedRequest( - typing.cast(UnauthorizedRequestErrorBody, parse_obj_as(type_=UnauthorizedRequestErrorBody, object_=_response.json())) # type: ignore + typing.cast( + UnauthorizedRequestErrorBody, + parse_obj_as( + type_=UnauthorizedRequestErrorBody, object_=_response.json() + ), + ) # type: ignore ) _response_json = _response.json() except JSONDecodeError: @@ -155,7 +191,10 @@ async def main() -> None: raise ApiError(status_code=_response.status_code, body=_response_json) async def post_with_custom_auth( - self, *, request: typing.Any, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Any, + request_options: typing.Optional[RequestOptions] = None, ) -> bool: """ POST request with custom auth scheme @@ -192,14 +231,25 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "custom-auth", method="POST", json=request, request_options=request_options, omit=OMIT + "custom-auth", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore if _response.status_code == 401: raise UnauthorizedRequest( - typing.cast(UnauthorizedRequestErrorBody, parse_obj_as(type_=UnauthorizedRequestErrorBody, object_=_response.json())) # type: ignore + typing.cast( + UnauthorizedRequestErrorBody, + parse_obj_as( + type_=UnauthorizedRequestErrorBody, object_=_response.json() + ), + ) # type: ignore ) if _response.status_code == 400: raise BadRequest() diff --git a/seed/python-sdk/custom-auth/src/seed/errors/types/unauthorized_request_error_body.py b/seed/python-sdk/custom-auth/src/seed/errors/types/unauthorized_request_error_body.py index 2a84d1263c6..4e83edd5002 100644 --- a/seed/python-sdk/custom-auth/src/seed/errors/types/unauthorized_request_error_body.py +++ b/seed/python-sdk/custom-auth/src/seed/errors/types/unauthorized_request_error_body.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class UnauthorizedRequestErrorBody(UniversalBaseModel): message: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/custom-auth/src/seed/version.py b/seed/python-sdk/custom-auth/src/seed/version.py index e77c4cae8cd..841138bb60d 100644 --- a/seed/python-sdk/custom-auth/src/seed/version.py +++ b/seed/python-sdk/custom-auth/src/seed/version.py @@ -1,4 +1,3 @@ - from importlib import metadata __version__ = metadata.version("fern_custom-auth") diff --git a/seed/python-sdk/custom-auth/tests/conftest.py b/seed/python-sdk/custom-auth/tests/conftest.py index b9a66b212ae..7160a323dd7 100644 --- a/seed/python-sdk/custom-auth/tests/conftest.py +++ b/seed/python-sdk/custom-auth/tests/conftest.py @@ -1,9 +1,9 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedCustomAuth import os - import pytest -from seed import AsyncSeedCustomAuth, SeedCustomAuth +from seed import AsyncSeedCustomAuth @pytest.fixture diff --git a/seed/python-sdk/custom-auth/tests/custom/test_client.py b/seed/python-sdk/custom-auth/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/python-sdk/custom-auth/tests/custom/test_client.py +++ b/seed/python-sdk/custom-auth/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/python-sdk/custom-auth/tests/test_custom_auth.py b/seed/python-sdk/custom-auth/tests/test_custom_auth.py index 95712cd26d9..0573a083ebb 100644 --- a/seed/python-sdk/custom-auth/tests/test_custom_auth.py +++ b/seed/python-sdk/custom-auth/tests/test_custom_auth.py @@ -1,13 +1,14 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedCustomAuth +from seed import AsyncSeedCustomAuth import typing - -from seed import AsyncSeedCustomAuth, SeedCustomAuth - from .utilities import validate_response -async def test_get_with_custom_auth(client: SeedCustomAuth, async_client: AsyncSeedCustomAuth) -> None: +async def test_get_with_custom_auth( + client: SeedCustomAuth, async_client: AsyncSeedCustomAuth +) -> None: expected_response: typing.Any = True expected_types: typing.Any = None response = client.custom_auth.get_with_custom_auth() @@ -17,11 +18,15 @@ async def test_get_with_custom_auth(client: SeedCustomAuth, async_client: AsyncS validate_response(async_response, expected_response, expected_types) -async def test_post_with_custom_auth(client: SeedCustomAuth, async_client: AsyncSeedCustomAuth) -> None: +async def test_post_with_custom_auth( + client: SeedCustomAuth, async_client: AsyncSeedCustomAuth +) -> None: expected_response: typing.Any = True expected_types: typing.Any = None response = client.custom_auth.post_with_custom_auth(request={"key": "value"}) validate_response(response, expected_response, expected_types) - async_response = await async_client.custom_auth.post_with_custom_auth(request={"key": "value"}) + async_response = await async_client.custom_auth.post_with_custom_auth( + request={"key": "value"} + ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/custom-auth/tests/utilities.py b/seed/python-sdk/custom-auth/tests/utilities.py index 13da208eb3a..e8f4472564c 100644 --- a/seed/python-sdk/custom-auth/tests/utilities.py +++ b/seed/python-sdk/custom-auth/tests/utilities.py @@ -3,11 +3,14 @@ import typing import uuid -import pydantic from dateutil import parser +import pydantic + -def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> typing.Any: +def cast_field( + json_expectation: typing.Any, type_expectation: typing.Any +) -> typing.Any: # Cast these specific types which come through as string and expect our # models to cast to the correct type. if type_expectation == "uuid": @@ -25,7 +28,9 @@ def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> ty return json_expectation -def validate_field(response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any) -> None: +def validate_field( + response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectation == "no_validate": return @@ -44,7 +49,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(entry_expectation, dict): is_container_of_complex_type = True validate_response( - response=response[idx], json_expectation=ex, type_expectations=entry_expectation + response=response[idx], + json_expectation=ex, + type_expectations=entry_expectation, ) else: cast_json_expectation.append(cast_field(ex, entry_expectation)) @@ -56,7 +63,10 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # if any of the values of the set have a type_expectation of a dict, we're assuming it's a pydantic # model and keeping it a list. if container_expectation != "set" or not any( - map(lambda value: isinstance(value, dict), list(contents_expectation.values())) + map( + lambda value: isinstance(value, dict), + list(contents_expectation.values()), + ) ): json_expectation = cast_field(json_expectation, container_expectation) elif isinstance(type_expectation, tuple): @@ -65,9 +75,15 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(contents_expectation, dict): json_expectation = { cast_field( - key, contents_expectation.get(idx)[0] if contents_expectation.get(idx) is not None else None # type: ignore + key, + contents_expectation.get(idx)[0] + if contents_expectation.get(idx) is not None + else None, # type: ignore ): cast_field( - value, contents_expectation.get(idx)[1] if contents_expectation.get(idx) is not None else None # type: ignore + value, + contents_expectation.get(idx)[1] + if contents_expectation.get(idx) is not None + else None, # type: ignore ) for idx, (key, value) in enumerate(json_expectation.items()) } @@ -86,7 +102,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # Arg type_expectations is a deeply nested structure that matches the response, but with the values replaced with the expected types -def validate_response(response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any) -> None: +def validate_response( + response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectations == "no_validate": return @@ -96,11 +114,17 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e and not isinstance(response, dict) and not issubclass(type(response), pydantic.BaseModel) ): - validate_field(response=response, json_expectation=json_expectation, type_expectation=type_expectations) + validate_field( + response=response, + json_expectation=json_expectation, + type_expectation=type_expectations, + ) return if isinstance(response, list): - assert len(response) == len(json_expectation), "Length mismatch, expected: {0}, Actual: {1}".format( + assert len(response) == len( + json_expectation + ), "Length mismatch, expected: {0}, Actual: {1}".format( len(response), len(json_expectation) ) content_expectation = type_expectations @@ -108,7 +132,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e content_expectation = type_expectations[1] for idx, item in enumerate(response): validate_response( - response=item, json_expectation=json_expectation[idx], type_expectations=content_expectation[idx] + response=item, + json_expectation=json_expectation[idx], + type_expectations=content_expectation[idx], ) else: response_json = response @@ -116,7 +142,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e response_json = response.dict(by_alias=True) for key, value in json_expectation.items(): - assert key in response_json, "Field {0} not found within the response object: {1}".format( + assert ( + key in response_json + ), "Field {0} not found within the response object: {1}".format( key, response_json ) @@ -128,11 +156,19 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e # Otherwise, we're just validating a single field that's a pydantic model. if isinstance(value, dict) and not isinstance(type_expectation, tuple): validate_response( - response=response_json[key], json_expectation=value, type_expectations=type_expectation + response=response_json[key], + json_expectation=value, + type_expectations=type_expectation, ) else: - validate_field(response=response_json[key], json_expectation=value, type_expectation=type_expectation) + validate_field( + response=response_json[key], + json_expectation=value, + type_expectation=type_expectation, + ) # Ensure there are no additional fields here either del response_json[key] - assert len(response_json) == 0, "Additional fields found, expected None: {0}".format(response_json) + assert ( + len(response_json) == 0 + ), "Additional fields found, expected None: {0}".format(response_json) diff --git a/seed/python-sdk/custom-auth/tests/utils/assets/models/__init__.py b/seed/python-sdk/custom-auth/tests/utils/assets/models/__init__.py index 2cf01263529..3a1c852e71e 100644 --- a/seed/python-sdk/custom-auth/tests/utils/assets/models/__init__.py +++ b/seed/python-sdk/custom-auth/tests/utils/assets/models/__init__.py @@ -5,7 +5,7 @@ from .circle import CircleParams from .object_with_defaults import ObjectWithDefaultsParams from .object_with_optional_field import ObjectWithOptionalFieldParams -from .shape import Shape_CircleParams, Shape_SquareParams, ShapeParams +from .shape import ShapeParams, Shape_CircleParams, Shape_SquareParams from .square import SquareParams from .undiscriminated_shape import UndiscriminatedShapeParams diff --git a/seed/python-sdk/custom-auth/tests/utils/assets/models/circle.py b/seed/python-sdk/custom-auth/tests/utils/assets/models/circle.py index af7a1bf8a8e..253f12d38b3 100644 --- a/seed/python-sdk/custom-auth/tests/utils/assets/models/circle.py +++ b/seed/python-sdk/custom-auth/tests/utils/assets/models/circle.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class CircleParams(typing_extensions.TypedDict): - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] diff --git a/seed/python-sdk/custom-auth/tests/utils/assets/models/object_with_optional_field.py b/seed/python-sdk/custom-auth/tests/utils/assets/models/object_with_optional_field.py index 3ad93d5f305..ebe7dc80547 100644 --- a/seed/python-sdk/custom-auth/tests/utils/assets/models/object_with_optional_field.py +++ b/seed/python-sdk/custom-auth/tests/utils/assets/models/object_with_optional_field.py @@ -7,8 +7,8 @@ import uuid import typing_extensions -from seed.core.serialization import FieldMetadata +from seed.core.serialization import FieldMetadata from .color import Color from .shape import ShapeParams from .undiscriminated_shape import UndiscriminatedShapeParams @@ -18,16 +18,30 @@ class ObjectWithOptionalFieldParams(typing_extensions.TypedDict): literal: typing.Literal["lit_one"] string: typing_extensions.NotRequired[str] integer: typing_extensions.NotRequired[int] - long_: typing_extensions.NotRequired[typing_extensions.Annotated[int, FieldMetadata(alias="long")]] + long_: typing_extensions.NotRequired[ + typing_extensions.Annotated[int, FieldMetadata(alias="long")] + ] double: typing_extensions.NotRequired[float] - bool_: typing_extensions.NotRequired[typing_extensions.Annotated[bool, FieldMetadata(alias="bool")]] + bool_: typing_extensions.NotRequired[ + typing_extensions.Annotated[bool, FieldMetadata(alias="bool")] + ] datetime: typing_extensions.NotRequired[dt.datetime] date: typing_extensions.NotRequired[dt.date] - uuid_: typing_extensions.NotRequired[typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")]] - base_64: typing_extensions.NotRequired[typing_extensions.Annotated[str, FieldMetadata(alias="base64")]] - list_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")]] - set_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")]] - map_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")]] + uuid_: typing_extensions.NotRequired[ + typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")] + ] + base_64: typing_extensions.NotRequired[ + typing_extensions.Annotated[str, FieldMetadata(alias="base64")] + ] + list_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")] + ] + set_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")] + ] + map_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")] + ] enum: typing_extensions.NotRequired[Color] union: typing_extensions.NotRequired[ShapeParams] second_union: typing_extensions.NotRequired[ShapeParams] diff --git a/seed/python-sdk/custom-auth/tests/utils/assets/models/shape.py b/seed/python-sdk/custom-auth/tests/utils/assets/models/shape.py index 2c33c877951..816ffc51bdc 100644 --- a/seed/python-sdk/custom-auth/tests/utils/assets/models/shape.py +++ b/seed/python-sdk/custom-auth/tests/utils/assets/models/shape.py @@ -7,6 +7,7 @@ import typing import typing_extensions + from seed.core.serialization import FieldMetadata @@ -15,13 +16,21 @@ class Base(typing_extensions.TypedDict): class Shape_CircleParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["circle"], FieldMetadata(alias="shapeType")] - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["circle"], FieldMetadata(alias="shapeType") + ] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] class Shape_SquareParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["square"], FieldMetadata(alias="shapeType")] - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["square"], FieldMetadata(alias="shapeType") + ] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] ShapeParams = typing.Union[Shape_CircleParams, Shape_SquareParams] diff --git a/seed/python-sdk/custom-auth/tests/utils/assets/models/square.py b/seed/python-sdk/custom-auth/tests/utils/assets/models/square.py index b9b7dd319bc..bcf08a723c5 100644 --- a/seed/python-sdk/custom-auth/tests/utils/assets/models/square.py +++ b/seed/python-sdk/custom-auth/tests/utils/assets/models/square.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class SquareParams(typing_extensions.TypedDict): - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] diff --git a/seed/python-sdk/custom-auth/tests/utils/test_http_client.py b/seed/python-sdk/custom-auth/tests/utils/test_http_client.py index edd11ca7afb..f5a874a75f3 100644 --- a/seed/python-sdk/custom-auth/tests/utils/test_http_client.py +++ b/seed/python-sdk/custom-auth/tests/utils/test_http_client.py @@ -9,12 +9,17 @@ def get_request_options() -> RequestOptions: def test_get_json_request_body() -> None: - json_body, data_body = get_request_body(json={"hello": "world"}, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json={"hello": "world"}, data=None, request_options=None, omit=None + ) assert json_body == {"hello": "world"} assert data_body is None json_body_extras, data_body_extras = get_request_body( - json={"goodbye": "world"}, data=None, request_options=get_request_options(), omit=None + json={"goodbye": "world"}, + data=None, + request_options=get_request_options(), + omit=None, ) assert json_body_extras == {"goodbye": "world", "see you": "later"} @@ -22,12 +27,17 @@ def test_get_json_request_body() -> None: def test_get_files_request_body() -> None: - json_body, data_body = get_request_body(json=None, data={"hello": "world"}, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data={"hello": "world"}, request_options=None, omit=None + ) assert data_body == {"hello": "world"} assert json_body is None json_body_extras, data_body_extras = get_request_body( - json=None, data={"goodbye": "world"}, request_options=get_request_options(), omit=None + json=None, + data={"goodbye": "world"}, + request_options=get_request_options(), + omit=None, ) assert data_body_extras == {"goodbye": "world", "see you": "later"} @@ -35,7 +45,9 @@ def test_get_files_request_body() -> None: def test_get_none_request_body() -> None: - json_body, data_body = get_request_body(json=None, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data=None, request_options=None, omit=None + ) assert data_body is None assert json_body is None diff --git a/seed/python-sdk/custom-auth/tests/utils/test_query_encoding.py b/seed/python-sdk/custom-auth/tests/utils/test_query_encoding.py index 247e1551b46..fbc8f402167 100644 --- a/seed/python-sdk/custom-auth/tests/utils/test_query_encoding.py +++ b/seed/python-sdk/custom-auth/tests/utils/test_query_encoding.py @@ -4,9 +4,15 @@ def test_query_encoding() -> None: - assert encode_query({"hello world": "hello world"}) == {"hello world": "hello world"} - assert encode_query({"hello_world": {"hello": "world"}}) == {"hello_world[hello]": "world"} - assert encode_query({"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"}) == { + assert encode_query({"hello world": "hello world"}) == { + "hello world": "hello world" + } + assert encode_query({"hello_world": {"hello": "world"}}) == { + "hello_world[hello]": "world" + } + assert encode_query( + {"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"} + ) == { "hello_world[hello][world]": "today", "hello_world[test]": "this", "hi": "there", diff --git a/seed/python-sdk/custom-auth/tests/utils/test_serialization.py b/seed/python-sdk/custom-auth/tests/utils/test_serialization.py index 58b1ed66e6d..5ca956916dd 100644 --- a/seed/python-sdk/custom-auth/tests/utils/test_serialization.py +++ b/seed/python-sdk/custom-auth/tests/utils/test_serialization.py @@ -1,10 +1,12 @@ # This file was auto-generated by Fern from our API Definition. -from typing import Any, List +from typing import List, Any -from seed.core.serialization import convert_and_respect_annotation_metadata +from seed.core.serialization import ( + convert_and_respect_annotation_metadata, +) +from .assets.models import ShapeParams, ObjectWithOptionalFieldParams -from .assets.models import ObjectWithOptionalFieldParams, ShapeParams UNION_TEST: ShapeParams = {"radius_measurement": 1.0, "shape_type": "circle", "id": "1"} UNION_TEST_CONVERTED = {"shapeType": "circle", "radiusMeasurement": 1.0, "id": "1"} @@ -18,20 +20,54 @@ def test_convert_and_respect_annotation_metadata() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) - assert converted == {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"} + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) + assert converted == { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + } def test_convert_and_respect_annotation_metadata_in_list() -> None: data: List[ObjectWithOptionalFieldParams] = [ - {"string": "string", "long_": 12345, "bool_": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long_": 67890, "list_": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long_": 12345, + "bool_": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long_": 67890, + "list_": [], + "literal": "lit_one", + "any": "any", + }, ] - converted = convert_and_respect_annotation_metadata(object_=data, annotation=List[ObjectWithOptionalFieldParams]) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=List[ObjectWithOptionalFieldParams] + ) assert converted == [ - {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long": 67890, "list": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long": 67890, + "list": [], + "literal": "lit_one", + "any": "any", + }, ] @@ -43,7 +79,9 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) assert converted == { "string": "string", @@ -55,12 +93,16 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: def test_convert_and_respect_annotation_metadata_in_union() -> None: - converted = convert_and_respect_annotation_metadata(object_=UNION_TEST, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=UNION_TEST, annotation=ShapeParams + ) assert converted == UNION_TEST_CONVERTED def test_convert_and_respect_annotation_metadata_with_empty_object() -> None: data: Any = {} - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ShapeParams + ) assert converted == data diff --git a/seed/python-sdk/enum/no-custom-config/pyproject.toml b/seed/python-sdk/enum/no-custom-config/pyproject.toml index 72388612317..e5c016b90f4 100644 --- a/seed/python-sdk/enum/no-custom-config/pyproject.toml +++ b/seed/python-sdk/enum/no-custom-config/pyproject.toml @@ -43,6 +43,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/python-sdk/enum/no-custom-config/src/seed/client.py b/seed/python-sdk/enum/no-custom-config/src/seed/client.py index eaf3716d820..0ee6436e5a1 100644 --- a/seed/python-sdk/enum/no-custom-config/src/seed/client.py +++ b/seed/python-sdk/enum/no-custom-config/src/seed/client.py @@ -1,13 +1,15 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from .inlined_request.client import AsyncInlinedRequestClient, InlinedRequestClient -from .path_param.client import AsyncPathParamClient, PathParamClient -from .query_param.client import AsyncQueryParamClient, QueryParamClient +from .core.client_wrapper import SyncClientWrapper +from .inlined_request.client import InlinedRequestClient +from .path_param.client import PathParamClient +from .query_param.client import QueryParamClient +from .core.client_wrapper import AsyncClientWrapper +from .inlined_request.client import AsyncInlinedRequestClient +from .path_param.client import AsyncPathParamClient +from .query_param.client import AsyncQueryParamClient class SeedEnum: @@ -43,14 +45,18 @@ def __init__( base_url: str, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.Client] = None + httpx_client: typing.Optional[httpx.Client] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = SyncClientWrapper( base_url=base_url, httpx_client=httpx_client if httpx_client is not None - else httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.Client( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.Client(timeout=_defaulted_timeout), timeout=_defaulted_timeout, @@ -93,18 +99,24 @@ def __init__( base_url: str, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.AsyncClient] = None + httpx_client: typing.Optional[httpx.AsyncClient] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = AsyncClientWrapper( base_url=base_url, httpx_client=httpx_client if httpx_client is not None - else httpx.AsyncClient(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.AsyncClient( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.AsyncClient(timeout=_defaulted_timeout), timeout=_defaulted_timeout, ) - self.inlined_request = AsyncInlinedRequestClient(client_wrapper=self._client_wrapper) + self.inlined_request = AsyncInlinedRequestClient( + client_wrapper=self._client_wrapper + ) self.path_param = AsyncPathParamClient(client_wrapper=self._client_wrapper) self.query_param = AsyncQueryParamClient(client_wrapper=self._client_wrapper) diff --git a/seed/python-sdk/enum/no-custom-config/src/seed/core/api_error.py b/seed/python-sdk/enum/no-custom-config/src/seed/core/api_error.py index 2e9fc5431cd..da734b58068 100644 --- a/seed/python-sdk/enum/no-custom-config/src/seed/core/api_error.py +++ b/seed/python-sdk/enum/no-custom-config/src/seed/core/api_error.py @@ -7,7 +7,9 @@ class ApiError(Exception): status_code: typing.Optional[int] body: typing.Any - def __init__(self, *, status_code: typing.Optional[int] = None, body: typing.Any = None): + def __init__( + self, *, status_code: typing.Optional[int] = None, body: typing.Any = None + ): self.status_code = status_code self.body = body diff --git a/seed/python-sdk/enum/no-custom-config/src/seed/core/client_wrapper.py b/seed/python-sdk/enum/no-custom-config/src/seed/core/client_wrapper.py index 5bf926b7b30..ce13bb27a6b 100644 --- a/seed/python-sdk/enum/no-custom-config/src/seed/core/client_wrapper.py +++ b/seed/python-sdk/enum/no-custom-config/src/seed/core/client_wrapper.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .http_client import AsyncHttpClient, HttpClient +from .http_client import HttpClient +from .http_client import AsyncHttpClient class BaseClientWrapper: @@ -28,7 +27,13 @@ def get_timeout(self) -> typing.Optional[float]: class SyncClientWrapper(BaseClientWrapper): - def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, httpx_client: httpx.Client): + def __init__( + self, + *, + base_url: str, + timeout: typing.Optional[float] = None, + httpx_client: httpx.Client, + ): super().__init__(base_url=base_url, timeout=timeout) self.httpx_client = HttpClient( httpx_client=httpx_client, @@ -39,7 +44,13 @@ def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, htt class AsyncClientWrapper(BaseClientWrapper): - def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, httpx_client: httpx.AsyncClient): + def __init__( + self, + *, + base_url: str, + timeout: typing.Optional[float] = None, + httpx_client: httpx.AsyncClient, + ): super().__init__(base_url=base_url, timeout=timeout) self.httpx_client = AsyncHttpClient( httpx_client=httpx_client, diff --git a/seed/python-sdk/enum/no-custom-config/src/seed/core/datetime_utils.py b/seed/python-sdk/enum/no-custom-config/src/seed/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/python-sdk/enum/no-custom-config/src/seed/core/datetime_utils.py +++ b/seed/python-sdk/enum/no-custom-config/src/seed/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/python-sdk/enum/no-custom-config/src/seed/core/file.py b/seed/python-sdk/enum/no-custom-config/src/seed/core/file.py index cb0d40bbbf3..6e0f92bfcb1 100644 --- a/seed/python-sdk/enum/no-custom-config/src/seed/core/file.py +++ b/seed/python-sdk/enum/no-custom-config/src/seed/core/file.py @@ -13,12 +13,17 @@ # (filename, file (or bytes), content_type) typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str]], # (filename, file (or bytes), content_type, headers) - typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str], typing.Mapping[str, str]], + typing.Tuple[ + typing.Optional[str], + FileContent, + typing.Optional[str], + typing.Mapping[str, str], + ], ] def convert_file_dict_to_httpx_tuples( - d: typing.Dict[str, typing.Union[File, typing.List[File]]] + d: typing.Dict[str, typing.Union[File, typing.List[File]]], ) -> typing.List[typing.Tuple[str, File]]: """ The format we use is a list of tuples, where the first element is the diff --git a/seed/python-sdk/enum/no-custom-config/src/seed/core/http_client.py b/seed/python-sdk/enum/no-custom-config/src/seed/core/http_client.py index 9333d8a7f15..091f71bc185 100644 --- a/seed/python-sdk/enum/no-custom-config/src/seed/core/http_client.py +++ b/seed/python-sdk/enum/no-custom-config/src/seed/core/http_client.py @@ -77,7 +77,9 @@ def _retry_timeout(response: httpx.Response, retries: int) -> float: return retry_after # Apply exponential backoff, capped at MAX_RETRY_DELAY_SECONDS. - retry_delay = min(INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS) + retry_delay = min( + INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS + ) # Add a randomness / jitter to the retry delay to avoid overwhelming the server with retries. timeout = retry_delay * (1 - 0.25 * random()) @@ -90,7 +92,8 @@ def _should_retry(response: httpx.Response) -> bool: def remove_omit_from_dict( - original: typing.Dict[str, typing.Optional[typing.Any]], omit: typing.Optional[typing.Any] + original: typing.Dict[str, typing.Optional[typing.Any]], + omit: typing.Optional[typing.Any], ) -> typing.Dict[str, typing.Any]: if omit is None: return original @@ -108,7 +111,8 @@ def maybe_filter_request_body( ) -> typing.Optional[typing.Any]: if data is None: return ( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else None ) @@ -118,7 +122,8 @@ def maybe_filter_request_body( data_content = { **(jsonable_encoder(remove_omit_from_dict(data, omit))), # type: ignore **( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else {} ), @@ -162,7 +167,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url def request( @@ -174,8 +181,12 @@ def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -184,11 +195,14 @@ def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) response = self.httpx_client.request( method=method, @@ -198,7 +212,11 @@ def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -209,7 +227,10 @@ def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -222,11 +243,15 @@ def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: time.sleep(_retry_timeout(response=response, retries=retries)) @@ -256,8 +281,12 @@ def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -266,11 +295,14 @@ def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) with self.httpx_client.stream( method=method, @@ -280,7 +312,11 @@ def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -291,7 +327,9 @@ def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -304,7 +342,9 @@ def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream @@ -327,7 +367,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url async def request( @@ -339,8 +381,12 @@ async def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -349,11 +395,14 @@ async def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) # Add the input to each of these and do None-safety checks response = await self.httpx_client.request( @@ -364,7 +413,11 @@ async def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -375,7 +428,10 @@ async def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -388,11 +444,15 @@ async def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: await asyncio.sleep(_retry_timeout(response=response, retries=retries)) @@ -421,8 +481,12 @@ async def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -431,11 +495,14 @@ async def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) async with self.httpx_client.stream( method=method, @@ -445,7 +512,11 @@ async def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -456,7 +527,9 @@ async def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -469,7 +542,9 @@ async def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream diff --git a/seed/python-sdk/enum/no-custom-config/src/seed/core/jsonable_encoder.py b/seed/python-sdk/enum/no-custom-config/src/seed/core/jsonable_encoder.py index d3fd328fd41..12a8b52fc22 100644 --- a/seed/python-sdk/enum/no-custom-config/src/seed/core/jsonable_encoder.py +++ b/seed/python-sdk/enum/no-custom-config/src/seed/core/jsonable_encoder.py @@ -19,13 +19,19 @@ import pydantic from .datetime_utils import serialize_datetime -from .pydantic_utilities import IS_PYDANTIC_V2, encode_by_type, to_jsonable_with_fallback +from .pydantic_utilities import ( + IS_PYDANTIC_V2, + encode_by_type, + to_jsonable_with_fallback, +) SetIntStr = Set[Union[int, str]] DictIntStrAny = Dict[Union[int, str], Any] -def jsonable_encoder(obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None) -> Any: +def jsonable_encoder( + obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None +) -> Any: custom_encoder = custom_encoder or {} if custom_encoder: if type(obj) in custom_encoder: diff --git a/seed/python-sdk/enum/no-custom-config/src/seed/core/pydantic_utilities.py b/seed/python-sdk/enum/no-custom-config/src/seed/core/pydantic_utilities.py index 170a563d6eb..c63935c32a2 100644 --- a/seed/python-sdk/enum/no-custom-config/src/seed/core/pydantic_utilities.py +++ b/seed/python-sdk/enum/no-custom-config/src/seed/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) # type: ignore # Pydantic v1 diff --git a/seed/python-sdk/enum/no-custom-config/src/seed/core/query_encoder.py b/seed/python-sdk/enum/no-custom-config/src/seed/core/query_encoder.py index 24076d72ee9..7cb98f52cd7 100644 --- a/seed/python-sdk/enum/no-custom-config/src/seed/core/query_encoder.py +++ b/seed/python-sdk/enum/no-custom-config/src/seed/core/query_encoder.py @@ -7,7 +7,9 @@ # Flattens dicts to be of the form {"key[subkey][subkey2]": value} where value is not a dict -def traverse_query_dict(dict_flat: Dict[str, Any], key_prefix: Optional[str] = None) -> Dict[str, Any]: +def traverse_query_dict( + dict_flat: Dict[str, Any], key_prefix: Optional[str] = None +) -> Dict[str, Any]: result = {} for k, v in dict_flat.items(): key = f"{key_prefix}[{k}]" if key_prefix is not None else k @@ -30,4 +32,8 @@ def single_query_encoder(query_key: str, query_value: Any) -> Dict[str, Any]: def encode_query(query: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: - return dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) if query is not None else None + return ( + dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) + if query is not None + else None + ) diff --git a/seed/python-sdk/enum/no-custom-config/src/seed/core/serialization.py b/seed/python-sdk/enum/no-custom-config/src/seed/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/python-sdk/enum/no-custom-config/src/seed/core/serialization.py +++ b/seed/python-sdk/enum/no-custom-config/src/seed/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/python-sdk/enum/no-custom-config/src/seed/inlined_request/client.py b/seed/python-sdk/enum/no-custom-config/src/seed/inlined_request/client.py index 2f899ac9802..53c4040e37a 100644 --- a/seed/python-sdk/enum/no-custom-config/src/seed/inlined_request/client.py +++ b/seed/python-sdk/enum/no-custom-config/src/seed/inlined_request/client.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. import typing +from ..core.client_wrapper import SyncClientWrapper +from ..types.operand import Operand +from ..types.color_or_operand import ColorOrOperand +from ..core.request_options import RequestOptions from json.decoder import JSONDecodeError - from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.request_options import RequestOptions -from ..types.color_or_operand import ColorOrOperand -from ..types.operand import Operand +from ..core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -24,7 +24,7 @@ def send( operand_or_color: ColorOrOperand, maybe_operand: typing.Optional[Operand] = OMIT, maybe_operand_or_color: typing.Optional[ColorOrOperand] = OMIT, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ Parameters @@ -88,7 +88,7 @@ async def send( operand_or_color: ColorOrOperand, maybe_operand: typing.Optional[Operand] = OMIT, maybe_operand_or_color: typing.Optional[ColorOrOperand] = OMIT, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ Parameters diff --git a/seed/python-sdk/enum/no-custom-config/src/seed/path_param/client.py b/seed/python-sdk/enum/no-custom-config/src/seed/path_param/client.py index 12849485cdb..7f358ef6cbc 100644 --- a/seed/python-sdk/enum/no-custom-config/src/seed/path_param/client.py +++ b/seed/python-sdk/enum/no-custom-config/src/seed/path_param/client.py @@ -1,14 +1,14 @@ # This file was auto-generated by Fern from our API Definition. +from ..core.client_wrapper import SyncClientWrapper +from ..types.operand import Operand import typing +from ..types.color_or_operand import ColorOrOperand +from ..core.request_options import RequestOptions +from ..core.jsonable_encoder import jsonable_encoder from json.decoder import JSONDecodeError - from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.jsonable_encoder import jsonable_encoder -from ..core.request_options import RequestOptions -from ..types.color_or_operand import ColorOrOperand -from ..types.operand import Operand +from ..core.client_wrapper import AsyncClientWrapper class PathParamClient: diff --git a/seed/python-sdk/enum/no-custom-config/src/seed/query_param/client.py b/seed/python-sdk/enum/no-custom-config/src/seed/query_param/client.py index 799d5ee8f9a..8c1235f9667 100644 --- a/seed/python-sdk/enum/no-custom-config/src/seed/query_param/client.py +++ b/seed/python-sdk/enum/no-custom-config/src/seed/query_param/client.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. +from ..core.client_wrapper import SyncClientWrapper +from ..types.operand import Operand +from ..types.color_or_operand import ColorOrOperand import typing +from ..core.request_options import RequestOptions from json.decoder import JSONDecodeError - from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.request_options import RequestOptions -from ..types.color_or_operand import ColorOrOperand -from ..types.operand import Operand +from ..core.client_wrapper import AsyncClientWrapper class QueryParamClient: @@ -21,7 +21,7 @@ def send( operand_or_color: ColorOrOperand, maybe_operand: typing.Optional[Operand] = None, maybe_operand_or_color: typing.Optional[ColorOrOperand] = None, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ Parameters @@ -77,9 +77,13 @@ def send_list( *, operand: typing.Union[Operand, typing.Sequence[Operand]], operand_or_color: typing.Union[ColorOrOperand, typing.Sequence[ColorOrOperand]], - maybe_operand: typing.Optional[typing.Union[Operand, typing.Sequence[Operand]]] = None, - maybe_operand_or_color: typing.Optional[typing.Union[ColorOrOperand, typing.Sequence[ColorOrOperand]]] = None, - request_options: typing.Optional[RequestOptions] = None + maybe_operand: typing.Optional[ + typing.Union[Operand, typing.Sequence[Operand]] + ] = None, + maybe_operand_or_color: typing.Optional[ + typing.Union[ColorOrOperand, typing.Sequence[ColorOrOperand]] + ] = None, + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ Parameters @@ -144,7 +148,7 @@ async def send( operand_or_color: ColorOrOperand, maybe_operand: typing.Optional[Operand] = None, maybe_operand_or_color: typing.Optional[ColorOrOperand] = None, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ Parameters @@ -208,9 +212,13 @@ async def send_list( *, operand: typing.Union[Operand, typing.Sequence[Operand]], operand_or_color: typing.Union[ColorOrOperand, typing.Sequence[ColorOrOperand]], - maybe_operand: typing.Optional[typing.Union[Operand, typing.Sequence[Operand]]] = None, - maybe_operand_or_color: typing.Optional[typing.Union[ColorOrOperand, typing.Sequence[ColorOrOperand]]] = None, - request_options: typing.Optional[RequestOptions] = None + maybe_operand: typing.Optional[ + typing.Union[Operand, typing.Sequence[Operand]] + ] = None, + maybe_operand_or_color: typing.Optional[ + typing.Union[ColorOrOperand, typing.Sequence[ColorOrOperand]] + ] = None, + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ Parameters diff --git a/seed/python-sdk/enum/no-custom-config/src/seed/types/color_or_operand.py b/seed/python-sdk/enum/no-custom-config/src/seed/types/color_or_operand.py index 5de8179707c..1bbec1032b1 100644 --- a/seed/python-sdk/enum/no-custom-config/src/seed/types/color_or_operand.py +++ b/seed/python-sdk/enum/no-custom-config/src/seed/types/color_or_operand.py @@ -1,7 +1,6 @@ # This file was auto-generated by Fern from our API Definition. import typing - from .color import Color from .operand import Operand diff --git a/seed/python-sdk/enum/no-custom-config/src/seed/version.py b/seed/python-sdk/enum/no-custom-config/src/seed/version.py index d345d6a9fb2..2355c6d81ab 100644 --- a/seed/python-sdk/enum/no-custom-config/src/seed/version.py +++ b/seed/python-sdk/enum/no-custom-config/src/seed/version.py @@ -1,4 +1,3 @@ - from importlib import metadata __version__ = metadata.version("fern_enum") diff --git a/seed/python-sdk/enum/no-custom-config/tests/conftest.py b/seed/python-sdk/enum/no-custom-config/tests/conftest.py index 1b3ac7545f4..1ab8753c9f4 100644 --- a/seed/python-sdk/enum/no-custom-config/tests/conftest.py +++ b/seed/python-sdk/enum/no-custom-config/tests/conftest.py @@ -1,9 +1,9 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedEnum import os - import pytest -from seed import AsyncSeedEnum, SeedEnum +from seed import AsyncSeedEnum @pytest.fixture diff --git a/seed/python-sdk/enum/no-custom-config/tests/custom/test_client.py b/seed/python-sdk/enum/no-custom-config/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/python-sdk/enum/no-custom-config/tests/custom/test_client.py +++ b/seed/python-sdk/enum/no-custom-config/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/python-sdk/enum/no-custom-config/tests/test_inlined_request.py b/seed/python-sdk/enum/no-custom-config/tests/test_inlined_request.py index 69729cb5d54..ae04a061add 100644 --- a/seed/python-sdk/enum/no-custom-config/tests/test_inlined_request.py +++ b/seed/python-sdk/enum/no-custom-config/tests/test_inlined_request.py @@ -1,10 +1,14 @@ # This file was auto-generated by Fern from our API Definition. -from seed import AsyncSeedEnum, SeedEnum +from seed import SeedEnum +from seed import AsyncSeedEnum async def test_send(client: SeedEnum, async_client: AsyncSeedEnum) -> None: # Type ignore to avoid mypy complaining about the function not being meant to return a value assert client.inlined_request.send(operand=">", operand_or_color="red") is None # type: ignore[func-returns-value] - assert await async_client.inlined_request.send(operand=">", operand_or_color="red") is None # type: ignore[func-returns-value] + assert ( + await async_client.inlined_request.send(operand=">", operand_or_color="red") + is None + ) # type: ignore[func-returns-value] diff --git a/seed/python-sdk/enum/no-custom-config/tests/test_path_param.py b/seed/python-sdk/enum/no-custom-config/tests/test_path_param.py index 2d7180380ec..982460b82e1 100644 --- a/seed/python-sdk/enum/no-custom-config/tests/test_path_param.py +++ b/seed/python-sdk/enum/no-custom-config/tests/test_path_param.py @@ -1,10 +1,27 @@ # This file was auto-generated by Fern from our API Definition. -from seed import AsyncSeedEnum, SeedEnum +from seed import SeedEnum +from seed import AsyncSeedEnum async def test_send(client: SeedEnum, async_client: AsyncSeedEnum) -> None: # Type ignore to avoid mypy complaining about the function not being meant to return a value - assert client.path_param.send(operand=">", maybe_operand="less_than", operand_or_color="red", maybe_operand_or_color="red") is None # type: ignore[func-returns-value] + assert ( + client.path_param.send( + operand=">", + maybe_operand="less_than", + operand_or_color="red", + maybe_operand_or_color="red", + ) + is None + ) # type: ignore[func-returns-value] - assert await async_client.path_param.send(operand=">", maybe_operand="less_than", operand_or_color="red", maybe_operand_or_color="red") is None # type: ignore[func-returns-value] + assert ( + await async_client.path_param.send( + operand=">", + maybe_operand="less_than", + operand_or_color="red", + maybe_operand_or_color="red", + ) + is None + ) # type: ignore[func-returns-value] diff --git a/seed/python-sdk/enum/no-custom-config/tests/test_query_param.py b/seed/python-sdk/enum/no-custom-config/tests/test_query_param.py index 374e5b19fd1..c610d4d0f1f 100644 --- a/seed/python-sdk/enum/no-custom-config/tests/test_query_param.py +++ b/seed/python-sdk/enum/no-custom-config/tests/test_query_param.py @@ -1,17 +1,36 @@ # This file was auto-generated by Fern from our API Definition. -from seed import AsyncSeedEnum, SeedEnum +from seed import SeedEnum +from seed import AsyncSeedEnum async def test_send(client: SeedEnum, async_client: AsyncSeedEnum) -> None: # Type ignore to avoid mypy complaining about the function not being meant to return a value assert client.query_param.send(operand=">", operand_or_color="red") is None # type: ignore[func-returns-value] - assert await async_client.query_param.send(operand=">", operand_or_color="red") is None # type: ignore[func-returns-value] + assert ( + await async_client.query_param.send(operand=">", operand_or_color="red") is None + ) # type: ignore[func-returns-value] async def test_send_list(client: SeedEnum, async_client: AsyncSeedEnum) -> None: # Type ignore to avoid mypy complaining about the function not being meant to return a value - assert client.query_param.send_list(operand=">", maybe_operand=">", operand_or_color="red", maybe_operand_or_color="red") is None # type: ignore[func-returns-value] + assert ( + client.query_param.send_list( + operand=">", + maybe_operand=">", + operand_or_color="red", + maybe_operand_or_color="red", + ) + is None + ) # type: ignore[func-returns-value] - assert await async_client.query_param.send_list(operand=">", maybe_operand=">", operand_or_color="red", maybe_operand_or_color="red") is None # type: ignore[func-returns-value] + assert ( + await async_client.query_param.send_list( + operand=">", + maybe_operand=">", + operand_or_color="red", + maybe_operand_or_color="red", + ) + is None + ) # type: ignore[func-returns-value] diff --git a/seed/python-sdk/enum/no-custom-config/tests/utilities.py b/seed/python-sdk/enum/no-custom-config/tests/utilities.py index 13da208eb3a..e8f4472564c 100644 --- a/seed/python-sdk/enum/no-custom-config/tests/utilities.py +++ b/seed/python-sdk/enum/no-custom-config/tests/utilities.py @@ -3,11 +3,14 @@ import typing import uuid -import pydantic from dateutil import parser +import pydantic + -def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> typing.Any: +def cast_field( + json_expectation: typing.Any, type_expectation: typing.Any +) -> typing.Any: # Cast these specific types which come through as string and expect our # models to cast to the correct type. if type_expectation == "uuid": @@ -25,7 +28,9 @@ def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> ty return json_expectation -def validate_field(response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any) -> None: +def validate_field( + response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectation == "no_validate": return @@ -44,7 +49,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(entry_expectation, dict): is_container_of_complex_type = True validate_response( - response=response[idx], json_expectation=ex, type_expectations=entry_expectation + response=response[idx], + json_expectation=ex, + type_expectations=entry_expectation, ) else: cast_json_expectation.append(cast_field(ex, entry_expectation)) @@ -56,7 +63,10 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # if any of the values of the set have a type_expectation of a dict, we're assuming it's a pydantic # model and keeping it a list. if container_expectation != "set" or not any( - map(lambda value: isinstance(value, dict), list(contents_expectation.values())) + map( + lambda value: isinstance(value, dict), + list(contents_expectation.values()), + ) ): json_expectation = cast_field(json_expectation, container_expectation) elif isinstance(type_expectation, tuple): @@ -65,9 +75,15 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(contents_expectation, dict): json_expectation = { cast_field( - key, contents_expectation.get(idx)[0] if contents_expectation.get(idx) is not None else None # type: ignore + key, + contents_expectation.get(idx)[0] + if contents_expectation.get(idx) is not None + else None, # type: ignore ): cast_field( - value, contents_expectation.get(idx)[1] if contents_expectation.get(idx) is not None else None # type: ignore + value, + contents_expectation.get(idx)[1] + if contents_expectation.get(idx) is not None + else None, # type: ignore ) for idx, (key, value) in enumerate(json_expectation.items()) } @@ -86,7 +102,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # Arg type_expectations is a deeply nested structure that matches the response, but with the values replaced with the expected types -def validate_response(response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any) -> None: +def validate_response( + response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectations == "no_validate": return @@ -96,11 +114,17 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e and not isinstance(response, dict) and not issubclass(type(response), pydantic.BaseModel) ): - validate_field(response=response, json_expectation=json_expectation, type_expectation=type_expectations) + validate_field( + response=response, + json_expectation=json_expectation, + type_expectation=type_expectations, + ) return if isinstance(response, list): - assert len(response) == len(json_expectation), "Length mismatch, expected: {0}, Actual: {1}".format( + assert len(response) == len( + json_expectation + ), "Length mismatch, expected: {0}, Actual: {1}".format( len(response), len(json_expectation) ) content_expectation = type_expectations @@ -108,7 +132,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e content_expectation = type_expectations[1] for idx, item in enumerate(response): validate_response( - response=item, json_expectation=json_expectation[idx], type_expectations=content_expectation[idx] + response=item, + json_expectation=json_expectation[idx], + type_expectations=content_expectation[idx], ) else: response_json = response @@ -116,7 +142,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e response_json = response.dict(by_alias=True) for key, value in json_expectation.items(): - assert key in response_json, "Field {0} not found within the response object: {1}".format( + assert ( + key in response_json + ), "Field {0} not found within the response object: {1}".format( key, response_json ) @@ -128,11 +156,19 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e # Otherwise, we're just validating a single field that's a pydantic model. if isinstance(value, dict) and not isinstance(type_expectation, tuple): validate_response( - response=response_json[key], json_expectation=value, type_expectations=type_expectation + response=response_json[key], + json_expectation=value, + type_expectations=type_expectation, ) else: - validate_field(response=response_json[key], json_expectation=value, type_expectation=type_expectation) + validate_field( + response=response_json[key], + json_expectation=value, + type_expectation=type_expectation, + ) # Ensure there are no additional fields here either del response_json[key] - assert len(response_json) == 0, "Additional fields found, expected None: {0}".format(response_json) + assert ( + len(response_json) == 0 + ), "Additional fields found, expected None: {0}".format(response_json) diff --git a/seed/python-sdk/enum/no-custom-config/tests/utils/assets/models/__init__.py b/seed/python-sdk/enum/no-custom-config/tests/utils/assets/models/__init__.py index 2cf01263529..3a1c852e71e 100644 --- a/seed/python-sdk/enum/no-custom-config/tests/utils/assets/models/__init__.py +++ b/seed/python-sdk/enum/no-custom-config/tests/utils/assets/models/__init__.py @@ -5,7 +5,7 @@ from .circle import CircleParams from .object_with_defaults import ObjectWithDefaultsParams from .object_with_optional_field import ObjectWithOptionalFieldParams -from .shape import Shape_CircleParams, Shape_SquareParams, ShapeParams +from .shape import ShapeParams, Shape_CircleParams, Shape_SquareParams from .square import SquareParams from .undiscriminated_shape import UndiscriminatedShapeParams diff --git a/seed/python-sdk/enum/no-custom-config/tests/utils/assets/models/circle.py b/seed/python-sdk/enum/no-custom-config/tests/utils/assets/models/circle.py index af7a1bf8a8e..253f12d38b3 100644 --- a/seed/python-sdk/enum/no-custom-config/tests/utils/assets/models/circle.py +++ b/seed/python-sdk/enum/no-custom-config/tests/utils/assets/models/circle.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class CircleParams(typing_extensions.TypedDict): - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] diff --git a/seed/python-sdk/enum/no-custom-config/tests/utils/assets/models/object_with_optional_field.py b/seed/python-sdk/enum/no-custom-config/tests/utils/assets/models/object_with_optional_field.py index 3ad93d5f305..ebe7dc80547 100644 --- a/seed/python-sdk/enum/no-custom-config/tests/utils/assets/models/object_with_optional_field.py +++ b/seed/python-sdk/enum/no-custom-config/tests/utils/assets/models/object_with_optional_field.py @@ -7,8 +7,8 @@ import uuid import typing_extensions -from seed.core.serialization import FieldMetadata +from seed.core.serialization import FieldMetadata from .color import Color from .shape import ShapeParams from .undiscriminated_shape import UndiscriminatedShapeParams @@ -18,16 +18,30 @@ class ObjectWithOptionalFieldParams(typing_extensions.TypedDict): literal: typing.Literal["lit_one"] string: typing_extensions.NotRequired[str] integer: typing_extensions.NotRequired[int] - long_: typing_extensions.NotRequired[typing_extensions.Annotated[int, FieldMetadata(alias="long")]] + long_: typing_extensions.NotRequired[ + typing_extensions.Annotated[int, FieldMetadata(alias="long")] + ] double: typing_extensions.NotRequired[float] - bool_: typing_extensions.NotRequired[typing_extensions.Annotated[bool, FieldMetadata(alias="bool")]] + bool_: typing_extensions.NotRequired[ + typing_extensions.Annotated[bool, FieldMetadata(alias="bool")] + ] datetime: typing_extensions.NotRequired[dt.datetime] date: typing_extensions.NotRequired[dt.date] - uuid_: typing_extensions.NotRequired[typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")]] - base_64: typing_extensions.NotRequired[typing_extensions.Annotated[str, FieldMetadata(alias="base64")]] - list_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")]] - set_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")]] - map_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")]] + uuid_: typing_extensions.NotRequired[ + typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")] + ] + base_64: typing_extensions.NotRequired[ + typing_extensions.Annotated[str, FieldMetadata(alias="base64")] + ] + list_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")] + ] + set_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")] + ] + map_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")] + ] enum: typing_extensions.NotRequired[Color] union: typing_extensions.NotRequired[ShapeParams] second_union: typing_extensions.NotRequired[ShapeParams] diff --git a/seed/python-sdk/enum/no-custom-config/tests/utils/assets/models/shape.py b/seed/python-sdk/enum/no-custom-config/tests/utils/assets/models/shape.py index 2c33c877951..816ffc51bdc 100644 --- a/seed/python-sdk/enum/no-custom-config/tests/utils/assets/models/shape.py +++ b/seed/python-sdk/enum/no-custom-config/tests/utils/assets/models/shape.py @@ -7,6 +7,7 @@ import typing import typing_extensions + from seed.core.serialization import FieldMetadata @@ -15,13 +16,21 @@ class Base(typing_extensions.TypedDict): class Shape_CircleParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["circle"], FieldMetadata(alias="shapeType")] - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["circle"], FieldMetadata(alias="shapeType") + ] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] class Shape_SquareParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["square"], FieldMetadata(alias="shapeType")] - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["square"], FieldMetadata(alias="shapeType") + ] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] ShapeParams = typing.Union[Shape_CircleParams, Shape_SquareParams] diff --git a/seed/python-sdk/enum/no-custom-config/tests/utils/assets/models/square.py b/seed/python-sdk/enum/no-custom-config/tests/utils/assets/models/square.py index b9b7dd319bc..bcf08a723c5 100644 --- a/seed/python-sdk/enum/no-custom-config/tests/utils/assets/models/square.py +++ b/seed/python-sdk/enum/no-custom-config/tests/utils/assets/models/square.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class SquareParams(typing_extensions.TypedDict): - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] diff --git a/seed/python-sdk/enum/no-custom-config/tests/utils/test_http_client.py b/seed/python-sdk/enum/no-custom-config/tests/utils/test_http_client.py index edd11ca7afb..f5a874a75f3 100644 --- a/seed/python-sdk/enum/no-custom-config/tests/utils/test_http_client.py +++ b/seed/python-sdk/enum/no-custom-config/tests/utils/test_http_client.py @@ -9,12 +9,17 @@ def get_request_options() -> RequestOptions: def test_get_json_request_body() -> None: - json_body, data_body = get_request_body(json={"hello": "world"}, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json={"hello": "world"}, data=None, request_options=None, omit=None + ) assert json_body == {"hello": "world"} assert data_body is None json_body_extras, data_body_extras = get_request_body( - json={"goodbye": "world"}, data=None, request_options=get_request_options(), omit=None + json={"goodbye": "world"}, + data=None, + request_options=get_request_options(), + omit=None, ) assert json_body_extras == {"goodbye": "world", "see you": "later"} @@ -22,12 +27,17 @@ def test_get_json_request_body() -> None: def test_get_files_request_body() -> None: - json_body, data_body = get_request_body(json=None, data={"hello": "world"}, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data={"hello": "world"}, request_options=None, omit=None + ) assert data_body == {"hello": "world"} assert json_body is None json_body_extras, data_body_extras = get_request_body( - json=None, data={"goodbye": "world"}, request_options=get_request_options(), omit=None + json=None, + data={"goodbye": "world"}, + request_options=get_request_options(), + omit=None, ) assert data_body_extras == {"goodbye": "world", "see you": "later"} @@ -35,7 +45,9 @@ def test_get_files_request_body() -> None: def test_get_none_request_body() -> None: - json_body, data_body = get_request_body(json=None, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data=None, request_options=None, omit=None + ) assert data_body is None assert json_body is None diff --git a/seed/python-sdk/enum/no-custom-config/tests/utils/test_query_encoding.py b/seed/python-sdk/enum/no-custom-config/tests/utils/test_query_encoding.py index 247e1551b46..fbc8f402167 100644 --- a/seed/python-sdk/enum/no-custom-config/tests/utils/test_query_encoding.py +++ b/seed/python-sdk/enum/no-custom-config/tests/utils/test_query_encoding.py @@ -4,9 +4,15 @@ def test_query_encoding() -> None: - assert encode_query({"hello world": "hello world"}) == {"hello world": "hello world"} - assert encode_query({"hello_world": {"hello": "world"}}) == {"hello_world[hello]": "world"} - assert encode_query({"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"}) == { + assert encode_query({"hello world": "hello world"}) == { + "hello world": "hello world" + } + assert encode_query({"hello_world": {"hello": "world"}}) == { + "hello_world[hello]": "world" + } + assert encode_query( + {"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"} + ) == { "hello_world[hello][world]": "today", "hello_world[test]": "this", "hi": "there", diff --git a/seed/python-sdk/enum/no-custom-config/tests/utils/test_serialization.py b/seed/python-sdk/enum/no-custom-config/tests/utils/test_serialization.py index 58b1ed66e6d..5ca956916dd 100644 --- a/seed/python-sdk/enum/no-custom-config/tests/utils/test_serialization.py +++ b/seed/python-sdk/enum/no-custom-config/tests/utils/test_serialization.py @@ -1,10 +1,12 @@ # This file was auto-generated by Fern from our API Definition. -from typing import Any, List +from typing import List, Any -from seed.core.serialization import convert_and_respect_annotation_metadata +from seed.core.serialization import ( + convert_and_respect_annotation_metadata, +) +from .assets.models import ShapeParams, ObjectWithOptionalFieldParams -from .assets.models import ObjectWithOptionalFieldParams, ShapeParams UNION_TEST: ShapeParams = {"radius_measurement": 1.0, "shape_type": "circle", "id": "1"} UNION_TEST_CONVERTED = {"shapeType": "circle", "radiusMeasurement": 1.0, "id": "1"} @@ -18,20 +20,54 @@ def test_convert_and_respect_annotation_metadata() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) - assert converted == {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"} + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) + assert converted == { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + } def test_convert_and_respect_annotation_metadata_in_list() -> None: data: List[ObjectWithOptionalFieldParams] = [ - {"string": "string", "long_": 12345, "bool_": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long_": 67890, "list_": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long_": 12345, + "bool_": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long_": 67890, + "list_": [], + "literal": "lit_one", + "any": "any", + }, ] - converted = convert_and_respect_annotation_metadata(object_=data, annotation=List[ObjectWithOptionalFieldParams]) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=List[ObjectWithOptionalFieldParams] + ) assert converted == [ - {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long": 67890, "list": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long": 67890, + "list": [], + "literal": "lit_one", + "any": "any", + }, ] @@ -43,7 +79,9 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) assert converted == { "string": "string", @@ -55,12 +93,16 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: def test_convert_and_respect_annotation_metadata_in_union() -> None: - converted = convert_and_respect_annotation_metadata(object_=UNION_TEST, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=UNION_TEST, annotation=ShapeParams + ) assert converted == UNION_TEST_CONVERTED def test_convert_and_respect_annotation_metadata_with_empty_object() -> None: data: Any = {} - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ShapeParams + ) assert converted == data diff --git a/seed/python-sdk/enum/strenum/pyproject.toml b/seed/python-sdk/enum/strenum/pyproject.toml index 72388612317..e5c016b90f4 100644 --- a/seed/python-sdk/enum/strenum/pyproject.toml +++ b/seed/python-sdk/enum/strenum/pyproject.toml @@ -43,6 +43,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/python-sdk/enum/strenum/src/seed/client.py b/seed/python-sdk/enum/strenum/src/seed/client.py index eaf3716d820..0ee6436e5a1 100644 --- a/seed/python-sdk/enum/strenum/src/seed/client.py +++ b/seed/python-sdk/enum/strenum/src/seed/client.py @@ -1,13 +1,15 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from .inlined_request.client import AsyncInlinedRequestClient, InlinedRequestClient -from .path_param.client import AsyncPathParamClient, PathParamClient -from .query_param.client import AsyncQueryParamClient, QueryParamClient +from .core.client_wrapper import SyncClientWrapper +from .inlined_request.client import InlinedRequestClient +from .path_param.client import PathParamClient +from .query_param.client import QueryParamClient +from .core.client_wrapper import AsyncClientWrapper +from .inlined_request.client import AsyncInlinedRequestClient +from .path_param.client import AsyncPathParamClient +from .query_param.client import AsyncQueryParamClient class SeedEnum: @@ -43,14 +45,18 @@ def __init__( base_url: str, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.Client] = None + httpx_client: typing.Optional[httpx.Client] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = SyncClientWrapper( base_url=base_url, httpx_client=httpx_client if httpx_client is not None - else httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.Client( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.Client(timeout=_defaulted_timeout), timeout=_defaulted_timeout, @@ -93,18 +99,24 @@ def __init__( base_url: str, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.AsyncClient] = None + httpx_client: typing.Optional[httpx.AsyncClient] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = AsyncClientWrapper( base_url=base_url, httpx_client=httpx_client if httpx_client is not None - else httpx.AsyncClient(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.AsyncClient( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.AsyncClient(timeout=_defaulted_timeout), timeout=_defaulted_timeout, ) - self.inlined_request = AsyncInlinedRequestClient(client_wrapper=self._client_wrapper) + self.inlined_request = AsyncInlinedRequestClient( + client_wrapper=self._client_wrapper + ) self.path_param = AsyncPathParamClient(client_wrapper=self._client_wrapper) self.query_param = AsyncQueryParamClient(client_wrapper=self._client_wrapper) diff --git a/seed/python-sdk/enum/strenum/src/seed/core/api_error.py b/seed/python-sdk/enum/strenum/src/seed/core/api_error.py index 2e9fc5431cd..da734b58068 100644 --- a/seed/python-sdk/enum/strenum/src/seed/core/api_error.py +++ b/seed/python-sdk/enum/strenum/src/seed/core/api_error.py @@ -7,7 +7,9 @@ class ApiError(Exception): status_code: typing.Optional[int] body: typing.Any - def __init__(self, *, status_code: typing.Optional[int] = None, body: typing.Any = None): + def __init__( + self, *, status_code: typing.Optional[int] = None, body: typing.Any = None + ): self.status_code = status_code self.body = body diff --git a/seed/python-sdk/enum/strenum/src/seed/core/client_wrapper.py b/seed/python-sdk/enum/strenum/src/seed/core/client_wrapper.py index 5bf926b7b30..ce13bb27a6b 100644 --- a/seed/python-sdk/enum/strenum/src/seed/core/client_wrapper.py +++ b/seed/python-sdk/enum/strenum/src/seed/core/client_wrapper.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .http_client import AsyncHttpClient, HttpClient +from .http_client import HttpClient +from .http_client import AsyncHttpClient class BaseClientWrapper: @@ -28,7 +27,13 @@ def get_timeout(self) -> typing.Optional[float]: class SyncClientWrapper(BaseClientWrapper): - def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, httpx_client: httpx.Client): + def __init__( + self, + *, + base_url: str, + timeout: typing.Optional[float] = None, + httpx_client: httpx.Client, + ): super().__init__(base_url=base_url, timeout=timeout) self.httpx_client = HttpClient( httpx_client=httpx_client, @@ -39,7 +44,13 @@ def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, htt class AsyncClientWrapper(BaseClientWrapper): - def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, httpx_client: httpx.AsyncClient): + def __init__( + self, + *, + base_url: str, + timeout: typing.Optional[float] = None, + httpx_client: httpx.AsyncClient, + ): super().__init__(base_url=base_url, timeout=timeout) self.httpx_client = AsyncHttpClient( httpx_client=httpx_client, diff --git a/seed/python-sdk/enum/strenum/src/seed/core/datetime_utils.py b/seed/python-sdk/enum/strenum/src/seed/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/python-sdk/enum/strenum/src/seed/core/datetime_utils.py +++ b/seed/python-sdk/enum/strenum/src/seed/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/python-sdk/enum/strenum/src/seed/core/file.py b/seed/python-sdk/enum/strenum/src/seed/core/file.py index cb0d40bbbf3..6e0f92bfcb1 100644 --- a/seed/python-sdk/enum/strenum/src/seed/core/file.py +++ b/seed/python-sdk/enum/strenum/src/seed/core/file.py @@ -13,12 +13,17 @@ # (filename, file (or bytes), content_type) typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str]], # (filename, file (or bytes), content_type, headers) - typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str], typing.Mapping[str, str]], + typing.Tuple[ + typing.Optional[str], + FileContent, + typing.Optional[str], + typing.Mapping[str, str], + ], ] def convert_file_dict_to_httpx_tuples( - d: typing.Dict[str, typing.Union[File, typing.List[File]]] + d: typing.Dict[str, typing.Union[File, typing.List[File]]], ) -> typing.List[typing.Tuple[str, File]]: """ The format we use is a list of tuples, where the first element is the diff --git a/seed/python-sdk/enum/strenum/src/seed/core/http_client.py b/seed/python-sdk/enum/strenum/src/seed/core/http_client.py index 9333d8a7f15..091f71bc185 100644 --- a/seed/python-sdk/enum/strenum/src/seed/core/http_client.py +++ b/seed/python-sdk/enum/strenum/src/seed/core/http_client.py @@ -77,7 +77,9 @@ def _retry_timeout(response: httpx.Response, retries: int) -> float: return retry_after # Apply exponential backoff, capped at MAX_RETRY_DELAY_SECONDS. - retry_delay = min(INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS) + retry_delay = min( + INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS + ) # Add a randomness / jitter to the retry delay to avoid overwhelming the server with retries. timeout = retry_delay * (1 - 0.25 * random()) @@ -90,7 +92,8 @@ def _should_retry(response: httpx.Response) -> bool: def remove_omit_from_dict( - original: typing.Dict[str, typing.Optional[typing.Any]], omit: typing.Optional[typing.Any] + original: typing.Dict[str, typing.Optional[typing.Any]], + omit: typing.Optional[typing.Any], ) -> typing.Dict[str, typing.Any]: if omit is None: return original @@ -108,7 +111,8 @@ def maybe_filter_request_body( ) -> typing.Optional[typing.Any]: if data is None: return ( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else None ) @@ -118,7 +122,8 @@ def maybe_filter_request_body( data_content = { **(jsonable_encoder(remove_omit_from_dict(data, omit))), # type: ignore **( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else {} ), @@ -162,7 +167,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url def request( @@ -174,8 +181,12 @@ def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -184,11 +195,14 @@ def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) response = self.httpx_client.request( method=method, @@ -198,7 +212,11 @@ def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -209,7 +227,10 @@ def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -222,11 +243,15 @@ def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: time.sleep(_retry_timeout(response=response, retries=retries)) @@ -256,8 +281,12 @@ def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -266,11 +295,14 @@ def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) with self.httpx_client.stream( method=method, @@ -280,7 +312,11 @@ def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -291,7 +327,9 @@ def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -304,7 +342,9 @@ def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream @@ -327,7 +367,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url async def request( @@ -339,8 +381,12 @@ async def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -349,11 +395,14 @@ async def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) # Add the input to each of these and do None-safety checks response = await self.httpx_client.request( @@ -364,7 +413,11 @@ async def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -375,7 +428,10 @@ async def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -388,11 +444,15 @@ async def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: await asyncio.sleep(_retry_timeout(response=response, retries=retries)) @@ -421,8 +481,12 @@ async def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -431,11 +495,14 @@ async def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) async with self.httpx_client.stream( method=method, @@ -445,7 +512,11 @@ async def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -456,7 +527,9 @@ async def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -469,7 +542,9 @@ async def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream diff --git a/seed/python-sdk/enum/strenum/src/seed/core/jsonable_encoder.py b/seed/python-sdk/enum/strenum/src/seed/core/jsonable_encoder.py index d3fd328fd41..12a8b52fc22 100644 --- a/seed/python-sdk/enum/strenum/src/seed/core/jsonable_encoder.py +++ b/seed/python-sdk/enum/strenum/src/seed/core/jsonable_encoder.py @@ -19,13 +19,19 @@ import pydantic from .datetime_utils import serialize_datetime -from .pydantic_utilities import IS_PYDANTIC_V2, encode_by_type, to_jsonable_with_fallback +from .pydantic_utilities import ( + IS_PYDANTIC_V2, + encode_by_type, + to_jsonable_with_fallback, +) SetIntStr = Set[Union[int, str]] DictIntStrAny = Dict[Union[int, str], Any] -def jsonable_encoder(obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None) -> Any: +def jsonable_encoder( + obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None +) -> Any: custom_encoder = custom_encoder or {} if custom_encoder: if type(obj) in custom_encoder: diff --git a/seed/python-sdk/enum/strenum/src/seed/core/pydantic_utilities.py b/seed/python-sdk/enum/strenum/src/seed/core/pydantic_utilities.py index 170a563d6eb..c63935c32a2 100644 --- a/seed/python-sdk/enum/strenum/src/seed/core/pydantic_utilities.py +++ b/seed/python-sdk/enum/strenum/src/seed/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) # type: ignore # Pydantic v1 diff --git a/seed/python-sdk/enum/strenum/src/seed/core/query_encoder.py b/seed/python-sdk/enum/strenum/src/seed/core/query_encoder.py index 24076d72ee9..7cb98f52cd7 100644 --- a/seed/python-sdk/enum/strenum/src/seed/core/query_encoder.py +++ b/seed/python-sdk/enum/strenum/src/seed/core/query_encoder.py @@ -7,7 +7,9 @@ # Flattens dicts to be of the form {"key[subkey][subkey2]": value} where value is not a dict -def traverse_query_dict(dict_flat: Dict[str, Any], key_prefix: Optional[str] = None) -> Dict[str, Any]: +def traverse_query_dict( + dict_flat: Dict[str, Any], key_prefix: Optional[str] = None +) -> Dict[str, Any]: result = {} for k, v in dict_flat.items(): key = f"{key_prefix}[{k}]" if key_prefix is not None else k @@ -30,4 +32,8 @@ def single_query_encoder(query_key: str, query_value: Any) -> Dict[str, Any]: def encode_query(query: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: - return dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) if query is not None else None + return ( + dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) + if query is not None + else None + ) diff --git a/seed/python-sdk/enum/strenum/src/seed/core/serialization.py b/seed/python-sdk/enum/strenum/src/seed/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/python-sdk/enum/strenum/src/seed/core/serialization.py +++ b/seed/python-sdk/enum/strenum/src/seed/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/python-sdk/enum/strenum/src/seed/inlined_request/client.py b/seed/python-sdk/enum/strenum/src/seed/inlined_request/client.py index 2f899ac9802..53c4040e37a 100644 --- a/seed/python-sdk/enum/strenum/src/seed/inlined_request/client.py +++ b/seed/python-sdk/enum/strenum/src/seed/inlined_request/client.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. import typing +from ..core.client_wrapper import SyncClientWrapper +from ..types.operand import Operand +from ..types.color_or_operand import ColorOrOperand +from ..core.request_options import RequestOptions from json.decoder import JSONDecodeError - from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.request_options import RequestOptions -from ..types.color_or_operand import ColorOrOperand -from ..types.operand import Operand +from ..core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -24,7 +24,7 @@ def send( operand_or_color: ColorOrOperand, maybe_operand: typing.Optional[Operand] = OMIT, maybe_operand_or_color: typing.Optional[ColorOrOperand] = OMIT, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ Parameters @@ -88,7 +88,7 @@ async def send( operand_or_color: ColorOrOperand, maybe_operand: typing.Optional[Operand] = OMIT, maybe_operand_or_color: typing.Optional[ColorOrOperand] = OMIT, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ Parameters diff --git a/seed/python-sdk/enum/strenum/src/seed/path_param/client.py b/seed/python-sdk/enum/strenum/src/seed/path_param/client.py index 12849485cdb..7f358ef6cbc 100644 --- a/seed/python-sdk/enum/strenum/src/seed/path_param/client.py +++ b/seed/python-sdk/enum/strenum/src/seed/path_param/client.py @@ -1,14 +1,14 @@ # This file was auto-generated by Fern from our API Definition. +from ..core.client_wrapper import SyncClientWrapper +from ..types.operand import Operand import typing +from ..types.color_or_operand import ColorOrOperand +from ..core.request_options import RequestOptions +from ..core.jsonable_encoder import jsonable_encoder from json.decoder import JSONDecodeError - from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.jsonable_encoder import jsonable_encoder -from ..core.request_options import RequestOptions -from ..types.color_or_operand import ColorOrOperand -from ..types.operand import Operand +from ..core.client_wrapper import AsyncClientWrapper class PathParamClient: diff --git a/seed/python-sdk/enum/strenum/src/seed/query_param/client.py b/seed/python-sdk/enum/strenum/src/seed/query_param/client.py index 799d5ee8f9a..8c1235f9667 100644 --- a/seed/python-sdk/enum/strenum/src/seed/query_param/client.py +++ b/seed/python-sdk/enum/strenum/src/seed/query_param/client.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. +from ..core.client_wrapper import SyncClientWrapper +from ..types.operand import Operand +from ..types.color_or_operand import ColorOrOperand import typing +from ..core.request_options import RequestOptions from json.decoder import JSONDecodeError - from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.request_options import RequestOptions -from ..types.color_or_operand import ColorOrOperand -from ..types.operand import Operand +from ..core.client_wrapper import AsyncClientWrapper class QueryParamClient: @@ -21,7 +21,7 @@ def send( operand_or_color: ColorOrOperand, maybe_operand: typing.Optional[Operand] = None, maybe_operand_or_color: typing.Optional[ColorOrOperand] = None, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ Parameters @@ -77,9 +77,13 @@ def send_list( *, operand: typing.Union[Operand, typing.Sequence[Operand]], operand_or_color: typing.Union[ColorOrOperand, typing.Sequence[ColorOrOperand]], - maybe_operand: typing.Optional[typing.Union[Operand, typing.Sequence[Operand]]] = None, - maybe_operand_or_color: typing.Optional[typing.Union[ColorOrOperand, typing.Sequence[ColorOrOperand]]] = None, - request_options: typing.Optional[RequestOptions] = None + maybe_operand: typing.Optional[ + typing.Union[Operand, typing.Sequence[Operand]] + ] = None, + maybe_operand_or_color: typing.Optional[ + typing.Union[ColorOrOperand, typing.Sequence[ColorOrOperand]] + ] = None, + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ Parameters @@ -144,7 +148,7 @@ async def send( operand_or_color: ColorOrOperand, maybe_operand: typing.Optional[Operand] = None, maybe_operand_or_color: typing.Optional[ColorOrOperand] = None, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ Parameters @@ -208,9 +212,13 @@ async def send_list( *, operand: typing.Union[Operand, typing.Sequence[Operand]], operand_or_color: typing.Union[ColorOrOperand, typing.Sequence[ColorOrOperand]], - maybe_operand: typing.Optional[typing.Union[Operand, typing.Sequence[Operand]]] = None, - maybe_operand_or_color: typing.Optional[typing.Union[ColorOrOperand, typing.Sequence[ColorOrOperand]]] = None, - request_options: typing.Optional[RequestOptions] = None + maybe_operand: typing.Optional[ + typing.Union[Operand, typing.Sequence[Operand]] + ] = None, + maybe_operand_or_color: typing.Optional[ + typing.Union[ColorOrOperand, typing.Sequence[ColorOrOperand]] + ] = None, + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ Parameters diff --git a/seed/python-sdk/enum/strenum/src/seed/types/color_or_operand.py b/seed/python-sdk/enum/strenum/src/seed/types/color_or_operand.py index 5de8179707c..1bbec1032b1 100644 --- a/seed/python-sdk/enum/strenum/src/seed/types/color_or_operand.py +++ b/seed/python-sdk/enum/strenum/src/seed/types/color_or_operand.py @@ -1,7 +1,6 @@ # This file was auto-generated by Fern from our API Definition. import typing - from .color import Color from .operand import Operand diff --git a/seed/python-sdk/enum/strenum/src/seed/version.py b/seed/python-sdk/enum/strenum/src/seed/version.py index d345d6a9fb2..2355c6d81ab 100644 --- a/seed/python-sdk/enum/strenum/src/seed/version.py +++ b/seed/python-sdk/enum/strenum/src/seed/version.py @@ -1,4 +1,3 @@ - from importlib import metadata __version__ = metadata.version("fern_enum") diff --git a/seed/python-sdk/enum/strenum/tests/conftest.py b/seed/python-sdk/enum/strenum/tests/conftest.py index 1b3ac7545f4..1ab8753c9f4 100644 --- a/seed/python-sdk/enum/strenum/tests/conftest.py +++ b/seed/python-sdk/enum/strenum/tests/conftest.py @@ -1,9 +1,9 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedEnum import os - import pytest -from seed import AsyncSeedEnum, SeedEnum +from seed import AsyncSeedEnum @pytest.fixture diff --git a/seed/python-sdk/enum/strenum/tests/custom/test_client.py b/seed/python-sdk/enum/strenum/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/python-sdk/enum/strenum/tests/custom/test_client.py +++ b/seed/python-sdk/enum/strenum/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/python-sdk/enum/strenum/tests/test_inlined_request.py b/seed/python-sdk/enum/strenum/tests/test_inlined_request.py index 69729cb5d54..ae04a061add 100644 --- a/seed/python-sdk/enum/strenum/tests/test_inlined_request.py +++ b/seed/python-sdk/enum/strenum/tests/test_inlined_request.py @@ -1,10 +1,14 @@ # This file was auto-generated by Fern from our API Definition. -from seed import AsyncSeedEnum, SeedEnum +from seed import SeedEnum +from seed import AsyncSeedEnum async def test_send(client: SeedEnum, async_client: AsyncSeedEnum) -> None: # Type ignore to avoid mypy complaining about the function not being meant to return a value assert client.inlined_request.send(operand=">", operand_or_color="red") is None # type: ignore[func-returns-value] - assert await async_client.inlined_request.send(operand=">", operand_or_color="red") is None # type: ignore[func-returns-value] + assert ( + await async_client.inlined_request.send(operand=">", operand_or_color="red") + is None + ) # type: ignore[func-returns-value] diff --git a/seed/python-sdk/enum/strenum/tests/test_path_param.py b/seed/python-sdk/enum/strenum/tests/test_path_param.py index 2d7180380ec..982460b82e1 100644 --- a/seed/python-sdk/enum/strenum/tests/test_path_param.py +++ b/seed/python-sdk/enum/strenum/tests/test_path_param.py @@ -1,10 +1,27 @@ # This file was auto-generated by Fern from our API Definition. -from seed import AsyncSeedEnum, SeedEnum +from seed import SeedEnum +from seed import AsyncSeedEnum async def test_send(client: SeedEnum, async_client: AsyncSeedEnum) -> None: # Type ignore to avoid mypy complaining about the function not being meant to return a value - assert client.path_param.send(operand=">", maybe_operand="less_than", operand_or_color="red", maybe_operand_or_color="red") is None # type: ignore[func-returns-value] + assert ( + client.path_param.send( + operand=">", + maybe_operand="less_than", + operand_or_color="red", + maybe_operand_or_color="red", + ) + is None + ) # type: ignore[func-returns-value] - assert await async_client.path_param.send(operand=">", maybe_operand="less_than", operand_or_color="red", maybe_operand_or_color="red") is None # type: ignore[func-returns-value] + assert ( + await async_client.path_param.send( + operand=">", + maybe_operand="less_than", + operand_or_color="red", + maybe_operand_or_color="red", + ) + is None + ) # type: ignore[func-returns-value] diff --git a/seed/python-sdk/enum/strenum/tests/test_query_param.py b/seed/python-sdk/enum/strenum/tests/test_query_param.py index 374e5b19fd1..c610d4d0f1f 100644 --- a/seed/python-sdk/enum/strenum/tests/test_query_param.py +++ b/seed/python-sdk/enum/strenum/tests/test_query_param.py @@ -1,17 +1,36 @@ # This file was auto-generated by Fern from our API Definition. -from seed import AsyncSeedEnum, SeedEnum +from seed import SeedEnum +from seed import AsyncSeedEnum async def test_send(client: SeedEnum, async_client: AsyncSeedEnum) -> None: # Type ignore to avoid mypy complaining about the function not being meant to return a value assert client.query_param.send(operand=">", operand_or_color="red") is None # type: ignore[func-returns-value] - assert await async_client.query_param.send(operand=">", operand_or_color="red") is None # type: ignore[func-returns-value] + assert ( + await async_client.query_param.send(operand=">", operand_or_color="red") is None + ) # type: ignore[func-returns-value] async def test_send_list(client: SeedEnum, async_client: AsyncSeedEnum) -> None: # Type ignore to avoid mypy complaining about the function not being meant to return a value - assert client.query_param.send_list(operand=">", maybe_operand=">", operand_or_color="red", maybe_operand_or_color="red") is None # type: ignore[func-returns-value] + assert ( + client.query_param.send_list( + operand=">", + maybe_operand=">", + operand_or_color="red", + maybe_operand_or_color="red", + ) + is None + ) # type: ignore[func-returns-value] - assert await async_client.query_param.send_list(operand=">", maybe_operand=">", operand_or_color="red", maybe_operand_or_color="red") is None # type: ignore[func-returns-value] + assert ( + await async_client.query_param.send_list( + operand=">", + maybe_operand=">", + operand_or_color="red", + maybe_operand_or_color="red", + ) + is None + ) # type: ignore[func-returns-value] diff --git a/seed/python-sdk/enum/strenum/tests/utilities.py b/seed/python-sdk/enum/strenum/tests/utilities.py index 13da208eb3a..e8f4472564c 100644 --- a/seed/python-sdk/enum/strenum/tests/utilities.py +++ b/seed/python-sdk/enum/strenum/tests/utilities.py @@ -3,11 +3,14 @@ import typing import uuid -import pydantic from dateutil import parser +import pydantic + -def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> typing.Any: +def cast_field( + json_expectation: typing.Any, type_expectation: typing.Any +) -> typing.Any: # Cast these specific types which come through as string and expect our # models to cast to the correct type. if type_expectation == "uuid": @@ -25,7 +28,9 @@ def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> ty return json_expectation -def validate_field(response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any) -> None: +def validate_field( + response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectation == "no_validate": return @@ -44,7 +49,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(entry_expectation, dict): is_container_of_complex_type = True validate_response( - response=response[idx], json_expectation=ex, type_expectations=entry_expectation + response=response[idx], + json_expectation=ex, + type_expectations=entry_expectation, ) else: cast_json_expectation.append(cast_field(ex, entry_expectation)) @@ -56,7 +63,10 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # if any of the values of the set have a type_expectation of a dict, we're assuming it's a pydantic # model and keeping it a list. if container_expectation != "set" or not any( - map(lambda value: isinstance(value, dict), list(contents_expectation.values())) + map( + lambda value: isinstance(value, dict), + list(contents_expectation.values()), + ) ): json_expectation = cast_field(json_expectation, container_expectation) elif isinstance(type_expectation, tuple): @@ -65,9 +75,15 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(contents_expectation, dict): json_expectation = { cast_field( - key, contents_expectation.get(idx)[0] if contents_expectation.get(idx) is not None else None # type: ignore + key, + contents_expectation.get(idx)[0] + if contents_expectation.get(idx) is not None + else None, # type: ignore ): cast_field( - value, contents_expectation.get(idx)[1] if contents_expectation.get(idx) is not None else None # type: ignore + value, + contents_expectation.get(idx)[1] + if contents_expectation.get(idx) is not None + else None, # type: ignore ) for idx, (key, value) in enumerate(json_expectation.items()) } @@ -86,7 +102,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # Arg type_expectations is a deeply nested structure that matches the response, but with the values replaced with the expected types -def validate_response(response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any) -> None: +def validate_response( + response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectations == "no_validate": return @@ -96,11 +114,17 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e and not isinstance(response, dict) and not issubclass(type(response), pydantic.BaseModel) ): - validate_field(response=response, json_expectation=json_expectation, type_expectation=type_expectations) + validate_field( + response=response, + json_expectation=json_expectation, + type_expectation=type_expectations, + ) return if isinstance(response, list): - assert len(response) == len(json_expectation), "Length mismatch, expected: {0}, Actual: {1}".format( + assert len(response) == len( + json_expectation + ), "Length mismatch, expected: {0}, Actual: {1}".format( len(response), len(json_expectation) ) content_expectation = type_expectations @@ -108,7 +132,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e content_expectation = type_expectations[1] for idx, item in enumerate(response): validate_response( - response=item, json_expectation=json_expectation[idx], type_expectations=content_expectation[idx] + response=item, + json_expectation=json_expectation[idx], + type_expectations=content_expectation[idx], ) else: response_json = response @@ -116,7 +142,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e response_json = response.dict(by_alias=True) for key, value in json_expectation.items(): - assert key in response_json, "Field {0} not found within the response object: {1}".format( + assert ( + key in response_json + ), "Field {0} not found within the response object: {1}".format( key, response_json ) @@ -128,11 +156,19 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e # Otherwise, we're just validating a single field that's a pydantic model. if isinstance(value, dict) and not isinstance(type_expectation, tuple): validate_response( - response=response_json[key], json_expectation=value, type_expectations=type_expectation + response=response_json[key], + json_expectation=value, + type_expectations=type_expectation, ) else: - validate_field(response=response_json[key], json_expectation=value, type_expectation=type_expectation) + validate_field( + response=response_json[key], + json_expectation=value, + type_expectation=type_expectation, + ) # Ensure there are no additional fields here either del response_json[key] - assert len(response_json) == 0, "Additional fields found, expected None: {0}".format(response_json) + assert ( + len(response_json) == 0 + ), "Additional fields found, expected None: {0}".format(response_json) diff --git a/seed/python-sdk/enum/strenum/tests/utils/assets/models/__init__.py b/seed/python-sdk/enum/strenum/tests/utils/assets/models/__init__.py index 2cf01263529..3a1c852e71e 100644 --- a/seed/python-sdk/enum/strenum/tests/utils/assets/models/__init__.py +++ b/seed/python-sdk/enum/strenum/tests/utils/assets/models/__init__.py @@ -5,7 +5,7 @@ from .circle import CircleParams from .object_with_defaults import ObjectWithDefaultsParams from .object_with_optional_field import ObjectWithOptionalFieldParams -from .shape import Shape_CircleParams, Shape_SquareParams, ShapeParams +from .shape import ShapeParams, Shape_CircleParams, Shape_SquareParams from .square import SquareParams from .undiscriminated_shape import UndiscriminatedShapeParams diff --git a/seed/python-sdk/enum/strenum/tests/utils/assets/models/circle.py b/seed/python-sdk/enum/strenum/tests/utils/assets/models/circle.py index af7a1bf8a8e..253f12d38b3 100644 --- a/seed/python-sdk/enum/strenum/tests/utils/assets/models/circle.py +++ b/seed/python-sdk/enum/strenum/tests/utils/assets/models/circle.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class CircleParams(typing_extensions.TypedDict): - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] diff --git a/seed/python-sdk/enum/strenum/tests/utils/assets/models/object_with_optional_field.py b/seed/python-sdk/enum/strenum/tests/utils/assets/models/object_with_optional_field.py index 3ad93d5f305..ebe7dc80547 100644 --- a/seed/python-sdk/enum/strenum/tests/utils/assets/models/object_with_optional_field.py +++ b/seed/python-sdk/enum/strenum/tests/utils/assets/models/object_with_optional_field.py @@ -7,8 +7,8 @@ import uuid import typing_extensions -from seed.core.serialization import FieldMetadata +from seed.core.serialization import FieldMetadata from .color import Color from .shape import ShapeParams from .undiscriminated_shape import UndiscriminatedShapeParams @@ -18,16 +18,30 @@ class ObjectWithOptionalFieldParams(typing_extensions.TypedDict): literal: typing.Literal["lit_one"] string: typing_extensions.NotRequired[str] integer: typing_extensions.NotRequired[int] - long_: typing_extensions.NotRequired[typing_extensions.Annotated[int, FieldMetadata(alias="long")]] + long_: typing_extensions.NotRequired[ + typing_extensions.Annotated[int, FieldMetadata(alias="long")] + ] double: typing_extensions.NotRequired[float] - bool_: typing_extensions.NotRequired[typing_extensions.Annotated[bool, FieldMetadata(alias="bool")]] + bool_: typing_extensions.NotRequired[ + typing_extensions.Annotated[bool, FieldMetadata(alias="bool")] + ] datetime: typing_extensions.NotRequired[dt.datetime] date: typing_extensions.NotRequired[dt.date] - uuid_: typing_extensions.NotRequired[typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")]] - base_64: typing_extensions.NotRequired[typing_extensions.Annotated[str, FieldMetadata(alias="base64")]] - list_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")]] - set_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")]] - map_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")]] + uuid_: typing_extensions.NotRequired[ + typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")] + ] + base_64: typing_extensions.NotRequired[ + typing_extensions.Annotated[str, FieldMetadata(alias="base64")] + ] + list_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")] + ] + set_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")] + ] + map_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")] + ] enum: typing_extensions.NotRequired[Color] union: typing_extensions.NotRequired[ShapeParams] second_union: typing_extensions.NotRequired[ShapeParams] diff --git a/seed/python-sdk/enum/strenum/tests/utils/assets/models/shape.py b/seed/python-sdk/enum/strenum/tests/utils/assets/models/shape.py index 2c33c877951..816ffc51bdc 100644 --- a/seed/python-sdk/enum/strenum/tests/utils/assets/models/shape.py +++ b/seed/python-sdk/enum/strenum/tests/utils/assets/models/shape.py @@ -7,6 +7,7 @@ import typing import typing_extensions + from seed.core.serialization import FieldMetadata @@ -15,13 +16,21 @@ class Base(typing_extensions.TypedDict): class Shape_CircleParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["circle"], FieldMetadata(alias="shapeType")] - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["circle"], FieldMetadata(alias="shapeType") + ] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] class Shape_SquareParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["square"], FieldMetadata(alias="shapeType")] - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["square"], FieldMetadata(alias="shapeType") + ] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] ShapeParams = typing.Union[Shape_CircleParams, Shape_SquareParams] diff --git a/seed/python-sdk/enum/strenum/tests/utils/assets/models/square.py b/seed/python-sdk/enum/strenum/tests/utils/assets/models/square.py index b9b7dd319bc..bcf08a723c5 100644 --- a/seed/python-sdk/enum/strenum/tests/utils/assets/models/square.py +++ b/seed/python-sdk/enum/strenum/tests/utils/assets/models/square.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class SquareParams(typing_extensions.TypedDict): - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] diff --git a/seed/python-sdk/enum/strenum/tests/utils/test_http_client.py b/seed/python-sdk/enum/strenum/tests/utils/test_http_client.py index edd11ca7afb..f5a874a75f3 100644 --- a/seed/python-sdk/enum/strenum/tests/utils/test_http_client.py +++ b/seed/python-sdk/enum/strenum/tests/utils/test_http_client.py @@ -9,12 +9,17 @@ def get_request_options() -> RequestOptions: def test_get_json_request_body() -> None: - json_body, data_body = get_request_body(json={"hello": "world"}, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json={"hello": "world"}, data=None, request_options=None, omit=None + ) assert json_body == {"hello": "world"} assert data_body is None json_body_extras, data_body_extras = get_request_body( - json={"goodbye": "world"}, data=None, request_options=get_request_options(), omit=None + json={"goodbye": "world"}, + data=None, + request_options=get_request_options(), + omit=None, ) assert json_body_extras == {"goodbye": "world", "see you": "later"} @@ -22,12 +27,17 @@ def test_get_json_request_body() -> None: def test_get_files_request_body() -> None: - json_body, data_body = get_request_body(json=None, data={"hello": "world"}, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data={"hello": "world"}, request_options=None, omit=None + ) assert data_body == {"hello": "world"} assert json_body is None json_body_extras, data_body_extras = get_request_body( - json=None, data={"goodbye": "world"}, request_options=get_request_options(), omit=None + json=None, + data={"goodbye": "world"}, + request_options=get_request_options(), + omit=None, ) assert data_body_extras == {"goodbye": "world", "see you": "later"} @@ -35,7 +45,9 @@ def test_get_files_request_body() -> None: def test_get_none_request_body() -> None: - json_body, data_body = get_request_body(json=None, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data=None, request_options=None, omit=None + ) assert data_body is None assert json_body is None diff --git a/seed/python-sdk/enum/strenum/tests/utils/test_query_encoding.py b/seed/python-sdk/enum/strenum/tests/utils/test_query_encoding.py index 247e1551b46..fbc8f402167 100644 --- a/seed/python-sdk/enum/strenum/tests/utils/test_query_encoding.py +++ b/seed/python-sdk/enum/strenum/tests/utils/test_query_encoding.py @@ -4,9 +4,15 @@ def test_query_encoding() -> None: - assert encode_query({"hello world": "hello world"}) == {"hello world": "hello world"} - assert encode_query({"hello_world": {"hello": "world"}}) == {"hello_world[hello]": "world"} - assert encode_query({"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"}) == { + assert encode_query({"hello world": "hello world"}) == { + "hello world": "hello world" + } + assert encode_query({"hello_world": {"hello": "world"}}) == { + "hello_world[hello]": "world" + } + assert encode_query( + {"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"} + ) == { "hello_world[hello][world]": "today", "hello_world[test]": "this", "hi": "there", diff --git a/seed/python-sdk/enum/strenum/tests/utils/test_serialization.py b/seed/python-sdk/enum/strenum/tests/utils/test_serialization.py index 58b1ed66e6d..5ca956916dd 100644 --- a/seed/python-sdk/enum/strenum/tests/utils/test_serialization.py +++ b/seed/python-sdk/enum/strenum/tests/utils/test_serialization.py @@ -1,10 +1,12 @@ # This file was auto-generated by Fern from our API Definition. -from typing import Any, List +from typing import List, Any -from seed.core.serialization import convert_and_respect_annotation_metadata +from seed.core.serialization import ( + convert_and_respect_annotation_metadata, +) +from .assets.models import ShapeParams, ObjectWithOptionalFieldParams -from .assets.models import ObjectWithOptionalFieldParams, ShapeParams UNION_TEST: ShapeParams = {"radius_measurement": 1.0, "shape_type": "circle", "id": "1"} UNION_TEST_CONVERTED = {"shapeType": "circle", "radiusMeasurement": 1.0, "id": "1"} @@ -18,20 +20,54 @@ def test_convert_and_respect_annotation_metadata() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) - assert converted == {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"} + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) + assert converted == { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + } def test_convert_and_respect_annotation_metadata_in_list() -> None: data: List[ObjectWithOptionalFieldParams] = [ - {"string": "string", "long_": 12345, "bool_": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long_": 67890, "list_": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long_": 12345, + "bool_": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long_": 67890, + "list_": [], + "literal": "lit_one", + "any": "any", + }, ] - converted = convert_and_respect_annotation_metadata(object_=data, annotation=List[ObjectWithOptionalFieldParams]) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=List[ObjectWithOptionalFieldParams] + ) assert converted == [ - {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long": 67890, "list": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long": 67890, + "list": [], + "literal": "lit_one", + "any": "any", + }, ] @@ -43,7 +79,9 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) assert converted == { "string": "string", @@ -55,12 +93,16 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: def test_convert_and_respect_annotation_metadata_in_union() -> None: - converted = convert_and_respect_annotation_metadata(object_=UNION_TEST, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=UNION_TEST, annotation=ShapeParams + ) assert converted == UNION_TEST_CONVERTED def test_convert_and_respect_annotation_metadata_with_empty_object() -> None: data: Any = {} - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ShapeParams + ) assert converted == data diff --git a/seed/python-sdk/enum/tests/custom/test_client.py b/seed/python-sdk/enum/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/python-sdk/enum/tests/custom/test_client.py +++ b/seed/python-sdk/enum/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/python-sdk/enum/tests/test_json.py b/seed/python-sdk/enum/tests/test_json.py index 5c88bda29a1..7a5a563113f 100644 --- a/seed/python-sdk/enum/tests/test_json.py +++ b/seed/python-sdk/enum/tests/test_json.py @@ -1,16 +1,17 @@ from seed.types.operand import Operand from src.seed.client import SeedEnum + def test_json() -> None: client = SeedEnum(base_url="https://yourhost.com/path/to/api") - + try: print("---- parameters ----") client.path_param.send( operand=Operand.EQUAL_TO, maybe_operand=Operand.EQUAL_TO, operand_or_color=Operand.EQUAL_TO, - maybe_operand_or_color=None + maybe_operand_or_color=None, ) except: pass @@ -21,7 +22,7 @@ def test_json() -> None: operand=Operand.EQUAL_TO, maybe_operand=Operand.EQUAL_TO, operand_or_color=Operand.EQUAL_TO, - maybe_operand_or_color=None + maybe_operand_or_color=None, ) except: pass @@ -32,7 +33,7 @@ def test_json() -> None: operand=Operand.EQUAL_TO, maybe_operand=Operand.EQUAL_TO, operand_or_color=Operand.EQUAL_TO, - maybe_operand_or_color=None + maybe_operand_or_color=None, ) except: - pass \ No newline at end of file + pass diff --git a/seed/python-sdk/error-property/pyproject.toml b/seed/python-sdk/error-property/pyproject.toml index eccda597be7..1b5068c2d92 100644 --- a/seed/python-sdk/error-property/pyproject.toml +++ b/seed/python-sdk/error-property/pyproject.toml @@ -43,6 +43,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/python-sdk/error-property/src/seed/client.py b/seed/python-sdk/error-property/src/seed/client.py index 1e2ec38c107..9de4b83a8e7 100644 --- a/seed/python-sdk/error-property/src/seed/client.py +++ b/seed/python-sdk/error-property/src/seed/client.py @@ -1,11 +1,11 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from .property_based_error.client import AsyncPropertyBasedErrorClient, PropertyBasedErrorClient +from .core.client_wrapper import SyncClientWrapper +from .property_based_error.client import PropertyBasedErrorClient +from .core.client_wrapper import AsyncClientWrapper +from .property_based_error.client import AsyncPropertyBasedErrorClient class SeedErrorProperty: @@ -41,19 +41,25 @@ def __init__( base_url: str, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.Client] = None + httpx_client: typing.Optional[httpx.Client] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = SyncClientWrapper( base_url=base_url, httpx_client=httpx_client if httpx_client is not None - else httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.Client( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.Client(timeout=_defaulted_timeout), timeout=_defaulted_timeout, ) - self.property_based_error = PropertyBasedErrorClient(client_wrapper=self._client_wrapper) + self.property_based_error = PropertyBasedErrorClient( + client_wrapper=self._client_wrapper + ) class AsyncSeedErrorProperty: @@ -89,16 +95,22 @@ def __init__( base_url: str, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.AsyncClient] = None + httpx_client: typing.Optional[httpx.AsyncClient] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = AsyncClientWrapper( base_url=base_url, httpx_client=httpx_client if httpx_client is not None - else httpx.AsyncClient(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.AsyncClient( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.AsyncClient(timeout=_defaulted_timeout), timeout=_defaulted_timeout, ) - self.property_based_error = AsyncPropertyBasedErrorClient(client_wrapper=self._client_wrapper) + self.property_based_error = AsyncPropertyBasedErrorClient( + client_wrapper=self._client_wrapper + ) diff --git a/seed/python-sdk/error-property/src/seed/core/api_error.py b/seed/python-sdk/error-property/src/seed/core/api_error.py index 2e9fc5431cd..da734b58068 100644 --- a/seed/python-sdk/error-property/src/seed/core/api_error.py +++ b/seed/python-sdk/error-property/src/seed/core/api_error.py @@ -7,7 +7,9 @@ class ApiError(Exception): status_code: typing.Optional[int] body: typing.Any - def __init__(self, *, status_code: typing.Optional[int] = None, body: typing.Any = None): + def __init__( + self, *, status_code: typing.Optional[int] = None, body: typing.Any = None + ): self.status_code = status_code self.body = body diff --git a/seed/python-sdk/error-property/src/seed/core/client_wrapper.py b/seed/python-sdk/error-property/src/seed/core/client_wrapper.py index 67d93313e4c..89c9609b2bb 100644 --- a/seed/python-sdk/error-property/src/seed/core/client_wrapper.py +++ b/seed/python-sdk/error-property/src/seed/core/client_wrapper.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .http_client import AsyncHttpClient, HttpClient +from .http_client import HttpClient +from .http_client import AsyncHttpClient class BaseClientWrapper: @@ -28,7 +27,13 @@ def get_timeout(self) -> typing.Optional[float]: class SyncClientWrapper(BaseClientWrapper): - def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, httpx_client: httpx.Client): + def __init__( + self, + *, + base_url: str, + timeout: typing.Optional[float] = None, + httpx_client: httpx.Client, + ): super().__init__(base_url=base_url, timeout=timeout) self.httpx_client = HttpClient( httpx_client=httpx_client, @@ -39,7 +44,13 @@ def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, htt class AsyncClientWrapper(BaseClientWrapper): - def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, httpx_client: httpx.AsyncClient): + def __init__( + self, + *, + base_url: str, + timeout: typing.Optional[float] = None, + httpx_client: httpx.AsyncClient, + ): super().__init__(base_url=base_url, timeout=timeout) self.httpx_client = AsyncHttpClient( httpx_client=httpx_client, diff --git a/seed/python-sdk/error-property/src/seed/core/datetime_utils.py b/seed/python-sdk/error-property/src/seed/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/python-sdk/error-property/src/seed/core/datetime_utils.py +++ b/seed/python-sdk/error-property/src/seed/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/python-sdk/error-property/src/seed/core/file.py b/seed/python-sdk/error-property/src/seed/core/file.py index cb0d40bbbf3..6e0f92bfcb1 100644 --- a/seed/python-sdk/error-property/src/seed/core/file.py +++ b/seed/python-sdk/error-property/src/seed/core/file.py @@ -13,12 +13,17 @@ # (filename, file (or bytes), content_type) typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str]], # (filename, file (or bytes), content_type, headers) - typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str], typing.Mapping[str, str]], + typing.Tuple[ + typing.Optional[str], + FileContent, + typing.Optional[str], + typing.Mapping[str, str], + ], ] def convert_file_dict_to_httpx_tuples( - d: typing.Dict[str, typing.Union[File, typing.List[File]]] + d: typing.Dict[str, typing.Union[File, typing.List[File]]], ) -> typing.List[typing.Tuple[str, File]]: """ The format we use is a list of tuples, where the first element is the diff --git a/seed/python-sdk/error-property/src/seed/core/http_client.py b/seed/python-sdk/error-property/src/seed/core/http_client.py index 9333d8a7f15..091f71bc185 100644 --- a/seed/python-sdk/error-property/src/seed/core/http_client.py +++ b/seed/python-sdk/error-property/src/seed/core/http_client.py @@ -77,7 +77,9 @@ def _retry_timeout(response: httpx.Response, retries: int) -> float: return retry_after # Apply exponential backoff, capped at MAX_RETRY_DELAY_SECONDS. - retry_delay = min(INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS) + retry_delay = min( + INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS + ) # Add a randomness / jitter to the retry delay to avoid overwhelming the server with retries. timeout = retry_delay * (1 - 0.25 * random()) @@ -90,7 +92,8 @@ def _should_retry(response: httpx.Response) -> bool: def remove_omit_from_dict( - original: typing.Dict[str, typing.Optional[typing.Any]], omit: typing.Optional[typing.Any] + original: typing.Dict[str, typing.Optional[typing.Any]], + omit: typing.Optional[typing.Any], ) -> typing.Dict[str, typing.Any]: if omit is None: return original @@ -108,7 +111,8 @@ def maybe_filter_request_body( ) -> typing.Optional[typing.Any]: if data is None: return ( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else None ) @@ -118,7 +122,8 @@ def maybe_filter_request_body( data_content = { **(jsonable_encoder(remove_omit_from_dict(data, omit))), # type: ignore **( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else {} ), @@ -162,7 +167,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url def request( @@ -174,8 +181,12 @@ def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -184,11 +195,14 @@ def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) response = self.httpx_client.request( method=method, @@ -198,7 +212,11 @@ def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -209,7 +227,10 @@ def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -222,11 +243,15 @@ def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: time.sleep(_retry_timeout(response=response, retries=retries)) @@ -256,8 +281,12 @@ def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -266,11 +295,14 @@ def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) with self.httpx_client.stream( method=method, @@ -280,7 +312,11 @@ def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -291,7 +327,9 @@ def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -304,7 +342,9 @@ def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream @@ -327,7 +367,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url async def request( @@ -339,8 +381,12 @@ async def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -349,11 +395,14 @@ async def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) # Add the input to each of these and do None-safety checks response = await self.httpx_client.request( @@ -364,7 +413,11 @@ async def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -375,7 +428,10 @@ async def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -388,11 +444,15 @@ async def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: await asyncio.sleep(_retry_timeout(response=response, retries=retries)) @@ -421,8 +481,12 @@ async def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -431,11 +495,14 @@ async def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) async with self.httpx_client.stream( method=method, @@ -445,7 +512,11 @@ async def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -456,7 +527,9 @@ async def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -469,7 +542,9 @@ async def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream diff --git a/seed/python-sdk/error-property/src/seed/core/jsonable_encoder.py b/seed/python-sdk/error-property/src/seed/core/jsonable_encoder.py index d3fd328fd41..12a8b52fc22 100644 --- a/seed/python-sdk/error-property/src/seed/core/jsonable_encoder.py +++ b/seed/python-sdk/error-property/src/seed/core/jsonable_encoder.py @@ -19,13 +19,19 @@ import pydantic from .datetime_utils import serialize_datetime -from .pydantic_utilities import IS_PYDANTIC_V2, encode_by_type, to_jsonable_with_fallback +from .pydantic_utilities import ( + IS_PYDANTIC_V2, + encode_by_type, + to_jsonable_with_fallback, +) SetIntStr = Set[Union[int, str]] DictIntStrAny = Dict[Union[int, str], Any] -def jsonable_encoder(obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None) -> Any: +def jsonable_encoder( + obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None +) -> Any: custom_encoder = custom_encoder or {} if custom_encoder: if type(obj) in custom_encoder: diff --git a/seed/python-sdk/error-property/src/seed/core/pydantic_utilities.py b/seed/python-sdk/error-property/src/seed/core/pydantic_utilities.py index 170a563d6eb..c63935c32a2 100644 --- a/seed/python-sdk/error-property/src/seed/core/pydantic_utilities.py +++ b/seed/python-sdk/error-property/src/seed/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) # type: ignore # Pydantic v1 diff --git a/seed/python-sdk/error-property/src/seed/core/query_encoder.py b/seed/python-sdk/error-property/src/seed/core/query_encoder.py index 24076d72ee9..7cb98f52cd7 100644 --- a/seed/python-sdk/error-property/src/seed/core/query_encoder.py +++ b/seed/python-sdk/error-property/src/seed/core/query_encoder.py @@ -7,7 +7,9 @@ # Flattens dicts to be of the form {"key[subkey][subkey2]": value} where value is not a dict -def traverse_query_dict(dict_flat: Dict[str, Any], key_prefix: Optional[str] = None) -> Dict[str, Any]: +def traverse_query_dict( + dict_flat: Dict[str, Any], key_prefix: Optional[str] = None +) -> Dict[str, Any]: result = {} for k, v in dict_flat.items(): key = f"{key_prefix}[{k}]" if key_prefix is not None else k @@ -30,4 +32,8 @@ def single_query_encoder(query_key: str, query_value: Any) -> Dict[str, Any]: def encode_query(query: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: - return dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) if query is not None else None + return ( + dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) + if query is not None + else None + ) diff --git a/seed/python-sdk/error-property/src/seed/core/serialization.py b/seed/python-sdk/error-property/src/seed/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/python-sdk/error-property/src/seed/core/serialization.py +++ b/seed/python-sdk/error-property/src/seed/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/python-sdk/error-property/src/seed/errors/types/property_based_error_test_body.py b/seed/python-sdk/error-property/src/seed/errors/types/property_based_error_test_body.py index 464fa54ec60..9d75d0ec393 100644 --- a/seed/python-sdk/error-property/src/seed/errors/types/property_based_error_test_body.py +++ b/seed/python-sdk/error-property/src/seed/errors/types/property_based_error_test_body.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class PropertyBasedErrorTestBody(UniversalBaseModel): message: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/error-property/src/seed/property_based_error/client.py b/seed/python-sdk/error-property/src/seed/property_based_error/client.py index b2afa0d279b..2fbafffdca7 100644 --- a/seed/python-sdk/error-property/src/seed/property_based_error/client.py +++ b/seed/python-sdk/error-property/src/seed/property_based_error/client.py @@ -1,21 +1,23 @@ # This file was auto-generated by Fern from our API Definition. +from ..core.client_wrapper import SyncClientWrapper import typing +from ..core.request_options import RequestOptions from json.decoder import JSONDecodeError - from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper from ..core.pydantic_utilities import parse_obj_as -from ..core.request_options import RequestOptions from ..errors.errors.property_based_error_test import PropertyBasedErrorTest from ..errors.types.property_based_error_test_body import PropertyBasedErrorTestBody +from ..core.client_wrapper import AsyncClientWrapper class PropertyBasedErrorClient: def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper - def throw_error(self, *, request_options: typing.Optional[RequestOptions] = None) -> str: + def throw_error( + self, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ GET request that always throws an error @@ -38,7 +40,9 @@ def throw_error(self, *, request_options: typing.Optional[RequestOptions] = None client.property_based_error.throw_error() """ _response = self._client_wrapper.httpx_client.request( - "property-based-error", method="GET", request_options=request_options + "property-based-error", + method="GET", + request_options=request_options, ) try: _response_json = _response.json() @@ -49,7 +53,13 @@ def throw_error(self, *, request_options: typing.Optional[RequestOptions] = None if "errorName" in _response_json: if _response_json["errorName"] == "PropertyBasedErrorTest": raise PropertyBasedErrorTest( - typing.cast(PropertyBasedErrorTestBody, parse_obj_as(type_=PropertyBasedErrorTestBody, object_=_response_json["content"])) # type: ignore + typing.cast( + PropertyBasedErrorTestBody, + parse_obj_as( + type_=PropertyBasedErrorTestBody, + object_=_response_json["content"], + ), + ) # type: ignore ) raise ApiError(status_code=_response.status_code, body=_response_json) @@ -58,7 +68,9 @@ class AsyncPropertyBasedErrorClient: def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper - async def throw_error(self, *, request_options: typing.Optional[RequestOptions] = None) -> str: + async def throw_error( + self, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ GET request that always throws an error @@ -89,7 +101,9 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "property-based-error", method="GET", request_options=request_options + "property-based-error", + method="GET", + request_options=request_options, ) try: _response_json = _response.json() @@ -100,6 +114,12 @@ async def main() -> None: if "errorName" in _response_json: if _response_json["errorName"] == "PropertyBasedErrorTest": raise PropertyBasedErrorTest( - typing.cast(PropertyBasedErrorTestBody, parse_obj_as(type_=PropertyBasedErrorTestBody, object_=_response_json["content"])) # type: ignore + typing.cast( + PropertyBasedErrorTestBody, + parse_obj_as( + type_=PropertyBasedErrorTestBody, + object_=_response_json["content"], + ), + ) # type: ignore ) raise ApiError(status_code=_response.status_code, body=_response_json) diff --git a/seed/python-sdk/error-property/src/seed/version.py b/seed/python-sdk/error-property/src/seed/version.py index 01bffa921e2..10d62e8a1f1 100644 --- a/seed/python-sdk/error-property/src/seed/version.py +++ b/seed/python-sdk/error-property/src/seed/version.py @@ -1,4 +1,3 @@ - from importlib import metadata __version__ = metadata.version("fern_error-property") diff --git a/seed/python-sdk/error-property/tests/conftest.py b/seed/python-sdk/error-property/tests/conftest.py index 27743a0caf6..078579056fd 100644 --- a/seed/python-sdk/error-property/tests/conftest.py +++ b/seed/python-sdk/error-property/tests/conftest.py @@ -1,9 +1,9 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedErrorProperty import os - import pytest -from seed import AsyncSeedErrorProperty, SeedErrorProperty +from seed import AsyncSeedErrorProperty @pytest.fixture diff --git a/seed/python-sdk/error-property/tests/custom/test_client.py b/seed/python-sdk/error-property/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/python-sdk/error-property/tests/custom/test_client.py +++ b/seed/python-sdk/error-property/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/python-sdk/error-property/tests/test_property_based_error.py b/seed/python-sdk/error-property/tests/test_property_based_error.py index 7f1760e939b..455fa5499f0 100644 --- a/seed/python-sdk/error-property/tests/test_property_based_error.py +++ b/seed/python-sdk/error-property/tests/test_property_based_error.py @@ -1,13 +1,14 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedErrorProperty +from seed import AsyncSeedErrorProperty import typing - -from seed import AsyncSeedErrorProperty, SeedErrorProperty - from .utilities import validate_response -async def test_throw_error(client: SeedErrorProperty, async_client: AsyncSeedErrorProperty) -> None: +async def test_throw_error( + client: SeedErrorProperty, async_client: AsyncSeedErrorProperty +) -> None: expected_response: typing.Any = "string" expected_types: typing.Any = None response = client.property_based_error.throw_error() diff --git a/seed/python-sdk/error-property/tests/utilities.py b/seed/python-sdk/error-property/tests/utilities.py index 13da208eb3a..e8f4472564c 100644 --- a/seed/python-sdk/error-property/tests/utilities.py +++ b/seed/python-sdk/error-property/tests/utilities.py @@ -3,11 +3,14 @@ import typing import uuid -import pydantic from dateutil import parser +import pydantic + -def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> typing.Any: +def cast_field( + json_expectation: typing.Any, type_expectation: typing.Any +) -> typing.Any: # Cast these specific types which come through as string and expect our # models to cast to the correct type. if type_expectation == "uuid": @@ -25,7 +28,9 @@ def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> ty return json_expectation -def validate_field(response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any) -> None: +def validate_field( + response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectation == "no_validate": return @@ -44,7 +49,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(entry_expectation, dict): is_container_of_complex_type = True validate_response( - response=response[idx], json_expectation=ex, type_expectations=entry_expectation + response=response[idx], + json_expectation=ex, + type_expectations=entry_expectation, ) else: cast_json_expectation.append(cast_field(ex, entry_expectation)) @@ -56,7 +63,10 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # if any of the values of the set have a type_expectation of a dict, we're assuming it's a pydantic # model and keeping it a list. if container_expectation != "set" or not any( - map(lambda value: isinstance(value, dict), list(contents_expectation.values())) + map( + lambda value: isinstance(value, dict), + list(contents_expectation.values()), + ) ): json_expectation = cast_field(json_expectation, container_expectation) elif isinstance(type_expectation, tuple): @@ -65,9 +75,15 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(contents_expectation, dict): json_expectation = { cast_field( - key, contents_expectation.get(idx)[0] if contents_expectation.get(idx) is not None else None # type: ignore + key, + contents_expectation.get(idx)[0] + if contents_expectation.get(idx) is not None + else None, # type: ignore ): cast_field( - value, contents_expectation.get(idx)[1] if contents_expectation.get(idx) is not None else None # type: ignore + value, + contents_expectation.get(idx)[1] + if contents_expectation.get(idx) is not None + else None, # type: ignore ) for idx, (key, value) in enumerate(json_expectation.items()) } @@ -86,7 +102,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # Arg type_expectations is a deeply nested structure that matches the response, but with the values replaced with the expected types -def validate_response(response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any) -> None: +def validate_response( + response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectations == "no_validate": return @@ -96,11 +114,17 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e and not isinstance(response, dict) and not issubclass(type(response), pydantic.BaseModel) ): - validate_field(response=response, json_expectation=json_expectation, type_expectation=type_expectations) + validate_field( + response=response, + json_expectation=json_expectation, + type_expectation=type_expectations, + ) return if isinstance(response, list): - assert len(response) == len(json_expectation), "Length mismatch, expected: {0}, Actual: {1}".format( + assert len(response) == len( + json_expectation + ), "Length mismatch, expected: {0}, Actual: {1}".format( len(response), len(json_expectation) ) content_expectation = type_expectations @@ -108,7 +132,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e content_expectation = type_expectations[1] for idx, item in enumerate(response): validate_response( - response=item, json_expectation=json_expectation[idx], type_expectations=content_expectation[idx] + response=item, + json_expectation=json_expectation[idx], + type_expectations=content_expectation[idx], ) else: response_json = response @@ -116,7 +142,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e response_json = response.dict(by_alias=True) for key, value in json_expectation.items(): - assert key in response_json, "Field {0} not found within the response object: {1}".format( + assert ( + key in response_json + ), "Field {0} not found within the response object: {1}".format( key, response_json ) @@ -128,11 +156,19 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e # Otherwise, we're just validating a single field that's a pydantic model. if isinstance(value, dict) and not isinstance(type_expectation, tuple): validate_response( - response=response_json[key], json_expectation=value, type_expectations=type_expectation + response=response_json[key], + json_expectation=value, + type_expectations=type_expectation, ) else: - validate_field(response=response_json[key], json_expectation=value, type_expectation=type_expectation) + validate_field( + response=response_json[key], + json_expectation=value, + type_expectation=type_expectation, + ) # Ensure there are no additional fields here either del response_json[key] - assert len(response_json) == 0, "Additional fields found, expected None: {0}".format(response_json) + assert ( + len(response_json) == 0 + ), "Additional fields found, expected None: {0}".format(response_json) diff --git a/seed/python-sdk/error-property/tests/utils/assets/models/__init__.py b/seed/python-sdk/error-property/tests/utils/assets/models/__init__.py index 2cf01263529..3a1c852e71e 100644 --- a/seed/python-sdk/error-property/tests/utils/assets/models/__init__.py +++ b/seed/python-sdk/error-property/tests/utils/assets/models/__init__.py @@ -5,7 +5,7 @@ from .circle import CircleParams from .object_with_defaults import ObjectWithDefaultsParams from .object_with_optional_field import ObjectWithOptionalFieldParams -from .shape import Shape_CircleParams, Shape_SquareParams, ShapeParams +from .shape import ShapeParams, Shape_CircleParams, Shape_SquareParams from .square import SquareParams from .undiscriminated_shape import UndiscriminatedShapeParams diff --git a/seed/python-sdk/error-property/tests/utils/assets/models/circle.py b/seed/python-sdk/error-property/tests/utils/assets/models/circle.py index af7a1bf8a8e..253f12d38b3 100644 --- a/seed/python-sdk/error-property/tests/utils/assets/models/circle.py +++ b/seed/python-sdk/error-property/tests/utils/assets/models/circle.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class CircleParams(typing_extensions.TypedDict): - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] diff --git a/seed/python-sdk/error-property/tests/utils/assets/models/object_with_optional_field.py b/seed/python-sdk/error-property/tests/utils/assets/models/object_with_optional_field.py index 3ad93d5f305..ebe7dc80547 100644 --- a/seed/python-sdk/error-property/tests/utils/assets/models/object_with_optional_field.py +++ b/seed/python-sdk/error-property/tests/utils/assets/models/object_with_optional_field.py @@ -7,8 +7,8 @@ import uuid import typing_extensions -from seed.core.serialization import FieldMetadata +from seed.core.serialization import FieldMetadata from .color import Color from .shape import ShapeParams from .undiscriminated_shape import UndiscriminatedShapeParams @@ -18,16 +18,30 @@ class ObjectWithOptionalFieldParams(typing_extensions.TypedDict): literal: typing.Literal["lit_one"] string: typing_extensions.NotRequired[str] integer: typing_extensions.NotRequired[int] - long_: typing_extensions.NotRequired[typing_extensions.Annotated[int, FieldMetadata(alias="long")]] + long_: typing_extensions.NotRequired[ + typing_extensions.Annotated[int, FieldMetadata(alias="long")] + ] double: typing_extensions.NotRequired[float] - bool_: typing_extensions.NotRequired[typing_extensions.Annotated[bool, FieldMetadata(alias="bool")]] + bool_: typing_extensions.NotRequired[ + typing_extensions.Annotated[bool, FieldMetadata(alias="bool")] + ] datetime: typing_extensions.NotRequired[dt.datetime] date: typing_extensions.NotRequired[dt.date] - uuid_: typing_extensions.NotRequired[typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")]] - base_64: typing_extensions.NotRequired[typing_extensions.Annotated[str, FieldMetadata(alias="base64")]] - list_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")]] - set_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")]] - map_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")]] + uuid_: typing_extensions.NotRequired[ + typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")] + ] + base_64: typing_extensions.NotRequired[ + typing_extensions.Annotated[str, FieldMetadata(alias="base64")] + ] + list_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")] + ] + set_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")] + ] + map_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")] + ] enum: typing_extensions.NotRequired[Color] union: typing_extensions.NotRequired[ShapeParams] second_union: typing_extensions.NotRequired[ShapeParams] diff --git a/seed/python-sdk/error-property/tests/utils/assets/models/shape.py b/seed/python-sdk/error-property/tests/utils/assets/models/shape.py index 2c33c877951..816ffc51bdc 100644 --- a/seed/python-sdk/error-property/tests/utils/assets/models/shape.py +++ b/seed/python-sdk/error-property/tests/utils/assets/models/shape.py @@ -7,6 +7,7 @@ import typing import typing_extensions + from seed.core.serialization import FieldMetadata @@ -15,13 +16,21 @@ class Base(typing_extensions.TypedDict): class Shape_CircleParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["circle"], FieldMetadata(alias="shapeType")] - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["circle"], FieldMetadata(alias="shapeType") + ] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] class Shape_SquareParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["square"], FieldMetadata(alias="shapeType")] - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["square"], FieldMetadata(alias="shapeType") + ] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] ShapeParams = typing.Union[Shape_CircleParams, Shape_SquareParams] diff --git a/seed/python-sdk/error-property/tests/utils/assets/models/square.py b/seed/python-sdk/error-property/tests/utils/assets/models/square.py index b9b7dd319bc..bcf08a723c5 100644 --- a/seed/python-sdk/error-property/tests/utils/assets/models/square.py +++ b/seed/python-sdk/error-property/tests/utils/assets/models/square.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class SquareParams(typing_extensions.TypedDict): - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] diff --git a/seed/python-sdk/error-property/tests/utils/test_http_client.py b/seed/python-sdk/error-property/tests/utils/test_http_client.py index edd11ca7afb..f5a874a75f3 100644 --- a/seed/python-sdk/error-property/tests/utils/test_http_client.py +++ b/seed/python-sdk/error-property/tests/utils/test_http_client.py @@ -9,12 +9,17 @@ def get_request_options() -> RequestOptions: def test_get_json_request_body() -> None: - json_body, data_body = get_request_body(json={"hello": "world"}, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json={"hello": "world"}, data=None, request_options=None, omit=None + ) assert json_body == {"hello": "world"} assert data_body is None json_body_extras, data_body_extras = get_request_body( - json={"goodbye": "world"}, data=None, request_options=get_request_options(), omit=None + json={"goodbye": "world"}, + data=None, + request_options=get_request_options(), + omit=None, ) assert json_body_extras == {"goodbye": "world", "see you": "later"} @@ -22,12 +27,17 @@ def test_get_json_request_body() -> None: def test_get_files_request_body() -> None: - json_body, data_body = get_request_body(json=None, data={"hello": "world"}, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data={"hello": "world"}, request_options=None, omit=None + ) assert data_body == {"hello": "world"} assert json_body is None json_body_extras, data_body_extras = get_request_body( - json=None, data={"goodbye": "world"}, request_options=get_request_options(), omit=None + json=None, + data={"goodbye": "world"}, + request_options=get_request_options(), + omit=None, ) assert data_body_extras == {"goodbye": "world", "see you": "later"} @@ -35,7 +45,9 @@ def test_get_files_request_body() -> None: def test_get_none_request_body() -> None: - json_body, data_body = get_request_body(json=None, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data=None, request_options=None, omit=None + ) assert data_body is None assert json_body is None diff --git a/seed/python-sdk/error-property/tests/utils/test_query_encoding.py b/seed/python-sdk/error-property/tests/utils/test_query_encoding.py index 247e1551b46..fbc8f402167 100644 --- a/seed/python-sdk/error-property/tests/utils/test_query_encoding.py +++ b/seed/python-sdk/error-property/tests/utils/test_query_encoding.py @@ -4,9 +4,15 @@ def test_query_encoding() -> None: - assert encode_query({"hello world": "hello world"}) == {"hello world": "hello world"} - assert encode_query({"hello_world": {"hello": "world"}}) == {"hello_world[hello]": "world"} - assert encode_query({"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"}) == { + assert encode_query({"hello world": "hello world"}) == { + "hello world": "hello world" + } + assert encode_query({"hello_world": {"hello": "world"}}) == { + "hello_world[hello]": "world" + } + assert encode_query( + {"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"} + ) == { "hello_world[hello][world]": "today", "hello_world[test]": "this", "hi": "there", diff --git a/seed/python-sdk/error-property/tests/utils/test_serialization.py b/seed/python-sdk/error-property/tests/utils/test_serialization.py index 58b1ed66e6d..5ca956916dd 100644 --- a/seed/python-sdk/error-property/tests/utils/test_serialization.py +++ b/seed/python-sdk/error-property/tests/utils/test_serialization.py @@ -1,10 +1,12 @@ # This file was auto-generated by Fern from our API Definition. -from typing import Any, List +from typing import List, Any -from seed.core.serialization import convert_and_respect_annotation_metadata +from seed.core.serialization import ( + convert_and_respect_annotation_metadata, +) +from .assets.models import ShapeParams, ObjectWithOptionalFieldParams -from .assets.models import ObjectWithOptionalFieldParams, ShapeParams UNION_TEST: ShapeParams = {"radius_measurement": 1.0, "shape_type": "circle", "id": "1"} UNION_TEST_CONVERTED = {"shapeType": "circle", "radiusMeasurement": 1.0, "id": "1"} @@ -18,20 +20,54 @@ def test_convert_and_respect_annotation_metadata() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) - assert converted == {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"} + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) + assert converted == { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + } def test_convert_and_respect_annotation_metadata_in_list() -> None: data: List[ObjectWithOptionalFieldParams] = [ - {"string": "string", "long_": 12345, "bool_": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long_": 67890, "list_": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long_": 12345, + "bool_": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long_": 67890, + "list_": [], + "literal": "lit_one", + "any": "any", + }, ] - converted = convert_and_respect_annotation_metadata(object_=data, annotation=List[ObjectWithOptionalFieldParams]) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=List[ObjectWithOptionalFieldParams] + ) assert converted == [ - {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long": 67890, "list": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long": 67890, + "list": [], + "literal": "lit_one", + "any": "any", + }, ] @@ -43,7 +79,9 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) assert converted == { "string": "string", @@ -55,12 +93,16 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: def test_convert_and_respect_annotation_metadata_in_union() -> None: - converted = convert_and_respect_annotation_metadata(object_=UNION_TEST, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=UNION_TEST, annotation=ShapeParams + ) assert converted == UNION_TEST_CONVERTED def test_convert_and_respect_annotation_metadata_with_empty_object() -> None: data: Any = {} - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ShapeParams + ) assert converted == data diff --git a/seed/python-sdk/examples/client-filename/pyproject.toml b/seed/python-sdk/examples/client-filename/pyproject.toml index adf3a468dac..c248e8d8f0c 100644 --- a/seed/python-sdk/examples/client-filename/pyproject.toml +++ b/seed/python-sdk/examples/client-filename/pyproject.toml @@ -43,6 +43,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/python-sdk/examples/client-filename/src/seed/base_client.py b/seed/python-sdk/examples/client-filename/src/seed/base_client.py index 6dc6d9a581c..45645ba7879 100644 --- a/seed/python-sdk/examples/client-filename/src/seed/base_client.py +++ b/seed/python-sdk/examples/client-filename/src/seed/base_client.py @@ -1,18 +1,20 @@ # This file was auto-generated by Fern from our API Definition. import typing -from json.decoder import JSONDecodeError - +from .environment import SeedExhaustiveEnvironment import httpx - -from .core.api_error import ApiError -from .core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from .core.pydantic_utilities import parse_obj_as +from .core.client_wrapper import SyncClientWrapper +from .file.client import FileClient +from .health.client import HealthClient +from .service.client import ServiceClient from .core.request_options import RequestOptions -from .environment import SeedExhaustiveEnvironment -from .file.client import AsyncFileClient, FileClient -from .health.client import AsyncHealthClient, HealthClient -from .service.client import AsyncServiceClient, ServiceClient +from .core.pydantic_utilities import parse_obj_as +from json.decoder import JSONDecodeError +from .core.api_error import ApiError +from .core.client_wrapper import AsyncClientWrapper +from .file.client import AsyncFileClient +from .health.client import AsyncHealthClient +from .service.client import AsyncServiceClient # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -59,15 +61,19 @@ def __init__( token: typing.Optional[typing.Union[str, typing.Callable[[], str]]] = None, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.Client] = None + httpx_client: typing.Optional[httpx.Client] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = SyncClientWrapper( base_url=_get_base_url(base_url=base_url, environment=environment), token=token, httpx_client=httpx_client if httpx_client is not None - else httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.Client( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.Client(timeout=_defaulted_timeout), timeout=_defaulted_timeout, @@ -76,7 +82,9 @@ def __init__( self.health = HealthClient(client_wrapper=self._client_wrapper) self.service = ServiceClient(client_wrapper=self._client_wrapper) - def echo(self, *, request: str, request_options: typing.Optional[RequestOptions] = None) -> str: + def echo( + self, *, request: str, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -103,11 +111,16 @@ def echo(self, *, request: str, request_options: typing.Optional[RequestOptions] ) """ _response = self._client_wrapper.httpx_client.request( - method="POST", json=request, request_options=request_options, omit=OMIT + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -155,15 +168,19 @@ def __init__( token: typing.Optional[typing.Union[str, typing.Callable[[], str]]] = None, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.AsyncClient] = None + httpx_client: typing.Optional[httpx.AsyncClient] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = AsyncClientWrapper( base_url=_get_base_url(base_url=base_url, environment=environment), token=token, httpx_client=httpx_client if httpx_client is not None - else httpx.AsyncClient(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.AsyncClient( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.AsyncClient(timeout=_defaulted_timeout), timeout=_defaulted_timeout, @@ -172,7 +189,9 @@ def __init__( self.health = AsyncHealthClient(client_wrapper=self._client_wrapper) self.service = AsyncServiceClient(client_wrapper=self._client_wrapper) - async def echo(self, *, request: str, request_options: typing.Optional[RequestOptions] = None) -> str: + async def echo( + self, *, request: str, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -207,11 +226,16 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - method="POST", json=request, request_options=request_options, omit=OMIT + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -219,11 +243,15 @@ async def main() -> None: def _get_base_url( - *, base_url: typing.Optional[str] = None, environment: typing.Optional[SeedExhaustiveEnvironment] = None + *, + base_url: typing.Optional[str] = None, + environment: typing.Optional[SeedExhaustiveEnvironment] = None, ) -> str: if base_url is not None: return base_url elif environment is not None: return environment.value else: - raise Exception("Please pass in either base_url or environment to construct the client") + raise Exception( + "Please pass in either base_url or environment to construct the client" + ) diff --git a/seed/python-sdk/examples/client-filename/src/seed/client.py b/seed/python-sdk/examples/client-filename/src/seed/client.py index 50bc5d3319f..17d56ae144c 100644 --- a/seed/python-sdk/examples/client-filename/src/seed/client.py +++ b/seed/python-sdk/examples/client-filename/src/seed/client.py @@ -4,5 +4,6 @@ class SeedExhaustive(BaseSeedExhaustive): pass + class AsyncSeedExhaustive(AsyncBaseSeedExhaustive): pass diff --git a/seed/python-sdk/examples/client-filename/src/seed/commons/__init__.py b/seed/python-sdk/examples/client-filename/src/seed/commons/__init__.py index 1d968e36800..03f39303b3d 100644 --- a/seed/python-sdk/examples/client-filename/src/seed/commons/__init__.py +++ b/seed/python-sdk/examples/client-filename/src/seed/commons/__init__.py @@ -1,6 +1,15 @@ # This file was auto-generated by Fern from our API Definition. -from .types import Data, Data_Base64, Data_String, EventInfo, EventInfo_Metadata, EventInfo_Tag, Metadata, Tag +from .types import ( + Data, + Data_Base64, + Data_String, + EventInfo, + EventInfo_Metadata, + EventInfo_Tag, + Metadata, + Tag, +) from . import types __all__ = [ diff --git a/seed/python-sdk/examples/client-filename/src/seed/commons/types/__init__.py b/seed/python-sdk/examples/client-filename/src/seed/commons/types/__init__.py index 319c40f2c26..bddae54aee3 100644 --- a/seed/python-sdk/examples/client-filename/src/seed/commons/types/__init__.py +++ b/seed/python-sdk/examples/client-filename/src/seed/commons/types/__init__.py @@ -1,5 +1,23 @@ # This file was auto-generated by Fern from our API Definition. -from .types import Data, Data_Base64, Data_String, EventInfo, EventInfo_Metadata, EventInfo_Tag, Metadata, Tag +from .types import ( + Data, + Data_Base64, + Data_String, + EventInfo, + EventInfo_Metadata, + EventInfo_Tag, + Metadata, + Tag, +) -__all__ = ["Data", "Data_Base64", "Data_String", "EventInfo", "EventInfo_Metadata", "EventInfo_Tag", "Metadata", "Tag"] +__all__ = [ + "Data", + "Data_Base64", + "Data_String", + "EventInfo", + "EventInfo_Metadata", + "EventInfo_Tag", + "Metadata", + "Tag", +] diff --git a/seed/python-sdk/examples/client-filename/src/seed/commons/types/types/__init__.py b/seed/python-sdk/examples/client-filename/src/seed/commons/types/types/__init__.py index a73f9e83b6c..9c78512dba5 100644 --- a/seed/python-sdk/examples/client-filename/src/seed/commons/types/types/__init__.py +++ b/seed/python-sdk/examples/client-filename/src/seed/commons/types/types/__init__.py @@ -5,4 +5,13 @@ from .metadata import Metadata from .tag import Tag -__all__ = ["Data", "Data_Base64", "Data_String", "EventInfo", "EventInfo_Metadata", "EventInfo_Tag", "Metadata", "Tag"] +__all__ = [ + "Data", + "Data_Base64", + "Data_String", + "EventInfo", + "EventInfo_Metadata", + "EventInfo_Tag", + "Metadata", + "Tag", +] diff --git a/seed/python-sdk/examples/client-filename/src/seed/commons/types/types/data.py b/seed/python-sdk/examples/client-filename/src/seed/commons/types/types/data.py index a2e7f693004..c491904b237 100644 --- a/seed/python-sdk/examples/client-filename/src/seed/commons/types/types/data.py +++ b/seed/python-sdk/examples/client-filename/src/seed/commons/types/types/data.py @@ -1,20 +1,20 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ....core.pydantic_utilities import UniversalBaseModel import typing - +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class Data_String(UniversalBaseModel): value: str type: typing.Literal["string"] = "string" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + frozen=True + ) # type: ignore # Pydantic v2 else: class Config: @@ -27,7 +27,9 @@ class Data_Base64(UniversalBaseModel): type: typing.Literal["base64"] = "base64" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/examples/client-filename/src/seed/commons/types/types/event_info.py b/seed/python-sdk/examples/client-filename/src/seed/commons/types/types/event_info.py index 1ec20f1861f..3e3e4d96864 100644 --- a/seed/python-sdk/examples/client-filename/src/seed/commons/types/types/event_info.py +++ b/seed/python-sdk/examples/client-filename/src/seed/commons/types/types/event_info.py @@ -1,12 +1,10 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ....core.pydantic_utilities import UniversalBaseModel import typing - import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 from .tag import Tag @@ -29,7 +27,9 @@ class EventInfo_Metadata(UniversalBaseModel): json_string: typing.Optional[str] = pydantic.Field(alias="jsonString", default=None) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: @@ -43,7 +43,9 @@ class EventInfo_Tag(UniversalBaseModel): type: typing.Literal["tag"] = "tag" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/examples/client-filename/src/seed/commons/types/types/metadata.py b/seed/python-sdk/examples/client-filename/src/seed/commons/types/types/metadata.py index a8795aa41a6..52808334881 100644 --- a/seed/python-sdk/examples/client-filename/src/seed/commons/types/types/metadata.py +++ b/seed/python-sdk/examples/client-filename/src/seed/commons/types/types/metadata.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class Metadata(UniversalBaseModel): @@ -25,7 +24,9 @@ class Metadata(UniversalBaseModel): json_string: typing.Optional[str] = pydantic.Field(alias="jsonString", default=None) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/examples/client-filename/src/seed/commons/types/types/tag.py b/seed/python-sdk/examples/client-filename/src/seed/commons/types/types/tag.py index ae576888232..ad97a39db4c 100644 --- a/seed/python-sdk/examples/client-filename/src/seed/commons/types/types/tag.py +++ b/seed/python-sdk/examples/client-filename/src/seed/commons/types/types/tag.py @@ -3,4 +3,5 @@ """ "tag-wf9as23d" """ + Tag = str diff --git a/seed/python-sdk/examples/client-filename/src/seed/core/api_error.py b/seed/python-sdk/examples/client-filename/src/seed/core/api_error.py index 2e9fc5431cd..da734b58068 100644 --- a/seed/python-sdk/examples/client-filename/src/seed/core/api_error.py +++ b/seed/python-sdk/examples/client-filename/src/seed/core/api_error.py @@ -7,7 +7,9 @@ class ApiError(Exception): status_code: typing.Optional[int] body: typing.Any - def __init__(self, *, status_code: typing.Optional[int] = None, body: typing.Any = None): + def __init__( + self, *, status_code: typing.Optional[int] = None, body: typing.Any = None + ): self.status_code = status_code self.body = body diff --git a/seed/python-sdk/examples/client-filename/src/seed/core/client_wrapper.py b/seed/python-sdk/examples/client-filename/src/seed/core/client_wrapper.py index ef78d78ed99..88e5016aa3f 100644 --- a/seed/python-sdk/examples/client-filename/src/seed/core/client_wrapper.py +++ b/seed/python-sdk/examples/client-filename/src/seed/core/client_wrapper.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .http_client import AsyncHttpClient, HttpClient +from .http_client import HttpClient +from .http_client import AsyncHttpClient class BaseClientWrapper: diff --git a/seed/python-sdk/examples/client-filename/src/seed/core/datetime_utils.py b/seed/python-sdk/examples/client-filename/src/seed/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/python-sdk/examples/client-filename/src/seed/core/datetime_utils.py +++ b/seed/python-sdk/examples/client-filename/src/seed/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/python-sdk/examples/client-filename/src/seed/core/file.py b/seed/python-sdk/examples/client-filename/src/seed/core/file.py index cb0d40bbbf3..6e0f92bfcb1 100644 --- a/seed/python-sdk/examples/client-filename/src/seed/core/file.py +++ b/seed/python-sdk/examples/client-filename/src/seed/core/file.py @@ -13,12 +13,17 @@ # (filename, file (or bytes), content_type) typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str]], # (filename, file (or bytes), content_type, headers) - typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str], typing.Mapping[str, str]], + typing.Tuple[ + typing.Optional[str], + FileContent, + typing.Optional[str], + typing.Mapping[str, str], + ], ] def convert_file_dict_to_httpx_tuples( - d: typing.Dict[str, typing.Union[File, typing.List[File]]] + d: typing.Dict[str, typing.Union[File, typing.List[File]]], ) -> typing.List[typing.Tuple[str, File]]: """ The format we use is a list of tuples, where the first element is the diff --git a/seed/python-sdk/examples/client-filename/src/seed/core/http_client.py b/seed/python-sdk/examples/client-filename/src/seed/core/http_client.py index 9333d8a7f15..091f71bc185 100644 --- a/seed/python-sdk/examples/client-filename/src/seed/core/http_client.py +++ b/seed/python-sdk/examples/client-filename/src/seed/core/http_client.py @@ -77,7 +77,9 @@ def _retry_timeout(response: httpx.Response, retries: int) -> float: return retry_after # Apply exponential backoff, capped at MAX_RETRY_DELAY_SECONDS. - retry_delay = min(INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS) + retry_delay = min( + INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS + ) # Add a randomness / jitter to the retry delay to avoid overwhelming the server with retries. timeout = retry_delay * (1 - 0.25 * random()) @@ -90,7 +92,8 @@ def _should_retry(response: httpx.Response) -> bool: def remove_omit_from_dict( - original: typing.Dict[str, typing.Optional[typing.Any]], omit: typing.Optional[typing.Any] + original: typing.Dict[str, typing.Optional[typing.Any]], + omit: typing.Optional[typing.Any], ) -> typing.Dict[str, typing.Any]: if omit is None: return original @@ -108,7 +111,8 @@ def maybe_filter_request_body( ) -> typing.Optional[typing.Any]: if data is None: return ( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else None ) @@ -118,7 +122,8 @@ def maybe_filter_request_body( data_content = { **(jsonable_encoder(remove_omit_from_dict(data, omit))), # type: ignore **( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else {} ), @@ -162,7 +167,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url def request( @@ -174,8 +181,12 @@ def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -184,11 +195,14 @@ def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) response = self.httpx_client.request( method=method, @@ -198,7 +212,11 @@ def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -209,7 +227,10 @@ def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -222,11 +243,15 @@ def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: time.sleep(_retry_timeout(response=response, retries=retries)) @@ -256,8 +281,12 @@ def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -266,11 +295,14 @@ def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) with self.httpx_client.stream( method=method, @@ -280,7 +312,11 @@ def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -291,7 +327,9 @@ def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -304,7 +342,9 @@ def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream @@ -327,7 +367,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url async def request( @@ -339,8 +381,12 @@ async def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -349,11 +395,14 @@ async def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) # Add the input to each of these and do None-safety checks response = await self.httpx_client.request( @@ -364,7 +413,11 @@ async def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -375,7 +428,10 @@ async def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -388,11 +444,15 @@ async def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: await asyncio.sleep(_retry_timeout(response=response, retries=retries)) @@ -421,8 +481,12 @@ async def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -431,11 +495,14 @@ async def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) async with self.httpx_client.stream( method=method, @@ -445,7 +512,11 @@ async def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -456,7 +527,9 @@ async def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -469,7 +542,9 @@ async def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream diff --git a/seed/python-sdk/examples/client-filename/src/seed/core/jsonable_encoder.py b/seed/python-sdk/examples/client-filename/src/seed/core/jsonable_encoder.py index d3fd328fd41..12a8b52fc22 100644 --- a/seed/python-sdk/examples/client-filename/src/seed/core/jsonable_encoder.py +++ b/seed/python-sdk/examples/client-filename/src/seed/core/jsonable_encoder.py @@ -19,13 +19,19 @@ import pydantic from .datetime_utils import serialize_datetime -from .pydantic_utilities import IS_PYDANTIC_V2, encode_by_type, to_jsonable_with_fallback +from .pydantic_utilities import ( + IS_PYDANTIC_V2, + encode_by_type, + to_jsonable_with_fallback, +) SetIntStr = Set[Union[int, str]] DictIntStrAny = Dict[Union[int, str], Any] -def jsonable_encoder(obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None) -> Any: +def jsonable_encoder( + obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None +) -> Any: custom_encoder = custom_encoder or {} if custom_encoder: if type(obj) in custom_encoder: diff --git a/seed/python-sdk/examples/client-filename/src/seed/core/pydantic_utilities.py b/seed/python-sdk/examples/client-filename/src/seed/core/pydantic_utilities.py index 170a563d6eb..c63935c32a2 100644 --- a/seed/python-sdk/examples/client-filename/src/seed/core/pydantic_utilities.py +++ b/seed/python-sdk/examples/client-filename/src/seed/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) # type: ignore # Pydantic v1 diff --git a/seed/python-sdk/examples/client-filename/src/seed/core/query_encoder.py b/seed/python-sdk/examples/client-filename/src/seed/core/query_encoder.py index 24076d72ee9..7cb98f52cd7 100644 --- a/seed/python-sdk/examples/client-filename/src/seed/core/query_encoder.py +++ b/seed/python-sdk/examples/client-filename/src/seed/core/query_encoder.py @@ -7,7 +7,9 @@ # Flattens dicts to be of the form {"key[subkey][subkey2]": value} where value is not a dict -def traverse_query_dict(dict_flat: Dict[str, Any], key_prefix: Optional[str] = None) -> Dict[str, Any]: +def traverse_query_dict( + dict_flat: Dict[str, Any], key_prefix: Optional[str] = None +) -> Dict[str, Any]: result = {} for k, v in dict_flat.items(): key = f"{key_prefix}[{k}]" if key_prefix is not None else k @@ -30,4 +32,8 @@ def single_query_encoder(query_key: str, query_value: Any) -> Dict[str, Any]: def encode_query(query: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: - return dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) if query is not None else None + return ( + dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) + if query is not None + else None + ) diff --git a/seed/python-sdk/examples/client-filename/src/seed/core/serialization.py b/seed/python-sdk/examples/client-filename/src/seed/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/python-sdk/examples/client-filename/src/seed/core/serialization.py +++ b/seed/python-sdk/examples/client-filename/src/seed/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/python-sdk/examples/client-filename/src/seed/file/client.py b/seed/python-sdk/examples/client-filename/src/seed/file/client.py index 81bb5dc7923..b6004e87af6 100644 --- a/seed/python-sdk/examples/client-filename/src/seed/file/client.py +++ b/seed/python-sdk/examples/client-filename/src/seed/file/client.py @@ -1,8 +1,11 @@ # This file was auto-generated by Fern from our API Definition. -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from .notification.client import AsyncNotificationClient, NotificationClient -from .service.client import AsyncServiceClient, ServiceClient +from ..core.client_wrapper import SyncClientWrapper +from .notification.client import NotificationClient +from .service.client import ServiceClient +from ..core.client_wrapper import AsyncClientWrapper +from .notification.client import AsyncNotificationClient +from .service.client import AsyncServiceClient class FileClient: diff --git a/seed/python-sdk/examples/client-filename/src/seed/file/notification/client.py b/seed/python-sdk/examples/client-filename/src/seed/file/notification/client.py index e8077a84043..7ecd8bc9048 100644 --- a/seed/python-sdk/examples/client-filename/src/seed/file/notification/client.py +++ b/seed/python-sdk/examples/client-filename/src/seed/file/notification/client.py @@ -1,7 +1,9 @@ # This file was auto-generated by Fern from our API Definition. -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from .service.client import AsyncServiceClient, ServiceClient +from ...core.client_wrapper import SyncClientWrapper +from .service.client import ServiceClient +from ...core.client_wrapper import AsyncClientWrapper +from .service.client import AsyncServiceClient class NotificationClient: diff --git a/seed/python-sdk/examples/client-filename/src/seed/file/notification/service/client.py b/seed/python-sdk/examples/client-filename/src/seed/file/notification/service/client.py index d4d38c21a25..b24efb6142b 100644 --- a/seed/python-sdk/examples/client-filename/src/seed/file/notification/service/client.py +++ b/seed/python-sdk/examples/client-filename/src/seed/file/notification/service/client.py @@ -1,14 +1,14 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.client_wrapper import SyncClientWrapper import typing -from json.decoder import JSONDecodeError - -from ....core.api_error import ApiError -from ....core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ....core.jsonable_encoder import jsonable_encoder -from ....core.pydantic_utilities import parse_obj_as from ....core.request_options import RequestOptions from ....types.types.exception import Exception +from ....core.jsonable_encoder import jsonable_encoder +from ....core.pydantic_utilities import parse_obj_as +from json.decoder import JSONDecodeError +from ....core.api_error import ApiError +from ....core.client_wrapper import AsyncClientWrapper class ServiceClient: @@ -16,7 +16,10 @@ def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper def get_exception( - self, notification_id: str, *, request_options: typing.Optional[RequestOptions] = None + self, + notification_id: str, + *, + request_options: typing.Optional[RequestOptions] = None, ) -> Exception: """ Parameters @@ -44,11 +47,15 @@ def get_exception( ) """ _response = self._client_wrapper.httpx_client.request( - f"file/notification/{jsonable_encoder(notification_id)}", method="GET", request_options=request_options + f"file/notification/{jsonable_encoder(notification_id)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(Exception, parse_obj_as(type_=Exception, object_=_response.json())) # type: ignore + return typing.cast( + Exception, parse_obj_as(type_=Exception, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -60,7 +67,10 @@ def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper async def get_exception( - self, notification_id: str, *, request_options: typing.Optional[RequestOptions] = None + self, + notification_id: str, + *, + request_options: typing.Optional[RequestOptions] = None, ) -> Exception: """ Parameters @@ -96,11 +106,15 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - f"file/notification/{jsonable_encoder(notification_id)}", method="GET", request_options=request_options + f"file/notification/{jsonable_encoder(notification_id)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(Exception, parse_obj_as(type_=Exception, object_=_response.json())) # type: ignore + return typing.cast( + Exception, parse_obj_as(type_=Exception, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/examples/client-filename/src/seed/file/service/client.py b/seed/python-sdk/examples/client-filename/src/seed/file/service/client.py index 62a851cc16e..8ce2c99ee79 100644 --- a/seed/python-sdk/examples/client-filename/src/seed/file/service/client.py +++ b/seed/python-sdk/examples/client-filename/src/seed/file/service/client.py @@ -1,15 +1,15 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.client_wrapper import SyncClientWrapper import typing -from json.decoder import JSONDecodeError - -from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper +from ...core.request_options import RequestOptions +from ...types.types.file import File from ...core.jsonable_encoder import jsonable_encoder from ...core.pydantic_utilities import parse_obj_as -from ...core.request_options import RequestOptions from ...types.errors.not_found_error import NotFoundError -from ...types.types.file import File +from json.decoder import JSONDecodeError +from ...core.api_error import ApiError +from ...core.client_wrapper import AsyncClientWrapper class ServiceClient: @@ -17,7 +17,11 @@ def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper def get_file( - self, filename: str, *, x_file_api_version: str, request_options: typing.Optional[RequestOptions] = None + self, + filename: str, + *, + x_file_api_version: str, + request_options: typing.Optional[RequestOptions] = None, ) -> File: """ This endpoint returns a file by its name. @@ -53,14 +57,22 @@ def get_file( _response = self._client_wrapper.httpx_client.request( f"file/{jsonable_encoder(filename)}", method="GET", - headers={"X-File-API-Version": str(x_file_api_version) if x_file_api_version is not None else None}, + headers={ + "X-File-API-Version": str(x_file_api_version) + if x_file_api_version is not None + else None, + }, request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(File, parse_obj_as(type_=File, object_=_response.json())) # type: ignore + return typing.cast( + File, parse_obj_as(type_=File, object_=_response.json()) + ) # type: ignore if _response.status_code == 404: - raise NotFoundError(typing.cast(str, parse_obj_as(type_=str, object_=_response.json()))) # type: ignore + raise NotFoundError( + typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + ) _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -72,7 +84,11 @@ def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper async def get_file( - self, filename: str, *, x_file_api_version: str, request_options: typing.Optional[RequestOptions] = None + self, + filename: str, + *, + x_file_api_version: str, + request_options: typing.Optional[RequestOptions] = None, ) -> File: """ This endpoint returns a file by its name. @@ -116,14 +132,22 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( f"file/{jsonable_encoder(filename)}", method="GET", - headers={"X-File-API-Version": str(x_file_api_version) if x_file_api_version is not None else None}, + headers={ + "X-File-API-Version": str(x_file_api_version) + if x_file_api_version is not None + else None, + }, request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(File, parse_obj_as(type_=File, object_=_response.json())) # type: ignore + return typing.cast( + File, parse_obj_as(type_=File, object_=_response.json()) + ) # type: ignore if _response.status_code == 404: - raise NotFoundError(typing.cast(str, parse_obj_as(type_=str, object_=_response.json()))) # type: ignore + raise NotFoundError( + typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + ) _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/examples/client-filename/src/seed/file/service/types/filename.py b/seed/python-sdk/examples/client-filename/src/seed/file/service/types/filename.py index add91706b10..2531edee925 100644 --- a/seed/python-sdk/examples/client-filename/src/seed/file/service/types/filename.py +++ b/seed/python-sdk/examples/client-filename/src/seed/file/service/types/filename.py @@ -3,4 +3,5 @@ """ "file.txt" """ + Filename = str diff --git a/seed/python-sdk/examples/client-filename/src/seed/health/client.py b/seed/python-sdk/examples/client-filename/src/seed/health/client.py index a17be0c2502..d55aad7cbe9 100644 --- a/seed/python-sdk/examples/client-filename/src/seed/health/client.py +++ b/seed/python-sdk/examples/client-filename/src/seed/health/client.py @@ -1,7 +1,9 @@ # This file was auto-generated by Fern from our API Definition. -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from .service.client import AsyncServiceClient, ServiceClient +from ..core.client_wrapper import SyncClientWrapper +from .service.client import ServiceClient +from ..core.client_wrapper import AsyncClientWrapper +from .service.client import AsyncServiceClient class HealthClient: diff --git a/seed/python-sdk/examples/client-filename/src/seed/health/service/client.py b/seed/python-sdk/examples/client-filename/src/seed/health/service/client.py index 9e49237f310..8e103864db3 100644 --- a/seed/python-sdk/examples/client-filename/src/seed/health/service/client.py +++ b/seed/python-sdk/examples/client-filename/src/seed/health/service/client.py @@ -1,20 +1,22 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.client_wrapper import SyncClientWrapper import typing +from ...core.request_options import RequestOptions +from ...core.jsonable_encoder import jsonable_encoder from json.decoder import JSONDecodeError - from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ...core.jsonable_encoder import jsonable_encoder from ...core.pydantic_utilities import parse_obj_as -from ...core.request_options import RequestOptions +from ...core.client_wrapper import AsyncClientWrapper class ServiceClient: def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper - def check(self, id: str, *, request_options: typing.Optional[RequestOptions] = None) -> None: + def check( + self, id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> None: """ This endpoint checks the health of a resource. @@ -44,7 +46,9 @@ def check(self, id: str, *, request_options: typing.Optional[RequestOptions] = N ) """ _response = self._client_wrapper.httpx_client.request( - f"check/{jsonable_encoder(id)}", method="GET", request_options=request_options + f"check/{jsonable_encoder(id)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: @@ -78,10 +82,16 @@ def ping(self, *, request_options: typing.Optional[RequestOptions] = None) -> bo ) client.health.service.ping() """ - _response = self._client_wrapper.httpx_client.request("ping", method="GET", request_options=request_options) + _response = self._client_wrapper.httpx_client.request( + "ping", + method="GET", + request_options=request_options, + ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -92,7 +102,9 @@ class AsyncServiceClient: def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper - async def check(self, id: str, *, request_options: typing.Optional[RequestOptions] = None) -> None: + async def check( + self, id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> None: """ This endpoint checks the health of a resource. @@ -130,7 +142,9 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - f"check/{jsonable_encoder(id)}", method="GET", request_options=request_options + f"check/{jsonable_encoder(id)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: @@ -140,7 +154,9 @@ async def main() -> None: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - async def ping(self, *, request_options: typing.Optional[RequestOptions] = None) -> bool: + async def ping( + self, *, request_options: typing.Optional[RequestOptions] = None + ) -> bool: """ This endpoint checks the health of the service. @@ -173,11 +189,15 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "ping", method="GET", request_options=request_options + "ping", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/examples/client-filename/src/seed/service/client.py b/seed/python-sdk/examples/client-filename/src/seed/service/client.py index d3ff9f505d5..818888b91ed 100644 --- a/seed/python-sdk/examples/client-filename/src/seed/service/client.py +++ b/seed/python-sdk/examples/client-filename/src/seed/service/client.py @@ -1,18 +1,18 @@ # This file was auto-generated by Fern from our API Definition. import typing -from json.decoder import JSONDecodeError - -from ..commons.types.types.tag import Tag -from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper +from ..core.client_wrapper import SyncClientWrapper +from ..types.types.movie_id import MovieId +from ..core.request_options import RequestOptions +from ..types.types.movie import Movie from ..core.jsonable_encoder import jsonable_encoder from ..core.pydantic_utilities import parse_obj_as -from ..core.request_options import RequestOptions +from json.decoder import JSONDecodeError +from ..core.api_error import ApiError +from ..commons.types.types.tag import Tag from ..types.types.metadata import Metadata -from ..types.types.movie import Movie -from ..types.types.movie_id import MovieId from ..types.types.response import Response +from ..core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -22,7 +22,12 @@ class ServiceClient: def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper - def get_movie(self, movie_id: MovieId, *, request_options: typing.Optional[RequestOptions] = None) -> Movie: + def get_movie( + self, + movie_id: MovieId, + *, + request_options: typing.Optional[RequestOptions] = None, + ) -> Movie: """ Parameters ---------- @@ -49,11 +54,15 @@ def get_movie(self, movie_id: MovieId, *, request_options: typing.Optional[Reque ) """ _response = self._client_wrapper.httpx_client.request( - f"movie/{jsonable_encoder(movie_id)}", method="GET", request_options=request_options + f"movie/{jsonable_encoder(movie_id)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(Movie, parse_obj_as(type_=Movie, object_=_response.json())) # type: ignore + return typing.cast( + Movie, parse_obj_as(type_=Movie, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -141,7 +150,9 @@ def create_movie( ) try: if 200 <= _response.status_code < 300: - return typing.cast(MovieId, parse_obj_as(type_=MovieId, object_=_response.json())) # type: ignore + return typing.cast( + MovieId, parse_obj_as(type_=MovieId, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -189,19 +200,30 @@ def get_metadata( _response = self._client_wrapper.httpx_client.request( "metadata", method="GET", - params={"shallow": shallow, "tag": tag}, - headers={"X-API-Version": str(x_api_version) if x_api_version is not None else None}, + params={ + "shallow": shallow, + "tag": tag, + }, + headers={ + "X-API-Version": str(x_api_version) + if x_api_version is not None + else None, + }, request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(Metadata, parse_obj_as(type_=Metadata, object_=_response.json())) # type: ignore + return typing.cast( + Metadata, parse_obj_as(type_=Metadata, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def get_response(self, *, request_options: typing.Optional[RequestOptions] = None) -> Response: + def get_response( + self, *, request_options: typing.Optional[RequestOptions] = None + ) -> Response: """ Parameters ---------- @@ -224,11 +246,15 @@ def get_response(self, *, request_options: typing.Optional[RequestOptions] = Non client.service.get_response() """ _response = self._client_wrapper.httpx_client.request( - "response", method="POST", request_options=request_options + "response", + method="POST", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(Response, parse_obj_as(type_=Response, object_=_response.json())) # type: ignore + return typing.cast( + Response, parse_obj_as(type_=Response, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -239,7 +265,12 @@ class AsyncServiceClient: def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper - async def get_movie(self, movie_id: MovieId, *, request_options: typing.Optional[RequestOptions] = None) -> Movie: + async def get_movie( + self, + movie_id: MovieId, + *, + request_options: typing.Optional[RequestOptions] = None, + ) -> Movie: """ Parameters ---------- @@ -274,11 +305,15 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - f"movie/{jsonable_encoder(movie_id)}", method="GET", request_options=request_options + f"movie/{jsonable_encoder(movie_id)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(Movie, parse_obj_as(type_=Movie, object_=_response.json())) # type: ignore + return typing.cast( + Movie, parse_obj_as(type_=Movie, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -374,7 +409,9 @@ async def main() -> None: ) try: if 200 <= _response.status_code < 300: - return typing.cast(MovieId, parse_obj_as(type_=MovieId, object_=_response.json())) # type: ignore + return typing.cast( + MovieId, parse_obj_as(type_=MovieId, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -430,19 +467,30 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( "metadata", method="GET", - params={"shallow": shallow, "tag": tag}, - headers={"X-API-Version": str(x_api_version) if x_api_version is not None else None}, + params={ + "shallow": shallow, + "tag": tag, + }, + headers={ + "X-API-Version": str(x_api_version) + if x_api_version is not None + else None, + }, request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(Metadata, parse_obj_as(type_=Metadata, object_=_response.json())) # type: ignore + return typing.cast( + Metadata, parse_obj_as(type_=Metadata, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - async def get_response(self, *, request_options: typing.Optional[RequestOptions] = None) -> Response: + async def get_response( + self, *, request_options: typing.Optional[RequestOptions] = None + ) -> Response: """ Parameters ---------- @@ -473,11 +521,15 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "response", method="POST", request_options=request_options + "response", + method="POST", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(Response, parse_obj_as(type_=Response, object_=_response.json())) # type: ignore + return typing.cast( + Response, parse_obj_as(type_=Response, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/examples/client-filename/src/seed/types/identifier.py b/seed/python-sdk/examples/client-filename/src/seed/types/identifier.py index ae9367a447c..f6ff0a9818b 100644 --- a/seed/python-sdk/examples/client-filename/src/seed/types/identifier.py +++ b/seed/python-sdk/examples/client-filename/src/seed/types/identifier.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. +from ..core.pydantic_utilities import UniversalBaseModel +from .type import Type +from ..core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .type import Type - class Identifier(UniversalBaseModel): type: Type @@ -14,7 +13,9 @@ class Identifier(UniversalBaseModel): label: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/examples/client-filename/src/seed/types/type.py b/seed/python-sdk/examples/client-filename/src/seed/types/type.py index 09d1c916dfd..e77e5e18b15 100644 --- a/seed/python-sdk/examples/client-filename/src/seed/types/type.py +++ b/seed/python-sdk/examples/client-filename/src/seed/types/type.py @@ -1,7 +1,6 @@ # This file was auto-generated by Fern from our API Definition. import typing - from .basic_type import BasicType from .complex_type import ComplexType diff --git a/seed/python-sdk/examples/client-filename/src/seed/types/types/actor.py b/seed/python-sdk/examples/client-filename/src/seed/types/types/actor.py index 0838e363001..7808438f935 100644 --- a/seed/python-sdk/examples/client-filename/src/seed/types/types/actor.py +++ b/seed/python-sdk/examples/client-filename/src/seed/types/types/actor.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class Actor(UniversalBaseModel): name: str id: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/examples/client-filename/src/seed/types/types/actress.py b/seed/python-sdk/examples/client-filename/src/seed/types/types/actress.py index 607abb7e0e3..9f6f48e855d 100644 --- a/seed/python-sdk/examples/client-filename/src/seed/types/types/actress.py +++ b/seed/python-sdk/examples/client-filename/src/seed/types/types/actress.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class Actress(UniversalBaseModel): """ @@ -23,7 +22,9 @@ class Actress(UniversalBaseModel): id: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/examples/client-filename/src/seed/types/types/cast_member.py b/seed/python-sdk/examples/client-filename/src/seed/types/types/cast_member.py index d73c89864e1..8be1a0b0a2a 100644 --- a/seed/python-sdk/examples/client-filename/src/seed/types/types/cast_member.py +++ b/seed/python-sdk/examples/client-filename/src/seed/types/types/cast_member.py @@ -1,7 +1,6 @@ # This file was auto-generated by Fern from our API Definition. import typing - from .actor import Actor from .actress import Actress from .stunt_double import StuntDouble diff --git a/seed/python-sdk/examples/client-filename/src/seed/types/types/directory.py b/seed/python-sdk/examples/client-filename/src/seed/types/types/directory.py index 92d8efa9c38..049ed2f2cd5 100644 --- a/seed/python-sdk/examples/client-filename/src/seed/types/types/directory.py +++ b/seed/python-sdk/examples/client-filename/src/seed/types/types/directory.py @@ -1,13 +1,12 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ...core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel, update_forward_refs from .file import File +from ...core.pydantic_utilities import IS_PYDANTIC_V2 +import pydantic +from ...core.pydantic_utilities import update_forward_refs class Directory(UniversalBaseModel): @@ -43,7 +42,9 @@ class Directory(UniversalBaseModel): directories: typing.Optional[typing.List[Directory]] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/examples/client-filename/src/seed/types/types/entity.py b/seed/python-sdk/examples/client-filename/src/seed/types/types/entity.py index e6500e2af7d..3c5b7349621 100644 --- a/seed/python-sdk/examples/client-filename/src/seed/types/types/entity.py +++ b/seed/python-sdk/examples/client-filename/src/seed/types/types/entity.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ..type import Type +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from ..type import Type - class Entity(UniversalBaseModel): """ @@ -24,7 +23,9 @@ class Entity(UniversalBaseModel): name: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/examples/client-filename/src/seed/types/types/exception.py b/seed/python-sdk/examples/client-filename/src/seed/types/types/exception.py index 851835745bd..a61252d9fc4 100644 --- a/seed/python-sdk/examples/client-filename/src/seed/types/types/exception.py +++ b/seed/python-sdk/examples/client-filename/src/seed/types/types/exception.py @@ -1,12 +1,10 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ...core.pydantic_utilities import UniversalBaseModel import typing - import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 class Exception_Generic(UniversalBaseModel): @@ -28,7 +26,9 @@ class Exception_Generic(UniversalBaseModel): exception_stacktrace: str = pydantic.Field(alias="exceptionStacktrace") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: @@ -53,7 +53,9 @@ class Exception_Timeout(UniversalBaseModel): type: typing.Literal["timeout"] = "timeout" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/examples/client-filename/src/seed/types/types/exception_info.py b/seed/python-sdk/examples/client-filename/src/seed/types/types/exception_info.py index 2d902a51d05..220ddb6a0c7 100644 --- a/seed/python-sdk/examples/client-filename/src/seed/types/types/exception_info.py +++ b/seed/python-sdk/examples/client-filename/src/seed/types/types/exception_info.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ...core.pydantic_utilities import UniversalBaseModel import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class ExceptionInfo(UniversalBaseModel): @@ -25,7 +24,9 @@ class ExceptionInfo(UniversalBaseModel): exception_stacktrace: str = pydantic.Field(alias="exceptionStacktrace") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/examples/client-filename/src/seed/types/types/extended_movie.py b/seed/python-sdk/examples/client-filename/src/seed/types/types/extended_movie.py index 41d92df7718..8b48ecddcbe 100644 --- a/seed/python-sdk/examples/client-filename/src/seed/types/types/extended_movie.py +++ b/seed/python-sdk/examples/client-filename/src/seed/types/types/extended_movie.py @@ -1,11 +1,9 @@ # This file was auto-generated by Fern from our API Definition. +from .movie import Movie import typing - -import pydantic - from ...core.pydantic_utilities import IS_PYDANTIC_V2 -from .movie import Movie +import pydantic class ExtendedMovie(Movie): @@ -32,7 +30,9 @@ class ExtendedMovie(Movie): cast: typing.List[str] if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/examples/client-filename/src/seed/types/types/file.py b/seed/python-sdk/examples/client-filename/src/seed/types/types/file.py index 9103c9ec9c6..af2112c9a3d 100644 --- a/seed/python-sdk/examples/client-filename/src/seed/types/types/file.py +++ b/seed/python-sdk/examples/client-filename/src/seed/types/types/file.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class File(UniversalBaseModel): """ @@ -23,7 +22,9 @@ class File(UniversalBaseModel): contents: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/examples/client-filename/src/seed/types/types/metadata.py b/seed/python-sdk/examples/client-filename/src/seed/types/types/metadata.py index 924c6e5a00b..9081aa0b389 100644 --- a/seed/python-sdk/examples/client-filename/src/seed/types/types/metadata.py +++ b/seed/python-sdk/examples/client-filename/src/seed/types/types/metadata.py @@ -1,13 +1,11 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ...core.pydantic_utilities import UniversalBaseModel import typing - +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class Base(UniversalBaseModel): """ @@ -22,7 +20,9 @@ class Base(UniversalBaseModel): tags: typing.Set[str] if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: @@ -36,7 +36,9 @@ class Metadata_Html(Base): type: typing.Literal["html"] = "html" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + frozen=True + ) # type: ignore # Pydantic v2 else: class Config: @@ -49,7 +51,9 @@ class Metadata_Markdown(Base): type: typing.Literal["markdown"] = "markdown" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/examples/client-filename/src/seed/types/types/migration.py b/seed/python-sdk/examples/client-filename/src/seed/types/types/migration.py index 68f4d579dea..eb6cd3736bd 100644 --- a/seed/python-sdk/examples/client-filename/src/seed/types/types/migration.py +++ b/seed/python-sdk/examples/client-filename/src/seed/types/types/migration.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from .migration_status import MigrationStatus +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .migration_status import MigrationStatus - class Migration(UniversalBaseModel): """ @@ -24,7 +23,9 @@ class Migration(UniversalBaseModel): status: MigrationStatus if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/examples/client-filename/src/seed/types/types/migration_status.py b/seed/python-sdk/examples/client-filename/src/seed/types/types/migration_status.py index c5a2e76b4af..e14e67e1b5a 100644 --- a/seed/python-sdk/examples/client-filename/src/seed/types/types/migration_status.py +++ b/seed/python-sdk/examples/client-filename/src/seed/types/types/migration_status.py @@ -2,4 +2,6 @@ import typing -MigrationStatus = typing.Union[typing.Literal["RUNNING", "FAILED", "FINISHED"], typing.Any] +MigrationStatus = typing.Union[ + typing.Literal["RUNNING", "FAILED", "FINISHED"], typing.Any +] diff --git a/seed/python-sdk/examples/client-filename/src/seed/types/types/moment.py b/seed/python-sdk/examples/client-filename/src/seed/types/types/moment.py index 820b4ff0e86..b344b30e496 100644 --- a/seed/python-sdk/examples/client-filename/src/seed/types/types/moment.py +++ b/seed/python-sdk/examples/client-filename/src/seed/types/types/moment.py @@ -1,13 +1,12 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +import uuid import datetime as dt +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing -import uuid - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class Moment(UniversalBaseModel): """ @@ -36,7 +35,9 @@ class Moment(UniversalBaseModel): datetime: dt.datetime if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/examples/client-filename/src/seed/types/types/movie.py b/seed/python-sdk/examples/client-filename/src/seed/types/types/movie.py index 9e67c2456ea..426206249be 100644 --- a/seed/python-sdk/examples/client-filename/src/seed/types/types/movie.py +++ b/seed/python-sdk/examples/client-filename/src/seed/types/types/movie.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from .movie_id import MovieId import typing - import pydantic - from ...commons.types.types.tag import Tag -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .movie_id import MovieId +from ...core.pydantic_utilities import IS_PYDANTIC_V2 class Movie(UniversalBaseModel): @@ -45,7 +44,9 @@ class Movie(UniversalBaseModel): metadata: typing.Dict[str, typing.Any] if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/examples/client-filename/src/seed/types/types/movie_id.py b/seed/python-sdk/examples/client-filename/src/seed/types/types/movie_id.py index 86f7a4f4651..86945f3b676 100644 --- a/seed/python-sdk/examples/client-filename/src/seed/types/types/movie_id.py +++ b/seed/python-sdk/examples/client-filename/src/seed/types/types/movie_id.py @@ -3,4 +3,5 @@ """ "movie-c06a4ad7" """ + MovieId = str diff --git a/seed/python-sdk/examples/client-filename/src/seed/types/types/node.py b/seed/python-sdk/examples/client-filename/src/seed/types/types/node.py index 77f2a5e87da..9a5f5952b59 100644 --- a/seed/python-sdk/examples/client-filename/src/seed/types/types/node.py +++ b/seed/python-sdk/examples/client-filename/src/seed/types/types/node.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ...core.pydantic_utilities import UniversalBaseModel import typing - +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel, update_forward_refs +from ...core.pydantic_utilities import update_forward_refs class Node(UniversalBaseModel): @@ -45,7 +44,9 @@ class Node(UniversalBaseModel): trees: typing.Optional[typing.List[Tree]] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/examples/client-filename/src/seed/types/types/request.py b/seed/python-sdk/examples/client-filename/src/seed/types/types/request.py index a2ff0455aa0..7649502a04c 100644 --- a/seed/python-sdk/examples/client-filename/src/seed/types/types/request.py +++ b/seed/python-sdk/examples/client-filename/src/seed/types/types/request.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel import typing - +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class Request(UniversalBaseModel): """ @@ -21,7 +20,9 @@ class Request(UniversalBaseModel): request: typing.Any if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/examples/client-filename/src/seed/types/types/response.py b/seed/python-sdk/examples/client-filename/src/seed/types/types/response.py index edcd3f24da1..d17192b48e6 100644 --- a/seed/python-sdk/examples/client-filename/src/seed/types/types/response.py +++ b/seed/python-sdk/examples/client-filename/src/seed/types/types/response.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from ..identifier import Identifier +from ...core.pydantic_utilities import IS_PYDANTIC_V2 +import pydantic class Response(UniversalBaseModel): @@ -36,7 +35,9 @@ class Response(UniversalBaseModel): identifiers: typing.List[Identifier] if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/examples/client-filename/src/seed/types/types/response_type.py b/seed/python-sdk/examples/client-filename/src/seed/types/types/response_type.py index c5777220170..8b43d297ad3 100644 --- a/seed/python-sdk/examples/client-filename/src/seed/types/types/response_type.py +++ b/seed/python-sdk/examples/client-filename/src/seed/types/types/response_type.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ..type import Type +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from ..type import Type - class ResponseType(UniversalBaseModel): type: Type if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/examples/client-filename/src/seed/types/types/stunt_double.py b/seed/python-sdk/examples/client-filename/src/seed/types/types/stunt_double.py index f2b3a81d999..f3faa0fd65b 100644 --- a/seed/python-sdk/examples/client-filename/src/seed/types/types/stunt_double.py +++ b/seed/python-sdk/examples/client-filename/src/seed/types/types/stunt_double.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ...core.pydantic_utilities import UniversalBaseModel import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class StuntDouble(UniversalBaseModel): @@ -12,7 +11,9 @@ class StuntDouble(UniversalBaseModel): actor_or_actress_id: str = pydantic.Field(alias="actorOrActressId") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/examples/client-filename/src/seed/types/types/test.py b/seed/python-sdk/examples/client-filename/src/seed/types/types/test.py index 3a0d88bb4b1..b9d6b204965 100644 --- a/seed/python-sdk/examples/client-filename/src/seed/types/types/test.py +++ b/seed/python-sdk/examples/client-filename/src/seed/types/types/test.py @@ -1,20 +1,20 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ...core.pydantic_utilities import UniversalBaseModel import typing - +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class Test_And(UniversalBaseModel): value: bool type: typing.Literal["and"] = "and" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + frozen=True + ) # type: ignore # Pydantic v2 else: class Config: @@ -27,7 +27,9 @@ class Test_Or(UniversalBaseModel): type: typing.Literal["or"] = "or" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/examples/client-filename/src/seed/types/types/tree.py b/seed/python-sdk/examples/client-filename/src/seed/types/types/tree.py index 52b70602a21..c159c5c2ee4 100644 --- a/seed/python-sdk/examples/client-filename/src/seed/types/types/tree.py +++ b/seed/python-sdk/examples/client-filename/src/seed/types/types/tree.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ...core.pydantic_utilities import UniversalBaseModel import typing - +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel, update_forward_refs +from ...core.pydantic_utilities import update_forward_refs class Tree(UniversalBaseModel): @@ -30,7 +29,9 @@ class Tree(UniversalBaseModel): nodes: typing.Optional[typing.List[Node]] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/examples/client-filename/src/seed/version.py b/seed/python-sdk/examples/client-filename/src/seed/version.py index b6f2c764388..ad7a9c63cc2 100644 --- a/seed/python-sdk/examples/client-filename/src/seed/version.py +++ b/seed/python-sdk/examples/client-filename/src/seed/version.py @@ -1,4 +1,3 @@ - from importlib import metadata __version__ = metadata.version("fern_examples") diff --git a/seed/python-sdk/examples/client-filename/tests/conftest.py b/seed/python-sdk/examples/client-filename/tests/conftest.py index b5b50383b94..86cb2b41af8 100644 --- a/seed/python-sdk/examples/client-filename/tests/conftest.py +++ b/seed/python-sdk/examples/client-filename/tests/conftest.py @@ -1,16 +1,22 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive import os - import pytest -from seed import AsyncSeedExhaustive, SeedExhaustive +from seed import AsyncSeedExhaustive @pytest.fixture def client() -> SeedExhaustive: - return SeedExhaustive(token=os.getenv("ENV_TOKEN", "token"), base_url=os.getenv("TESTS_BASE_URL", "base_url")) + return SeedExhaustive( + token=os.getenv("ENV_TOKEN", "token"), + base_url=os.getenv("TESTS_BASE_URL", "base_url"), + ) @pytest.fixture def async_client() -> AsyncSeedExhaustive: - return AsyncSeedExhaustive(token=os.getenv("ENV_TOKEN", "token"), base_url=os.getenv("TESTS_BASE_URL", "base_url")) + return AsyncSeedExhaustive( + token=os.getenv("ENV_TOKEN", "token"), + base_url=os.getenv("TESTS_BASE_URL", "base_url"), + ) diff --git a/seed/python-sdk/examples/client-filename/tests/custom/test_client.py b/seed/python-sdk/examples/client-filename/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/python-sdk/examples/client-filename/tests/custom/test_client.py +++ b/seed/python-sdk/examples/client-filename/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/python-sdk/examples/client-filename/tests/file/notification/test_service.py b/seed/python-sdk/examples/client-filename/tests/file/notification/test_service.py index 1a0dcb56d23..c5c3b5330c6 100644 --- a/seed/python-sdk/examples/client-filename/tests/file/notification/test_service.py +++ b/seed/python-sdk/examples/client-filename/tests/file/notification/test_service.py @@ -1,13 +1,14 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing - -from seed import AsyncSeedExhaustive, SeedExhaustive - from ...utilities import validate_response -async def test_get_exception(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_exception( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = { "type": "generic", "exceptionType": "Unavailable", @@ -15,8 +16,12 @@ async def test_get_exception(client: SeedExhaustive, async_client: AsyncSeedExha "exceptionStacktrace": "", } expected_types: typing.Any = "no_validate" - response = client.file.notification.service.get_exception(notification_id="notification-hsy129x") + response = client.file.notification.service.get_exception( + notification_id="notification-hsy129x" + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.file.notification.service.get_exception(notification_id="notification-hsy129x") + async_response = await async_client.file.notification.service.get_exception( + notification_id="notification-hsy129x" + ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/examples/client-filename/tests/health/test_service.py b/seed/python-sdk/examples/client-filename/tests/health/test_service.py index 6708e15bd6d..df9195dd35b 100644 --- a/seed/python-sdk/examples/client-filename/tests/health/test_service.py +++ b/seed/python-sdk/examples/client-filename/tests/health/test_service.py @@ -1,9 +1,8 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing - -from seed import AsyncSeedExhaustive, SeedExhaustive - from ..utilities import validate_response diff --git a/seed/python-sdk/examples/client-filename/tests/test_root.py b/seed/python-sdk/examples/client-filename/tests/test_root.py index df8c78a7bb7..88a9bc428c9 100644 --- a/seed/python-sdk/examples/client-filename/tests/test_root.py +++ b/seed/python-sdk/examples/client-filename/tests/test_root.py @@ -1,9 +1,8 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing - -from seed import AsyncSeedExhaustive, SeedExhaustive - from .utilities import validate_response @@ -13,5 +12,7 @@ async def test_echo(client: SeedExhaustive, async_client: AsyncSeedExhaustive) - response = client.echo(request="Hello world!\\n\\nwith\\n\\tnewlines") validate_response(response, expected_response, expected_types) - async_response = await async_client.echo(request="Hello world!\\n\\nwith\\n\\tnewlines") + async_response = await async_client.echo( + request="Hello world!\\n\\nwith\\n\\tnewlines" + ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/examples/client-filename/tests/test_service.py b/seed/python-sdk/examples/client-filename/tests/test_service.py index 08e53845866..b15c5db1a4d 100644 --- a/seed/python-sdk/examples/client-filename/tests/test_service.py +++ b/seed/python-sdk/examples/client-filename/tests/test_service.py @@ -1,13 +1,14 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing - -from seed import AsyncSeedExhaustive, SeedExhaustive - from .utilities import validate_response -async def test_get_movie(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_movie( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = { "id": "movie-c06a4ad7", "prequel": "movie-cv9b914f", @@ -39,7 +40,9 @@ async def test_get_movie(client: SeedExhaustive, async_client: AsyncSeedExhausti validate_response(async_response, expected_response, expected_types) -async def test_create_movie(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_create_movie( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "movie-c06a4ad7" expected_types: typing.Any = None response = client.service.create_movie( @@ -73,7 +76,9 @@ async def test_create_movie(client: SeedExhaustive, async_client: AsyncSeedExhau validate_response(async_response, expected_response, expected_types) -async def test_get_metadata(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_metadata( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = { "type": "html", "extra": {"version": "0.0.1", "tenancy": "test"}, @@ -81,14 +86,20 @@ async def test_get_metadata(client: SeedExhaustive, async_client: AsyncSeedExhau "value": "...", } expected_types: typing.Any = "no_validate" - response = client.service.get_metadata(x_api_version="0.0.1", shallow=False, tag="development") + response = client.service.get_metadata( + x_api_version="0.0.1", shallow=False, tag="development" + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.service.get_metadata(x_api_version="0.0.1", shallow=False, tag="development") + async_response = await async_client.service.get_metadata( + x_api_version="0.0.1", shallow=False, tag="development" + ) validate_response(async_response, expected_response, expected_types) -async def test_get_response(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_response( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = { "response": "Initializing...", "identifiers": [ @@ -100,7 +111,10 @@ async def test_get_response(client: SeedExhaustive, async_client: AsyncSeedExhau "response": None, "identifiers": ( "list", - {0: {"type": None, "value": None, "label": None}, 1: {"type": None, "value": None, "label": None}}, + { + 0: {"type": None, "value": None, "label": None}, + 1: {"type": None, "value": None, "label": None}, + }, ), } response = client.service.get_response() diff --git a/seed/python-sdk/examples/client-filename/tests/utilities.py b/seed/python-sdk/examples/client-filename/tests/utilities.py index 13da208eb3a..e8f4472564c 100644 --- a/seed/python-sdk/examples/client-filename/tests/utilities.py +++ b/seed/python-sdk/examples/client-filename/tests/utilities.py @@ -3,11 +3,14 @@ import typing import uuid -import pydantic from dateutil import parser +import pydantic + -def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> typing.Any: +def cast_field( + json_expectation: typing.Any, type_expectation: typing.Any +) -> typing.Any: # Cast these specific types which come through as string and expect our # models to cast to the correct type. if type_expectation == "uuid": @@ -25,7 +28,9 @@ def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> ty return json_expectation -def validate_field(response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any) -> None: +def validate_field( + response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectation == "no_validate": return @@ -44,7 +49,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(entry_expectation, dict): is_container_of_complex_type = True validate_response( - response=response[idx], json_expectation=ex, type_expectations=entry_expectation + response=response[idx], + json_expectation=ex, + type_expectations=entry_expectation, ) else: cast_json_expectation.append(cast_field(ex, entry_expectation)) @@ -56,7 +63,10 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # if any of the values of the set have a type_expectation of a dict, we're assuming it's a pydantic # model and keeping it a list. if container_expectation != "set" or not any( - map(lambda value: isinstance(value, dict), list(contents_expectation.values())) + map( + lambda value: isinstance(value, dict), + list(contents_expectation.values()), + ) ): json_expectation = cast_field(json_expectation, container_expectation) elif isinstance(type_expectation, tuple): @@ -65,9 +75,15 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(contents_expectation, dict): json_expectation = { cast_field( - key, contents_expectation.get(idx)[0] if contents_expectation.get(idx) is not None else None # type: ignore + key, + contents_expectation.get(idx)[0] + if contents_expectation.get(idx) is not None + else None, # type: ignore ): cast_field( - value, contents_expectation.get(idx)[1] if contents_expectation.get(idx) is not None else None # type: ignore + value, + contents_expectation.get(idx)[1] + if contents_expectation.get(idx) is not None + else None, # type: ignore ) for idx, (key, value) in enumerate(json_expectation.items()) } @@ -86,7 +102,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # Arg type_expectations is a deeply nested structure that matches the response, but with the values replaced with the expected types -def validate_response(response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any) -> None: +def validate_response( + response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectations == "no_validate": return @@ -96,11 +114,17 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e and not isinstance(response, dict) and not issubclass(type(response), pydantic.BaseModel) ): - validate_field(response=response, json_expectation=json_expectation, type_expectation=type_expectations) + validate_field( + response=response, + json_expectation=json_expectation, + type_expectation=type_expectations, + ) return if isinstance(response, list): - assert len(response) == len(json_expectation), "Length mismatch, expected: {0}, Actual: {1}".format( + assert len(response) == len( + json_expectation + ), "Length mismatch, expected: {0}, Actual: {1}".format( len(response), len(json_expectation) ) content_expectation = type_expectations @@ -108,7 +132,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e content_expectation = type_expectations[1] for idx, item in enumerate(response): validate_response( - response=item, json_expectation=json_expectation[idx], type_expectations=content_expectation[idx] + response=item, + json_expectation=json_expectation[idx], + type_expectations=content_expectation[idx], ) else: response_json = response @@ -116,7 +142,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e response_json = response.dict(by_alias=True) for key, value in json_expectation.items(): - assert key in response_json, "Field {0} not found within the response object: {1}".format( + assert ( + key in response_json + ), "Field {0} not found within the response object: {1}".format( key, response_json ) @@ -128,11 +156,19 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e # Otherwise, we're just validating a single field that's a pydantic model. if isinstance(value, dict) and not isinstance(type_expectation, tuple): validate_response( - response=response_json[key], json_expectation=value, type_expectations=type_expectation + response=response_json[key], + json_expectation=value, + type_expectations=type_expectation, ) else: - validate_field(response=response_json[key], json_expectation=value, type_expectation=type_expectation) + validate_field( + response=response_json[key], + json_expectation=value, + type_expectation=type_expectation, + ) # Ensure there are no additional fields here either del response_json[key] - assert len(response_json) == 0, "Additional fields found, expected None: {0}".format(response_json) + assert ( + len(response_json) == 0 + ), "Additional fields found, expected None: {0}".format(response_json) diff --git a/seed/python-sdk/examples/client-filename/tests/utils/assets/models/__init__.py b/seed/python-sdk/examples/client-filename/tests/utils/assets/models/__init__.py index 2cf01263529..3a1c852e71e 100644 --- a/seed/python-sdk/examples/client-filename/tests/utils/assets/models/__init__.py +++ b/seed/python-sdk/examples/client-filename/tests/utils/assets/models/__init__.py @@ -5,7 +5,7 @@ from .circle import CircleParams from .object_with_defaults import ObjectWithDefaultsParams from .object_with_optional_field import ObjectWithOptionalFieldParams -from .shape import Shape_CircleParams, Shape_SquareParams, ShapeParams +from .shape import ShapeParams, Shape_CircleParams, Shape_SquareParams from .square import SquareParams from .undiscriminated_shape import UndiscriminatedShapeParams diff --git a/seed/python-sdk/examples/client-filename/tests/utils/assets/models/circle.py b/seed/python-sdk/examples/client-filename/tests/utils/assets/models/circle.py index af7a1bf8a8e..253f12d38b3 100644 --- a/seed/python-sdk/examples/client-filename/tests/utils/assets/models/circle.py +++ b/seed/python-sdk/examples/client-filename/tests/utils/assets/models/circle.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class CircleParams(typing_extensions.TypedDict): - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] diff --git a/seed/python-sdk/examples/client-filename/tests/utils/assets/models/object_with_optional_field.py b/seed/python-sdk/examples/client-filename/tests/utils/assets/models/object_with_optional_field.py index 3ad93d5f305..ebe7dc80547 100644 --- a/seed/python-sdk/examples/client-filename/tests/utils/assets/models/object_with_optional_field.py +++ b/seed/python-sdk/examples/client-filename/tests/utils/assets/models/object_with_optional_field.py @@ -7,8 +7,8 @@ import uuid import typing_extensions -from seed.core.serialization import FieldMetadata +from seed.core.serialization import FieldMetadata from .color import Color from .shape import ShapeParams from .undiscriminated_shape import UndiscriminatedShapeParams @@ -18,16 +18,30 @@ class ObjectWithOptionalFieldParams(typing_extensions.TypedDict): literal: typing.Literal["lit_one"] string: typing_extensions.NotRequired[str] integer: typing_extensions.NotRequired[int] - long_: typing_extensions.NotRequired[typing_extensions.Annotated[int, FieldMetadata(alias="long")]] + long_: typing_extensions.NotRequired[ + typing_extensions.Annotated[int, FieldMetadata(alias="long")] + ] double: typing_extensions.NotRequired[float] - bool_: typing_extensions.NotRequired[typing_extensions.Annotated[bool, FieldMetadata(alias="bool")]] + bool_: typing_extensions.NotRequired[ + typing_extensions.Annotated[bool, FieldMetadata(alias="bool")] + ] datetime: typing_extensions.NotRequired[dt.datetime] date: typing_extensions.NotRequired[dt.date] - uuid_: typing_extensions.NotRequired[typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")]] - base_64: typing_extensions.NotRequired[typing_extensions.Annotated[str, FieldMetadata(alias="base64")]] - list_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")]] - set_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")]] - map_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")]] + uuid_: typing_extensions.NotRequired[ + typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")] + ] + base_64: typing_extensions.NotRequired[ + typing_extensions.Annotated[str, FieldMetadata(alias="base64")] + ] + list_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")] + ] + set_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")] + ] + map_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")] + ] enum: typing_extensions.NotRequired[Color] union: typing_extensions.NotRequired[ShapeParams] second_union: typing_extensions.NotRequired[ShapeParams] diff --git a/seed/python-sdk/examples/client-filename/tests/utils/assets/models/shape.py b/seed/python-sdk/examples/client-filename/tests/utils/assets/models/shape.py index 2c33c877951..816ffc51bdc 100644 --- a/seed/python-sdk/examples/client-filename/tests/utils/assets/models/shape.py +++ b/seed/python-sdk/examples/client-filename/tests/utils/assets/models/shape.py @@ -7,6 +7,7 @@ import typing import typing_extensions + from seed.core.serialization import FieldMetadata @@ -15,13 +16,21 @@ class Base(typing_extensions.TypedDict): class Shape_CircleParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["circle"], FieldMetadata(alias="shapeType")] - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["circle"], FieldMetadata(alias="shapeType") + ] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] class Shape_SquareParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["square"], FieldMetadata(alias="shapeType")] - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["square"], FieldMetadata(alias="shapeType") + ] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] ShapeParams = typing.Union[Shape_CircleParams, Shape_SquareParams] diff --git a/seed/python-sdk/examples/client-filename/tests/utils/assets/models/square.py b/seed/python-sdk/examples/client-filename/tests/utils/assets/models/square.py index b9b7dd319bc..bcf08a723c5 100644 --- a/seed/python-sdk/examples/client-filename/tests/utils/assets/models/square.py +++ b/seed/python-sdk/examples/client-filename/tests/utils/assets/models/square.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class SquareParams(typing_extensions.TypedDict): - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] diff --git a/seed/python-sdk/examples/client-filename/tests/utils/test_http_client.py b/seed/python-sdk/examples/client-filename/tests/utils/test_http_client.py index edd11ca7afb..f5a874a75f3 100644 --- a/seed/python-sdk/examples/client-filename/tests/utils/test_http_client.py +++ b/seed/python-sdk/examples/client-filename/tests/utils/test_http_client.py @@ -9,12 +9,17 @@ def get_request_options() -> RequestOptions: def test_get_json_request_body() -> None: - json_body, data_body = get_request_body(json={"hello": "world"}, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json={"hello": "world"}, data=None, request_options=None, omit=None + ) assert json_body == {"hello": "world"} assert data_body is None json_body_extras, data_body_extras = get_request_body( - json={"goodbye": "world"}, data=None, request_options=get_request_options(), omit=None + json={"goodbye": "world"}, + data=None, + request_options=get_request_options(), + omit=None, ) assert json_body_extras == {"goodbye": "world", "see you": "later"} @@ -22,12 +27,17 @@ def test_get_json_request_body() -> None: def test_get_files_request_body() -> None: - json_body, data_body = get_request_body(json=None, data={"hello": "world"}, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data={"hello": "world"}, request_options=None, omit=None + ) assert data_body == {"hello": "world"} assert json_body is None json_body_extras, data_body_extras = get_request_body( - json=None, data={"goodbye": "world"}, request_options=get_request_options(), omit=None + json=None, + data={"goodbye": "world"}, + request_options=get_request_options(), + omit=None, ) assert data_body_extras == {"goodbye": "world", "see you": "later"} @@ -35,7 +45,9 @@ def test_get_files_request_body() -> None: def test_get_none_request_body() -> None: - json_body, data_body = get_request_body(json=None, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data=None, request_options=None, omit=None + ) assert data_body is None assert json_body is None diff --git a/seed/python-sdk/examples/client-filename/tests/utils/test_query_encoding.py b/seed/python-sdk/examples/client-filename/tests/utils/test_query_encoding.py index 247e1551b46..fbc8f402167 100644 --- a/seed/python-sdk/examples/client-filename/tests/utils/test_query_encoding.py +++ b/seed/python-sdk/examples/client-filename/tests/utils/test_query_encoding.py @@ -4,9 +4,15 @@ def test_query_encoding() -> None: - assert encode_query({"hello world": "hello world"}) == {"hello world": "hello world"} - assert encode_query({"hello_world": {"hello": "world"}}) == {"hello_world[hello]": "world"} - assert encode_query({"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"}) == { + assert encode_query({"hello world": "hello world"}) == { + "hello world": "hello world" + } + assert encode_query({"hello_world": {"hello": "world"}}) == { + "hello_world[hello]": "world" + } + assert encode_query( + {"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"} + ) == { "hello_world[hello][world]": "today", "hello_world[test]": "this", "hi": "there", diff --git a/seed/python-sdk/examples/client-filename/tests/utils/test_serialization.py b/seed/python-sdk/examples/client-filename/tests/utils/test_serialization.py index 58b1ed66e6d..5ca956916dd 100644 --- a/seed/python-sdk/examples/client-filename/tests/utils/test_serialization.py +++ b/seed/python-sdk/examples/client-filename/tests/utils/test_serialization.py @@ -1,10 +1,12 @@ # This file was auto-generated by Fern from our API Definition. -from typing import Any, List +from typing import List, Any -from seed.core.serialization import convert_and_respect_annotation_metadata +from seed.core.serialization import ( + convert_and_respect_annotation_metadata, +) +from .assets.models import ShapeParams, ObjectWithOptionalFieldParams -from .assets.models import ObjectWithOptionalFieldParams, ShapeParams UNION_TEST: ShapeParams = {"radius_measurement": 1.0, "shape_type": "circle", "id": "1"} UNION_TEST_CONVERTED = {"shapeType": "circle", "radiusMeasurement": 1.0, "id": "1"} @@ -18,20 +20,54 @@ def test_convert_and_respect_annotation_metadata() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) - assert converted == {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"} + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) + assert converted == { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + } def test_convert_and_respect_annotation_metadata_in_list() -> None: data: List[ObjectWithOptionalFieldParams] = [ - {"string": "string", "long_": 12345, "bool_": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long_": 67890, "list_": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long_": 12345, + "bool_": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long_": 67890, + "list_": [], + "literal": "lit_one", + "any": "any", + }, ] - converted = convert_and_respect_annotation_metadata(object_=data, annotation=List[ObjectWithOptionalFieldParams]) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=List[ObjectWithOptionalFieldParams] + ) assert converted == [ - {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long": 67890, "list": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long": 67890, + "list": [], + "literal": "lit_one", + "any": "any", + }, ] @@ -43,7 +79,9 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) assert converted == { "string": "string", @@ -55,12 +93,16 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: def test_convert_and_respect_annotation_metadata_in_union() -> None: - converted = convert_and_respect_annotation_metadata(object_=UNION_TEST, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=UNION_TEST, annotation=ShapeParams + ) assert converted == UNION_TEST_CONVERTED def test_convert_and_respect_annotation_metadata_with_empty_object() -> None: data: Any = {} - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ShapeParams + ) assert converted == data diff --git a/seed/python-sdk/examples/no-custom-config/pyproject.toml b/seed/python-sdk/examples/no-custom-config/pyproject.toml index adf3a468dac..c248e8d8f0c 100644 --- a/seed/python-sdk/examples/no-custom-config/pyproject.toml +++ b/seed/python-sdk/examples/no-custom-config/pyproject.toml @@ -43,6 +43,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/python-sdk/examples/no-custom-config/src/seed/client.py b/seed/python-sdk/examples/no-custom-config/src/seed/client.py index fa561061df4..920e3a662a9 100644 --- a/seed/python-sdk/examples/no-custom-config/src/seed/client.py +++ b/seed/python-sdk/examples/no-custom-config/src/seed/client.py @@ -1,18 +1,20 @@ # This file was auto-generated by Fern from our API Definition. import typing -from json.decoder import JSONDecodeError - +from .environment import SeedExamplesEnvironment import httpx - -from .core.api_error import ApiError -from .core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from .core.pydantic_utilities import parse_obj_as +from .core.client_wrapper import SyncClientWrapper +from .file.client import FileClient +from .health.client import HealthClient +from .service.client import ServiceClient from .core.request_options import RequestOptions -from .environment import SeedExamplesEnvironment -from .file.client import AsyncFileClient, FileClient -from .health.client import AsyncHealthClient, HealthClient -from .service.client import AsyncServiceClient, ServiceClient +from .core.pydantic_utilities import parse_obj_as +from json.decoder import JSONDecodeError +from .core.api_error import ApiError +from .core.client_wrapper import AsyncClientWrapper +from .file.client import AsyncFileClient +from .health.client import AsyncHealthClient +from .service.client import AsyncServiceClient # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -59,15 +61,19 @@ def __init__( token: typing.Optional[typing.Union[str, typing.Callable[[], str]]] = None, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.Client] = None + httpx_client: typing.Optional[httpx.Client] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = SyncClientWrapper( base_url=_get_base_url(base_url=base_url, environment=environment), token=token, httpx_client=httpx_client if httpx_client is not None - else httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.Client( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.Client(timeout=_defaulted_timeout), timeout=_defaulted_timeout, @@ -76,7 +82,9 @@ def __init__( self.health = HealthClient(client_wrapper=self._client_wrapper) self.service = ServiceClient(client_wrapper=self._client_wrapper) - def echo(self, *, request: str, request_options: typing.Optional[RequestOptions] = None) -> str: + def echo( + self, *, request: str, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -103,11 +111,16 @@ def echo(self, *, request: str, request_options: typing.Optional[RequestOptions] ) """ _response = self._client_wrapper.httpx_client.request( - method="POST", json=request, request_options=request_options, omit=OMIT + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -155,15 +168,19 @@ def __init__( token: typing.Optional[typing.Union[str, typing.Callable[[], str]]] = None, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.AsyncClient] = None + httpx_client: typing.Optional[httpx.AsyncClient] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = AsyncClientWrapper( base_url=_get_base_url(base_url=base_url, environment=environment), token=token, httpx_client=httpx_client if httpx_client is not None - else httpx.AsyncClient(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.AsyncClient( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.AsyncClient(timeout=_defaulted_timeout), timeout=_defaulted_timeout, @@ -172,7 +189,9 @@ def __init__( self.health = AsyncHealthClient(client_wrapper=self._client_wrapper) self.service = AsyncServiceClient(client_wrapper=self._client_wrapper) - async def echo(self, *, request: str, request_options: typing.Optional[RequestOptions] = None) -> str: + async def echo( + self, *, request: str, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -207,11 +226,16 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - method="POST", json=request, request_options=request_options, omit=OMIT + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -219,11 +243,15 @@ async def main() -> None: def _get_base_url( - *, base_url: typing.Optional[str] = None, environment: typing.Optional[SeedExamplesEnvironment] = None + *, + base_url: typing.Optional[str] = None, + environment: typing.Optional[SeedExamplesEnvironment] = None, ) -> str: if base_url is not None: return base_url elif environment is not None: return environment.value else: - raise Exception("Please pass in either base_url or environment to construct the client") + raise Exception( + "Please pass in either base_url or environment to construct the client" + ) diff --git a/seed/python-sdk/examples/no-custom-config/src/seed/commons/__init__.py b/seed/python-sdk/examples/no-custom-config/src/seed/commons/__init__.py index 1d968e36800..03f39303b3d 100644 --- a/seed/python-sdk/examples/no-custom-config/src/seed/commons/__init__.py +++ b/seed/python-sdk/examples/no-custom-config/src/seed/commons/__init__.py @@ -1,6 +1,15 @@ # This file was auto-generated by Fern from our API Definition. -from .types import Data, Data_Base64, Data_String, EventInfo, EventInfo_Metadata, EventInfo_Tag, Metadata, Tag +from .types import ( + Data, + Data_Base64, + Data_String, + EventInfo, + EventInfo_Metadata, + EventInfo_Tag, + Metadata, + Tag, +) from . import types __all__ = [ diff --git a/seed/python-sdk/examples/no-custom-config/src/seed/commons/types/__init__.py b/seed/python-sdk/examples/no-custom-config/src/seed/commons/types/__init__.py index 319c40f2c26..bddae54aee3 100644 --- a/seed/python-sdk/examples/no-custom-config/src/seed/commons/types/__init__.py +++ b/seed/python-sdk/examples/no-custom-config/src/seed/commons/types/__init__.py @@ -1,5 +1,23 @@ # This file was auto-generated by Fern from our API Definition. -from .types import Data, Data_Base64, Data_String, EventInfo, EventInfo_Metadata, EventInfo_Tag, Metadata, Tag +from .types import ( + Data, + Data_Base64, + Data_String, + EventInfo, + EventInfo_Metadata, + EventInfo_Tag, + Metadata, + Tag, +) -__all__ = ["Data", "Data_Base64", "Data_String", "EventInfo", "EventInfo_Metadata", "EventInfo_Tag", "Metadata", "Tag"] +__all__ = [ + "Data", + "Data_Base64", + "Data_String", + "EventInfo", + "EventInfo_Metadata", + "EventInfo_Tag", + "Metadata", + "Tag", +] diff --git a/seed/python-sdk/examples/no-custom-config/src/seed/commons/types/types/__init__.py b/seed/python-sdk/examples/no-custom-config/src/seed/commons/types/types/__init__.py index a73f9e83b6c..9c78512dba5 100644 --- a/seed/python-sdk/examples/no-custom-config/src/seed/commons/types/types/__init__.py +++ b/seed/python-sdk/examples/no-custom-config/src/seed/commons/types/types/__init__.py @@ -5,4 +5,13 @@ from .metadata import Metadata from .tag import Tag -__all__ = ["Data", "Data_Base64", "Data_String", "EventInfo", "EventInfo_Metadata", "EventInfo_Tag", "Metadata", "Tag"] +__all__ = [ + "Data", + "Data_Base64", + "Data_String", + "EventInfo", + "EventInfo_Metadata", + "EventInfo_Tag", + "Metadata", + "Tag", +] diff --git a/seed/python-sdk/examples/no-custom-config/src/seed/commons/types/types/data.py b/seed/python-sdk/examples/no-custom-config/src/seed/commons/types/types/data.py index a2e7f693004..c491904b237 100644 --- a/seed/python-sdk/examples/no-custom-config/src/seed/commons/types/types/data.py +++ b/seed/python-sdk/examples/no-custom-config/src/seed/commons/types/types/data.py @@ -1,20 +1,20 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ....core.pydantic_utilities import UniversalBaseModel import typing - +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class Data_String(UniversalBaseModel): value: str type: typing.Literal["string"] = "string" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + frozen=True + ) # type: ignore # Pydantic v2 else: class Config: @@ -27,7 +27,9 @@ class Data_Base64(UniversalBaseModel): type: typing.Literal["base64"] = "base64" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/examples/no-custom-config/src/seed/commons/types/types/event_info.py b/seed/python-sdk/examples/no-custom-config/src/seed/commons/types/types/event_info.py index 1ec20f1861f..3e3e4d96864 100644 --- a/seed/python-sdk/examples/no-custom-config/src/seed/commons/types/types/event_info.py +++ b/seed/python-sdk/examples/no-custom-config/src/seed/commons/types/types/event_info.py @@ -1,12 +1,10 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ....core.pydantic_utilities import UniversalBaseModel import typing - import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 from .tag import Tag @@ -29,7 +27,9 @@ class EventInfo_Metadata(UniversalBaseModel): json_string: typing.Optional[str] = pydantic.Field(alias="jsonString", default=None) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: @@ -43,7 +43,9 @@ class EventInfo_Tag(UniversalBaseModel): type: typing.Literal["tag"] = "tag" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/examples/no-custom-config/src/seed/commons/types/types/metadata.py b/seed/python-sdk/examples/no-custom-config/src/seed/commons/types/types/metadata.py index a8795aa41a6..52808334881 100644 --- a/seed/python-sdk/examples/no-custom-config/src/seed/commons/types/types/metadata.py +++ b/seed/python-sdk/examples/no-custom-config/src/seed/commons/types/types/metadata.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class Metadata(UniversalBaseModel): @@ -25,7 +24,9 @@ class Metadata(UniversalBaseModel): json_string: typing.Optional[str] = pydantic.Field(alias="jsonString", default=None) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/examples/no-custom-config/src/seed/commons/types/types/tag.py b/seed/python-sdk/examples/no-custom-config/src/seed/commons/types/types/tag.py index ae576888232..ad97a39db4c 100644 --- a/seed/python-sdk/examples/no-custom-config/src/seed/commons/types/types/tag.py +++ b/seed/python-sdk/examples/no-custom-config/src/seed/commons/types/types/tag.py @@ -3,4 +3,5 @@ """ "tag-wf9as23d" """ + Tag = str diff --git a/seed/python-sdk/examples/no-custom-config/src/seed/core/api_error.py b/seed/python-sdk/examples/no-custom-config/src/seed/core/api_error.py index 2e9fc5431cd..da734b58068 100644 --- a/seed/python-sdk/examples/no-custom-config/src/seed/core/api_error.py +++ b/seed/python-sdk/examples/no-custom-config/src/seed/core/api_error.py @@ -7,7 +7,9 @@ class ApiError(Exception): status_code: typing.Optional[int] body: typing.Any - def __init__(self, *, status_code: typing.Optional[int] = None, body: typing.Any = None): + def __init__( + self, *, status_code: typing.Optional[int] = None, body: typing.Any = None + ): self.status_code = status_code self.body = body diff --git a/seed/python-sdk/examples/no-custom-config/src/seed/core/client_wrapper.py b/seed/python-sdk/examples/no-custom-config/src/seed/core/client_wrapper.py index ef78d78ed99..88e5016aa3f 100644 --- a/seed/python-sdk/examples/no-custom-config/src/seed/core/client_wrapper.py +++ b/seed/python-sdk/examples/no-custom-config/src/seed/core/client_wrapper.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .http_client import AsyncHttpClient, HttpClient +from .http_client import HttpClient +from .http_client import AsyncHttpClient class BaseClientWrapper: diff --git a/seed/python-sdk/examples/no-custom-config/src/seed/core/datetime_utils.py b/seed/python-sdk/examples/no-custom-config/src/seed/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/python-sdk/examples/no-custom-config/src/seed/core/datetime_utils.py +++ b/seed/python-sdk/examples/no-custom-config/src/seed/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/python-sdk/examples/no-custom-config/src/seed/core/file.py b/seed/python-sdk/examples/no-custom-config/src/seed/core/file.py index cb0d40bbbf3..6e0f92bfcb1 100644 --- a/seed/python-sdk/examples/no-custom-config/src/seed/core/file.py +++ b/seed/python-sdk/examples/no-custom-config/src/seed/core/file.py @@ -13,12 +13,17 @@ # (filename, file (or bytes), content_type) typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str]], # (filename, file (or bytes), content_type, headers) - typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str], typing.Mapping[str, str]], + typing.Tuple[ + typing.Optional[str], + FileContent, + typing.Optional[str], + typing.Mapping[str, str], + ], ] def convert_file_dict_to_httpx_tuples( - d: typing.Dict[str, typing.Union[File, typing.List[File]]] + d: typing.Dict[str, typing.Union[File, typing.List[File]]], ) -> typing.List[typing.Tuple[str, File]]: """ The format we use is a list of tuples, where the first element is the diff --git a/seed/python-sdk/examples/no-custom-config/src/seed/core/http_client.py b/seed/python-sdk/examples/no-custom-config/src/seed/core/http_client.py index 9333d8a7f15..091f71bc185 100644 --- a/seed/python-sdk/examples/no-custom-config/src/seed/core/http_client.py +++ b/seed/python-sdk/examples/no-custom-config/src/seed/core/http_client.py @@ -77,7 +77,9 @@ def _retry_timeout(response: httpx.Response, retries: int) -> float: return retry_after # Apply exponential backoff, capped at MAX_RETRY_DELAY_SECONDS. - retry_delay = min(INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS) + retry_delay = min( + INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS + ) # Add a randomness / jitter to the retry delay to avoid overwhelming the server with retries. timeout = retry_delay * (1 - 0.25 * random()) @@ -90,7 +92,8 @@ def _should_retry(response: httpx.Response) -> bool: def remove_omit_from_dict( - original: typing.Dict[str, typing.Optional[typing.Any]], omit: typing.Optional[typing.Any] + original: typing.Dict[str, typing.Optional[typing.Any]], + omit: typing.Optional[typing.Any], ) -> typing.Dict[str, typing.Any]: if omit is None: return original @@ -108,7 +111,8 @@ def maybe_filter_request_body( ) -> typing.Optional[typing.Any]: if data is None: return ( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else None ) @@ -118,7 +122,8 @@ def maybe_filter_request_body( data_content = { **(jsonable_encoder(remove_omit_from_dict(data, omit))), # type: ignore **( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else {} ), @@ -162,7 +167,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url def request( @@ -174,8 +181,12 @@ def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -184,11 +195,14 @@ def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) response = self.httpx_client.request( method=method, @@ -198,7 +212,11 @@ def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -209,7 +227,10 @@ def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -222,11 +243,15 @@ def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: time.sleep(_retry_timeout(response=response, retries=retries)) @@ -256,8 +281,12 @@ def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -266,11 +295,14 @@ def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) with self.httpx_client.stream( method=method, @@ -280,7 +312,11 @@ def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -291,7 +327,9 @@ def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -304,7 +342,9 @@ def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream @@ -327,7 +367,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url async def request( @@ -339,8 +381,12 @@ async def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -349,11 +395,14 @@ async def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) # Add the input to each of these and do None-safety checks response = await self.httpx_client.request( @@ -364,7 +413,11 @@ async def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -375,7 +428,10 @@ async def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -388,11 +444,15 @@ async def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: await asyncio.sleep(_retry_timeout(response=response, retries=retries)) @@ -421,8 +481,12 @@ async def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -431,11 +495,14 @@ async def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) async with self.httpx_client.stream( method=method, @@ -445,7 +512,11 @@ async def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -456,7 +527,9 @@ async def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -469,7 +542,9 @@ async def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream diff --git a/seed/python-sdk/examples/no-custom-config/src/seed/core/jsonable_encoder.py b/seed/python-sdk/examples/no-custom-config/src/seed/core/jsonable_encoder.py index d3fd328fd41..12a8b52fc22 100644 --- a/seed/python-sdk/examples/no-custom-config/src/seed/core/jsonable_encoder.py +++ b/seed/python-sdk/examples/no-custom-config/src/seed/core/jsonable_encoder.py @@ -19,13 +19,19 @@ import pydantic from .datetime_utils import serialize_datetime -from .pydantic_utilities import IS_PYDANTIC_V2, encode_by_type, to_jsonable_with_fallback +from .pydantic_utilities import ( + IS_PYDANTIC_V2, + encode_by_type, + to_jsonable_with_fallback, +) SetIntStr = Set[Union[int, str]] DictIntStrAny = Dict[Union[int, str], Any] -def jsonable_encoder(obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None) -> Any: +def jsonable_encoder( + obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None +) -> Any: custom_encoder = custom_encoder or {} if custom_encoder: if type(obj) in custom_encoder: diff --git a/seed/python-sdk/examples/no-custom-config/src/seed/core/pydantic_utilities.py b/seed/python-sdk/examples/no-custom-config/src/seed/core/pydantic_utilities.py index 170a563d6eb..c63935c32a2 100644 --- a/seed/python-sdk/examples/no-custom-config/src/seed/core/pydantic_utilities.py +++ b/seed/python-sdk/examples/no-custom-config/src/seed/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) # type: ignore # Pydantic v1 diff --git a/seed/python-sdk/examples/no-custom-config/src/seed/core/query_encoder.py b/seed/python-sdk/examples/no-custom-config/src/seed/core/query_encoder.py index 24076d72ee9..7cb98f52cd7 100644 --- a/seed/python-sdk/examples/no-custom-config/src/seed/core/query_encoder.py +++ b/seed/python-sdk/examples/no-custom-config/src/seed/core/query_encoder.py @@ -7,7 +7,9 @@ # Flattens dicts to be of the form {"key[subkey][subkey2]": value} where value is not a dict -def traverse_query_dict(dict_flat: Dict[str, Any], key_prefix: Optional[str] = None) -> Dict[str, Any]: +def traverse_query_dict( + dict_flat: Dict[str, Any], key_prefix: Optional[str] = None +) -> Dict[str, Any]: result = {} for k, v in dict_flat.items(): key = f"{key_prefix}[{k}]" if key_prefix is not None else k @@ -30,4 +32,8 @@ def single_query_encoder(query_key: str, query_value: Any) -> Dict[str, Any]: def encode_query(query: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: - return dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) if query is not None else None + return ( + dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) + if query is not None + else None + ) diff --git a/seed/python-sdk/examples/no-custom-config/src/seed/core/serialization.py b/seed/python-sdk/examples/no-custom-config/src/seed/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/python-sdk/examples/no-custom-config/src/seed/core/serialization.py +++ b/seed/python-sdk/examples/no-custom-config/src/seed/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/python-sdk/examples/no-custom-config/src/seed/file/client.py b/seed/python-sdk/examples/no-custom-config/src/seed/file/client.py index 81bb5dc7923..b6004e87af6 100644 --- a/seed/python-sdk/examples/no-custom-config/src/seed/file/client.py +++ b/seed/python-sdk/examples/no-custom-config/src/seed/file/client.py @@ -1,8 +1,11 @@ # This file was auto-generated by Fern from our API Definition. -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from .notification.client import AsyncNotificationClient, NotificationClient -from .service.client import AsyncServiceClient, ServiceClient +from ..core.client_wrapper import SyncClientWrapper +from .notification.client import NotificationClient +from .service.client import ServiceClient +from ..core.client_wrapper import AsyncClientWrapper +from .notification.client import AsyncNotificationClient +from .service.client import AsyncServiceClient class FileClient: diff --git a/seed/python-sdk/examples/no-custom-config/src/seed/file/notification/client.py b/seed/python-sdk/examples/no-custom-config/src/seed/file/notification/client.py index e8077a84043..7ecd8bc9048 100644 --- a/seed/python-sdk/examples/no-custom-config/src/seed/file/notification/client.py +++ b/seed/python-sdk/examples/no-custom-config/src/seed/file/notification/client.py @@ -1,7 +1,9 @@ # This file was auto-generated by Fern from our API Definition. -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from .service.client import AsyncServiceClient, ServiceClient +from ...core.client_wrapper import SyncClientWrapper +from .service.client import ServiceClient +from ...core.client_wrapper import AsyncClientWrapper +from .service.client import AsyncServiceClient class NotificationClient: diff --git a/seed/python-sdk/examples/no-custom-config/src/seed/file/notification/service/client.py b/seed/python-sdk/examples/no-custom-config/src/seed/file/notification/service/client.py index 3f4653f18c3..094ca0c7538 100644 --- a/seed/python-sdk/examples/no-custom-config/src/seed/file/notification/service/client.py +++ b/seed/python-sdk/examples/no-custom-config/src/seed/file/notification/service/client.py @@ -1,14 +1,14 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.client_wrapper import SyncClientWrapper import typing -from json.decoder import JSONDecodeError - -from ....core.api_error import ApiError -from ....core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ....core.jsonable_encoder import jsonable_encoder -from ....core.pydantic_utilities import parse_obj_as from ....core.request_options import RequestOptions from ....types.types.exception import Exception +from ....core.jsonable_encoder import jsonable_encoder +from ....core.pydantic_utilities import parse_obj_as +from json.decoder import JSONDecodeError +from ....core.api_error import ApiError +from ....core.client_wrapper import AsyncClientWrapper class ServiceClient: @@ -16,7 +16,10 @@ def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper def get_exception( - self, notification_id: str, *, request_options: typing.Optional[RequestOptions] = None + self, + notification_id: str, + *, + request_options: typing.Optional[RequestOptions] = None, ) -> Exception: """ Parameters @@ -44,11 +47,15 @@ def get_exception( ) """ _response = self._client_wrapper.httpx_client.request( - f"file/notification/{jsonable_encoder(notification_id)}", method="GET", request_options=request_options + f"file/notification/{jsonable_encoder(notification_id)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(Exception, parse_obj_as(type_=Exception, object_=_response.json())) # type: ignore + return typing.cast( + Exception, parse_obj_as(type_=Exception, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -60,7 +67,10 @@ def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper async def get_exception( - self, notification_id: str, *, request_options: typing.Optional[RequestOptions] = None + self, + notification_id: str, + *, + request_options: typing.Optional[RequestOptions] = None, ) -> Exception: """ Parameters @@ -96,11 +106,15 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - f"file/notification/{jsonable_encoder(notification_id)}", method="GET", request_options=request_options + f"file/notification/{jsonable_encoder(notification_id)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(Exception, parse_obj_as(type_=Exception, object_=_response.json())) # type: ignore + return typing.cast( + Exception, parse_obj_as(type_=Exception, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/examples/no-custom-config/src/seed/file/service/client.py b/seed/python-sdk/examples/no-custom-config/src/seed/file/service/client.py index a211630dbaa..f262f07ece9 100644 --- a/seed/python-sdk/examples/no-custom-config/src/seed/file/service/client.py +++ b/seed/python-sdk/examples/no-custom-config/src/seed/file/service/client.py @@ -1,15 +1,15 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.client_wrapper import SyncClientWrapper import typing -from json.decoder import JSONDecodeError - -from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper +from ...core.request_options import RequestOptions +from ...types.types.file import File from ...core.jsonable_encoder import jsonable_encoder from ...core.pydantic_utilities import parse_obj_as -from ...core.request_options import RequestOptions from ...types.errors.not_found_error import NotFoundError -from ...types.types.file import File +from json.decoder import JSONDecodeError +from ...core.api_error import ApiError +from ...core.client_wrapper import AsyncClientWrapper class ServiceClient: @@ -17,7 +17,11 @@ def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper def get_file( - self, filename: str, *, x_file_api_version: str, request_options: typing.Optional[RequestOptions] = None + self, + filename: str, + *, + x_file_api_version: str, + request_options: typing.Optional[RequestOptions] = None, ) -> File: """ This endpoint returns a file by its name. @@ -53,14 +57,22 @@ def get_file( _response = self._client_wrapper.httpx_client.request( f"file/{jsonable_encoder(filename)}", method="GET", - headers={"X-File-API-Version": str(x_file_api_version) if x_file_api_version is not None else None}, + headers={ + "X-File-API-Version": str(x_file_api_version) + if x_file_api_version is not None + else None, + }, request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(File, parse_obj_as(type_=File, object_=_response.json())) # type: ignore + return typing.cast( + File, parse_obj_as(type_=File, object_=_response.json()) + ) # type: ignore if _response.status_code == 404: - raise NotFoundError(typing.cast(str, parse_obj_as(type_=str, object_=_response.json()))) # type: ignore + raise NotFoundError( + typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + ) _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -72,7 +84,11 @@ def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper async def get_file( - self, filename: str, *, x_file_api_version: str, request_options: typing.Optional[RequestOptions] = None + self, + filename: str, + *, + x_file_api_version: str, + request_options: typing.Optional[RequestOptions] = None, ) -> File: """ This endpoint returns a file by its name. @@ -116,14 +132,22 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( f"file/{jsonable_encoder(filename)}", method="GET", - headers={"X-File-API-Version": str(x_file_api_version) if x_file_api_version is not None else None}, + headers={ + "X-File-API-Version": str(x_file_api_version) + if x_file_api_version is not None + else None, + }, request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(File, parse_obj_as(type_=File, object_=_response.json())) # type: ignore + return typing.cast( + File, parse_obj_as(type_=File, object_=_response.json()) + ) # type: ignore if _response.status_code == 404: - raise NotFoundError(typing.cast(str, parse_obj_as(type_=str, object_=_response.json()))) # type: ignore + raise NotFoundError( + typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + ) _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/examples/no-custom-config/src/seed/file/service/types/filename.py b/seed/python-sdk/examples/no-custom-config/src/seed/file/service/types/filename.py index add91706b10..2531edee925 100644 --- a/seed/python-sdk/examples/no-custom-config/src/seed/file/service/types/filename.py +++ b/seed/python-sdk/examples/no-custom-config/src/seed/file/service/types/filename.py @@ -3,4 +3,5 @@ """ "file.txt" """ + Filename = str diff --git a/seed/python-sdk/examples/no-custom-config/src/seed/health/client.py b/seed/python-sdk/examples/no-custom-config/src/seed/health/client.py index a17be0c2502..d55aad7cbe9 100644 --- a/seed/python-sdk/examples/no-custom-config/src/seed/health/client.py +++ b/seed/python-sdk/examples/no-custom-config/src/seed/health/client.py @@ -1,7 +1,9 @@ # This file was auto-generated by Fern from our API Definition. -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from .service.client import AsyncServiceClient, ServiceClient +from ..core.client_wrapper import SyncClientWrapper +from .service.client import ServiceClient +from ..core.client_wrapper import AsyncClientWrapper +from .service.client import AsyncServiceClient class HealthClient: diff --git a/seed/python-sdk/examples/no-custom-config/src/seed/health/service/client.py b/seed/python-sdk/examples/no-custom-config/src/seed/health/service/client.py index ad81b2f5b83..fb380badd43 100644 --- a/seed/python-sdk/examples/no-custom-config/src/seed/health/service/client.py +++ b/seed/python-sdk/examples/no-custom-config/src/seed/health/service/client.py @@ -1,20 +1,22 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.client_wrapper import SyncClientWrapper import typing +from ...core.request_options import RequestOptions +from ...core.jsonable_encoder import jsonable_encoder from json.decoder import JSONDecodeError - from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ...core.jsonable_encoder import jsonable_encoder from ...core.pydantic_utilities import parse_obj_as -from ...core.request_options import RequestOptions +from ...core.client_wrapper import AsyncClientWrapper class ServiceClient: def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper - def check(self, id: str, *, request_options: typing.Optional[RequestOptions] = None) -> None: + def check( + self, id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> None: """ This endpoint checks the health of a resource. @@ -44,7 +46,9 @@ def check(self, id: str, *, request_options: typing.Optional[RequestOptions] = N ) """ _response = self._client_wrapper.httpx_client.request( - f"check/{jsonable_encoder(id)}", method="GET", request_options=request_options + f"check/{jsonable_encoder(id)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: @@ -78,10 +82,16 @@ def ping(self, *, request_options: typing.Optional[RequestOptions] = None) -> bo ) client.health.service.ping() """ - _response = self._client_wrapper.httpx_client.request("ping", method="GET", request_options=request_options) + _response = self._client_wrapper.httpx_client.request( + "ping", + method="GET", + request_options=request_options, + ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -92,7 +102,9 @@ class AsyncServiceClient: def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper - async def check(self, id: str, *, request_options: typing.Optional[RequestOptions] = None) -> None: + async def check( + self, id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> None: """ This endpoint checks the health of a resource. @@ -130,7 +142,9 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - f"check/{jsonable_encoder(id)}", method="GET", request_options=request_options + f"check/{jsonable_encoder(id)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: @@ -140,7 +154,9 @@ async def main() -> None: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - async def ping(self, *, request_options: typing.Optional[RequestOptions] = None) -> bool: + async def ping( + self, *, request_options: typing.Optional[RequestOptions] = None + ) -> bool: """ This endpoint checks the health of the service. @@ -173,11 +189,15 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "ping", method="GET", request_options=request_options + "ping", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/examples/no-custom-config/src/seed/service/client.py b/seed/python-sdk/examples/no-custom-config/src/seed/service/client.py index 15cb1fc5d1e..45317ff71a0 100644 --- a/seed/python-sdk/examples/no-custom-config/src/seed/service/client.py +++ b/seed/python-sdk/examples/no-custom-config/src/seed/service/client.py @@ -1,18 +1,18 @@ # This file was auto-generated by Fern from our API Definition. import typing -from json.decoder import JSONDecodeError - -from ..commons.types.types.tag import Tag -from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper +from ..core.client_wrapper import SyncClientWrapper +from ..types.types.movie_id import MovieId +from ..core.request_options import RequestOptions +from ..types.types.movie import Movie from ..core.jsonable_encoder import jsonable_encoder from ..core.pydantic_utilities import parse_obj_as -from ..core.request_options import RequestOptions +from json.decoder import JSONDecodeError +from ..core.api_error import ApiError +from ..commons.types.types.tag import Tag from ..types.types.metadata import Metadata -from ..types.types.movie import Movie -from ..types.types.movie_id import MovieId from ..types.types.response import Response +from ..core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -22,7 +22,12 @@ class ServiceClient: def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper - def get_movie(self, movie_id: MovieId, *, request_options: typing.Optional[RequestOptions] = None) -> Movie: + def get_movie( + self, + movie_id: MovieId, + *, + request_options: typing.Optional[RequestOptions] = None, + ) -> Movie: """ Parameters ---------- @@ -49,11 +54,15 @@ def get_movie(self, movie_id: MovieId, *, request_options: typing.Optional[Reque ) """ _response = self._client_wrapper.httpx_client.request( - f"movie/{jsonable_encoder(movie_id)}", method="GET", request_options=request_options + f"movie/{jsonable_encoder(movie_id)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(Movie, parse_obj_as(type_=Movie, object_=_response.json())) # type: ignore + return typing.cast( + Movie, parse_obj_as(type_=Movie, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -141,7 +150,9 @@ def create_movie( ) try: if 200 <= _response.status_code < 300: - return typing.cast(MovieId, parse_obj_as(type_=MovieId, object_=_response.json())) # type: ignore + return typing.cast( + MovieId, parse_obj_as(type_=MovieId, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -189,19 +200,30 @@ def get_metadata( _response = self._client_wrapper.httpx_client.request( "metadata", method="GET", - params={"shallow": shallow, "tag": tag}, - headers={"X-API-Version": str(x_api_version) if x_api_version is not None else None}, + params={ + "shallow": shallow, + "tag": tag, + }, + headers={ + "X-API-Version": str(x_api_version) + if x_api_version is not None + else None, + }, request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(Metadata, parse_obj_as(type_=Metadata, object_=_response.json())) # type: ignore + return typing.cast( + Metadata, parse_obj_as(type_=Metadata, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def get_response(self, *, request_options: typing.Optional[RequestOptions] = None) -> Response: + def get_response( + self, *, request_options: typing.Optional[RequestOptions] = None + ) -> Response: """ Parameters ---------- @@ -224,11 +246,15 @@ def get_response(self, *, request_options: typing.Optional[RequestOptions] = Non client.service.get_response() """ _response = self._client_wrapper.httpx_client.request( - "response", method="POST", request_options=request_options + "response", + method="POST", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(Response, parse_obj_as(type_=Response, object_=_response.json())) # type: ignore + return typing.cast( + Response, parse_obj_as(type_=Response, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -239,7 +265,12 @@ class AsyncServiceClient: def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper - async def get_movie(self, movie_id: MovieId, *, request_options: typing.Optional[RequestOptions] = None) -> Movie: + async def get_movie( + self, + movie_id: MovieId, + *, + request_options: typing.Optional[RequestOptions] = None, + ) -> Movie: """ Parameters ---------- @@ -274,11 +305,15 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - f"movie/{jsonable_encoder(movie_id)}", method="GET", request_options=request_options + f"movie/{jsonable_encoder(movie_id)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(Movie, parse_obj_as(type_=Movie, object_=_response.json())) # type: ignore + return typing.cast( + Movie, parse_obj_as(type_=Movie, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -374,7 +409,9 @@ async def main() -> None: ) try: if 200 <= _response.status_code < 300: - return typing.cast(MovieId, parse_obj_as(type_=MovieId, object_=_response.json())) # type: ignore + return typing.cast( + MovieId, parse_obj_as(type_=MovieId, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -430,19 +467,30 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( "metadata", method="GET", - params={"shallow": shallow, "tag": tag}, - headers={"X-API-Version": str(x_api_version) if x_api_version is not None else None}, + params={ + "shallow": shallow, + "tag": tag, + }, + headers={ + "X-API-Version": str(x_api_version) + if x_api_version is not None + else None, + }, request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(Metadata, parse_obj_as(type_=Metadata, object_=_response.json())) # type: ignore + return typing.cast( + Metadata, parse_obj_as(type_=Metadata, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - async def get_response(self, *, request_options: typing.Optional[RequestOptions] = None) -> Response: + async def get_response( + self, *, request_options: typing.Optional[RequestOptions] = None + ) -> Response: """ Parameters ---------- @@ -473,11 +521,15 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "response", method="POST", request_options=request_options + "response", + method="POST", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(Response, parse_obj_as(type_=Response, object_=_response.json())) # type: ignore + return typing.cast( + Response, parse_obj_as(type_=Response, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/examples/no-custom-config/src/seed/types/identifier.py b/seed/python-sdk/examples/no-custom-config/src/seed/types/identifier.py index ae9367a447c..f6ff0a9818b 100644 --- a/seed/python-sdk/examples/no-custom-config/src/seed/types/identifier.py +++ b/seed/python-sdk/examples/no-custom-config/src/seed/types/identifier.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. +from ..core.pydantic_utilities import UniversalBaseModel +from .type import Type +from ..core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .type import Type - class Identifier(UniversalBaseModel): type: Type @@ -14,7 +13,9 @@ class Identifier(UniversalBaseModel): label: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/examples/no-custom-config/src/seed/types/type.py b/seed/python-sdk/examples/no-custom-config/src/seed/types/type.py index 09d1c916dfd..e77e5e18b15 100644 --- a/seed/python-sdk/examples/no-custom-config/src/seed/types/type.py +++ b/seed/python-sdk/examples/no-custom-config/src/seed/types/type.py @@ -1,7 +1,6 @@ # This file was auto-generated by Fern from our API Definition. import typing - from .basic_type import BasicType from .complex_type import ComplexType diff --git a/seed/python-sdk/examples/no-custom-config/src/seed/types/types/actor.py b/seed/python-sdk/examples/no-custom-config/src/seed/types/types/actor.py index 0838e363001..7808438f935 100644 --- a/seed/python-sdk/examples/no-custom-config/src/seed/types/types/actor.py +++ b/seed/python-sdk/examples/no-custom-config/src/seed/types/types/actor.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class Actor(UniversalBaseModel): name: str id: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/examples/no-custom-config/src/seed/types/types/actress.py b/seed/python-sdk/examples/no-custom-config/src/seed/types/types/actress.py index 607abb7e0e3..9f6f48e855d 100644 --- a/seed/python-sdk/examples/no-custom-config/src/seed/types/types/actress.py +++ b/seed/python-sdk/examples/no-custom-config/src/seed/types/types/actress.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class Actress(UniversalBaseModel): """ @@ -23,7 +22,9 @@ class Actress(UniversalBaseModel): id: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/examples/no-custom-config/src/seed/types/types/cast_member.py b/seed/python-sdk/examples/no-custom-config/src/seed/types/types/cast_member.py index d73c89864e1..8be1a0b0a2a 100644 --- a/seed/python-sdk/examples/no-custom-config/src/seed/types/types/cast_member.py +++ b/seed/python-sdk/examples/no-custom-config/src/seed/types/types/cast_member.py @@ -1,7 +1,6 @@ # This file was auto-generated by Fern from our API Definition. import typing - from .actor import Actor from .actress import Actress from .stunt_double import StuntDouble diff --git a/seed/python-sdk/examples/no-custom-config/src/seed/types/types/directory.py b/seed/python-sdk/examples/no-custom-config/src/seed/types/types/directory.py index 92d8efa9c38..049ed2f2cd5 100644 --- a/seed/python-sdk/examples/no-custom-config/src/seed/types/types/directory.py +++ b/seed/python-sdk/examples/no-custom-config/src/seed/types/types/directory.py @@ -1,13 +1,12 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ...core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel, update_forward_refs from .file import File +from ...core.pydantic_utilities import IS_PYDANTIC_V2 +import pydantic +from ...core.pydantic_utilities import update_forward_refs class Directory(UniversalBaseModel): @@ -43,7 +42,9 @@ class Directory(UniversalBaseModel): directories: typing.Optional[typing.List[Directory]] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/examples/no-custom-config/src/seed/types/types/entity.py b/seed/python-sdk/examples/no-custom-config/src/seed/types/types/entity.py index e6500e2af7d..3c5b7349621 100644 --- a/seed/python-sdk/examples/no-custom-config/src/seed/types/types/entity.py +++ b/seed/python-sdk/examples/no-custom-config/src/seed/types/types/entity.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ..type import Type +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from ..type import Type - class Entity(UniversalBaseModel): """ @@ -24,7 +23,9 @@ class Entity(UniversalBaseModel): name: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/examples/no-custom-config/src/seed/types/types/exception.py b/seed/python-sdk/examples/no-custom-config/src/seed/types/types/exception.py index 851835745bd..a61252d9fc4 100644 --- a/seed/python-sdk/examples/no-custom-config/src/seed/types/types/exception.py +++ b/seed/python-sdk/examples/no-custom-config/src/seed/types/types/exception.py @@ -1,12 +1,10 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ...core.pydantic_utilities import UniversalBaseModel import typing - import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 class Exception_Generic(UniversalBaseModel): @@ -28,7 +26,9 @@ class Exception_Generic(UniversalBaseModel): exception_stacktrace: str = pydantic.Field(alias="exceptionStacktrace") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: @@ -53,7 +53,9 @@ class Exception_Timeout(UniversalBaseModel): type: typing.Literal["timeout"] = "timeout" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/examples/no-custom-config/src/seed/types/types/exception_info.py b/seed/python-sdk/examples/no-custom-config/src/seed/types/types/exception_info.py index 2d902a51d05..220ddb6a0c7 100644 --- a/seed/python-sdk/examples/no-custom-config/src/seed/types/types/exception_info.py +++ b/seed/python-sdk/examples/no-custom-config/src/seed/types/types/exception_info.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ...core.pydantic_utilities import UniversalBaseModel import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class ExceptionInfo(UniversalBaseModel): @@ -25,7 +24,9 @@ class ExceptionInfo(UniversalBaseModel): exception_stacktrace: str = pydantic.Field(alias="exceptionStacktrace") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/examples/no-custom-config/src/seed/types/types/extended_movie.py b/seed/python-sdk/examples/no-custom-config/src/seed/types/types/extended_movie.py index 41d92df7718..8b48ecddcbe 100644 --- a/seed/python-sdk/examples/no-custom-config/src/seed/types/types/extended_movie.py +++ b/seed/python-sdk/examples/no-custom-config/src/seed/types/types/extended_movie.py @@ -1,11 +1,9 @@ # This file was auto-generated by Fern from our API Definition. +from .movie import Movie import typing - -import pydantic - from ...core.pydantic_utilities import IS_PYDANTIC_V2 -from .movie import Movie +import pydantic class ExtendedMovie(Movie): @@ -32,7 +30,9 @@ class ExtendedMovie(Movie): cast: typing.List[str] if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/examples/no-custom-config/src/seed/types/types/file.py b/seed/python-sdk/examples/no-custom-config/src/seed/types/types/file.py index 9103c9ec9c6..af2112c9a3d 100644 --- a/seed/python-sdk/examples/no-custom-config/src/seed/types/types/file.py +++ b/seed/python-sdk/examples/no-custom-config/src/seed/types/types/file.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class File(UniversalBaseModel): """ @@ -23,7 +22,9 @@ class File(UniversalBaseModel): contents: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/examples/no-custom-config/src/seed/types/types/metadata.py b/seed/python-sdk/examples/no-custom-config/src/seed/types/types/metadata.py index 924c6e5a00b..9081aa0b389 100644 --- a/seed/python-sdk/examples/no-custom-config/src/seed/types/types/metadata.py +++ b/seed/python-sdk/examples/no-custom-config/src/seed/types/types/metadata.py @@ -1,13 +1,11 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ...core.pydantic_utilities import UniversalBaseModel import typing - +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class Base(UniversalBaseModel): """ @@ -22,7 +20,9 @@ class Base(UniversalBaseModel): tags: typing.Set[str] if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: @@ -36,7 +36,9 @@ class Metadata_Html(Base): type: typing.Literal["html"] = "html" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + frozen=True + ) # type: ignore # Pydantic v2 else: class Config: @@ -49,7 +51,9 @@ class Metadata_Markdown(Base): type: typing.Literal["markdown"] = "markdown" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/examples/no-custom-config/src/seed/types/types/migration.py b/seed/python-sdk/examples/no-custom-config/src/seed/types/types/migration.py index 68f4d579dea..eb6cd3736bd 100644 --- a/seed/python-sdk/examples/no-custom-config/src/seed/types/types/migration.py +++ b/seed/python-sdk/examples/no-custom-config/src/seed/types/types/migration.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from .migration_status import MigrationStatus +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .migration_status import MigrationStatus - class Migration(UniversalBaseModel): """ @@ -24,7 +23,9 @@ class Migration(UniversalBaseModel): status: MigrationStatus if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/examples/no-custom-config/src/seed/types/types/migration_status.py b/seed/python-sdk/examples/no-custom-config/src/seed/types/types/migration_status.py index c5a2e76b4af..e14e67e1b5a 100644 --- a/seed/python-sdk/examples/no-custom-config/src/seed/types/types/migration_status.py +++ b/seed/python-sdk/examples/no-custom-config/src/seed/types/types/migration_status.py @@ -2,4 +2,6 @@ import typing -MigrationStatus = typing.Union[typing.Literal["RUNNING", "FAILED", "FINISHED"], typing.Any] +MigrationStatus = typing.Union[ + typing.Literal["RUNNING", "FAILED", "FINISHED"], typing.Any +] diff --git a/seed/python-sdk/examples/no-custom-config/src/seed/types/types/moment.py b/seed/python-sdk/examples/no-custom-config/src/seed/types/types/moment.py index 820b4ff0e86..b344b30e496 100644 --- a/seed/python-sdk/examples/no-custom-config/src/seed/types/types/moment.py +++ b/seed/python-sdk/examples/no-custom-config/src/seed/types/types/moment.py @@ -1,13 +1,12 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +import uuid import datetime as dt +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing -import uuid - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class Moment(UniversalBaseModel): """ @@ -36,7 +35,9 @@ class Moment(UniversalBaseModel): datetime: dt.datetime if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/examples/no-custom-config/src/seed/types/types/movie.py b/seed/python-sdk/examples/no-custom-config/src/seed/types/types/movie.py index 9e67c2456ea..426206249be 100644 --- a/seed/python-sdk/examples/no-custom-config/src/seed/types/types/movie.py +++ b/seed/python-sdk/examples/no-custom-config/src/seed/types/types/movie.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from .movie_id import MovieId import typing - import pydantic - from ...commons.types.types.tag import Tag -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .movie_id import MovieId +from ...core.pydantic_utilities import IS_PYDANTIC_V2 class Movie(UniversalBaseModel): @@ -45,7 +44,9 @@ class Movie(UniversalBaseModel): metadata: typing.Dict[str, typing.Any] if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/examples/no-custom-config/src/seed/types/types/movie_id.py b/seed/python-sdk/examples/no-custom-config/src/seed/types/types/movie_id.py index 86f7a4f4651..86945f3b676 100644 --- a/seed/python-sdk/examples/no-custom-config/src/seed/types/types/movie_id.py +++ b/seed/python-sdk/examples/no-custom-config/src/seed/types/types/movie_id.py @@ -3,4 +3,5 @@ """ "movie-c06a4ad7" """ + MovieId = str diff --git a/seed/python-sdk/examples/no-custom-config/src/seed/types/types/node.py b/seed/python-sdk/examples/no-custom-config/src/seed/types/types/node.py index 77f2a5e87da..9a5f5952b59 100644 --- a/seed/python-sdk/examples/no-custom-config/src/seed/types/types/node.py +++ b/seed/python-sdk/examples/no-custom-config/src/seed/types/types/node.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ...core.pydantic_utilities import UniversalBaseModel import typing - +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel, update_forward_refs +from ...core.pydantic_utilities import update_forward_refs class Node(UniversalBaseModel): @@ -45,7 +44,9 @@ class Node(UniversalBaseModel): trees: typing.Optional[typing.List[Tree]] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/examples/no-custom-config/src/seed/types/types/request.py b/seed/python-sdk/examples/no-custom-config/src/seed/types/types/request.py index a2ff0455aa0..7649502a04c 100644 --- a/seed/python-sdk/examples/no-custom-config/src/seed/types/types/request.py +++ b/seed/python-sdk/examples/no-custom-config/src/seed/types/types/request.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel import typing - +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class Request(UniversalBaseModel): """ @@ -21,7 +20,9 @@ class Request(UniversalBaseModel): request: typing.Any if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/examples/no-custom-config/src/seed/types/types/response.py b/seed/python-sdk/examples/no-custom-config/src/seed/types/types/response.py index edcd3f24da1..d17192b48e6 100644 --- a/seed/python-sdk/examples/no-custom-config/src/seed/types/types/response.py +++ b/seed/python-sdk/examples/no-custom-config/src/seed/types/types/response.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from ..identifier import Identifier +from ...core.pydantic_utilities import IS_PYDANTIC_V2 +import pydantic class Response(UniversalBaseModel): @@ -36,7 +35,9 @@ class Response(UniversalBaseModel): identifiers: typing.List[Identifier] if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/examples/no-custom-config/src/seed/types/types/response_type.py b/seed/python-sdk/examples/no-custom-config/src/seed/types/types/response_type.py index c5777220170..8b43d297ad3 100644 --- a/seed/python-sdk/examples/no-custom-config/src/seed/types/types/response_type.py +++ b/seed/python-sdk/examples/no-custom-config/src/seed/types/types/response_type.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ..type import Type +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from ..type import Type - class ResponseType(UniversalBaseModel): type: Type if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/examples/no-custom-config/src/seed/types/types/stunt_double.py b/seed/python-sdk/examples/no-custom-config/src/seed/types/types/stunt_double.py index f2b3a81d999..f3faa0fd65b 100644 --- a/seed/python-sdk/examples/no-custom-config/src/seed/types/types/stunt_double.py +++ b/seed/python-sdk/examples/no-custom-config/src/seed/types/types/stunt_double.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ...core.pydantic_utilities import UniversalBaseModel import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class StuntDouble(UniversalBaseModel): @@ -12,7 +11,9 @@ class StuntDouble(UniversalBaseModel): actor_or_actress_id: str = pydantic.Field(alias="actorOrActressId") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/examples/no-custom-config/src/seed/types/types/test.py b/seed/python-sdk/examples/no-custom-config/src/seed/types/types/test.py index 3a0d88bb4b1..b9d6b204965 100644 --- a/seed/python-sdk/examples/no-custom-config/src/seed/types/types/test.py +++ b/seed/python-sdk/examples/no-custom-config/src/seed/types/types/test.py @@ -1,20 +1,20 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ...core.pydantic_utilities import UniversalBaseModel import typing - +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class Test_And(UniversalBaseModel): value: bool type: typing.Literal["and"] = "and" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + frozen=True + ) # type: ignore # Pydantic v2 else: class Config: @@ -27,7 +27,9 @@ class Test_Or(UniversalBaseModel): type: typing.Literal["or"] = "or" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/examples/no-custom-config/src/seed/types/types/tree.py b/seed/python-sdk/examples/no-custom-config/src/seed/types/types/tree.py index 52b70602a21..c159c5c2ee4 100644 --- a/seed/python-sdk/examples/no-custom-config/src/seed/types/types/tree.py +++ b/seed/python-sdk/examples/no-custom-config/src/seed/types/types/tree.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ...core.pydantic_utilities import UniversalBaseModel import typing - +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel, update_forward_refs +from ...core.pydantic_utilities import update_forward_refs class Tree(UniversalBaseModel): @@ -30,7 +29,9 @@ class Tree(UniversalBaseModel): nodes: typing.Optional[typing.List[Node]] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/examples/no-custom-config/src/seed/version.py b/seed/python-sdk/examples/no-custom-config/src/seed/version.py index b6f2c764388..ad7a9c63cc2 100644 --- a/seed/python-sdk/examples/no-custom-config/src/seed/version.py +++ b/seed/python-sdk/examples/no-custom-config/src/seed/version.py @@ -1,4 +1,3 @@ - from importlib import metadata __version__ = metadata.version("fern_examples") diff --git a/seed/python-sdk/examples/no-custom-config/tests/conftest.py b/seed/python-sdk/examples/no-custom-config/tests/conftest.py index 6287438ce63..55b62025b51 100644 --- a/seed/python-sdk/examples/no-custom-config/tests/conftest.py +++ b/seed/python-sdk/examples/no-custom-config/tests/conftest.py @@ -1,16 +1,22 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExamples import os - import pytest -from seed import AsyncSeedExamples, SeedExamples +from seed import AsyncSeedExamples @pytest.fixture def client() -> SeedExamples: - return SeedExamples(token=os.getenv("ENV_TOKEN", "token"), base_url=os.getenv("TESTS_BASE_URL", "base_url")) + return SeedExamples( + token=os.getenv("ENV_TOKEN", "token"), + base_url=os.getenv("TESTS_BASE_URL", "base_url"), + ) @pytest.fixture def async_client() -> AsyncSeedExamples: - return AsyncSeedExamples(token=os.getenv("ENV_TOKEN", "token"), base_url=os.getenv("TESTS_BASE_URL", "base_url")) + return AsyncSeedExamples( + token=os.getenv("ENV_TOKEN", "token"), + base_url=os.getenv("TESTS_BASE_URL", "base_url"), + ) diff --git a/seed/python-sdk/examples/no-custom-config/tests/custom/test_client.py b/seed/python-sdk/examples/no-custom-config/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/python-sdk/examples/no-custom-config/tests/custom/test_client.py +++ b/seed/python-sdk/examples/no-custom-config/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/python-sdk/examples/no-custom-config/tests/file/notification/test_service.py b/seed/python-sdk/examples/no-custom-config/tests/file/notification/test_service.py index e9ce274f7b9..425f6251bd2 100644 --- a/seed/python-sdk/examples/no-custom-config/tests/file/notification/test_service.py +++ b/seed/python-sdk/examples/no-custom-config/tests/file/notification/test_service.py @@ -1,13 +1,14 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExamples +from seed import AsyncSeedExamples import typing - -from seed import AsyncSeedExamples, SeedExamples - from ...utilities import validate_response -async def test_get_exception(client: SeedExamples, async_client: AsyncSeedExamples) -> None: +async def test_get_exception( + client: SeedExamples, async_client: AsyncSeedExamples +) -> None: expected_response: typing.Any = { "type": "generic", "exceptionType": "Unavailable", @@ -15,8 +16,12 @@ async def test_get_exception(client: SeedExamples, async_client: AsyncSeedExampl "exceptionStacktrace": "", } expected_types: typing.Any = "no_validate" - response = client.file.notification.service.get_exception(notification_id="notification-hsy129x") + response = client.file.notification.service.get_exception( + notification_id="notification-hsy129x" + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.file.notification.service.get_exception(notification_id="notification-hsy129x") + async_response = await async_client.file.notification.service.get_exception( + notification_id="notification-hsy129x" + ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/examples/no-custom-config/tests/health/test_service.py b/seed/python-sdk/examples/no-custom-config/tests/health/test_service.py index 84940f4fd4c..75cbe574de1 100644 --- a/seed/python-sdk/examples/no-custom-config/tests/health/test_service.py +++ b/seed/python-sdk/examples/no-custom-config/tests/health/test_service.py @@ -1,9 +1,8 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExamples +from seed import AsyncSeedExamples import typing - -from seed import AsyncSeedExamples, SeedExamples - from ..utilities import validate_response diff --git a/seed/python-sdk/examples/no-custom-config/tests/test_root.py b/seed/python-sdk/examples/no-custom-config/tests/test_root.py index e9a402e2322..474790891ae 100644 --- a/seed/python-sdk/examples/no-custom-config/tests/test_root.py +++ b/seed/python-sdk/examples/no-custom-config/tests/test_root.py @@ -1,9 +1,8 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExamples +from seed import AsyncSeedExamples import typing - -from seed import AsyncSeedExamples, SeedExamples - from .utilities import validate_response @@ -13,5 +12,7 @@ async def test_echo(client: SeedExamples, async_client: AsyncSeedExamples) -> No response = client.echo(request="Hello world!\\n\\nwith\\n\\tnewlines") validate_response(response, expected_response, expected_types) - async_response = await async_client.echo(request="Hello world!\\n\\nwith\\n\\tnewlines") + async_response = await async_client.echo( + request="Hello world!\\n\\nwith\\n\\tnewlines" + ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/examples/no-custom-config/tests/test_service.py b/seed/python-sdk/examples/no-custom-config/tests/test_service.py index 5c00ddaf39d..40349c313f3 100644 --- a/seed/python-sdk/examples/no-custom-config/tests/test_service.py +++ b/seed/python-sdk/examples/no-custom-config/tests/test_service.py @@ -1,9 +1,8 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExamples +from seed import AsyncSeedExamples import typing - -from seed import AsyncSeedExamples, SeedExamples - from .utilities import validate_response @@ -39,7 +38,9 @@ async def test_get_movie(client: SeedExamples, async_client: AsyncSeedExamples) validate_response(async_response, expected_response, expected_types) -async def test_create_movie(client: SeedExamples, async_client: AsyncSeedExamples) -> None: +async def test_create_movie( + client: SeedExamples, async_client: AsyncSeedExamples +) -> None: expected_response: typing.Any = "movie-c06a4ad7" expected_types: typing.Any = None response = client.service.create_movie( @@ -73,7 +74,9 @@ async def test_create_movie(client: SeedExamples, async_client: AsyncSeedExample validate_response(async_response, expected_response, expected_types) -async def test_get_metadata(client: SeedExamples, async_client: AsyncSeedExamples) -> None: +async def test_get_metadata( + client: SeedExamples, async_client: AsyncSeedExamples +) -> None: expected_response: typing.Any = { "type": "html", "extra": {"version": "0.0.1", "tenancy": "test"}, @@ -81,14 +84,20 @@ async def test_get_metadata(client: SeedExamples, async_client: AsyncSeedExample "value": "...", } expected_types: typing.Any = "no_validate" - response = client.service.get_metadata(x_api_version="0.0.1", shallow=False, tag="development") + response = client.service.get_metadata( + x_api_version="0.0.1", shallow=False, tag="development" + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.service.get_metadata(x_api_version="0.0.1", shallow=False, tag="development") + async_response = await async_client.service.get_metadata( + x_api_version="0.0.1", shallow=False, tag="development" + ) validate_response(async_response, expected_response, expected_types) -async def test_get_response(client: SeedExamples, async_client: AsyncSeedExamples) -> None: +async def test_get_response( + client: SeedExamples, async_client: AsyncSeedExamples +) -> None: expected_response: typing.Any = { "response": "Initializing...", "identifiers": [ @@ -100,7 +109,10 @@ async def test_get_response(client: SeedExamples, async_client: AsyncSeedExample "response": None, "identifiers": ( "list", - {0: {"type": None, "value": None, "label": None}, 1: {"type": None, "value": None, "label": None}}, + { + 0: {"type": None, "value": None, "label": None}, + 1: {"type": None, "value": None, "label": None}, + }, ), } response = client.service.get_response() diff --git a/seed/python-sdk/examples/no-custom-config/tests/utilities.py b/seed/python-sdk/examples/no-custom-config/tests/utilities.py index 13da208eb3a..e8f4472564c 100644 --- a/seed/python-sdk/examples/no-custom-config/tests/utilities.py +++ b/seed/python-sdk/examples/no-custom-config/tests/utilities.py @@ -3,11 +3,14 @@ import typing import uuid -import pydantic from dateutil import parser +import pydantic + -def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> typing.Any: +def cast_field( + json_expectation: typing.Any, type_expectation: typing.Any +) -> typing.Any: # Cast these specific types which come through as string and expect our # models to cast to the correct type. if type_expectation == "uuid": @@ -25,7 +28,9 @@ def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> ty return json_expectation -def validate_field(response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any) -> None: +def validate_field( + response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectation == "no_validate": return @@ -44,7 +49,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(entry_expectation, dict): is_container_of_complex_type = True validate_response( - response=response[idx], json_expectation=ex, type_expectations=entry_expectation + response=response[idx], + json_expectation=ex, + type_expectations=entry_expectation, ) else: cast_json_expectation.append(cast_field(ex, entry_expectation)) @@ -56,7 +63,10 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # if any of the values of the set have a type_expectation of a dict, we're assuming it's a pydantic # model and keeping it a list. if container_expectation != "set" or not any( - map(lambda value: isinstance(value, dict), list(contents_expectation.values())) + map( + lambda value: isinstance(value, dict), + list(contents_expectation.values()), + ) ): json_expectation = cast_field(json_expectation, container_expectation) elif isinstance(type_expectation, tuple): @@ -65,9 +75,15 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(contents_expectation, dict): json_expectation = { cast_field( - key, contents_expectation.get(idx)[0] if contents_expectation.get(idx) is not None else None # type: ignore + key, + contents_expectation.get(idx)[0] + if contents_expectation.get(idx) is not None + else None, # type: ignore ): cast_field( - value, contents_expectation.get(idx)[1] if contents_expectation.get(idx) is not None else None # type: ignore + value, + contents_expectation.get(idx)[1] + if contents_expectation.get(idx) is not None + else None, # type: ignore ) for idx, (key, value) in enumerate(json_expectation.items()) } @@ -86,7 +102,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # Arg type_expectations is a deeply nested structure that matches the response, but with the values replaced with the expected types -def validate_response(response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any) -> None: +def validate_response( + response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectations == "no_validate": return @@ -96,11 +114,17 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e and not isinstance(response, dict) and not issubclass(type(response), pydantic.BaseModel) ): - validate_field(response=response, json_expectation=json_expectation, type_expectation=type_expectations) + validate_field( + response=response, + json_expectation=json_expectation, + type_expectation=type_expectations, + ) return if isinstance(response, list): - assert len(response) == len(json_expectation), "Length mismatch, expected: {0}, Actual: {1}".format( + assert len(response) == len( + json_expectation + ), "Length mismatch, expected: {0}, Actual: {1}".format( len(response), len(json_expectation) ) content_expectation = type_expectations @@ -108,7 +132,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e content_expectation = type_expectations[1] for idx, item in enumerate(response): validate_response( - response=item, json_expectation=json_expectation[idx], type_expectations=content_expectation[idx] + response=item, + json_expectation=json_expectation[idx], + type_expectations=content_expectation[idx], ) else: response_json = response @@ -116,7 +142,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e response_json = response.dict(by_alias=True) for key, value in json_expectation.items(): - assert key in response_json, "Field {0} not found within the response object: {1}".format( + assert ( + key in response_json + ), "Field {0} not found within the response object: {1}".format( key, response_json ) @@ -128,11 +156,19 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e # Otherwise, we're just validating a single field that's a pydantic model. if isinstance(value, dict) and not isinstance(type_expectation, tuple): validate_response( - response=response_json[key], json_expectation=value, type_expectations=type_expectation + response=response_json[key], + json_expectation=value, + type_expectations=type_expectation, ) else: - validate_field(response=response_json[key], json_expectation=value, type_expectation=type_expectation) + validate_field( + response=response_json[key], + json_expectation=value, + type_expectation=type_expectation, + ) # Ensure there are no additional fields here either del response_json[key] - assert len(response_json) == 0, "Additional fields found, expected None: {0}".format(response_json) + assert ( + len(response_json) == 0 + ), "Additional fields found, expected None: {0}".format(response_json) diff --git a/seed/python-sdk/examples/no-custom-config/tests/utils/assets/models/__init__.py b/seed/python-sdk/examples/no-custom-config/tests/utils/assets/models/__init__.py index 2cf01263529..3a1c852e71e 100644 --- a/seed/python-sdk/examples/no-custom-config/tests/utils/assets/models/__init__.py +++ b/seed/python-sdk/examples/no-custom-config/tests/utils/assets/models/__init__.py @@ -5,7 +5,7 @@ from .circle import CircleParams from .object_with_defaults import ObjectWithDefaultsParams from .object_with_optional_field import ObjectWithOptionalFieldParams -from .shape import Shape_CircleParams, Shape_SquareParams, ShapeParams +from .shape import ShapeParams, Shape_CircleParams, Shape_SquareParams from .square import SquareParams from .undiscriminated_shape import UndiscriminatedShapeParams diff --git a/seed/python-sdk/examples/no-custom-config/tests/utils/assets/models/circle.py b/seed/python-sdk/examples/no-custom-config/tests/utils/assets/models/circle.py index af7a1bf8a8e..253f12d38b3 100644 --- a/seed/python-sdk/examples/no-custom-config/tests/utils/assets/models/circle.py +++ b/seed/python-sdk/examples/no-custom-config/tests/utils/assets/models/circle.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class CircleParams(typing_extensions.TypedDict): - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] diff --git a/seed/python-sdk/examples/no-custom-config/tests/utils/assets/models/object_with_optional_field.py b/seed/python-sdk/examples/no-custom-config/tests/utils/assets/models/object_with_optional_field.py index 3ad93d5f305..ebe7dc80547 100644 --- a/seed/python-sdk/examples/no-custom-config/tests/utils/assets/models/object_with_optional_field.py +++ b/seed/python-sdk/examples/no-custom-config/tests/utils/assets/models/object_with_optional_field.py @@ -7,8 +7,8 @@ import uuid import typing_extensions -from seed.core.serialization import FieldMetadata +from seed.core.serialization import FieldMetadata from .color import Color from .shape import ShapeParams from .undiscriminated_shape import UndiscriminatedShapeParams @@ -18,16 +18,30 @@ class ObjectWithOptionalFieldParams(typing_extensions.TypedDict): literal: typing.Literal["lit_one"] string: typing_extensions.NotRequired[str] integer: typing_extensions.NotRequired[int] - long_: typing_extensions.NotRequired[typing_extensions.Annotated[int, FieldMetadata(alias="long")]] + long_: typing_extensions.NotRequired[ + typing_extensions.Annotated[int, FieldMetadata(alias="long")] + ] double: typing_extensions.NotRequired[float] - bool_: typing_extensions.NotRequired[typing_extensions.Annotated[bool, FieldMetadata(alias="bool")]] + bool_: typing_extensions.NotRequired[ + typing_extensions.Annotated[bool, FieldMetadata(alias="bool")] + ] datetime: typing_extensions.NotRequired[dt.datetime] date: typing_extensions.NotRequired[dt.date] - uuid_: typing_extensions.NotRequired[typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")]] - base_64: typing_extensions.NotRequired[typing_extensions.Annotated[str, FieldMetadata(alias="base64")]] - list_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")]] - set_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")]] - map_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")]] + uuid_: typing_extensions.NotRequired[ + typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")] + ] + base_64: typing_extensions.NotRequired[ + typing_extensions.Annotated[str, FieldMetadata(alias="base64")] + ] + list_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")] + ] + set_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")] + ] + map_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")] + ] enum: typing_extensions.NotRequired[Color] union: typing_extensions.NotRequired[ShapeParams] second_union: typing_extensions.NotRequired[ShapeParams] diff --git a/seed/python-sdk/examples/no-custom-config/tests/utils/assets/models/shape.py b/seed/python-sdk/examples/no-custom-config/tests/utils/assets/models/shape.py index 2c33c877951..816ffc51bdc 100644 --- a/seed/python-sdk/examples/no-custom-config/tests/utils/assets/models/shape.py +++ b/seed/python-sdk/examples/no-custom-config/tests/utils/assets/models/shape.py @@ -7,6 +7,7 @@ import typing import typing_extensions + from seed.core.serialization import FieldMetadata @@ -15,13 +16,21 @@ class Base(typing_extensions.TypedDict): class Shape_CircleParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["circle"], FieldMetadata(alias="shapeType")] - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["circle"], FieldMetadata(alias="shapeType") + ] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] class Shape_SquareParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["square"], FieldMetadata(alias="shapeType")] - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["square"], FieldMetadata(alias="shapeType") + ] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] ShapeParams = typing.Union[Shape_CircleParams, Shape_SquareParams] diff --git a/seed/python-sdk/examples/no-custom-config/tests/utils/assets/models/square.py b/seed/python-sdk/examples/no-custom-config/tests/utils/assets/models/square.py index b9b7dd319bc..bcf08a723c5 100644 --- a/seed/python-sdk/examples/no-custom-config/tests/utils/assets/models/square.py +++ b/seed/python-sdk/examples/no-custom-config/tests/utils/assets/models/square.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class SquareParams(typing_extensions.TypedDict): - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] diff --git a/seed/python-sdk/examples/no-custom-config/tests/utils/test_http_client.py b/seed/python-sdk/examples/no-custom-config/tests/utils/test_http_client.py index edd11ca7afb..f5a874a75f3 100644 --- a/seed/python-sdk/examples/no-custom-config/tests/utils/test_http_client.py +++ b/seed/python-sdk/examples/no-custom-config/tests/utils/test_http_client.py @@ -9,12 +9,17 @@ def get_request_options() -> RequestOptions: def test_get_json_request_body() -> None: - json_body, data_body = get_request_body(json={"hello": "world"}, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json={"hello": "world"}, data=None, request_options=None, omit=None + ) assert json_body == {"hello": "world"} assert data_body is None json_body_extras, data_body_extras = get_request_body( - json={"goodbye": "world"}, data=None, request_options=get_request_options(), omit=None + json={"goodbye": "world"}, + data=None, + request_options=get_request_options(), + omit=None, ) assert json_body_extras == {"goodbye": "world", "see you": "later"} @@ -22,12 +27,17 @@ def test_get_json_request_body() -> None: def test_get_files_request_body() -> None: - json_body, data_body = get_request_body(json=None, data={"hello": "world"}, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data={"hello": "world"}, request_options=None, omit=None + ) assert data_body == {"hello": "world"} assert json_body is None json_body_extras, data_body_extras = get_request_body( - json=None, data={"goodbye": "world"}, request_options=get_request_options(), omit=None + json=None, + data={"goodbye": "world"}, + request_options=get_request_options(), + omit=None, ) assert data_body_extras == {"goodbye": "world", "see you": "later"} @@ -35,7 +45,9 @@ def test_get_files_request_body() -> None: def test_get_none_request_body() -> None: - json_body, data_body = get_request_body(json=None, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data=None, request_options=None, omit=None + ) assert data_body is None assert json_body is None diff --git a/seed/python-sdk/examples/no-custom-config/tests/utils/test_query_encoding.py b/seed/python-sdk/examples/no-custom-config/tests/utils/test_query_encoding.py index 247e1551b46..fbc8f402167 100644 --- a/seed/python-sdk/examples/no-custom-config/tests/utils/test_query_encoding.py +++ b/seed/python-sdk/examples/no-custom-config/tests/utils/test_query_encoding.py @@ -4,9 +4,15 @@ def test_query_encoding() -> None: - assert encode_query({"hello world": "hello world"}) == {"hello world": "hello world"} - assert encode_query({"hello_world": {"hello": "world"}}) == {"hello_world[hello]": "world"} - assert encode_query({"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"}) == { + assert encode_query({"hello world": "hello world"}) == { + "hello world": "hello world" + } + assert encode_query({"hello_world": {"hello": "world"}}) == { + "hello_world[hello]": "world" + } + assert encode_query( + {"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"} + ) == { "hello_world[hello][world]": "today", "hello_world[test]": "this", "hi": "there", diff --git a/seed/python-sdk/examples/no-custom-config/tests/utils/test_serialization.py b/seed/python-sdk/examples/no-custom-config/tests/utils/test_serialization.py index 58b1ed66e6d..5ca956916dd 100644 --- a/seed/python-sdk/examples/no-custom-config/tests/utils/test_serialization.py +++ b/seed/python-sdk/examples/no-custom-config/tests/utils/test_serialization.py @@ -1,10 +1,12 @@ # This file was auto-generated by Fern from our API Definition. -from typing import Any, List +from typing import List, Any -from seed.core.serialization import convert_and_respect_annotation_metadata +from seed.core.serialization import ( + convert_and_respect_annotation_metadata, +) +from .assets.models import ShapeParams, ObjectWithOptionalFieldParams -from .assets.models import ObjectWithOptionalFieldParams, ShapeParams UNION_TEST: ShapeParams = {"radius_measurement": 1.0, "shape_type": "circle", "id": "1"} UNION_TEST_CONVERTED = {"shapeType": "circle", "radiusMeasurement": 1.0, "id": "1"} @@ -18,20 +20,54 @@ def test_convert_and_respect_annotation_metadata() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) - assert converted == {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"} + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) + assert converted == { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + } def test_convert_and_respect_annotation_metadata_in_list() -> None: data: List[ObjectWithOptionalFieldParams] = [ - {"string": "string", "long_": 12345, "bool_": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long_": 67890, "list_": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long_": 12345, + "bool_": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long_": 67890, + "list_": [], + "literal": "lit_one", + "any": "any", + }, ] - converted = convert_and_respect_annotation_metadata(object_=data, annotation=List[ObjectWithOptionalFieldParams]) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=List[ObjectWithOptionalFieldParams] + ) assert converted == [ - {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long": 67890, "list": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long": 67890, + "list": [], + "literal": "lit_one", + "any": "any", + }, ] @@ -43,7 +79,9 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) assert converted == { "string": "string", @@ -55,12 +93,16 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: def test_convert_and_respect_annotation_metadata_in_union() -> None: - converted = convert_and_respect_annotation_metadata(object_=UNION_TEST, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=UNION_TEST, annotation=ShapeParams + ) assert converted == UNION_TEST_CONVERTED def test_convert_and_respect_annotation_metadata_with_empty_object() -> None: data: Any = {} - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ShapeParams + ) assert converted == data diff --git a/seed/python-sdk/examples/readme/pyproject.toml b/seed/python-sdk/examples/readme/pyproject.toml index adf3a468dac..c248e8d8f0c 100644 --- a/seed/python-sdk/examples/readme/pyproject.toml +++ b/seed/python-sdk/examples/readme/pyproject.toml @@ -43,6 +43,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/python-sdk/examples/readme/src/seed/client.py b/seed/python-sdk/examples/readme/src/seed/client.py index fa561061df4..920e3a662a9 100644 --- a/seed/python-sdk/examples/readme/src/seed/client.py +++ b/seed/python-sdk/examples/readme/src/seed/client.py @@ -1,18 +1,20 @@ # This file was auto-generated by Fern from our API Definition. import typing -from json.decoder import JSONDecodeError - +from .environment import SeedExamplesEnvironment import httpx - -from .core.api_error import ApiError -from .core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from .core.pydantic_utilities import parse_obj_as +from .core.client_wrapper import SyncClientWrapper +from .file.client import FileClient +from .health.client import HealthClient +from .service.client import ServiceClient from .core.request_options import RequestOptions -from .environment import SeedExamplesEnvironment -from .file.client import AsyncFileClient, FileClient -from .health.client import AsyncHealthClient, HealthClient -from .service.client import AsyncServiceClient, ServiceClient +from .core.pydantic_utilities import parse_obj_as +from json.decoder import JSONDecodeError +from .core.api_error import ApiError +from .core.client_wrapper import AsyncClientWrapper +from .file.client import AsyncFileClient +from .health.client import AsyncHealthClient +from .service.client import AsyncServiceClient # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -59,15 +61,19 @@ def __init__( token: typing.Optional[typing.Union[str, typing.Callable[[], str]]] = None, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.Client] = None + httpx_client: typing.Optional[httpx.Client] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = SyncClientWrapper( base_url=_get_base_url(base_url=base_url, environment=environment), token=token, httpx_client=httpx_client if httpx_client is not None - else httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.Client( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.Client(timeout=_defaulted_timeout), timeout=_defaulted_timeout, @@ -76,7 +82,9 @@ def __init__( self.health = HealthClient(client_wrapper=self._client_wrapper) self.service = ServiceClient(client_wrapper=self._client_wrapper) - def echo(self, *, request: str, request_options: typing.Optional[RequestOptions] = None) -> str: + def echo( + self, *, request: str, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -103,11 +111,16 @@ def echo(self, *, request: str, request_options: typing.Optional[RequestOptions] ) """ _response = self._client_wrapper.httpx_client.request( - method="POST", json=request, request_options=request_options, omit=OMIT + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -155,15 +168,19 @@ def __init__( token: typing.Optional[typing.Union[str, typing.Callable[[], str]]] = None, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.AsyncClient] = None + httpx_client: typing.Optional[httpx.AsyncClient] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = AsyncClientWrapper( base_url=_get_base_url(base_url=base_url, environment=environment), token=token, httpx_client=httpx_client if httpx_client is not None - else httpx.AsyncClient(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.AsyncClient( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.AsyncClient(timeout=_defaulted_timeout), timeout=_defaulted_timeout, @@ -172,7 +189,9 @@ def __init__( self.health = AsyncHealthClient(client_wrapper=self._client_wrapper) self.service = AsyncServiceClient(client_wrapper=self._client_wrapper) - async def echo(self, *, request: str, request_options: typing.Optional[RequestOptions] = None) -> str: + async def echo( + self, *, request: str, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -207,11 +226,16 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - method="POST", json=request, request_options=request_options, omit=OMIT + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -219,11 +243,15 @@ async def main() -> None: def _get_base_url( - *, base_url: typing.Optional[str] = None, environment: typing.Optional[SeedExamplesEnvironment] = None + *, + base_url: typing.Optional[str] = None, + environment: typing.Optional[SeedExamplesEnvironment] = None, ) -> str: if base_url is not None: return base_url elif environment is not None: return environment.value else: - raise Exception("Please pass in either base_url or environment to construct the client") + raise Exception( + "Please pass in either base_url or environment to construct the client" + ) diff --git a/seed/python-sdk/examples/readme/src/seed/commons/__init__.py b/seed/python-sdk/examples/readme/src/seed/commons/__init__.py index 1d968e36800..03f39303b3d 100644 --- a/seed/python-sdk/examples/readme/src/seed/commons/__init__.py +++ b/seed/python-sdk/examples/readme/src/seed/commons/__init__.py @@ -1,6 +1,15 @@ # This file was auto-generated by Fern from our API Definition. -from .types import Data, Data_Base64, Data_String, EventInfo, EventInfo_Metadata, EventInfo_Tag, Metadata, Tag +from .types import ( + Data, + Data_Base64, + Data_String, + EventInfo, + EventInfo_Metadata, + EventInfo_Tag, + Metadata, + Tag, +) from . import types __all__ = [ diff --git a/seed/python-sdk/examples/readme/src/seed/commons/types/__init__.py b/seed/python-sdk/examples/readme/src/seed/commons/types/__init__.py index 319c40f2c26..bddae54aee3 100644 --- a/seed/python-sdk/examples/readme/src/seed/commons/types/__init__.py +++ b/seed/python-sdk/examples/readme/src/seed/commons/types/__init__.py @@ -1,5 +1,23 @@ # This file was auto-generated by Fern from our API Definition. -from .types import Data, Data_Base64, Data_String, EventInfo, EventInfo_Metadata, EventInfo_Tag, Metadata, Tag +from .types import ( + Data, + Data_Base64, + Data_String, + EventInfo, + EventInfo_Metadata, + EventInfo_Tag, + Metadata, + Tag, +) -__all__ = ["Data", "Data_Base64", "Data_String", "EventInfo", "EventInfo_Metadata", "EventInfo_Tag", "Metadata", "Tag"] +__all__ = [ + "Data", + "Data_Base64", + "Data_String", + "EventInfo", + "EventInfo_Metadata", + "EventInfo_Tag", + "Metadata", + "Tag", +] diff --git a/seed/python-sdk/examples/readme/src/seed/commons/types/types/__init__.py b/seed/python-sdk/examples/readme/src/seed/commons/types/types/__init__.py index a73f9e83b6c..9c78512dba5 100644 --- a/seed/python-sdk/examples/readme/src/seed/commons/types/types/__init__.py +++ b/seed/python-sdk/examples/readme/src/seed/commons/types/types/__init__.py @@ -5,4 +5,13 @@ from .metadata import Metadata from .tag import Tag -__all__ = ["Data", "Data_Base64", "Data_String", "EventInfo", "EventInfo_Metadata", "EventInfo_Tag", "Metadata", "Tag"] +__all__ = [ + "Data", + "Data_Base64", + "Data_String", + "EventInfo", + "EventInfo_Metadata", + "EventInfo_Tag", + "Metadata", + "Tag", +] diff --git a/seed/python-sdk/examples/readme/src/seed/commons/types/types/data.py b/seed/python-sdk/examples/readme/src/seed/commons/types/types/data.py index a2e7f693004..c491904b237 100644 --- a/seed/python-sdk/examples/readme/src/seed/commons/types/types/data.py +++ b/seed/python-sdk/examples/readme/src/seed/commons/types/types/data.py @@ -1,20 +1,20 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ....core.pydantic_utilities import UniversalBaseModel import typing - +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class Data_String(UniversalBaseModel): value: str type: typing.Literal["string"] = "string" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + frozen=True + ) # type: ignore # Pydantic v2 else: class Config: @@ -27,7 +27,9 @@ class Data_Base64(UniversalBaseModel): type: typing.Literal["base64"] = "base64" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/examples/readme/src/seed/commons/types/types/event_info.py b/seed/python-sdk/examples/readme/src/seed/commons/types/types/event_info.py index 1ec20f1861f..3e3e4d96864 100644 --- a/seed/python-sdk/examples/readme/src/seed/commons/types/types/event_info.py +++ b/seed/python-sdk/examples/readme/src/seed/commons/types/types/event_info.py @@ -1,12 +1,10 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ....core.pydantic_utilities import UniversalBaseModel import typing - import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 from .tag import Tag @@ -29,7 +27,9 @@ class EventInfo_Metadata(UniversalBaseModel): json_string: typing.Optional[str] = pydantic.Field(alias="jsonString", default=None) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: @@ -43,7 +43,9 @@ class EventInfo_Tag(UniversalBaseModel): type: typing.Literal["tag"] = "tag" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/examples/readme/src/seed/commons/types/types/metadata.py b/seed/python-sdk/examples/readme/src/seed/commons/types/types/metadata.py index a8795aa41a6..52808334881 100644 --- a/seed/python-sdk/examples/readme/src/seed/commons/types/types/metadata.py +++ b/seed/python-sdk/examples/readme/src/seed/commons/types/types/metadata.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class Metadata(UniversalBaseModel): @@ -25,7 +24,9 @@ class Metadata(UniversalBaseModel): json_string: typing.Optional[str] = pydantic.Field(alias="jsonString", default=None) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/examples/readme/src/seed/commons/types/types/tag.py b/seed/python-sdk/examples/readme/src/seed/commons/types/types/tag.py index ae576888232..ad97a39db4c 100644 --- a/seed/python-sdk/examples/readme/src/seed/commons/types/types/tag.py +++ b/seed/python-sdk/examples/readme/src/seed/commons/types/types/tag.py @@ -3,4 +3,5 @@ """ "tag-wf9as23d" """ + Tag = str diff --git a/seed/python-sdk/examples/readme/src/seed/core/api_error.py b/seed/python-sdk/examples/readme/src/seed/core/api_error.py index 2e9fc5431cd..da734b58068 100644 --- a/seed/python-sdk/examples/readme/src/seed/core/api_error.py +++ b/seed/python-sdk/examples/readme/src/seed/core/api_error.py @@ -7,7 +7,9 @@ class ApiError(Exception): status_code: typing.Optional[int] body: typing.Any - def __init__(self, *, status_code: typing.Optional[int] = None, body: typing.Any = None): + def __init__( + self, *, status_code: typing.Optional[int] = None, body: typing.Any = None + ): self.status_code = status_code self.body = body diff --git a/seed/python-sdk/examples/readme/src/seed/core/client_wrapper.py b/seed/python-sdk/examples/readme/src/seed/core/client_wrapper.py index ef78d78ed99..88e5016aa3f 100644 --- a/seed/python-sdk/examples/readme/src/seed/core/client_wrapper.py +++ b/seed/python-sdk/examples/readme/src/seed/core/client_wrapper.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .http_client import AsyncHttpClient, HttpClient +from .http_client import HttpClient +from .http_client import AsyncHttpClient class BaseClientWrapper: diff --git a/seed/python-sdk/examples/readme/src/seed/core/datetime_utils.py b/seed/python-sdk/examples/readme/src/seed/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/python-sdk/examples/readme/src/seed/core/datetime_utils.py +++ b/seed/python-sdk/examples/readme/src/seed/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/python-sdk/examples/readme/src/seed/core/file.py b/seed/python-sdk/examples/readme/src/seed/core/file.py index cb0d40bbbf3..6e0f92bfcb1 100644 --- a/seed/python-sdk/examples/readme/src/seed/core/file.py +++ b/seed/python-sdk/examples/readme/src/seed/core/file.py @@ -13,12 +13,17 @@ # (filename, file (or bytes), content_type) typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str]], # (filename, file (or bytes), content_type, headers) - typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str], typing.Mapping[str, str]], + typing.Tuple[ + typing.Optional[str], + FileContent, + typing.Optional[str], + typing.Mapping[str, str], + ], ] def convert_file_dict_to_httpx_tuples( - d: typing.Dict[str, typing.Union[File, typing.List[File]]] + d: typing.Dict[str, typing.Union[File, typing.List[File]]], ) -> typing.List[typing.Tuple[str, File]]: """ The format we use is a list of tuples, where the first element is the diff --git a/seed/python-sdk/examples/readme/src/seed/core/http_client.py b/seed/python-sdk/examples/readme/src/seed/core/http_client.py index 9333d8a7f15..091f71bc185 100644 --- a/seed/python-sdk/examples/readme/src/seed/core/http_client.py +++ b/seed/python-sdk/examples/readme/src/seed/core/http_client.py @@ -77,7 +77,9 @@ def _retry_timeout(response: httpx.Response, retries: int) -> float: return retry_after # Apply exponential backoff, capped at MAX_RETRY_DELAY_SECONDS. - retry_delay = min(INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS) + retry_delay = min( + INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS + ) # Add a randomness / jitter to the retry delay to avoid overwhelming the server with retries. timeout = retry_delay * (1 - 0.25 * random()) @@ -90,7 +92,8 @@ def _should_retry(response: httpx.Response) -> bool: def remove_omit_from_dict( - original: typing.Dict[str, typing.Optional[typing.Any]], omit: typing.Optional[typing.Any] + original: typing.Dict[str, typing.Optional[typing.Any]], + omit: typing.Optional[typing.Any], ) -> typing.Dict[str, typing.Any]: if omit is None: return original @@ -108,7 +111,8 @@ def maybe_filter_request_body( ) -> typing.Optional[typing.Any]: if data is None: return ( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else None ) @@ -118,7 +122,8 @@ def maybe_filter_request_body( data_content = { **(jsonable_encoder(remove_omit_from_dict(data, omit))), # type: ignore **( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else {} ), @@ -162,7 +167,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url def request( @@ -174,8 +181,12 @@ def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -184,11 +195,14 @@ def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) response = self.httpx_client.request( method=method, @@ -198,7 +212,11 @@ def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -209,7 +227,10 @@ def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -222,11 +243,15 @@ def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: time.sleep(_retry_timeout(response=response, retries=retries)) @@ -256,8 +281,12 @@ def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -266,11 +295,14 @@ def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) with self.httpx_client.stream( method=method, @@ -280,7 +312,11 @@ def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -291,7 +327,9 @@ def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -304,7 +342,9 @@ def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream @@ -327,7 +367,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url async def request( @@ -339,8 +381,12 @@ async def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -349,11 +395,14 @@ async def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) # Add the input to each of these and do None-safety checks response = await self.httpx_client.request( @@ -364,7 +413,11 @@ async def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -375,7 +428,10 @@ async def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -388,11 +444,15 @@ async def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: await asyncio.sleep(_retry_timeout(response=response, retries=retries)) @@ -421,8 +481,12 @@ async def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -431,11 +495,14 @@ async def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) async with self.httpx_client.stream( method=method, @@ -445,7 +512,11 @@ async def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -456,7 +527,9 @@ async def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -469,7 +542,9 @@ async def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream diff --git a/seed/python-sdk/examples/readme/src/seed/core/jsonable_encoder.py b/seed/python-sdk/examples/readme/src/seed/core/jsonable_encoder.py index d3fd328fd41..12a8b52fc22 100644 --- a/seed/python-sdk/examples/readme/src/seed/core/jsonable_encoder.py +++ b/seed/python-sdk/examples/readme/src/seed/core/jsonable_encoder.py @@ -19,13 +19,19 @@ import pydantic from .datetime_utils import serialize_datetime -from .pydantic_utilities import IS_PYDANTIC_V2, encode_by_type, to_jsonable_with_fallback +from .pydantic_utilities import ( + IS_PYDANTIC_V2, + encode_by_type, + to_jsonable_with_fallback, +) SetIntStr = Set[Union[int, str]] DictIntStrAny = Dict[Union[int, str], Any] -def jsonable_encoder(obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None) -> Any: +def jsonable_encoder( + obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None +) -> Any: custom_encoder = custom_encoder or {} if custom_encoder: if type(obj) in custom_encoder: diff --git a/seed/python-sdk/examples/readme/src/seed/core/pydantic_utilities.py b/seed/python-sdk/examples/readme/src/seed/core/pydantic_utilities.py index 170a563d6eb..c63935c32a2 100644 --- a/seed/python-sdk/examples/readme/src/seed/core/pydantic_utilities.py +++ b/seed/python-sdk/examples/readme/src/seed/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) # type: ignore # Pydantic v1 diff --git a/seed/python-sdk/examples/readme/src/seed/core/query_encoder.py b/seed/python-sdk/examples/readme/src/seed/core/query_encoder.py index 24076d72ee9..7cb98f52cd7 100644 --- a/seed/python-sdk/examples/readme/src/seed/core/query_encoder.py +++ b/seed/python-sdk/examples/readme/src/seed/core/query_encoder.py @@ -7,7 +7,9 @@ # Flattens dicts to be of the form {"key[subkey][subkey2]": value} where value is not a dict -def traverse_query_dict(dict_flat: Dict[str, Any], key_prefix: Optional[str] = None) -> Dict[str, Any]: +def traverse_query_dict( + dict_flat: Dict[str, Any], key_prefix: Optional[str] = None +) -> Dict[str, Any]: result = {} for k, v in dict_flat.items(): key = f"{key_prefix}[{k}]" if key_prefix is not None else k @@ -30,4 +32,8 @@ def single_query_encoder(query_key: str, query_value: Any) -> Dict[str, Any]: def encode_query(query: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: - return dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) if query is not None else None + return ( + dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) + if query is not None + else None + ) diff --git a/seed/python-sdk/examples/readme/src/seed/core/serialization.py b/seed/python-sdk/examples/readme/src/seed/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/python-sdk/examples/readme/src/seed/core/serialization.py +++ b/seed/python-sdk/examples/readme/src/seed/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/python-sdk/examples/readme/src/seed/file/client.py b/seed/python-sdk/examples/readme/src/seed/file/client.py index 81bb5dc7923..b6004e87af6 100644 --- a/seed/python-sdk/examples/readme/src/seed/file/client.py +++ b/seed/python-sdk/examples/readme/src/seed/file/client.py @@ -1,8 +1,11 @@ # This file was auto-generated by Fern from our API Definition. -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from .notification.client import AsyncNotificationClient, NotificationClient -from .service.client import AsyncServiceClient, ServiceClient +from ..core.client_wrapper import SyncClientWrapper +from .notification.client import NotificationClient +from .service.client import ServiceClient +from ..core.client_wrapper import AsyncClientWrapper +from .notification.client import AsyncNotificationClient +from .service.client import AsyncServiceClient class FileClient: diff --git a/seed/python-sdk/examples/readme/src/seed/file/notification/client.py b/seed/python-sdk/examples/readme/src/seed/file/notification/client.py index e8077a84043..7ecd8bc9048 100644 --- a/seed/python-sdk/examples/readme/src/seed/file/notification/client.py +++ b/seed/python-sdk/examples/readme/src/seed/file/notification/client.py @@ -1,7 +1,9 @@ # This file was auto-generated by Fern from our API Definition. -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from .service.client import AsyncServiceClient, ServiceClient +from ...core.client_wrapper import SyncClientWrapper +from .service.client import ServiceClient +from ...core.client_wrapper import AsyncClientWrapper +from .service.client import AsyncServiceClient class NotificationClient: diff --git a/seed/python-sdk/examples/readme/src/seed/file/notification/service/client.py b/seed/python-sdk/examples/readme/src/seed/file/notification/service/client.py index 3f4653f18c3..094ca0c7538 100644 --- a/seed/python-sdk/examples/readme/src/seed/file/notification/service/client.py +++ b/seed/python-sdk/examples/readme/src/seed/file/notification/service/client.py @@ -1,14 +1,14 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.client_wrapper import SyncClientWrapper import typing -from json.decoder import JSONDecodeError - -from ....core.api_error import ApiError -from ....core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ....core.jsonable_encoder import jsonable_encoder -from ....core.pydantic_utilities import parse_obj_as from ....core.request_options import RequestOptions from ....types.types.exception import Exception +from ....core.jsonable_encoder import jsonable_encoder +from ....core.pydantic_utilities import parse_obj_as +from json.decoder import JSONDecodeError +from ....core.api_error import ApiError +from ....core.client_wrapper import AsyncClientWrapper class ServiceClient: @@ -16,7 +16,10 @@ def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper def get_exception( - self, notification_id: str, *, request_options: typing.Optional[RequestOptions] = None + self, + notification_id: str, + *, + request_options: typing.Optional[RequestOptions] = None, ) -> Exception: """ Parameters @@ -44,11 +47,15 @@ def get_exception( ) """ _response = self._client_wrapper.httpx_client.request( - f"file/notification/{jsonable_encoder(notification_id)}", method="GET", request_options=request_options + f"file/notification/{jsonable_encoder(notification_id)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(Exception, parse_obj_as(type_=Exception, object_=_response.json())) # type: ignore + return typing.cast( + Exception, parse_obj_as(type_=Exception, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -60,7 +67,10 @@ def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper async def get_exception( - self, notification_id: str, *, request_options: typing.Optional[RequestOptions] = None + self, + notification_id: str, + *, + request_options: typing.Optional[RequestOptions] = None, ) -> Exception: """ Parameters @@ -96,11 +106,15 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - f"file/notification/{jsonable_encoder(notification_id)}", method="GET", request_options=request_options + f"file/notification/{jsonable_encoder(notification_id)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(Exception, parse_obj_as(type_=Exception, object_=_response.json())) # type: ignore + return typing.cast( + Exception, parse_obj_as(type_=Exception, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/examples/readme/src/seed/file/service/client.py b/seed/python-sdk/examples/readme/src/seed/file/service/client.py index a211630dbaa..f262f07ece9 100644 --- a/seed/python-sdk/examples/readme/src/seed/file/service/client.py +++ b/seed/python-sdk/examples/readme/src/seed/file/service/client.py @@ -1,15 +1,15 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.client_wrapper import SyncClientWrapper import typing -from json.decoder import JSONDecodeError - -from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper +from ...core.request_options import RequestOptions +from ...types.types.file import File from ...core.jsonable_encoder import jsonable_encoder from ...core.pydantic_utilities import parse_obj_as -from ...core.request_options import RequestOptions from ...types.errors.not_found_error import NotFoundError -from ...types.types.file import File +from json.decoder import JSONDecodeError +from ...core.api_error import ApiError +from ...core.client_wrapper import AsyncClientWrapper class ServiceClient: @@ -17,7 +17,11 @@ def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper def get_file( - self, filename: str, *, x_file_api_version: str, request_options: typing.Optional[RequestOptions] = None + self, + filename: str, + *, + x_file_api_version: str, + request_options: typing.Optional[RequestOptions] = None, ) -> File: """ This endpoint returns a file by its name. @@ -53,14 +57,22 @@ def get_file( _response = self._client_wrapper.httpx_client.request( f"file/{jsonable_encoder(filename)}", method="GET", - headers={"X-File-API-Version": str(x_file_api_version) if x_file_api_version is not None else None}, + headers={ + "X-File-API-Version": str(x_file_api_version) + if x_file_api_version is not None + else None, + }, request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(File, parse_obj_as(type_=File, object_=_response.json())) # type: ignore + return typing.cast( + File, parse_obj_as(type_=File, object_=_response.json()) + ) # type: ignore if _response.status_code == 404: - raise NotFoundError(typing.cast(str, parse_obj_as(type_=str, object_=_response.json()))) # type: ignore + raise NotFoundError( + typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + ) _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -72,7 +84,11 @@ def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper async def get_file( - self, filename: str, *, x_file_api_version: str, request_options: typing.Optional[RequestOptions] = None + self, + filename: str, + *, + x_file_api_version: str, + request_options: typing.Optional[RequestOptions] = None, ) -> File: """ This endpoint returns a file by its name. @@ -116,14 +132,22 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( f"file/{jsonable_encoder(filename)}", method="GET", - headers={"X-File-API-Version": str(x_file_api_version) if x_file_api_version is not None else None}, + headers={ + "X-File-API-Version": str(x_file_api_version) + if x_file_api_version is not None + else None, + }, request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(File, parse_obj_as(type_=File, object_=_response.json())) # type: ignore + return typing.cast( + File, parse_obj_as(type_=File, object_=_response.json()) + ) # type: ignore if _response.status_code == 404: - raise NotFoundError(typing.cast(str, parse_obj_as(type_=str, object_=_response.json()))) # type: ignore + raise NotFoundError( + typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + ) _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/examples/readme/src/seed/file/service/types/filename.py b/seed/python-sdk/examples/readme/src/seed/file/service/types/filename.py index add91706b10..2531edee925 100644 --- a/seed/python-sdk/examples/readme/src/seed/file/service/types/filename.py +++ b/seed/python-sdk/examples/readme/src/seed/file/service/types/filename.py @@ -3,4 +3,5 @@ """ "file.txt" """ + Filename = str diff --git a/seed/python-sdk/examples/readme/src/seed/health/client.py b/seed/python-sdk/examples/readme/src/seed/health/client.py index a17be0c2502..d55aad7cbe9 100644 --- a/seed/python-sdk/examples/readme/src/seed/health/client.py +++ b/seed/python-sdk/examples/readme/src/seed/health/client.py @@ -1,7 +1,9 @@ # This file was auto-generated by Fern from our API Definition. -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from .service.client import AsyncServiceClient, ServiceClient +from ..core.client_wrapper import SyncClientWrapper +from .service.client import ServiceClient +from ..core.client_wrapper import AsyncClientWrapper +from .service.client import AsyncServiceClient class HealthClient: diff --git a/seed/python-sdk/examples/readme/src/seed/health/service/client.py b/seed/python-sdk/examples/readme/src/seed/health/service/client.py index ad81b2f5b83..fb380badd43 100644 --- a/seed/python-sdk/examples/readme/src/seed/health/service/client.py +++ b/seed/python-sdk/examples/readme/src/seed/health/service/client.py @@ -1,20 +1,22 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.client_wrapper import SyncClientWrapper import typing +from ...core.request_options import RequestOptions +from ...core.jsonable_encoder import jsonable_encoder from json.decoder import JSONDecodeError - from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ...core.jsonable_encoder import jsonable_encoder from ...core.pydantic_utilities import parse_obj_as -from ...core.request_options import RequestOptions +from ...core.client_wrapper import AsyncClientWrapper class ServiceClient: def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper - def check(self, id: str, *, request_options: typing.Optional[RequestOptions] = None) -> None: + def check( + self, id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> None: """ This endpoint checks the health of a resource. @@ -44,7 +46,9 @@ def check(self, id: str, *, request_options: typing.Optional[RequestOptions] = N ) """ _response = self._client_wrapper.httpx_client.request( - f"check/{jsonable_encoder(id)}", method="GET", request_options=request_options + f"check/{jsonable_encoder(id)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: @@ -78,10 +82,16 @@ def ping(self, *, request_options: typing.Optional[RequestOptions] = None) -> bo ) client.health.service.ping() """ - _response = self._client_wrapper.httpx_client.request("ping", method="GET", request_options=request_options) + _response = self._client_wrapper.httpx_client.request( + "ping", + method="GET", + request_options=request_options, + ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -92,7 +102,9 @@ class AsyncServiceClient: def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper - async def check(self, id: str, *, request_options: typing.Optional[RequestOptions] = None) -> None: + async def check( + self, id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> None: """ This endpoint checks the health of a resource. @@ -130,7 +142,9 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - f"check/{jsonable_encoder(id)}", method="GET", request_options=request_options + f"check/{jsonable_encoder(id)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: @@ -140,7 +154,9 @@ async def main() -> None: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - async def ping(self, *, request_options: typing.Optional[RequestOptions] = None) -> bool: + async def ping( + self, *, request_options: typing.Optional[RequestOptions] = None + ) -> bool: """ This endpoint checks the health of the service. @@ -173,11 +189,15 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "ping", method="GET", request_options=request_options + "ping", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/examples/readme/src/seed/service/client.py b/seed/python-sdk/examples/readme/src/seed/service/client.py index 15cb1fc5d1e..45317ff71a0 100644 --- a/seed/python-sdk/examples/readme/src/seed/service/client.py +++ b/seed/python-sdk/examples/readme/src/seed/service/client.py @@ -1,18 +1,18 @@ # This file was auto-generated by Fern from our API Definition. import typing -from json.decoder import JSONDecodeError - -from ..commons.types.types.tag import Tag -from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper +from ..core.client_wrapper import SyncClientWrapper +from ..types.types.movie_id import MovieId +from ..core.request_options import RequestOptions +from ..types.types.movie import Movie from ..core.jsonable_encoder import jsonable_encoder from ..core.pydantic_utilities import parse_obj_as -from ..core.request_options import RequestOptions +from json.decoder import JSONDecodeError +from ..core.api_error import ApiError +from ..commons.types.types.tag import Tag from ..types.types.metadata import Metadata -from ..types.types.movie import Movie -from ..types.types.movie_id import MovieId from ..types.types.response import Response +from ..core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -22,7 +22,12 @@ class ServiceClient: def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper - def get_movie(self, movie_id: MovieId, *, request_options: typing.Optional[RequestOptions] = None) -> Movie: + def get_movie( + self, + movie_id: MovieId, + *, + request_options: typing.Optional[RequestOptions] = None, + ) -> Movie: """ Parameters ---------- @@ -49,11 +54,15 @@ def get_movie(self, movie_id: MovieId, *, request_options: typing.Optional[Reque ) """ _response = self._client_wrapper.httpx_client.request( - f"movie/{jsonable_encoder(movie_id)}", method="GET", request_options=request_options + f"movie/{jsonable_encoder(movie_id)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(Movie, parse_obj_as(type_=Movie, object_=_response.json())) # type: ignore + return typing.cast( + Movie, parse_obj_as(type_=Movie, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -141,7 +150,9 @@ def create_movie( ) try: if 200 <= _response.status_code < 300: - return typing.cast(MovieId, parse_obj_as(type_=MovieId, object_=_response.json())) # type: ignore + return typing.cast( + MovieId, parse_obj_as(type_=MovieId, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -189,19 +200,30 @@ def get_metadata( _response = self._client_wrapper.httpx_client.request( "metadata", method="GET", - params={"shallow": shallow, "tag": tag}, - headers={"X-API-Version": str(x_api_version) if x_api_version is not None else None}, + params={ + "shallow": shallow, + "tag": tag, + }, + headers={ + "X-API-Version": str(x_api_version) + if x_api_version is not None + else None, + }, request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(Metadata, parse_obj_as(type_=Metadata, object_=_response.json())) # type: ignore + return typing.cast( + Metadata, parse_obj_as(type_=Metadata, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def get_response(self, *, request_options: typing.Optional[RequestOptions] = None) -> Response: + def get_response( + self, *, request_options: typing.Optional[RequestOptions] = None + ) -> Response: """ Parameters ---------- @@ -224,11 +246,15 @@ def get_response(self, *, request_options: typing.Optional[RequestOptions] = Non client.service.get_response() """ _response = self._client_wrapper.httpx_client.request( - "response", method="POST", request_options=request_options + "response", + method="POST", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(Response, parse_obj_as(type_=Response, object_=_response.json())) # type: ignore + return typing.cast( + Response, parse_obj_as(type_=Response, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -239,7 +265,12 @@ class AsyncServiceClient: def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper - async def get_movie(self, movie_id: MovieId, *, request_options: typing.Optional[RequestOptions] = None) -> Movie: + async def get_movie( + self, + movie_id: MovieId, + *, + request_options: typing.Optional[RequestOptions] = None, + ) -> Movie: """ Parameters ---------- @@ -274,11 +305,15 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - f"movie/{jsonable_encoder(movie_id)}", method="GET", request_options=request_options + f"movie/{jsonable_encoder(movie_id)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(Movie, parse_obj_as(type_=Movie, object_=_response.json())) # type: ignore + return typing.cast( + Movie, parse_obj_as(type_=Movie, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -374,7 +409,9 @@ async def main() -> None: ) try: if 200 <= _response.status_code < 300: - return typing.cast(MovieId, parse_obj_as(type_=MovieId, object_=_response.json())) # type: ignore + return typing.cast( + MovieId, parse_obj_as(type_=MovieId, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -430,19 +467,30 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( "metadata", method="GET", - params={"shallow": shallow, "tag": tag}, - headers={"X-API-Version": str(x_api_version) if x_api_version is not None else None}, + params={ + "shallow": shallow, + "tag": tag, + }, + headers={ + "X-API-Version": str(x_api_version) + if x_api_version is not None + else None, + }, request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(Metadata, parse_obj_as(type_=Metadata, object_=_response.json())) # type: ignore + return typing.cast( + Metadata, parse_obj_as(type_=Metadata, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - async def get_response(self, *, request_options: typing.Optional[RequestOptions] = None) -> Response: + async def get_response( + self, *, request_options: typing.Optional[RequestOptions] = None + ) -> Response: """ Parameters ---------- @@ -473,11 +521,15 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "response", method="POST", request_options=request_options + "response", + method="POST", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(Response, parse_obj_as(type_=Response, object_=_response.json())) # type: ignore + return typing.cast( + Response, parse_obj_as(type_=Response, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/examples/readme/src/seed/types/identifier.py b/seed/python-sdk/examples/readme/src/seed/types/identifier.py index ae9367a447c..f6ff0a9818b 100644 --- a/seed/python-sdk/examples/readme/src/seed/types/identifier.py +++ b/seed/python-sdk/examples/readme/src/seed/types/identifier.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. +from ..core.pydantic_utilities import UniversalBaseModel +from .type import Type +from ..core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .type import Type - class Identifier(UniversalBaseModel): type: Type @@ -14,7 +13,9 @@ class Identifier(UniversalBaseModel): label: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/examples/readme/src/seed/types/type.py b/seed/python-sdk/examples/readme/src/seed/types/type.py index 09d1c916dfd..e77e5e18b15 100644 --- a/seed/python-sdk/examples/readme/src/seed/types/type.py +++ b/seed/python-sdk/examples/readme/src/seed/types/type.py @@ -1,7 +1,6 @@ # This file was auto-generated by Fern from our API Definition. import typing - from .basic_type import BasicType from .complex_type import ComplexType diff --git a/seed/python-sdk/examples/readme/src/seed/types/types/actor.py b/seed/python-sdk/examples/readme/src/seed/types/types/actor.py index 0838e363001..7808438f935 100644 --- a/seed/python-sdk/examples/readme/src/seed/types/types/actor.py +++ b/seed/python-sdk/examples/readme/src/seed/types/types/actor.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class Actor(UniversalBaseModel): name: str id: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/examples/readme/src/seed/types/types/actress.py b/seed/python-sdk/examples/readme/src/seed/types/types/actress.py index 607abb7e0e3..9f6f48e855d 100644 --- a/seed/python-sdk/examples/readme/src/seed/types/types/actress.py +++ b/seed/python-sdk/examples/readme/src/seed/types/types/actress.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class Actress(UniversalBaseModel): """ @@ -23,7 +22,9 @@ class Actress(UniversalBaseModel): id: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/examples/readme/src/seed/types/types/cast_member.py b/seed/python-sdk/examples/readme/src/seed/types/types/cast_member.py index d73c89864e1..8be1a0b0a2a 100644 --- a/seed/python-sdk/examples/readme/src/seed/types/types/cast_member.py +++ b/seed/python-sdk/examples/readme/src/seed/types/types/cast_member.py @@ -1,7 +1,6 @@ # This file was auto-generated by Fern from our API Definition. import typing - from .actor import Actor from .actress import Actress from .stunt_double import StuntDouble diff --git a/seed/python-sdk/examples/readme/src/seed/types/types/directory.py b/seed/python-sdk/examples/readme/src/seed/types/types/directory.py index 92d8efa9c38..049ed2f2cd5 100644 --- a/seed/python-sdk/examples/readme/src/seed/types/types/directory.py +++ b/seed/python-sdk/examples/readme/src/seed/types/types/directory.py @@ -1,13 +1,12 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ...core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel, update_forward_refs from .file import File +from ...core.pydantic_utilities import IS_PYDANTIC_V2 +import pydantic +from ...core.pydantic_utilities import update_forward_refs class Directory(UniversalBaseModel): @@ -43,7 +42,9 @@ class Directory(UniversalBaseModel): directories: typing.Optional[typing.List[Directory]] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/examples/readme/src/seed/types/types/entity.py b/seed/python-sdk/examples/readme/src/seed/types/types/entity.py index e6500e2af7d..3c5b7349621 100644 --- a/seed/python-sdk/examples/readme/src/seed/types/types/entity.py +++ b/seed/python-sdk/examples/readme/src/seed/types/types/entity.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ..type import Type +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from ..type import Type - class Entity(UniversalBaseModel): """ @@ -24,7 +23,9 @@ class Entity(UniversalBaseModel): name: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/examples/readme/src/seed/types/types/exception.py b/seed/python-sdk/examples/readme/src/seed/types/types/exception.py index 851835745bd..a61252d9fc4 100644 --- a/seed/python-sdk/examples/readme/src/seed/types/types/exception.py +++ b/seed/python-sdk/examples/readme/src/seed/types/types/exception.py @@ -1,12 +1,10 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ...core.pydantic_utilities import UniversalBaseModel import typing - import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 class Exception_Generic(UniversalBaseModel): @@ -28,7 +26,9 @@ class Exception_Generic(UniversalBaseModel): exception_stacktrace: str = pydantic.Field(alias="exceptionStacktrace") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: @@ -53,7 +53,9 @@ class Exception_Timeout(UniversalBaseModel): type: typing.Literal["timeout"] = "timeout" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/examples/readme/src/seed/types/types/exception_info.py b/seed/python-sdk/examples/readme/src/seed/types/types/exception_info.py index 2d902a51d05..220ddb6a0c7 100644 --- a/seed/python-sdk/examples/readme/src/seed/types/types/exception_info.py +++ b/seed/python-sdk/examples/readme/src/seed/types/types/exception_info.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ...core.pydantic_utilities import UniversalBaseModel import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class ExceptionInfo(UniversalBaseModel): @@ -25,7 +24,9 @@ class ExceptionInfo(UniversalBaseModel): exception_stacktrace: str = pydantic.Field(alias="exceptionStacktrace") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/examples/readme/src/seed/types/types/extended_movie.py b/seed/python-sdk/examples/readme/src/seed/types/types/extended_movie.py index 41d92df7718..8b48ecddcbe 100644 --- a/seed/python-sdk/examples/readme/src/seed/types/types/extended_movie.py +++ b/seed/python-sdk/examples/readme/src/seed/types/types/extended_movie.py @@ -1,11 +1,9 @@ # This file was auto-generated by Fern from our API Definition. +from .movie import Movie import typing - -import pydantic - from ...core.pydantic_utilities import IS_PYDANTIC_V2 -from .movie import Movie +import pydantic class ExtendedMovie(Movie): @@ -32,7 +30,9 @@ class ExtendedMovie(Movie): cast: typing.List[str] if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/examples/readme/src/seed/types/types/file.py b/seed/python-sdk/examples/readme/src/seed/types/types/file.py index 9103c9ec9c6..af2112c9a3d 100644 --- a/seed/python-sdk/examples/readme/src/seed/types/types/file.py +++ b/seed/python-sdk/examples/readme/src/seed/types/types/file.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class File(UniversalBaseModel): """ @@ -23,7 +22,9 @@ class File(UniversalBaseModel): contents: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/examples/readme/src/seed/types/types/metadata.py b/seed/python-sdk/examples/readme/src/seed/types/types/metadata.py index 924c6e5a00b..9081aa0b389 100644 --- a/seed/python-sdk/examples/readme/src/seed/types/types/metadata.py +++ b/seed/python-sdk/examples/readme/src/seed/types/types/metadata.py @@ -1,13 +1,11 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ...core.pydantic_utilities import UniversalBaseModel import typing - +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class Base(UniversalBaseModel): """ @@ -22,7 +20,9 @@ class Base(UniversalBaseModel): tags: typing.Set[str] if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: @@ -36,7 +36,9 @@ class Metadata_Html(Base): type: typing.Literal["html"] = "html" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + frozen=True + ) # type: ignore # Pydantic v2 else: class Config: @@ -49,7 +51,9 @@ class Metadata_Markdown(Base): type: typing.Literal["markdown"] = "markdown" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/examples/readme/src/seed/types/types/migration.py b/seed/python-sdk/examples/readme/src/seed/types/types/migration.py index 68f4d579dea..eb6cd3736bd 100644 --- a/seed/python-sdk/examples/readme/src/seed/types/types/migration.py +++ b/seed/python-sdk/examples/readme/src/seed/types/types/migration.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from .migration_status import MigrationStatus +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .migration_status import MigrationStatus - class Migration(UniversalBaseModel): """ @@ -24,7 +23,9 @@ class Migration(UniversalBaseModel): status: MigrationStatus if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/examples/readme/src/seed/types/types/migration_status.py b/seed/python-sdk/examples/readme/src/seed/types/types/migration_status.py index c5a2e76b4af..e14e67e1b5a 100644 --- a/seed/python-sdk/examples/readme/src/seed/types/types/migration_status.py +++ b/seed/python-sdk/examples/readme/src/seed/types/types/migration_status.py @@ -2,4 +2,6 @@ import typing -MigrationStatus = typing.Union[typing.Literal["RUNNING", "FAILED", "FINISHED"], typing.Any] +MigrationStatus = typing.Union[ + typing.Literal["RUNNING", "FAILED", "FINISHED"], typing.Any +] diff --git a/seed/python-sdk/examples/readme/src/seed/types/types/moment.py b/seed/python-sdk/examples/readme/src/seed/types/types/moment.py index 820b4ff0e86..b344b30e496 100644 --- a/seed/python-sdk/examples/readme/src/seed/types/types/moment.py +++ b/seed/python-sdk/examples/readme/src/seed/types/types/moment.py @@ -1,13 +1,12 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +import uuid import datetime as dt +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing -import uuid - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class Moment(UniversalBaseModel): """ @@ -36,7 +35,9 @@ class Moment(UniversalBaseModel): datetime: dt.datetime if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/examples/readme/src/seed/types/types/movie.py b/seed/python-sdk/examples/readme/src/seed/types/types/movie.py index 9e67c2456ea..426206249be 100644 --- a/seed/python-sdk/examples/readme/src/seed/types/types/movie.py +++ b/seed/python-sdk/examples/readme/src/seed/types/types/movie.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from .movie_id import MovieId import typing - import pydantic - from ...commons.types.types.tag import Tag -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .movie_id import MovieId +from ...core.pydantic_utilities import IS_PYDANTIC_V2 class Movie(UniversalBaseModel): @@ -45,7 +44,9 @@ class Movie(UniversalBaseModel): metadata: typing.Dict[str, typing.Any] if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/examples/readme/src/seed/types/types/movie_id.py b/seed/python-sdk/examples/readme/src/seed/types/types/movie_id.py index 86f7a4f4651..86945f3b676 100644 --- a/seed/python-sdk/examples/readme/src/seed/types/types/movie_id.py +++ b/seed/python-sdk/examples/readme/src/seed/types/types/movie_id.py @@ -3,4 +3,5 @@ """ "movie-c06a4ad7" """ + MovieId = str diff --git a/seed/python-sdk/examples/readme/src/seed/types/types/node.py b/seed/python-sdk/examples/readme/src/seed/types/types/node.py index 77f2a5e87da..9a5f5952b59 100644 --- a/seed/python-sdk/examples/readme/src/seed/types/types/node.py +++ b/seed/python-sdk/examples/readme/src/seed/types/types/node.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ...core.pydantic_utilities import UniversalBaseModel import typing - +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel, update_forward_refs +from ...core.pydantic_utilities import update_forward_refs class Node(UniversalBaseModel): @@ -45,7 +44,9 @@ class Node(UniversalBaseModel): trees: typing.Optional[typing.List[Tree]] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/examples/readme/src/seed/types/types/request.py b/seed/python-sdk/examples/readme/src/seed/types/types/request.py index a2ff0455aa0..7649502a04c 100644 --- a/seed/python-sdk/examples/readme/src/seed/types/types/request.py +++ b/seed/python-sdk/examples/readme/src/seed/types/types/request.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel import typing - +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class Request(UniversalBaseModel): """ @@ -21,7 +20,9 @@ class Request(UniversalBaseModel): request: typing.Any if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/examples/readme/src/seed/types/types/response.py b/seed/python-sdk/examples/readme/src/seed/types/types/response.py index edcd3f24da1..d17192b48e6 100644 --- a/seed/python-sdk/examples/readme/src/seed/types/types/response.py +++ b/seed/python-sdk/examples/readme/src/seed/types/types/response.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from ..identifier import Identifier +from ...core.pydantic_utilities import IS_PYDANTIC_V2 +import pydantic class Response(UniversalBaseModel): @@ -36,7 +35,9 @@ class Response(UniversalBaseModel): identifiers: typing.List[Identifier] if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/examples/readme/src/seed/types/types/response_type.py b/seed/python-sdk/examples/readme/src/seed/types/types/response_type.py index c5777220170..8b43d297ad3 100644 --- a/seed/python-sdk/examples/readme/src/seed/types/types/response_type.py +++ b/seed/python-sdk/examples/readme/src/seed/types/types/response_type.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ..type import Type +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from ..type import Type - class ResponseType(UniversalBaseModel): type: Type if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/examples/readme/src/seed/types/types/stunt_double.py b/seed/python-sdk/examples/readme/src/seed/types/types/stunt_double.py index f2b3a81d999..f3faa0fd65b 100644 --- a/seed/python-sdk/examples/readme/src/seed/types/types/stunt_double.py +++ b/seed/python-sdk/examples/readme/src/seed/types/types/stunt_double.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ...core.pydantic_utilities import UniversalBaseModel import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class StuntDouble(UniversalBaseModel): @@ -12,7 +11,9 @@ class StuntDouble(UniversalBaseModel): actor_or_actress_id: str = pydantic.Field(alias="actorOrActressId") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/examples/readme/src/seed/types/types/test.py b/seed/python-sdk/examples/readme/src/seed/types/types/test.py index 3a0d88bb4b1..b9d6b204965 100644 --- a/seed/python-sdk/examples/readme/src/seed/types/types/test.py +++ b/seed/python-sdk/examples/readme/src/seed/types/types/test.py @@ -1,20 +1,20 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ...core.pydantic_utilities import UniversalBaseModel import typing - +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class Test_And(UniversalBaseModel): value: bool type: typing.Literal["and"] = "and" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + frozen=True + ) # type: ignore # Pydantic v2 else: class Config: @@ -27,7 +27,9 @@ class Test_Or(UniversalBaseModel): type: typing.Literal["or"] = "or" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/examples/readme/src/seed/types/types/tree.py b/seed/python-sdk/examples/readme/src/seed/types/types/tree.py index 52b70602a21..c159c5c2ee4 100644 --- a/seed/python-sdk/examples/readme/src/seed/types/types/tree.py +++ b/seed/python-sdk/examples/readme/src/seed/types/types/tree.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ...core.pydantic_utilities import UniversalBaseModel import typing - +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel, update_forward_refs +from ...core.pydantic_utilities import update_forward_refs class Tree(UniversalBaseModel): @@ -30,7 +29,9 @@ class Tree(UniversalBaseModel): nodes: typing.Optional[typing.List[Node]] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/examples/readme/src/seed/version.py b/seed/python-sdk/examples/readme/src/seed/version.py index b6f2c764388..ad7a9c63cc2 100644 --- a/seed/python-sdk/examples/readme/src/seed/version.py +++ b/seed/python-sdk/examples/readme/src/seed/version.py @@ -1,4 +1,3 @@ - from importlib import metadata __version__ = metadata.version("fern_examples") diff --git a/seed/python-sdk/examples/readme/tests/conftest.py b/seed/python-sdk/examples/readme/tests/conftest.py index 6287438ce63..55b62025b51 100644 --- a/seed/python-sdk/examples/readme/tests/conftest.py +++ b/seed/python-sdk/examples/readme/tests/conftest.py @@ -1,16 +1,22 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExamples import os - import pytest -from seed import AsyncSeedExamples, SeedExamples +from seed import AsyncSeedExamples @pytest.fixture def client() -> SeedExamples: - return SeedExamples(token=os.getenv("ENV_TOKEN", "token"), base_url=os.getenv("TESTS_BASE_URL", "base_url")) + return SeedExamples( + token=os.getenv("ENV_TOKEN", "token"), + base_url=os.getenv("TESTS_BASE_URL", "base_url"), + ) @pytest.fixture def async_client() -> AsyncSeedExamples: - return AsyncSeedExamples(token=os.getenv("ENV_TOKEN", "token"), base_url=os.getenv("TESTS_BASE_URL", "base_url")) + return AsyncSeedExamples( + token=os.getenv("ENV_TOKEN", "token"), + base_url=os.getenv("TESTS_BASE_URL", "base_url"), + ) diff --git a/seed/python-sdk/examples/readme/tests/custom/test_client.py b/seed/python-sdk/examples/readme/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/python-sdk/examples/readme/tests/custom/test_client.py +++ b/seed/python-sdk/examples/readme/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/python-sdk/examples/readme/tests/file/notification/test_service.py b/seed/python-sdk/examples/readme/tests/file/notification/test_service.py index e9ce274f7b9..425f6251bd2 100644 --- a/seed/python-sdk/examples/readme/tests/file/notification/test_service.py +++ b/seed/python-sdk/examples/readme/tests/file/notification/test_service.py @@ -1,13 +1,14 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExamples +from seed import AsyncSeedExamples import typing - -from seed import AsyncSeedExamples, SeedExamples - from ...utilities import validate_response -async def test_get_exception(client: SeedExamples, async_client: AsyncSeedExamples) -> None: +async def test_get_exception( + client: SeedExamples, async_client: AsyncSeedExamples +) -> None: expected_response: typing.Any = { "type": "generic", "exceptionType": "Unavailable", @@ -15,8 +16,12 @@ async def test_get_exception(client: SeedExamples, async_client: AsyncSeedExampl "exceptionStacktrace": "", } expected_types: typing.Any = "no_validate" - response = client.file.notification.service.get_exception(notification_id="notification-hsy129x") + response = client.file.notification.service.get_exception( + notification_id="notification-hsy129x" + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.file.notification.service.get_exception(notification_id="notification-hsy129x") + async_response = await async_client.file.notification.service.get_exception( + notification_id="notification-hsy129x" + ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/examples/readme/tests/health/test_service.py b/seed/python-sdk/examples/readme/tests/health/test_service.py index 84940f4fd4c..75cbe574de1 100644 --- a/seed/python-sdk/examples/readme/tests/health/test_service.py +++ b/seed/python-sdk/examples/readme/tests/health/test_service.py @@ -1,9 +1,8 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExamples +from seed import AsyncSeedExamples import typing - -from seed import AsyncSeedExamples, SeedExamples - from ..utilities import validate_response diff --git a/seed/python-sdk/examples/readme/tests/test_root.py b/seed/python-sdk/examples/readme/tests/test_root.py index e9a402e2322..474790891ae 100644 --- a/seed/python-sdk/examples/readme/tests/test_root.py +++ b/seed/python-sdk/examples/readme/tests/test_root.py @@ -1,9 +1,8 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExamples +from seed import AsyncSeedExamples import typing - -from seed import AsyncSeedExamples, SeedExamples - from .utilities import validate_response @@ -13,5 +12,7 @@ async def test_echo(client: SeedExamples, async_client: AsyncSeedExamples) -> No response = client.echo(request="Hello world!\\n\\nwith\\n\\tnewlines") validate_response(response, expected_response, expected_types) - async_response = await async_client.echo(request="Hello world!\\n\\nwith\\n\\tnewlines") + async_response = await async_client.echo( + request="Hello world!\\n\\nwith\\n\\tnewlines" + ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/examples/readme/tests/test_service.py b/seed/python-sdk/examples/readme/tests/test_service.py index 5c00ddaf39d..40349c313f3 100644 --- a/seed/python-sdk/examples/readme/tests/test_service.py +++ b/seed/python-sdk/examples/readme/tests/test_service.py @@ -1,9 +1,8 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExamples +from seed import AsyncSeedExamples import typing - -from seed import AsyncSeedExamples, SeedExamples - from .utilities import validate_response @@ -39,7 +38,9 @@ async def test_get_movie(client: SeedExamples, async_client: AsyncSeedExamples) validate_response(async_response, expected_response, expected_types) -async def test_create_movie(client: SeedExamples, async_client: AsyncSeedExamples) -> None: +async def test_create_movie( + client: SeedExamples, async_client: AsyncSeedExamples +) -> None: expected_response: typing.Any = "movie-c06a4ad7" expected_types: typing.Any = None response = client.service.create_movie( @@ -73,7 +74,9 @@ async def test_create_movie(client: SeedExamples, async_client: AsyncSeedExample validate_response(async_response, expected_response, expected_types) -async def test_get_metadata(client: SeedExamples, async_client: AsyncSeedExamples) -> None: +async def test_get_metadata( + client: SeedExamples, async_client: AsyncSeedExamples +) -> None: expected_response: typing.Any = { "type": "html", "extra": {"version": "0.0.1", "tenancy": "test"}, @@ -81,14 +84,20 @@ async def test_get_metadata(client: SeedExamples, async_client: AsyncSeedExample "value": "...", } expected_types: typing.Any = "no_validate" - response = client.service.get_metadata(x_api_version="0.0.1", shallow=False, tag="development") + response = client.service.get_metadata( + x_api_version="0.0.1", shallow=False, tag="development" + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.service.get_metadata(x_api_version="0.0.1", shallow=False, tag="development") + async_response = await async_client.service.get_metadata( + x_api_version="0.0.1", shallow=False, tag="development" + ) validate_response(async_response, expected_response, expected_types) -async def test_get_response(client: SeedExamples, async_client: AsyncSeedExamples) -> None: +async def test_get_response( + client: SeedExamples, async_client: AsyncSeedExamples +) -> None: expected_response: typing.Any = { "response": "Initializing...", "identifiers": [ @@ -100,7 +109,10 @@ async def test_get_response(client: SeedExamples, async_client: AsyncSeedExample "response": None, "identifiers": ( "list", - {0: {"type": None, "value": None, "label": None}, 1: {"type": None, "value": None, "label": None}}, + { + 0: {"type": None, "value": None, "label": None}, + 1: {"type": None, "value": None, "label": None}, + }, ), } response = client.service.get_response() diff --git a/seed/python-sdk/examples/readme/tests/utilities.py b/seed/python-sdk/examples/readme/tests/utilities.py index 13da208eb3a..e8f4472564c 100644 --- a/seed/python-sdk/examples/readme/tests/utilities.py +++ b/seed/python-sdk/examples/readme/tests/utilities.py @@ -3,11 +3,14 @@ import typing import uuid -import pydantic from dateutil import parser +import pydantic + -def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> typing.Any: +def cast_field( + json_expectation: typing.Any, type_expectation: typing.Any +) -> typing.Any: # Cast these specific types which come through as string and expect our # models to cast to the correct type. if type_expectation == "uuid": @@ -25,7 +28,9 @@ def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> ty return json_expectation -def validate_field(response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any) -> None: +def validate_field( + response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectation == "no_validate": return @@ -44,7 +49,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(entry_expectation, dict): is_container_of_complex_type = True validate_response( - response=response[idx], json_expectation=ex, type_expectations=entry_expectation + response=response[idx], + json_expectation=ex, + type_expectations=entry_expectation, ) else: cast_json_expectation.append(cast_field(ex, entry_expectation)) @@ -56,7 +63,10 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # if any of the values of the set have a type_expectation of a dict, we're assuming it's a pydantic # model and keeping it a list. if container_expectation != "set" or not any( - map(lambda value: isinstance(value, dict), list(contents_expectation.values())) + map( + lambda value: isinstance(value, dict), + list(contents_expectation.values()), + ) ): json_expectation = cast_field(json_expectation, container_expectation) elif isinstance(type_expectation, tuple): @@ -65,9 +75,15 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(contents_expectation, dict): json_expectation = { cast_field( - key, contents_expectation.get(idx)[0] if contents_expectation.get(idx) is not None else None # type: ignore + key, + contents_expectation.get(idx)[0] + if contents_expectation.get(idx) is not None + else None, # type: ignore ): cast_field( - value, contents_expectation.get(idx)[1] if contents_expectation.get(idx) is not None else None # type: ignore + value, + contents_expectation.get(idx)[1] + if contents_expectation.get(idx) is not None + else None, # type: ignore ) for idx, (key, value) in enumerate(json_expectation.items()) } @@ -86,7 +102,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # Arg type_expectations is a deeply nested structure that matches the response, but with the values replaced with the expected types -def validate_response(response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any) -> None: +def validate_response( + response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectations == "no_validate": return @@ -96,11 +114,17 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e and not isinstance(response, dict) and not issubclass(type(response), pydantic.BaseModel) ): - validate_field(response=response, json_expectation=json_expectation, type_expectation=type_expectations) + validate_field( + response=response, + json_expectation=json_expectation, + type_expectation=type_expectations, + ) return if isinstance(response, list): - assert len(response) == len(json_expectation), "Length mismatch, expected: {0}, Actual: {1}".format( + assert len(response) == len( + json_expectation + ), "Length mismatch, expected: {0}, Actual: {1}".format( len(response), len(json_expectation) ) content_expectation = type_expectations @@ -108,7 +132,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e content_expectation = type_expectations[1] for idx, item in enumerate(response): validate_response( - response=item, json_expectation=json_expectation[idx], type_expectations=content_expectation[idx] + response=item, + json_expectation=json_expectation[idx], + type_expectations=content_expectation[idx], ) else: response_json = response @@ -116,7 +142,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e response_json = response.dict(by_alias=True) for key, value in json_expectation.items(): - assert key in response_json, "Field {0} not found within the response object: {1}".format( + assert ( + key in response_json + ), "Field {0} not found within the response object: {1}".format( key, response_json ) @@ -128,11 +156,19 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e # Otherwise, we're just validating a single field that's a pydantic model. if isinstance(value, dict) and not isinstance(type_expectation, tuple): validate_response( - response=response_json[key], json_expectation=value, type_expectations=type_expectation + response=response_json[key], + json_expectation=value, + type_expectations=type_expectation, ) else: - validate_field(response=response_json[key], json_expectation=value, type_expectation=type_expectation) + validate_field( + response=response_json[key], + json_expectation=value, + type_expectation=type_expectation, + ) # Ensure there are no additional fields here either del response_json[key] - assert len(response_json) == 0, "Additional fields found, expected None: {0}".format(response_json) + assert ( + len(response_json) == 0 + ), "Additional fields found, expected None: {0}".format(response_json) diff --git a/seed/python-sdk/examples/readme/tests/utils/assets/models/__init__.py b/seed/python-sdk/examples/readme/tests/utils/assets/models/__init__.py index 2cf01263529..3a1c852e71e 100644 --- a/seed/python-sdk/examples/readme/tests/utils/assets/models/__init__.py +++ b/seed/python-sdk/examples/readme/tests/utils/assets/models/__init__.py @@ -5,7 +5,7 @@ from .circle import CircleParams from .object_with_defaults import ObjectWithDefaultsParams from .object_with_optional_field import ObjectWithOptionalFieldParams -from .shape import Shape_CircleParams, Shape_SquareParams, ShapeParams +from .shape import ShapeParams, Shape_CircleParams, Shape_SquareParams from .square import SquareParams from .undiscriminated_shape import UndiscriminatedShapeParams diff --git a/seed/python-sdk/examples/readme/tests/utils/assets/models/circle.py b/seed/python-sdk/examples/readme/tests/utils/assets/models/circle.py index af7a1bf8a8e..253f12d38b3 100644 --- a/seed/python-sdk/examples/readme/tests/utils/assets/models/circle.py +++ b/seed/python-sdk/examples/readme/tests/utils/assets/models/circle.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class CircleParams(typing_extensions.TypedDict): - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] diff --git a/seed/python-sdk/examples/readme/tests/utils/assets/models/object_with_optional_field.py b/seed/python-sdk/examples/readme/tests/utils/assets/models/object_with_optional_field.py index 3ad93d5f305..ebe7dc80547 100644 --- a/seed/python-sdk/examples/readme/tests/utils/assets/models/object_with_optional_field.py +++ b/seed/python-sdk/examples/readme/tests/utils/assets/models/object_with_optional_field.py @@ -7,8 +7,8 @@ import uuid import typing_extensions -from seed.core.serialization import FieldMetadata +from seed.core.serialization import FieldMetadata from .color import Color from .shape import ShapeParams from .undiscriminated_shape import UndiscriminatedShapeParams @@ -18,16 +18,30 @@ class ObjectWithOptionalFieldParams(typing_extensions.TypedDict): literal: typing.Literal["lit_one"] string: typing_extensions.NotRequired[str] integer: typing_extensions.NotRequired[int] - long_: typing_extensions.NotRequired[typing_extensions.Annotated[int, FieldMetadata(alias="long")]] + long_: typing_extensions.NotRequired[ + typing_extensions.Annotated[int, FieldMetadata(alias="long")] + ] double: typing_extensions.NotRequired[float] - bool_: typing_extensions.NotRequired[typing_extensions.Annotated[bool, FieldMetadata(alias="bool")]] + bool_: typing_extensions.NotRequired[ + typing_extensions.Annotated[bool, FieldMetadata(alias="bool")] + ] datetime: typing_extensions.NotRequired[dt.datetime] date: typing_extensions.NotRequired[dt.date] - uuid_: typing_extensions.NotRequired[typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")]] - base_64: typing_extensions.NotRequired[typing_extensions.Annotated[str, FieldMetadata(alias="base64")]] - list_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")]] - set_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")]] - map_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")]] + uuid_: typing_extensions.NotRequired[ + typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")] + ] + base_64: typing_extensions.NotRequired[ + typing_extensions.Annotated[str, FieldMetadata(alias="base64")] + ] + list_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")] + ] + set_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")] + ] + map_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")] + ] enum: typing_extensions.NotRequired[Color] union: typing_extensions.NotRequired[ShapeParams] second_union: typing_extensions.NotRequired[ShapeParams] diff --git a/seed/python-sdk/examples/readme/tests/utils/assets/models/shape.py b/seed/python-sdk/examples/readme/tests/utils/assets/models/shape.py index 2c33c877951..816ffc51bdc 100644 --- a/seed/python-sdk/examples/readme/tests/utils/assets/models/shape.py +++ b/seed/python-sdk/examples/readme/tests/utils/assets/models/shape.py @@ -7,6 +7,7 @@ import typing import typing_extensions + from seed.core.serialization import FieldMetadata @@ -15,13 +16,21 @@ class Base(typing_extensions.TypedDict): class Shape_CircleParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["circle"], FieldMetadata(alias="shapeType")] - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["circle"], FieldMetadata(alias="shapeType") + ] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] class Shape_SquareParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["square"], FieldMetadata(alias="shapeType")] - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["square"], FieldMetadata(alias="shapeType") + ] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] ShapeParams = typing.Union[Shape_CircleParams, Shape_SquareParams] diff --git a/seed/python-sdk/examples/readme/tests/utils/assets/models/square.py b/seed/python-sdk/examples/readme/tests/utils/assets/models/square.py index b9b7dd319bc..bcf08a723c5 100644 --- a/seed/python-sdk/examples/readme/tests/utils/assets/models/square.py +++ b/seed/python-sdk/examples/readme/tests/utils/assets/models/square.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class SquareParams(typing_extensions.TypedDict): - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] diff --git a/seed/python-sdk/examples/readme/tests/utils/test_http_client.py b/seed/python-sdk/examples/readme/tests/utils/test_http_client.py index edd11ca7afb..f5a874a75f3 100644 --- a/seed/python-sdk/examples/readme/tests/utils/test_http_client.py +++ b/seed/python-sdk/examples/readme/tests/utils/test_http_client.py @@ -9,12 +9,17 @@ def get_request_options() -> RequestOptions: def test_get_json_request_body() -> None: - json_body, data_body = get_request_body(json={"hello": "world"}, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json={"hello": "world"}, data=None, request_options=None, omit=None + ) assert json_body == {"hello": "world"} assert data_body is None json_body_extras, data_body_extras = get_request_body( - json={"goodbye": "world"}, data=None, request_options=get_request_options(), omit=None + json={"goodbye": "world"}, + data=None, + request_options=get_request_options(), + omit=None, ) assert json_body_extras == {"goodbye": "world", "see you": "later"} @@ -22,12 +27,17 @@ def test_get_json_request_body() -> None: def test_get_files_request_body() -> None: - json_body, data_body = get_request_body(json=None, data={"hello": "world"}, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data={"hello": "world"}, request_options=None, omit=None + ) assert data_body == {"hello": "world"} assert json_body is None json_body_extras, data_body_extras = get_request_body( - json=None, data={"goodbye": "world"}, request_options=get_request_options(), omit=None + json=None, + data={"goodbye": "world"}, + request_options=get_request_options(), + omit=None, ) assert data_body_extras == {"goodbye": "world", "see you": "later"} @@ -35,7 +45,9 @@ def test_get_files_request_body() -> None: def test_get_none_request_body() -> None: - json_body, data_body = get_request_body(json=None, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data=None, request_options=None, omit=None + ) assert data_body is None assert json_body is None diff --git a/seed/python-sdk/examples/readme/tests/utils/test_query_encoding.py b/seed/python-sdk/examples/readme/tests/utils/test_query_encoding.py index 247e1551b46..fbc8f402167 100644 --- a/seed/python-sdk/examples/readme/tests/utils/test_query_encoding.py +++ b/seed/python-sdk/examples/readme/tests/utils/test_query_encoding.py @@ -4,9 +4,15 @@ def test_query_encoding() -> None: - assert encode_query({"hello world": "hello world"}) == {"hello world": "hello world"} - assert encode_query({"hello_world": {"hello": "world"}}) == {"hello_world[hello]": "world"} - assert encode_query({"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"}) == { + assert encode_query({"hello world": "hello world"}) == { + "hello world": "hello world" + } + assert encode_query({"hello_world": {"hello": "world"}}) == { + "hello_world[hello]": "world" + } + assert encode_query( + {"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"} + ) == { "hello_world[hello][world]": "today", "hello_world[test]": "this", "hi": "there", diff --git a/seed/python-sdk/examples/readme/tests/utils/test_serialization.py b/seed/python-sdk/examples/readme/tests/utils/test_serialization.py index 58b1ed66e6d..5ca956916dd 100644 --- a/seed/python-sdk/examples/readme/tests/utils/test_serialization.py +++ b/seed/python-sdk/examples/readme/tests/utils/test_serialization.py @@ -1,10 +1,12 @@ # This file was auto-generated by Fern from our API Definition. -from typing import Any, List +from typing import List, Any -from seed.core.serialization import convert_and_respect_annotation_metadata +from seed.core.serialization import ( + convert_and_respect_annotation_metadata, +) +from .assets.models import ShapeParams, ObjectWithOptionalFieldParams -from .assets.models import ObjectWithOptionalFieldParams, ShapeParams UNION_TEST: ShapeParams = {"radius_measurement": 1.0, "shape_type": "circle", "id": "1"} UNION_TEST_CONVERTED = {"shapeType": "circle", "radiusMeasurement": 1.0, "id": "1"} @@ -18,20 +20,54 @@ def test_convert_and_respect_annotation_metadata() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) - assert converted == {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"} + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) + assert converted == { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + } def test_convert_and_respect_annotation_metadata_in_list() -> None: data: List[ObjectWithOptionalFieldParams] = [ - {"string": "string", "long_": 12345, "bool_": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long_": 67890, "list_": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long_": 12345, + "bool_": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long_": 67890, + "list_": [], + "literal": "lit_one", + "any": "any", + }, ] - converted = convert_and_respect_annotation_metadata(object_=data, annotation=List[ObjectWithOptionalFieldParams]) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=List[ObjectWithOptionalFieldParams] + ) assert converted == [ - {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long": 67890, "list": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long": 67890, + "list": [], + "literal": "lit_one", + "any": "any", + }, ] @@ -43,7 +79,9 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) assert converted == { "string": "string", @@ -55,12 +93,16 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: def test_convert_and_respect_annotation_metadata_in_union() -> None: - converted = convert_and_respect_annotation_metadata(object_=UNION_TEST, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=UNION_TEST, annotation=ShapeParams + ) assert converted == UNION_TEST_CONVERTED def test_convert_and_respect_annotation_metadata_with_empty_object() -> None: data: Any = {} - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ShapeParams + ) assert converted == data diff --git a/seed/python-sdk/exhaustive/deps_with_min_python_version/pyproject.toml b/seed/python-sdk/exhaustive/deps_with_min_python_version/pyproject.toml index 8e495b03172..a26ba5e4019 100644 --- a/seed/python-sdk/exhaustive/deps_with_min_python_version/pyproject.toml +++ b/seed/python-sdk/exhaustive/deps_with_min_python_version/pyproject.toml @@ -47,6 +47,7 @@ types-python-dateutil = "^2.9.0.20240316" langchain = "^0.1.3" langchain-openai = "^0.0.3" openai = "^1.9.0" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/__init__.py b/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/__init__.py index eb56b0ce275..dc1ef03a650 100644 --- a/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/__init__.py +++ b/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/__init__.py @@ -1,6 +1,14 @@ # This file was auto-generated by Fern from our API Definition. -from . import endpoints, general_errors, inlined_requests, no_auth, no_req_body, req_with_headers, types +from . import ( + endpoints, + general_errors, + inlined_requests, + no_auth, + no_req_body, + req_with_headers, + types, +) from .client import AsyncSeedExhaustive, SeedExhaustive from .general_errors import BadObjectRequestInfo, BadRequestBody from .version import __version__ diff --git a/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/client.py b/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/client.py index b1b9764c7a7..f5ab292af6b 100644 --- a/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/client.py +++ b/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/client.py @@ -1,15 +1,19 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from .endpoints.client import AsyncEndpointsClient, EndpointsClient -from .inlined_requests.client import AsyncInlinedRequestsClient, InlinedRequestsClient -from .no_auth.client import AsyncNoAuthClient, NoAuthClient -from .no_req_body.client import AsyncNoReqBodyClient, NoReqBodyClient -from .req_with_headers.client import AsyncReqWithHeadersClient, ReqWithHeadersClient +from .core.client_wrapper import SyncClientWrapper +from .endpoints.client import EndpointsClient +from .inlined_requests.client import InlinedRequestsClient +from .no_auth.client import NoAuthClient +from .no_req_body.client import NoReqBodyClient +from .req_with_headers.client import ReqWithHeadersClient +from .core.client_wrapper import AsyncClientWrapper +from .endpoints.client import AsyncEndpointsClient +from .inlined_requests.client import AsyncInlinedRequestsClient +from .no_auth.client import AsyncNoAuthClient +from .no_req_body.client import AsyncNoReqBodyClient +from .req_with_headers.client import AsyncReqWithHeadersClient class SeedExhaustive: @@ -48,24 +52,32 @@ def __init__( token: typing.Optional[typing.Union[str, typing.Callable[[], str]]] = None, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.Client] = None + httpx_client: typing.Optional[httpx.Client] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = SyncClientWrapper( base_url=base_url, token=token, httpx_client=httpx_client if httpx_client is not None - else httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.Client( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.Client(timeout=_defaulted_timeout), timeout=_defaulted_timeout, ) self.endpoints = EndpointsClient(client_wrapper=self._client_wrapper) - self.inlined_requests = InlinedRequestsClient(client_wrapper=self._client_wrapper) + self.inlined_requests = InlinedRequestsClient( + client_wrapper=self._client_wrapper + ) self.no_auth = NoAuthClient(client_wrapper=self._client_wrapper) self.no_req_body = NoReqBodyClient(client_wrapper=self._client_wrapper) - self.req_with_headers = ReqWithHeadersClient(client_wrapper=self._client_wrapper) + self.req_with_headers = ReqWithHeadersClient( + client_wrapper=self._client_wrapper + ) class AsyncSeedExhaustive: @@ -104,21 +116,29 @@ def __init__( token: typing.Optional[typing.Union[str, typing.Callable[[], str]]] = None, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.AsyncClient] = None + httpx_client: typing.Optional[httpx.AsyncClient] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = AsyncClientWrapper( base_url=base_url, token=token, httpx_client=httpx_client if httpx_client is not None - else httpx.AsyncClient(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.AsyncClient( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.AsyncClient(timeout=_defaulted_timeout), timeout=_defaulted_timeout, ) self.endpoints = AsyncEndpointsClient(client_wrapper=self._client_wrapper) - self.inlined_requests = AsyncInlinedRequestsClient(client_wrapper=self._client_wrapper) + self.inlined_requests = AsyncInlinedRequestsClient( + client_wrapper=self._client_wrapper + ) self.no_auth = AsyncNoAuthClient(client_wrapper=self._client_wrapper) self.no_req_body = AsyncNoReqBodyClient(client_wrapper=self._client_wrapper) - self.req_with_headers = AsyncReqWithHeadersClient(client_wrapper=self._client_wrapper) + self.req_with_headers = AsyncReqWithHeadersClient( + client_wrapper=self._client_wrapper + ) diff --git a/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/core/api_error.py b/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/core/api_error.py index 2e9fc5431cd..da734b58068 100644 --- a/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/core/api_error.py +++ b/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/core/api_error.py @@ -7,7 +7,9 @@ class ApiError(Exception): status_code: typing.Optional[int] body: typing.Any - def __init__(self, *, status_code: typing.Optional[int] = None, body: typing.Any = None): + def __init__( + self, *, status_code: typing.Optional[int] = None, body: typing.Any = None + ): self.status_code = status_code self.body = body diff --git a/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/core/client_wrapper.py b/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/core/client_wrapper.py index 8d01b584b82..d037184a816 100644 --- a/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/core/client_wrapper.py +++ b/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/core/client_wrapper.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .http_client import AsyncHttpClient, HttpClient +from .http_client import HttpClient +from .http_client import AsyncHttpClient class BaseClientWrapper: diff --git a/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/core/datetime_utils.py b/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/core/datetime_utils.py +++ b/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/core/file.py b/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/core/file.py index cb0d40bbbf3..6e0f92bfcb1 100644 --- a/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/core/file.py +++ b/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/core/file.py @@ -13,12 +13,17 @@ # (filename, file (or bytes), content_type) typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str]], # (filename, file (or bytes), content_type, headers) - typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str], typing.Mapping[str, str]], + typing.Tuple[ + typing.Optional[str], + FileContent, + typing.Optional[str], + typing.Mapping[str, str], + ], ] def convert_file_dict_to_httpx_tuples( - d: typing.Dict[str, typing.Union[File, typing.List[File]]] + d: typing.Dict[str, typing.Union[File, typing.List[File]]], ) -> typing.List[typing.Tuple[str, File]]: """ The format we use is a list of tuples, where the first element is the diff --git a/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/core/http_client.py b/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/core/http_client.py index 9333d8a7f15..091f71bc185 100644 --- a/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/core/http_client.py +++ b/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/core/http_client.py @@ -77,7 +77,9 @@ def _retry_timeout(response: httpx.Response, retries: int) -> float: return retry_after # Apply exponential backoff, capped at MAX_RETRY_DELAY_SECONDS. - retry_delay = min(INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS) + retry_delay = min( + INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS + ) # Add a randomness / jitter to the retry delay to avoid overwhelming the server with retries. timeout = retry_delay * (1 - 0.25 * random()) @@ -90,7 +92,8 @@ def _should_retry(response: httpx.Response) -> bool: def remove_omit_from_dict( - original: typing.Dict[str, typing.Optional[typing.Any]], omit: typing.Optional[typing.Any] + original: typing.Dict[str, typing.Optional[typing.Any]], + omit: typing.Optional[typing.Any], ) -> typing.Dict[str, typing.Any]: if omit is None: return original @@ -108,7 +111,8 @@ def maybe_filter_request_body( ) -> typing.Optional[typing.Any]: if data is None: return ( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else None ) @@ -118,7 +122,8 @@ def maybe_filter_request_body( data_content = { **(jsonable_encoder(remove_omit_from_dict(data, omit))), # type: ignore **( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else {} ), @@ -162,7 +167,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url def request( @@ -174,8 +181,12 @@ def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -184,11 +195,14 @@ def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) response = self.httpx_client.request( method=method, @@ -198,7 +212,11 @@ def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -209,7 +227,10 @@ def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -222,11 +243,15 @@ def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: time.sleep(_retry_timeout(response=response, retries=retries)) @@ -256,8 +281,12 @@ def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -266,11 +295,14 @@ def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) with self.httpx_client.stream( method=method, @@ -280,7 +312,11 @@ def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -291,7 +327,9 @@ def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -304,7 +342,9 @@ def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream @@ -327,7 +367,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url async def request( @@ -339,8 +381,12 @@ async def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -349,11 +395,14 @@ async def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) # Add the input to each of these and do None-safety checks response = await self.httpx_client.request( @@ -364,7 +413,11 @@ async def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -375,7 +428,10 @@ async def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -388,11 +444,15 @@ async def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: await asyncio.sleep(_retry_timeout(response=response, retries=retries)) @@ -421,8 +481,12 @@ async def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -431,11 +495,14 @@ async def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) async with self.httpx_client.stream( method=method, @@ -445,7 +512,11 @@ async def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -456,7 +527,9 @@ async def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -469,7 +542,9 @@ async def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream diff --git a/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/core/jsonable_encoder.py b/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/core/jsonable_encoder.py index d3fd328fd41..12a8b52fc22 100644 --- a/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/core/jsonable_encoder.py +++ b/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/core/jsonable_encoder.py @@ -19,13 +19,19 @@ import pydantic from .datetime_utils import serialize_datetime -from .pydantic_utilities import IS_PYDANTIC_V2, encode_by_type, to_jsonable_with_fallback +from .pydantic_utilities import ( + IS_PYDANTIC_V2, + encode_by_type, + to_jsonable_with_fallback, +) SetIntStr = Set[Union[int, str]] DictIntStrAny = Dict[Union[int, str], Any] -def jsonable_encoder(obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None) -> Any: +def jsonable_encoder( + obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None +) -> Any: custom_encoder = custom_encoder or {} if custom_encoder: if type(obj) in custom_encoder: diff --git a/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/core/pydantic_utilities.py b/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/core/pydantic_utilities.py index 170a563d6eb..c63935c32a2 100644 --- a/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/core/pydantic_utilities.py +++ b/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) # type: ignore # Pydantic v1 diff --git a/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/core/query_encoder.py b/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/core/query_encoder.py index 24076d72ee9..7cb98f52cd7 100644 --- a/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/core/query_encoder.py +++ b/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/core/query_encoder.py @@ -7,7 +7,9 @@ # Flattens dicts to be of the form {"key[subkey][subkey2]": value} where value is not a dict -def traverse_query_dict(dict_flat: Dict[str, Any], key_prefix: Optional[str] = None) -> Dict[str, Any]: +def traverse_query_dict( + dict_flat: Dict[str, Any], key_prefix: Optional[str] = None +) -> Dict[str, Any]: result = {} for k, v in dict_flat.items(): key = f"{key_prefix}[{k}]" if key_prefix is not None else k @@ -30,4 +32,8 @@ def single_query_encoder(query_key: str, query_value: Any) -> Dict[str, Any]: def encode_query(query: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: - return dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) if query is not None else None + return ( + dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) + if query is not None + else None + ) diff --git a/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/core/serialization.py b/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/core/serialization.py +++ b/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/endpoints/__init__.py b/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/endpoints/__init__.py index 92307cab7fe..a9496ece178 100644 --- a/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/endpoints/__init__.py +++ b/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/endpoints/__init__.py @@ -2,4 +2,12 @@ from . import container, enum, http_methods, object, params, primitive, union -__all__ = ["container", "enum", "http_methods", "object", "params", "primitive", "union"] +__all__ = [ + "container", + "enum", + "http_methods", + "object", + "params", + "primitive", + "union", +] diff --git a/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/endpoints/client.py b/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/endpoints/client.py index 18dc397fdf1..69930de54d7 100644 --- a/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/endpoints/client.py +++ b/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/endpoints/client.py @@ -1,13 +1,21 @@ # This file was auto-generated by Fern from our API Definition. -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from .container.client import AsyncContainerClient, ContainerClient -from .enum.client import AsyncEnumClient, EnumClient -from .http_methods.client import AsyncHttpMethodsClient, HttpMethodsClient -from .object.client import AsyncObjectClient, ObjectClient -from .params.client import AsyncParamsClient, ParamsClient -from .primitive.client import AsyncPrimitiveClient, PrimitiveClient -from .union.client import AsyncUnionClient, UnionClient +from ..core.client_wrapper import SyncClientWrapper +from .container.client import ContainerClient +from .enum.client import EnumClient +from .http_methods.client import HttpMethodsClient +from .object.client import ObjectClient +from .params.client import ParamsClient +from .primitive.client import PrimitiveClient +from .union.client import UnionClient +from ..core.client_wrapper import AsyncClientWrapper +from .container.client import AsyncContainerClient +from .enum.client import AsyncEnumClient +from .http_methods.client import AsyncHttpMethodsClient +from .object.client import AsyncObjectClient +from .params.client import AsyncParamsClient +from .primitive.client import AsyncPrimitiveClient +from .union.client import AsyncUnionClient class EndpointsClient: diff --git a/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/endpoints/container/client.py b/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/endpoints/container/client.py index c6cf14f63ac..4af9c12d534 100644 --- a/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/endpoints/container/client.py +++ b/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/endpoints/container/client.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. import typing +from ...core.client_wrapper import SyncClientWrapper +from ...core.request_options import RequestOptions +from ...core.pydantic_utilities import parse_obj_as from json.decoder import JSONDecodeError - from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ...core.pydantic_utilities import parse_obj_as -from ...core.request_options import RequestOptions from ...types.object.types.object_with_required_field import ObjectWithRequiredField +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -18,7 +18,10 @@ def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper def get_and_return_list_of_primitives( - self, *, request: typing.Sequence[str], request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Sequence[str], + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[str]: """ Parameters @@ -45,11 +48,18 @@ def get_and_return_list_of_primitives( ) """ _response = self._client_wrapper.httpx_client.request( - "container/list-of-primitives", method="POST", json=request, request_options=request_options, omit=OMIT + "container/list-of-primitives", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.List[str], parse_obj_as(type_=typing.List[str], object_=_response.json())) # type: ignore + return typing.cast( + typing.List[str], + parse_obj_as(type_=typing.List[str], object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -59,7 +69,7 @@ def get_and_return_list_of_objects( self, *, request: typing.Sequence[ObjectWithRequiredField], - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[ObjectWithRequiredField]: """ Parameters @@ -91,18 +101,31 @@ def get_and_return_list_of_objects( ) """ _response = self._client_wrapper.httpx_client.request( - "container/list-of-objects", method="POST", json=request, request_options=request_options, omit=OMIT + "container/list-of-objects", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.List[ObjectWithRequiredField], parse_obj_as(type_=typing.List[ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.List[ObjectWithRequiredField], + parse_obj_as( + type_=typing.List[ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_and_return_set_of_primitives( - self, *, request: typing.Set[str], request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Set[str], + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Set[str]: """ Parameters @@ -129,11 +152,18 @@ def get_and_return_set_of_primitives( ) """ _response = self._client_wrapper.httpx_client.request( - "container/set-of-primitives", method="POST", json=request, request_options=request_options, omit=OMIT + "container/set-of-primitives", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Set[str], parse_obj_as(type_=typing.Set[str], object_=_response.json())) # type: ignore + return typing.cast( + typing.Set[str], + parse_obj_as(type_=typing.Set[str], object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -143,7 +173,7 @@ def get_and_return_set_of_objects( self, *, request: typing.Sequence[ObjectWithRequiredField], - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[ObjectWithRequiredField]: """ Parameters @@ -175,18 +205,31 @@ def get_and_return_set_of_objects( ) """ _response = self._client_wrapper.httpx_client.request( - "container/set-of-objects", method="POST", json=request, request_options=request_options, omit=OMIT + "container/set-of-objects", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.List[ObjectWithRequiredField], parse_obj_as(type_=typing.List[ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.List[ObjectWithRequiredField], + parse_obj_as( + type_=typing.List[ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_and_return_map_prim_to_prim( - self, *, request: typing.Dict[str, str], request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Dict[str, str], + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Dict[str, str]: """ Parameters @@ -213,11 +256,18 @@ def get_and_return_map_prim_to_prim( ) """ _response = self._client_wrapper.httpx_client.request( - "container/map-prim-to-prim", method="POST", json=request, request_options=request_options, omit=OMIT + "container/map-prim-to-prim", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Dict[str, str], parse_obj_as(type_=typing.Dict[str, str], object_=_response.json())) # type: ignore + return typing.cast( + typing.Dict[str, str], + parse_obj_as(type_=typing.Dict[str, str], object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -227,7 +277,7 @@ def get_and_return_map_of_prim_to_object( self, *, request: typing.Dict[str, ObjectWithRequiredField], - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Dict[str, ObjectWithRequiredField]: """ Parameters @@ -259,11 +309,21 @@ def get_and_return_map_of_prim_to_object( ) """ _response = self._client_wrapper.httpx_client.request( - "container/map-prim-to-object", method="POST", json=request, request_options=request_options, omit=OMIT + "container/map-prim-to-object", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Dict[str, ObjectWithRequiredField], parse_obj_as(type_=typing.Dict[str, ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.Dict[str, ObjectWithRequiredField], + parse_obj_as( + type_=typing.Dict[str, ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -273,7 +333,7 @@ def get_and_return_optional( self, *, request: typing.Optional[ObjectWithRequiredField] = None, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Optional[ObjectWithRequiredField]: """ Parameters @@ -303,11 +363,21 @@ def get_and_return_optional( ) """ _response = self._client_wrapper.httpx_client.request( - "container/opt-objects", method="POST", json=request, request_options=request_options, omit=OMIT + "container/opt-objects", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Optional[ObjectWithRequiredField], parse_obj_as(type_=typing.Optional[ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.Optional[ObjectWithRequiredField], + parse_obj_as( + type_=typing.Optional[ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -319,7 +389,10 @@ def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper async def get_and_return_list_of_primitives( - self, *, request: typing.Sequence[str], request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Sequence[str], + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[str]: """ Parameters @@ -354,11 +427,18 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/list-of-primitives", method="POST", json=request, request_options=request_options, omit=OMIT + "container/list-of-primitives", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.List[str], parse_obj_as(type_=typing.List[str], object_=_response.json())) # type: ignore + return typing.cast( + typing.List[str], + parse_obj_as(type_=typing.List[str], object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -368,7 +448,7 @@ async def get_and_return_list_of_objects( self, *, request: typing.Sequence[ObjectWithRequiredField], - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[ObjectWithRequiredField]: """ Parameters @@ -408,18 +488,31 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/list-of-objects", method="POST", json=request, request_options=request_options, omit=OMIT + "container/list-of-objects", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.List[ObjectWithRequiredField], parse_obj_as(type_=typing.List[ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.List[ObjectWithRequiredField], + parse_obj_as( + type_=typing.List[ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_and_return_set_of_primitives( - self, *, request: typing.Set[str], request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Set[str], + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Set[str]: """ Parameters @@ -454,11 +547,18 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/set-of-primitives", method="POST", json=request, request_options=request_options, omit=OMIT + "container/set-of-primitives", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Set[str], parse_obj_as(type_=typing.Set[str], object_=_response.json())) # type: ignore + return typing.cast( + typing.Set[str], + parse_obj_as(type_=typing.Set[str], object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -468,7 +568,7 @@ async def get_and_return_set_of_objects( self, *, request: typing.Sequence[ObjectWithRequiredField], - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[ObjectWithRequiredField]: """ Parameters @@ -508,18 +608,31 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/set-of-objects", method="POST", json=request, request_options=request_options, omit=OMIT + "container/set-of-objects", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.List[ObjectWithRequiredField], parse_obj_as(type_=typing.List[ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.List[ObjectWithRequiredField], + parse_obj_as( + type_=typing.List[ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_and_return_map_prim_to_prim( - self, *, request: typing.Dict[str, str], request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Dict[str, str], + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Dict[str, str]: """ Parameters @@ -554,11 +667,18 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/map-prim-to-prim", method="POST", json=request, request_options=request_options, omit=OMIT + "container/map-prim-to-prim", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Dict[str, str], parse_obj_as(type_=typing.Dict[str, str], object_=_response.json())) # type: ignore + return typing.cast( + typing.Dict[str, str], + parse_obj_as(type_=typing.Dict[str, str], object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -568,7 +688,7 @@ async def get_and_return_map_of_prim_to_object( self, *, request: typing.Dict[str, ObjectWithRequiredField], - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Dict[str, ObjectWithRequiredField]: """ Parameters @@ -608,11 +728,21 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/map-prim-to-object", method="POST", json=request, request_options=request_options, omit=OMIT + "container/map-prim-to-object", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Dict[str, ObjectWithRequiredField], parse_obj_as(type_=typing.Dict[str, ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.Dict[str, ObjectWithRequiredField], + parse_obj_as( + type_=typing.Dict[str, ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -622,7 +752,7 @@ async def get_and_return_optional( self, *, request: typing.Optional[ObjectWithRequiredField] = None, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Optional[ObjectWithRequiredField]: """ Parameters @@ -660,11 +790,21 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/opt-objects", method="POST", json=request, request_options=request_options, omit=OMIT + "container/opt-objects", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Optional[ObjectWithRequiredField], parse_obj_as(type_=typing.Optional[ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.Optional[ObjectWithRequiredField], + parse_obj_as( + type_=typing.Optional[ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/endpoints/enum/client.py b/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/endpoints/enum/client.py index 44e2690ff6c..3e3208e3bcf 100644 --- a/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/endpoints/enum/client.py +++ b/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/endpoints/enum/client.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. import typing +from ...core.client_wrapper import SyncClientWrapper +from ...types.enum.types.weather_report import WeatherReport +from ...core.request_options import RequestOptions +from ...core.pydantic_utilities import parse_obj_as from json.decoder import JSONDecodeError - from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ...core.pydantic_utilities import parse_obj_as -from ...core.request_options import RequestOptions -from ...types.enum.types.weather_report import WeatherReport +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -18,7 +18,10 @@ def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper def get_and_return_enum( - self, *, request: WeatherReport, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: WeatherReport, + request_options: typing.Optional[RequestOptions] = None, ) -> WeatherReport: """ Parameters @@ -45,11 +48,18 @@ def get_and_return_enum( ) """ _response = self._client_wrapper.httpx_client.request( - "enum", method="POST", json=request, request_options=request_options, omit=OMIT + "enum", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(WeatherReport, parse_obj_as(type_=WeatherReport, object_=_response.json())) # type: ignore + return typing.cast( + WeatherReport, + parse_obj_as(type_=WeatherReport, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -61,7 +71,10 @@ def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper async def get_and_return_enum( - self, *, request: WeatherReport, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: WeatherReport, + request_options: typing.Optional[RequestOptions] = None, ) -> WeatherReport: """ Parameters @@ -96,11 +109,18 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "enum", method="POST", json=request, request_options=request_options, omit=OMIT + "enum", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(WeatherReport, parse_obj_as(type_=WeatherReport, object_=_response.json())) # type: ignore + return typing.cast( + WeatherReport, + parse_obj_as(type_=WeatherReport, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/endpoints/http_methods/client.py b/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/endpoints/http_methods/client.py index a2549280a1b..570a227844f 100644 --- a/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/endpoints/http_methods/client.py +++ b/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/endpoints/http_methods/client.py @@ -1,16 +1,16 @@ # This file was auto-generated by Fern from our API Definition. -import datetime as dt import typing -import uuid -from json.decoder import JSONDecodeError - -from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper +from ...core.client_wrapper import SyncClientWrapper +from ...core.request_options import RequestOptions from ...core.jsonable_encoder import jsonable_encoder from ...core.pydantic_utilities import parse_obj_as -from ...core.request_options import RequestOptions +from json.decoder import JSONDecodeError +from ...core.api_error import ApiError from ...types.object.types.object_with_optional_field import ObjectWithOptionalField +import datetime as dt +import uuid +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -20,7 +20,9 @@ class HttpMethodsClient: def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper - def test_get(self, id: str, *, request_options: typing.Optional[RequestOptions] = None) -> str: + def test_get( + self, id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -46,11 +48,15 @@ def test_get(self, id: str, *, request_options: typing.Optional[RequestOptions] ) """ _response = self._client_wrapper.httpx_client.request( - f"http-methods/{jsonable_encoder(id)}", method="GET", request_options=request_options + f"http-methods/{jsonable_encoder(id)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -84,18 +90,33 @@ def test_post( ) """ _response = self._client_wrapper.httpx_client.request( - "http-methods", method="POST", json={"string": string}, request_options=request_options, omit=OMIT + "http-methods", + method="POST", + json={ + "string": string, + }, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def test_put( - self, id: str, *, string: str, request_options: typing.Optional[RequestOptions] = None + self, + id: str, + *, + string: str, + request_options: typing.Optional[RequestOptions] = None, ) -> ObjectWithOptionalField: """ Parameters @@ -127,13 +148,20 @@ def test_put( _response = self._client_wrapper.httpx_client.request( f"http-methods/{jsonable_encoder(id)}", method="PUT", - json={"string": string}, + json={ + "string": string, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -254,13 +282,20 @@ def test_patch( ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def test_delete(self, id: str, *, request_options: typing.Optional[RequestOptions] = None) -> bool: + def test_delete( + self, id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> bool: """ Parameters ---------- @@ -286,11 +321,15 @@ def test_delete(self, id: str, *, request_options: typing.Optional[RequestOption ) """ _response = self._client_wrapper.httpx_client.request( - f"http-methods/{jsonable_encoder(id)}", method="DELETE", request_options=request_options + f"http-methods/{jsonable_encoder(id)}", + method="DELETE", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -301,7 +340,9 @@ class AsyncHttpMethodsClient: def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper - async def test_get(self, id: str, *, request_options: typing.Optional[RequestOptions] = None) -> str: + async def test_get( + self, id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -335,11 +376,15 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - f"http-methods/{jsonable_encoder(id)}", method="GET", request_options=request_options + f"http-methods/{jsonable_encoder(id)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -381,18 +426,33 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "http-methods", method="POST", json={"string": string}, request_options=request_options, omit=OMIT + "http-methods", + method="POST", + json={ + "string": string, + }, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def test_put( - self, id: str, *, string: str, request_options: typing.Optional[RequestOptions] = None + self, + id: str, + *, + string: str, + request_options: typing.Optional[RequestOptions] = None, ) -> ObjectWithOptionalField: """ Parameters @@ -432,13 +492,20 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( f"http-methods/{jsonable_encoder(id)}", method="PUT", - json={"string": string}, + json={ + "string": string, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -566,13 +633,20 @@ async def main() -> None: ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - async def test_delete(self, id: str, *, request_options: typing.Optional[RequestOptions] = None) -> bool: + async def test_delete( + self, id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> bool: """ Parameters ---------- @@ -606,11 +680,15 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - f"http-methods/{jsonable_encoder(id)}", method="DELETE", request_options=request_options + f"http-methods/{jsonable_encoder(id)}", + method="DELETE", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/endpoints/object/client.py b/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/endpoints/object/client.py index a724f959193..dcb1324b74b 100644 --- a/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/endpoints/object/client.py +++ b/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/endpoints/object/client.py @@ -1,20 +1,24 @@ # This file was auto-generated by Fern from our API Definition. -import datetime as dt import typing +from ...core.client_wrapper import SyncClientWrapper +import datetime as dt import uuid -from json.decoder import JSONDecodeError - -from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ...core.jsonable_encoder import jsonable_encoder -from ...core.pydantic_utilities import parse_obj_as from ...core.request_options import RequestOptions -from ...types.object.types.nested_object_with_optional_field import NestedObjectWithOptionalField -from ...types.object.types.nested_object_with_required_field import NestedObjectWithRequiredField -from ...types.object.types.object_with_map_of_map import ObjectWithMapOfMap from ...types.object.types.object_with_optional_field import ObjectWithOptionalField +from ...core.pydantic_utilities import parse_obj_as +from json.decoder import JSONDecodeError +from ...core.api_error import ApiError from ...types.object.types.object_with_required_field import ObjectWithRequiredField +from ...types.object.types.object_with_map_of_map import ObjectWithMapOfMap +from ...types.object.types.nested_object_with_optional_field import ( + NestedObjectWithOptionalField, +) +from ...types.object.types.nested_object_with_required_field import ( + NestedObjectWithRequiredField, +) +from ...core.jsonable_encoder import jsonable_encoder +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -135,7 +139,12 @@ def get_and_return_with_optional_field( ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -171,20 +180,30 @@ def get_and_return_with_required_field( _response = self._client_wrapper.httpx_client.request( "object/get-and-return-with-required-field", method="POST", - json={"string": string}, + json={ + "string": string, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithRequiredField, parse_obj_as(type_=ObjectWithRequiredField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithRequiredField, + parse_obj_as( + type_=ObjectWithRequiredField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_and_return_with_map_of_map( - self, *, map_: typing.Dict[str, typing.Dict[str, str]], request_options: typing.Optional[RequestOptions] = None + self, + *, + map_: typing.Dict[str, typing.Dict[str, str]], + request_options: typing.Optional[RequestOptions] = None, ) -> ObjectWithMapOfMap: """ Parameters @@ -213,13 +232,18 @@ def get_and_return_with_map_of_map( _response = self._client_wrapper.httpx_client.request( "object/get-and-return-with-map-of-map", method="POST", - json={"map": map_}, + json={ + "map": map_, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithMapOfMap, parse_obj_as(type_=ObjectWithMapOfMap, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithMapOfMap, + parse_obj_as(type_=ObjectWithMapOfMap, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -286,13 +310,21 @@ def get_and_return_nested_with_optional_field( _response = self._client_wrapper.httpx_client.request( "object/get-and-return-nested-with-optional-field", method="POST", - json={"string": string, "NestedObject": nested_object}, + json={ + "string": string, + "NestedObject": nested_object, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(NestedObjectWithOptionalField, parse_obj_as(type_=NestedObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + NestedObjectWithOptionalField, + parse_obj_as( + type_=NestedObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -363,13 +395,21 @@ def get_and_return_nested_with_required_field( _response = self._client_wrapper.httpx_client.request( f"object/get-and-return-nested-with-required-field/{jsonable_encoder(string_)}", method="POST", - json={"string": string, "NestedObject": nested_object}, + json={ + "string": string, + "NestedObject": nested_object, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(NestedObjectWithRequiredField, parse_obj_as(type_=NestedObjectWithRequiredField, object_=_response.json())) # type: ignore + return typing.cast( + NestedObjectWithRequiredField, + parse_obj_as( + type_=NestedObjectWithRequiredField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -446,7 +486,12 @@ def get_and_return_nested_with_required_field_as_list( ) try: if 200 <= _response.status_code < 300: - return typing.cast(NestedObjectWithRequiredField, parse_obj_as(type_=NestedObjectWithRequiredField, object_=_response.json())) # type: ignore + return typing.cast( + NestedObjectWithRequiredField, + parse_obj_as( + type_=NestedObjectWithRequiredField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -575,7 +620,12 @@ async def main() -> None: ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -619,20 +669,30 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( "object/get-and-return-with-required-field", method="POST", - json={"string": string}, + json={ + "string": string, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithRequiredField, parse_obj_as(type_=ObjectWithRequiredField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithRequiredField, + parse_obj_as( + type_=ObjectWithRequiredField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_and_return_with_map_of_map( - self, *, map_: typing.Dict[str, typing.Dict[str, str]], request_options: typing.Optional[RequestOptions] = None + self, + *, + map_: typing.Dict[str, typing.Dict[str, str]], + request_options: typing.Optional[RequestOptions] = None, ) -> ObjectWithMapOfMap: """ Parameters @@ -669,13 +729,18 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( "object/get-and-return-with-map-of-map", method="POST", - json={"map": map_}, + json={ + "map": map_, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithMapOfMap, parse_obj_as(type_=ObjectWithMapOfMap, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithMapOfMap, + parse_obj_as(type_=ObjectWithMapOfMap, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -749,13 +814,21 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( "object/get-and-return-nested-with-optional-field", method="POST", - json={"string": string, "NestedObject": nested_object}, + json={ + "string": string, + "NestedObject": nested_object, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(NestedObjectWithOptionalField, parse_obj_as(type_=NestedObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + NestedObjectWithOptionalField, + parse_obj_as( + type_=NestedObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -833,13 +906,21 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( f"object/get-and-return-nested-with-required-field/{jsonable_encoder(string_)}", method="POST", - json={"string": string, "NestedObject": nested_object}, + json={ + "string": string, + "NestedObject": nested_object, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(NestedObjectWithRequiredField, parse_obj_as(type_=NestedObjectWithRequiredField, object_=_response.json())) # type: ignore + return typing.cast( + NestedObjectWithRequiredField, + parse_obj_as( + type_=NestedObjectWithRequiredField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -923,7 +1004,12 @@ async def main() -> None: ) try: if 200 <= _response.status_code < 300: - return typing.cast(NestedObjectWithRequiredField, parse_obj_as(type_=NestedObjectWithRequiredField, object_=_response.json())) # type: ignore + return typing.cast( + NestedObjectWithRequiredField, + parse_obj_as( + type_=NestedObjectWithRequiredField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/endpoints/params/client.py b/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/endpoints/params/client.py index 5cd7ceef42a..a9187ac94b8 100644 --- a/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/endpoints/params/client.py +++ b/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/endpoints/params/client.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. import typing -from json.decoder import JSONDecodeError - -from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper +from ...core.client_wrapper import SyncClientWrapper +from ...core.request_options import RequestOptions from ...core.jsonable_encoder import jsonable_encoder from ...core.pydantic_utilities import parse_obj_as -from ...core.request_options import RequestOptions +from json.decoder import JSONDecodeError +from ...core.api_error import ApiError +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -17,7 +17,9 @@ class ParamsClient: def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper - def get_with_path(self, param: str, *, request_options: typing.Optional[RequestOptions] = None) -> str: + def get_with_path( + self, param: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ GET with path param @@ -45,18 +47,26 @@ def get_with_path(self, param: str, *, request_options: typing.Optional[RequestO ) """ _response = self._client_wrapper.httpx_client.request( - f"params/path/{jsonable_encoder(param)}", method="GET", request_options=request_options + f"params/path/{jsonable_encoder(param)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_with_query( - self, *, query: str, number: int, request_options: typing.Optional[RequestOptions] = None + self, + *, + query: str, + number: int, + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ GET with query param @@ -88,7 +98,13 @@ def get_with_query( ) """ _response = self._client_wrapper.httpx_client.request( - "params", method="GET", params={"query": query, "number": number}, request_options=request_options + "params", + method="GET", + params={ + "query": query, + "number": number, + }, + request_options=request_options, ) try: if 200 <= _response.status_code < 300: @@ -135,7 +151,13 @@ def get_with_allow_multiple_query( ) """ _response = self._client_wrapper.httpx_client.request( - "params", method="GET", params={"query": query, "numer": numer}, request_options=request_options + "params", + method="GET", + params={ + "query": query, + "numer": numer, + }, + request_options=request_options, ) try: if 200 <= _response.status_code < 300: @@ -146,7 +168,11 @@ def get_with_allow_multiple_query( raise ApiError(status_code=_response.status_code, body=_response_json) def get_with_path_and_query( - self, param: str, *, query: str, request_options: typing.Optional[RequestOptions] = None + self, + param: str, + *, + query: str, + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ GET with path and query params @@ -180,7 +206,9 @@ def get_with_path_and_query( _response = self._client_wrapper.httpx_client.request( f"params/path-query/{jsonable_encoder(param)}", method="GET", - params={"query": query}, + params={ + "query": query, + }, request_options=request_options, ) try: @@ -192,7 +220,11 @@ def get_with_path_and_query( raise ApiError(status_code=_response.status_code, body=_response_json) def modify_with_path( - self, param: str, *, request: str, request_options: typing.Optional[RequestOptions] = None + self, + param: str, + *, + request: str, + request_options: typing.Optional[RequestOptions] = None, ) -> str: """ PUT to update with path param @@ -232,7 +264,9 @@ def modify_with_path( ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -243,7 +277,9 @@ class AsyncParamsClient: def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper - async def get_with_path(self, param: str, *, request_options: typing.Optional[RequestOptions] = None) -> str: + async def get_with_path( + self, param: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ GET with path param @@ -279,18 +315,26 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - f"params/path/{jsonable_encoder(param)}", method="GET", request_options=request_options + f"params/path/{jsonable_encoder(param)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_with_query( - self, *, query: str, number: int, request_options: typing.Optional[RequestOptions] = None + self, + *, + query: str, + number: int, + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ GET with query param @@ -330,7 +374,13 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "params", method="GET", params={"query": query, "number": number}, request_options=request_options + "params", + method="GET", + params={ + "query": query, + "number": number, + }, + request_options=request_options, ) try: if 200 <= _response.status_code < 300: @@ -385,7 +435,13 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "params", method="GET", params={"query": query, "numer": numer}, request_options=request_options + "params", + method="GET", + params={ + "query": query, + "numer": numer, + }, + request_options=request_options, ) try: if 200 <= _response.status_code < 300: @@ -396,7 +452,11 @@ async def main() -> None: raise ApiError(status_code=_response.status_code, body=_response_json) async def get_with_path_and_query( - self, param: str, *, query: str, request_options: typing.Optional[RequestOptions] = None + self, + param: str, + *, + query: str, + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ GET with path and query params @@ -438,7 +498,9 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( f"params/path-query/{jsonable_encoder(param)}", method="GET", - params={"query": query}, + params={ + "query": query, + }, request_options=request_options, ) try: @@ -450,7 +512,11 @@ async def main() -> None: raise ApiError(status_code=_response.status_code, body=_response_json) async def modify_with_path( - self, param: str, *, request: str, request_options: typing.Optional[RequestOptions] = None + self, + param: str, + *, + request: str, + request_options: typing.Optional[RequestOptions] = None, ) -> str: """ PUT to update with path param @@ -498,7 +564,9 @@ async def main() -> None: ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/endpoints/primitive/client.py b/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/endpoints/primitive/client.py index 844b6a782f0..20a66f049b4 100644 --- a/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/endpoints/primitive/client.py +++ b/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/endpoints/primitive/client.py @@ -1,14 +1,14 @@ # This file was auto-generated by Fern from our API Definition. -import datetime as dt import typing -import uuid +from ...core.client_wrapper import SyncClientWrapper +from ...core.request_options import RequestOptions +from ...core.pydantic_utilities import parse_obj_as from json.decoder import JSONDecodeError - from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ...core.pydantic_utilities import parse_obj_as -from ...core.request_options import RequestOptions +import datetime as dt +import uuid +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -18,7 +18,9 @@ class PrimitiveClient: def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper - def get_and_return_string(self, *, request: str, request_options: typing.Optional[RequestOptions] = None) -> str: + def get_and_return_string( + self, *, request: str, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -44,17 +46,25 @@ def get_and_return_string(self, *, request: str, request_options: typing.Optiona ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/string", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/string", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def get_and_return_int(self, *, request: int, request_options: typing.Optional[RequestOptions] = None) -> int: + def get_and_return_int( + self, *, request: int, request_options: typing.Optional[RequestOptions] = None + ) -> int: """ Parameters ---------- @@ -80,17 +90,25 @@ def get_and_return_int(self, *, request: int, request_options: typing.Optional[R ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/integer", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/integer", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(int, parse_obj_as(type_=int, object_=_response.json())) # type: ignore + return typing.cast( + int, parse_obj_as(type_=int, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def get_and_return_long(self, *, request: int, request_options: typing.Optional[RequestOptions] = None) -> int: + def get_and_return_long( + self, *, request: int, request_options: typing.Optional[RequestOptions] = None + ) -> int: """ Parameters ---------- @@ -116,11 +134,17 @@ def get_and_return_long(self, *, request: int, request_options: typing.Optional[ ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/long", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/long", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(int, parse_obj_as(type_=int, object_=_response.json())) # type: ignore + return typing.cast( + int, parse_obj_as(type_=int, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -154,17 +178,25 @@ def get_and_return_double( ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/double", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/double", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(float, parse_obj_as(type_=float, object_=_response.json())) # type: ignore + return typing.cast( + float, parse_obj_as(type_=float, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def get_and_return_bool(self, *, request: bool, request_options: typing.Optional[RequestOptions] = None) -> bool: + def get_and_return_bool( + self, *, request: bool, request_options: typing.Optional[RequestOptions] = None + ) -> bool: """ Parameters ---------- @@ -190,18 +222,27 @@ def get_and_return_bool(self, *, request: bool, request_options: typing.Optional ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/boolean", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/boolean", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_and_return_datetime( - self, *, request: dt.datetime, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: dt.datetime, + request_options: typing.Optional[RequestOptions] = None, ) -> dt.datetime: """ Parameters @@ -232,18 +273,28 @@ def get_and_return_datetime( ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/datetime", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/datetime", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(dt.datetime, parse_obj_as(type_=dt.datetime, object_=_response.json())) # type: ignore + return typing.cast( + dt.datetime, + parse_obj_as(type_=dt.datetime, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_and_return_date( - self, *, request: dt.date, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: dt.date, + request_options: typing.Optional[RequestOptions] = None, ) -> dt.date: """ Parameters @@ -274,18 +325,27 @@ def get_and_return_date( ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/date", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/date", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(dt.date, parse_obj_as(type_=dt.date, object_=_response.json())) # type: ignore + return typing.cast( + dt.date, parse_obj_as(type_=dt.date, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_and_return_uuid( - self, *, request: uuid.UUID, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: uuid.UUID, + request_options: typing.Optional[RequestOptions] = None, ) -> uuid.UUID: """ Parameters @@ -316,17 +376,25 @@ def get_and_return_uuid( ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/uuid", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/uuid", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(uuid.UUID, parse_obj_as(type_=uuid.UUID, object_=_response.json())) # type: ignore + return typing.cast( + uuid.UUID, parse_obj_as(type_=uuid.UUID, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def get_and_return_base_64(self, *, request: str, request_options: typing.Optional[RequestOptions] = None) -> str: + def get_and_return_base_64( + self, *, request: str, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -352,11 +420,17 @@ def get_and_return_base_64(self, *, request: str, request_options: typing.Option ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/base64", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/base64", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -403,17 +477,25 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/string", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/string", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - async def get_and_return_int(self, *, request: int, request_options: typing.Optional[RequestOptions] = None) -> int: + async def get_and_return_int( + self, *, request: int, request_options: typing.Optional[RequestOptions] = None + ) -> int: """ Parameters ---------- @@ -447,11 +529,17 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/integer", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/integer", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(int, parse_obj_as(type_=int, object_=_response.json())) # type: ignore + return typing.cast( + int, parse_obj_as(type_=int, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -493,11 +581,17 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/long", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/long", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(int, parse_obj_as(type_=int, object_=_response.json())) # type: ignore + return typing.cast( + int, parse_obj_as(type_=int, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -539,11 +633,17 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/double", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/double", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(float, parse_obj_as(type_=float, object_=_response.json())) # type: ignore + return typing.cast( + float, parse_obj_as(type_=float, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -585,18 +685,27 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/boolean", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/boolean", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_and_return_datetime( - self, *, request: dt.datetime, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: dt.datetime, + request_options: typing.Optional[RequestOptions] = None, ) -> dt.datetime: """ Parameters @@ -634,18 +743,28 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/datetime", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/datetime", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(dt.datetime, parse_obj_as(type_=dt.datetime, object_=_response.json())) # type: ignore + return typing.cast( + dt.datetime, + parse_obj_as(type_=dt.datetime, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_and_return_date( - self, *, request: dt.date, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: dt.date, + request_options: typing.Optional[RequestOptions] = None, ) -> dt.date: """ Parameters @@ -683,18 +802,27 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/date", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/date", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(dt.date, parse_obj_as(type_=dt.date, object_=_response.json())) # type: ignore + return typing.cast( + dt.date, parse_obj_as(type_=dt.date, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_and_return_uuid( - self, *, request: uuid.UUID, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: uuid.UUID, + request_options: typing.Optional[RequestOptions] = None, ) -> uuid.UUID: """ Parameters @@ -732,11 +860,17 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/uuid", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/uuid", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(uuid.UUID, parse_obj_as(type_=uuid.UUID, object_=_response.json())) # type: ignore + return typing.cast( + uuid.UUID, parse_obj_as(type_=uuid.UUID, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -778,11 +912,17 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/base64", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/base64", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/endpoints/union/client.py b/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/endpoints/union/client.py index 77153587a27..f4c3d9312de 100644 --- a/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/endpoints/union/client.py +++ b/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/endpoints/union/client.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. import typing +from ...core.client_wrapper import SyncClientWrapper +from ...types.union.types.animal import Animal +from ...core.request_options import RequestOptions +from ...core.pydantic_utilities import parse_obj_as from json.decoder import JSONDecodeError - from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ...core.pydantic_utilities import parse_obj_as -from ...core.request_options import RequestOptions -from ...types.union.types.animal import Animal +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -18,7 +18,10 @@ def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper def get_and_return_union( - self, *, request: Animal, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: Animal, + request_options: typing.Optional[RequestOptions] = None, ) -> Animal: """ Parameters @@ -49,11 +52,17 @@ def get_and_return_union( ) """ _response = self._client_wrapper.httpx_client.request( - "union", method="POST", json=request, request_options=request_options, omit=OMIT + "union", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(Animal, parse_obj_as(type_=Animal, object_=_response.json())) # type: ignore + return typing.cast( + Animal, parse_obj_as(type_=Animal, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -65,7 +74,10 @@ def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper async def get_and_return_union( - self, *, request: Animal, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: Animal, + request_options: typing.Optional[RequestOptions] = None, ) -> Animal: """ Parameters @@ -104,11 +116,17 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "union", method="POST", json=request, request_options=request_options, omit=OMIT + "union", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(Animal, parse_obj_as(type_=Animal, object_=_response.json())) # type: ignore + return typing.cast( + Animal, parse_obj_as(type_=Animal, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/general_errors/types/bad_object_request_info.py b/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/general_errors/types/bad_object_request_info.py index 7f03429e922..73c44b89531 100644 --- a/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/general_errors/types/bad_object_request_info.py +++ b/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/general_errors/types/bad_object_request_info.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class BadObjectRequestInfo(UniversalBaseModel): message: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/inlined_requests/client.py b/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/inlined_requests/client.py index f7c46698eb9..39e0c8fe637 100644 --- a/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/inlined_requests/client.py +++ b/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/inlined_requests/client.py @@ -1,15 +1,15 @@ # This file was auto-generated by Fern from our API Definition. import typing -from json.decoder import JSONDecodeError - -from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.pydantic_utilities import parse_obj_as +from ..core.client_wrapper import SyncClientWrapper +from ..types.object.types.object_with_optional_field import ObjectWithOptionalField from ..core.request_options import RequestOptions +from ..core.pydantic_utilities import parse_obj_as from ..general_errors.errors.bad_request_body import BadRequestBody from ..general_errors.types.bad_object_request_info import BadObjectRequestInfo -from ..types.object.types.object_with_optional_field import ObjectWithOptionalField +from json.decoder import JSONDecodeError +from ..core.api_error import ApiError +from ..core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -25,7 +25,7 @@ def post_with_object_bodyand_response( string: str, integer: int, nested_object: ObjectWithOptionalField, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> ObjectWithOptionalField: """ POST with custom object in request body, response is an object @@ -86,16 +86,30 @@ def post_with_object_bodyand_response( _response = self._client_wrapper.httpx_client.request( "req-bodies/object", method="POST", - json={"string": string, "integer": integer, "NestedObject": nested_object}, + json={ + "string": string, + "integer": integer, + "NestedObject": nested_object, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore if _response.status_code == 400: raise BadRequestBody( - typing.cast(BadObjectRequestInfo, parse_obj_as(type_=BadObjectRequestInfo, object_=_response.json())) # type: ignore + typing.cast( + BadObjectRequestInfo, + parse_obj_as( + type_=BadObjectRequestInfo, object_=_response.json() + ), + ) # type: ignore ) _response_json = _response.json() except JSONDecodeError: @@ -113,7 +127,7 @@ async def post_with_object_bodyand_response( string: str, integer: int, nested_object: ObjectWithOptionalField, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> ObjectWithOptionalField: """ POST with custom object in request body, response is an object @@ -181,16 +195,30 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( "req-bodies/object", method="POST", - json={"string": string, "integer": integer, "NestedObject": nested_object}, + json={ + "string": string, + "integer": integer, + "NestedObject": nested_object, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore if _response.status_code == 400: raise BadRequestBody( - typing.cast(BadObjectRequestInfo, parse_obj_as(type_=BadObjectRequestInfo, object_=_response.json())) # type: ignore + typing.cast( + BadObjectRequestInfo, + parse_obj_as( + type_=BadObjectRequestInfo, object_=_response.json() + ), + ) # type: ignore ) _response_json = _response.json() except JSONDecodeError: diff --git a/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/no_auth/client.py b/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/no_auth/client.py index 3d203bcea34..e5590cde0df 100644 --- a/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/no_auth/client.py +++ b/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/no_auth/client.py @@ -1,14 +1,14 @@ # This file was auto-generated by Fern from our API Definition. import typing -from json.decoder import JSONDecodeError - -from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.pydantic_utilities import parse_obj_as +from ..core.client_wrapper import SyncClientWrapper from ..core.request_options import RequestOptions +from ..core.pydantic_utilities import parse_obj_as from ..general_errors.errors.bad_request_body import BadRequestBody from ..general_errors.types.bad_object_request_info import BadObjectRequestInfo +from json.decoder import JSONDecodeError +from ..core.api_error import ApiError +from ..core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -19,7 +19,10 @@ def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper def post_with_no_auth( - self, *, request: typing.Any, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Any, + request_options: typing.Optional[RequestOptions] = None, ) -> bool: """ POST request with no auth @@ -48,14 +51,25 @@ def post_with_no_auth( ) """ _response = self._client_wrapper.httpx_client.request( - "no-auth", method="POST", json=request, request_options=request_options, omit=OMIT + "no-auth", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore if _response.status_code == 400: raise BadRequestBody( - typing.cast(BadObjectRequestInfo, parse_obj_as(type_=BadObjectRequestInfo, object_=_response.json())) # type: ignore + typing.cast( + BadObjectRequestInfo, + parse_obj_as( + type_=BadObjectRequestInfo, object_=_response.json() + ), + ) # type: ignore ) _response_json = _response.json() except JSONDecodeError: @@ -68,7 +82,10 @@ def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper async def post_with_no_auth( - self, *, request: typing.Any, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Any, + request_options: typing.Optional[RequestOptions] = None, ) -> bool: """ POST request with no auth @@ -105,14 +122,25 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "no-auth", method="POST", json=request, request_options=request_options, omit=OMIT + "no-auth", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore if _response.status_code == 400: raise BadRequestBody( - typing.cast(BadObjectRequestInfo, parse_obj_as(type_=BadObjectRequestInfo, object_=_response.json())) # type: ignore + typing.cast( + BadObjectRequestInfo, + parse_obj_as( + type_=BadObjectRequestInfo, object_=_response.json() + ), + ) # type: ignore ) _response_json = _response.json() except JSONDecodeError: diff --git a/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/no_req_body/client.py b/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/no_req_body/client.py index 33fa0c77d27..5afdd703fdc 100644 --- a/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/no_req_body/client.py +++ b/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/no_req_body/client.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. +from ..core.client_wrapper import SyncClientWrapper import typing -from json.decoder import JSONDecodeError - -from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.pydantic_utilities import parse_obj_as from ..core.request_options import RequestOptions from ..types.object.types.object_with_optional_field import ObjectWithOptionalField +from ..core.pydantic_utilities import parse_obj_as +from json.decoder import JSONDecodeError +from ..core.api_error import ApiError +from ..core.client_wrapper import AsyncClientWrapper class NoReqBodyClient: @@ -38,17 +38,26 @@ def get_with_no_request_body( client.no_req_body.get_with_no_request_body() """ _response = self._client_wrapper.httpx_client.request( - "no-req-body", method="GET", request_options=request_options + "no-req-body", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def post_with_no_request_body(self, *, request_options: typing.Optional[RequestOptions] = None) -> str: + def post_with_no_request_body( + self, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -70,11 +79,15 @@ def post_with_no_request_body(self, *, request_options: typing.Optional[RequestO client.no_req_body.post_with_no_request_body() """ _response = self._client_wrapper.httpx_client.request( - "no-req-body", method="POST", request_options=request_options + "no-req-body", + method="POST", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -117,17 +130,26 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "no-req-body", method="GET", request_options=request_options + "no-req-body", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - async def post_with_no_request_body(self, *, request_options: typing.Optional[RequestOptions] = None) -> str: + async def post_with_no_request_body( + self, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -157,11 +179,15 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "no-req-body", method="POST", request_options=request_options + "no-req-body", + method="POST", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/req_with_headers/client.py b/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/req_with_headers/client.py index 655402249e9..984428516e3 100644 --- a/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/req_with_headers/client.py +++ b/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/req_with_headers/client.py @@ -1,11 +1,11 @@ # This file was auto-generated by Fern from our API Definition. import typing +from ..core.client_wrapper import SyncClientWrapper +from ..core.request_options import RequestOptions from json.decoder import JSONDecodeError - from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.request_options import RequestOptions +from ..core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -21,7 +21,7 @@ def get_with_custom_header( x_test_service_header: str, x_test_endpoint_header: str, request: str, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ Parameters @@ -58,8 +58,12 @@ def get_with_custom_header( method="POST", json=request, headers={ - "X-TEST-SERVICE-HEADER": str(x_test_service_header) if x_test_service_header is not None else None, - "X-TEST-ENDPOINT-HEADER": str(x_test_endpoint_header) if x_test_endpoint_header is not None else None, + "X-TEST-SERVICE-HEADER": str(x_test_service_header) + if x_test_service_header is not None + else None, + "X-TEST-ENDPOINT-HEADER": str(x_test_endpoint_header) + if x_test_endpoint_header is not None + else None, }, request_options=request_options, omit=OMIT, @@ -83,7 +87,7 @@ async def get_with_custom_header( x_test_service_header: str, x_test_endpoint_header: str, request: str, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ Parameters @@ -128,8 +132,12 @@ async def main() -> None: method="POST", json=request, headers={ - "X-TEST-SERVICE-HEADER": str(x_test_service_header) if x_test_service_header is not None else None, - "X-TEST-ENDPOINT-HEADER": str(x_test_endpoint_header) if x_test_endpoint_header is not None else None, + "X-TEST-SERVICE-HEADER": str(x_test_service_header) + if x_test_service_header is not None + else None, + "X-TEST-ENDPOINT-HEADER": str(x_test_endpoint_header) + if x_test_endpoint_header is not None + else None, }, request_options=request_options, omit=OMIT, diff --git a/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/types/enum/types/weather_report.py b/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/types/enum/types/weather_report.py index 2d54965dc22..84017ef161d 100644 --- a/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/types/enum/types/weather_report.py +++ b/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/types/enum/types/weather_report.py @@ -2,4 +2,6 @@ import typing -WeatherReport = typing.Union[typing.Literal["SUNNY", "CLOUDY", "RAINING", "SNOWING"], typing.Any] +WeatherReport = typing.Union[ + typing.Literal["SUNNY", "CLOUDY", "RAINING", "SNOWING"], typing.Any +] diff --git a/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/types/object/types/double_optional.py b/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/types/object/types/double_optional.py index ddf165b13bd..ed236347357 100644 --- a/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/types/object/types/double_optional.py +++ b/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/types/object/types/double_optional.py @@ -1,18 +1,21 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .optional_alias import OptionalAlias +import pydantic +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class DoubleOptional(UniversalBaseModel): - optional_alias: typing.Optional[OptionalAlias] = pydantic.Field(alias="optionalAlias", default=None) + optional_alias: typing.Optional[OptionalAlias] = pydantic.Field( + alias="optionalAlias", default=None + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/types/object/types/nested_object_with_optional_field.py b/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/types/object/types/nested_object_with_optional_field.py index 81669c0dd39..20a4d40a714 100644 --- a/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/types/object/types/nested_object_with_optional_field.py +++ b/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/types/object/types/nested_object_with_optional_field.py @@ -1,19 +1,22 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .object_with_optional_field import ObjectWithOptionalField +import pydantic +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class NestedObjectWithOptionalField(UniversalBaseModel): string: typing.Optional[str] = None - nested_object: typing.Optional[ObjectWithOptionalField] = pydantic.Field(alias="NestedObject", default=None) + nested_object: typing.Optional[ObjectWithOptionalField] = pydantic.Field( + alias="NestedObject", default=None + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/types/object/types/nested_object_with_required_field.py b/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/types/object/types/nested_object_with_required_field.py index 1a621942c6c..a6ca8781190 100644 --- a/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/types/object/types/nested_object_with_required_field.py +++ b/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/types/object/types/nested_object_with_required_field.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import UniversalBaseModel from .object_with_optional_field import ObjectWithOptionalField +import pydantic +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class NestedObjectWithRequiredField(UniversalBaseModel): @@ -13,7 +12,9 @@ class NestedObjectWithRequiredField(UniversalBaseModel): nested_object: ObjectWithOptionalField = pydantic.Field(alias="NestedObject") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/types/object/types/object_with_map_of_map.py b/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/types/object/types/object_with_map_of_map.py index 8883cc1d498..313cd25ceb8 100644 --- a/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/types/object/types/object_with_map_of_map.py +++ b/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/types/object/types/object_with_map_of_map.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class ObjectWithMapOfMap(UniversalBaseModel): map_: typing.Dict[str, typing.Dict[str, str]] = pydantic.Field(alias="map") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/types/object/types/object_with_optional_field.py b/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/types/object/types/object_with_optional_field.py index 6aab170be0c..9131f0e91d7 100644 --- a/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/types/object/types/object_with_optional_field.py +++ b/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/types/object/types/object_with_optional_field.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. -import datetime as dt +from ....core.pydantic_utilities import UniversalBaseModel import typing -import uuid - import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +import datetime as dt +import uuid +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class ObjectWithOptionalField(UniversalBaseModel): @@ -23,13 +22,19 @@ class ObjectWithOptionalField(UniversalBaseModel): date: typing.Optional[dt.date] = None uuid_: typing.Optional[uuid.UUID] = pydantic.Field(alias="uuid", default=None) base_64: typing.Optional[str] = pydantic.Field(alias="base64", default=None) - list_: typing.Optional[typing.List[str]] = pydantic.Field(alias="list", default=None) + list_: typing.Optional[typing.List[str]] = pydantic.Field( + alias="list", default=None + ) set_: typing.Optional[typing.Set[str]] = pydantic.Field(alias="set", default=None) - map_: typing.Optional[typing.Dict[int, str]] = pydantic.Field(alias="map", default=None) + map_: typing.Optional[typing.Dict[int, str]] = pydantic.Field( + alias="map", default=None + ) bigint: typing.Optional[str] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/types/object/types/object_with_required_field.py b/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/types/object/types/object_with_required_field.py index 61b98867984..24db26a3cf8 100644 --- a/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/types/object/types/object_with_required_field.py +++ b/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/types/object/types/object_with_required_field.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class ObjectWithRequiredField(UniversalBaseModel): string: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/types/union/types/animal.py b/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/types/union/types/animal.py index 1ae43d1663e..84c71d2009a 100644 --- a/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/types/union/types/animal.py +++ b/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/types/union/types/animal.py @@ -1,12 +1,10 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ....core.pydantic_utilities import UniversalBaseModel import typing - import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class Animal_Dog(UniversalBaseModel): @@ -15,7 +13,9 @@ class Animal_Dog(UniversalBaseModel): likes_to_woof: bool = pydantic.Field(alias="likesToWoof") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: @@ -30,7 +30,9 @@ class Animal_Cat(UniversalBaseModel): likes_to_meow: bool = pydantic.Field(alias="likesToMeow") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/types/union/types/cat.py b/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/types/union/types/cat.py index 61fc5527b1f..c59b78523c9 100644 --- a/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/types/union/types/cat.py +++ b/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/types/union/types/cat.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ....core.pydantic_utilities import UniversalBaseModel import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class Cat(UniversalBaseModel): @@ -12,7 +11,9 @@ class Cat(UniversalBaseModel): likes_to_meow: bool = pydantic.Field(alias="likesToMeow") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/types/union/types/dog.py b/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/types/union/types/dog.py index c1ff5339dfe..e250c72edef 100644 --- a/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/types/union/types/dog.py +++ b/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/types/union/types/dog.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ....core.pydantic_utilities import UniversalBaseModel import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class Dog(UniversalBaseModel): @@ -12,7 +11,9 @@ class Dog(UniversalBaseModel): likes_to_woof: bool = pydantic.Field(alias="likesToWoof") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/version.py b/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/version.py index 63ba170685a..ac44536abdb 100644 --- a/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/version.py +++ b/seed/python-sdk/exhaustive/deps_with_min_python_version/src/seed/version.py @@ -1,4 +1,3 @@ - from importlib import metadata __version__ = metadata.version("fern_exhaustive") diff --git a/seed/python-sdk/exhaustive/deps_with_min_python_version/tests/conftest.py b/seed/python-sdk/exhaustive/deps_with_min_python_version/tests/conftest.py index b5b50383b94..86cb2b41af8 100644 --- a/seed/python-sdk/exhaustive/deps_with_min_python_version/tests/conftest.py +++ b/seed/python-sdk/exhaustive/deps_with_min_python_version/tests/conftest.py @@ -1,16 +1,22 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive import os - import pytest -from seed import AsyncSeedExhaustive, SeedExhaustive +from seed import AsyncSeedExhaustive @pytest.fixture def client() -> SeedExhaustive: - return SeedExhaustive(token=os.getenv("ENV_TOKEN", "token"), base_url=os.getenv("TESTS_BASE_URL", "base_url")) + return SeedExhaustive( + token=os.getenv("ENV_TOKEN", "token"), + base_url=os.getenv("TESTS_BASE_URL", "base_url"), + ) @pytest.fixture def async_client() -> AsyncSeedExhaustive: - return AsyncSeedExhaustive(token=os.getenv("ENV_TOKEN", "token"), base_url=os.getenv("TESTS_BASE_URL", "base_url")) + return AsyncSeedExhaustive( + token=os.getenv("ENV_TOKEN", "token"), + base_url=os.getenv("TESTS_BASE_URL", "base_url"), + ) diff --git a/seed/python-sdk/exhaustive/deps_with_min_python_version/tests/custom/test_client.py b/seed/python-sdk/exhaustive/deps_with_min_python_version/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/python-sdk/exhaustive/deps_with_min_python_version/tests/custom/test_client.py +++ b/seed/python-sdk/exhaustive/deps_with_min_python_version/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/python-sdk/exhaustive/deps_with_min_python_version/tests/endpoints/test_container.py b/seed/python-sdk/exhaustive/deps_with_min_python_version/tests/endpoints/test_container.py index 17d9d75240d..240f16f2a8c 100644 --- a/seed/python-sdk/exhaustive/deps_with_min_python_version/tests/endpoints/test_container.py +++ b/seed/python-sdk/exhaustive/deps_with_min_python_version/tests/endpoints/test_container.py @@ -1,91 +1,137 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing - -from seed import AsyncSeedExhaustive, SeedExhaustive -from seed.types.object import ObjectWithRequiredField - from ..utilities import validate_response +from seed.types.object import ObjectWithRequiredField -async def test_get_and_return_list_of_primitives(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_list_of_primitives( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = ["string"] expected_types: typing.Tuple[typing.Any, typing.Any] = ("list", {0: None}) - response = client.endpoints.container.get_and_return_list_of_primitives(request=["string"]) + response = client.endpoints.container.get_and_return_list_of_primitives( + request=["string"] + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.container.get_and_return_list_of_primitives(request=["string"]) + async_response = ( + await async_client.endpoints.container.get_and_return_list_of_primitives( + request=["string"] + ) + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_list_of_objects(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_list_of_objects( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = [{"string": "string"}] - expected_types: typing.Tuple[typing.Any, typing.Any] = ("list", {0: {"string": None}}) + expected_types: typing.Tuple[typing.Any, typing.Any] = ( + "list", + {0: {"string": None}}, + ) response = client.endpoints.container.get_and_return_list_of_objects( request=[ObjectWithRequiredField(string="string")] ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.container.get_and_return_list_of_objects( - request=[ObjectWithRequiredField(string="string")] + async_response = ( + await async_client.endpoints.container.get_and_return_list_of_objects( + request=[ObjectWithRequiredField(string="string")] + ) ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_set_of_primitives(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_set_of_primitives( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = ["string"] expected_types: typing.Tuple[typing.Any, typing.Any] = ("set", {0: None}) - response = client.endpoints.container.get_and_return_set_of_primitives(request={"string"}) + response = client.endpoints.container.get_and_return_set_of_primitives( + request={"string"} + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.container.get_and_return_set_of_primitives(request={"string"}) + async_response = ( + await async_client.endpoints.container.get_and_return_set_of_primitives( + request={"string"} + ) + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_set_of_objects(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_set_of_objects( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = [{"string": "string"}] - expected_types: typing.Tuple[typing.Any, typing.Any] = ("set", {0: {"string": None}}) + expected_types: typing.Tuple[typing.Any, typing.Any] = ( + "set", + {0: {"string": None}}, + ) response = client.endpoints.container.get_and_return_set_of_objects( request=[ObjectWithRequiredField(string="string")] ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.container.get_and_return_set_of_objects( - request=[ObjectWithRequiredField(string="string")] + async_response = ( + await async_client.endpoints.container.get_and_return_set_of_objects( + request=[ObjectWithRequiredField(string="string")] + ) ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_map_prim_to_prim(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_map_prim_to_prim( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = {"string": "string"} expected_types: typing.Tuple[typing.Any, typing.Any] = ("dict", {0: (None, None)}) - response = client.endpoints.container.get_and_return_map_prim_to_prim(request={"string": "string"}) + response = client.endpoints.container.get_and_return_map_prim_to_prim( + request={"string": "string"} + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.container.get_and_return_map_prim_to_prim( - request={"string": "string"} + async_response = ( + await async_client.endpoints.container.get_and_return_map_prim_to_prim( + request={"string": "string"} + ) ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_map_of_prim_to_object(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_map_of_prim_to_object( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = {"string": {"string": "string"}} - expected_types: typing.Tuple[typing.Any, typing.Any] = ("dict", {0: (None, {"string": None})}) + expected_types: typing.Tuple[typing.Any, typing.Any] = ( + "dict", + {0: (None, {"string": None})}, + ) response = client.endpoints.container.get_and_return_map_of_prim_to_object( request={"string": ObjectWithRequiredField(string="string")} ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.container.get_and_return_map_of_prim_to_object( - request={"string": ObjectWithRequiredField(string="string")} + async_response = ( + await async_client.endpoints.container.get_and_return_map_of_prim_to_object( + request={"string": ObjectWithRequiredField(string="string")} + ) ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_optional(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_optional( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = {"string": "string"} expected_types: typing.Any = {"string": None} - response = client.endpoints.container.get_and_return_optional(request=ObjectWithRequiredField(string="string")) + response = client.endpoints.container.get_and_return_optional( + request=ObjectWithRequiredField(string="string") + ) validate_response(response, expected_response, expected_types) async_response = await async_client.endpoints.container.get_and_return_optional( diff --git a/seed/python-sdk/exhaustive/deps_with_min_python_version/tests/endpoints/test_enum.py b/seed/python-sdk/exhaustive/deps_with_min_python_version/tests/endpoints/test_enum.py index 890aada5ce4..ca3fca30b5a 100644 --- a/seed/python-sdk/exhaustive/deps_with_min_python_version/tests/endpoints/test_enum.py +++ b/seed/python-sdk/exhaustive/deps_with_min_python_version/tests/endpoints/test_enum.py @@ -1,17 +1,20 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing - -from seed import AsyncSeedExhaustive, SeedExhaustive - from ..utilities import validate_response -async def test_get_and_return_enum(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_enum( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "SUNNY" expected_types: typing.Any = None response = client.endpoints.enum.get_and_return_enum(request="SUNNY") validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.enum.get_and_return_enum(request="SUNNY") + async_response = await async_client.endpoints.enum.get_and_return_enum( + request="SUNNY" + ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/exhaustive/deps_with_min_python_version/tests/endpoints/test_http_methods.py b/seed/python-sdk/exhaustive/deps_with_min_python_version/tests/endpoints/test_http_methods.py index dc01bafcf6f..77131fc6e8b 100644 --- a/seed/python-sdk/exhaustive/deps_with_min_python_version/tests/endpoints/test_http_methods.py +++ b/seed/python-sdk/exhaustive/deps_with_min_python_version/tests/endpoints/test_http_methods.py @@ -1,15 +1,16 @@ # This file was auto-generated by Fern from our API Definition. -import datetime +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing -import uuid - -from seed import AsyncSeedExhaustive, SeedExhaustive - from ..utilities import validate_response +import datetime +import uuid -async def test_test_get(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_test_get( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "string" expected_types: typing.Any = None response = client.endpoints.http_methods.test_get(id="string") @@ -19,7 +20,9 @@ async def test_test_get(client: SeedExhaustive, async_client: AsyncSeedExhaustiv validate_response(async_response, expected_response, expected_types) -async def test_test_post(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_test_post( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = { "string": "string", "integer": 1, @@ -53,11 +56,15 @@ async def test_test_post(client: SeedExhaustive, async_client: AsyncSeedExhausti response = client.endpoints.http_methods.test_post(string="string") validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.http_methods.test_post(string="string") + async_response = await async_client.endpoints.http_methods.test_post( + string="string" + ) validate_response(async_response, expected_response, expected_types) -async def test_test_put(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_test_put( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = { "string": "string", "integer": 1, @@ -91,11 +98,15 @@ async def test_test_put(client: SeedExhaustive, async_client: AsyncSeedExhaustiv response = client.endpoints.http_methods.test_put(id="string", string="string") validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.http_methods.test_put(id="string", string="string") + async_response = await async_client.endpoints.http_methods.test_put( + id="string", string="string" + ) validate_response(async_response, expected_response, expected_types) -async def test_test_patch(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_test_patch( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = { "string": "string", "integer": 1, @@ -163,7 +174,9 @@ async def test_test_patch(client: SeedExhaustive, async_client: AsyncSeedExhaust validate_response(async_response, expected_response, expected_types) -async def test_test_delete(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_test_delete( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = True expected_types: typing.Any = None response = client.endpoints.http_methods.test_delete(id="string") diff --git a/seed/python-sdk/exhaustive/deps_with_min_python_version/tests/endpoints/test_object.py b/seed/python-sdk/exhaustive/deps_with_min_python_version/tests/endpoints/test_object.py index a9098b6e9ef..c48c4332b22 100644 --- a/seed/python-sdk/exhaustive/deps_with_min_python_version/tests/endpoints/test_object.py +++ b/seed/python-sdk/exhaustive/deps_with_min_python_version/tests/endpoints/test_object.py @@ -1,16 +1,18 @@ # This file was auto-generated by Fern from our API Definition. -import datetime +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing +import datetime import uuid - -from seed import AsyncSeedExhaustive, SeedExhaustive -from seed.types.object import NestedObjectWithRequiredField, ObjectWithOptionalField - from ..utilities import validate_response +from seed.types.object import ObjectWithOptionalField +from seed.types.object import NestedObjectWithRequiredField -async def test_get_and_return_with_optional_field(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_with_optional_field( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = { "string": "string", "integer": 1, @@ -58,38 +60,54 @@ async def test_get_and_return_with_optional_field(client: SeedExhaustive, async_ ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.object.get_and_return_with_optional_field( - string="string", - integer=1, - long_=1000000, - double=1.1, - bool_=True, - datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), - date=datetime.date.fromisoformat("2023-01-15"), - uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), - base_64="SGVsbG8gd29ybGQh", - list_=["string"], - set_={"string"}, - map_={1: "string"}, - bigint="123456789123456789", + async_response = ( + await async_client.endpoints.object.get_and_return_with_optional_field( + string="string", + integer=1, + long_=1000000, + double=1.1, + bool_=True, + datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), + date=datetime.date.fromisoformat("2023-01-15"), + uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + base_64="SGVsbG8gd29ybGQh", + list_=["string"], + set_={"string"}, + map_={1: "string"}, + bigint="123456789123456789", + ) ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_with_required_field(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_with_required_field( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = {"string": "string"} expected_types: typing.Any = {"string": None} - response = client.endpoints.object.get_and_return_with_required_field(string="string") + response = client.endpoints.object.get_and_return_with_required_field( + string="string" + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.object.get_and_return_with_required_field(string="string") + async_response = ( + await async_client.endpoints.object.get_and_return_with_required_field( + string="string" + ) + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_with_map_of_map(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_with_map_of_map( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = {"map": {"string": {"string": "string"}}} - expected_types: typing.Any = {"map": ("dict", {0: (None, ("dict", {0: (None, None)}))})} - response = client.endpoints.object.get_and_return_with_map_of_map(map_={"string": {"string": "string"}}) + expected_types: typing.Any = { + "map": ("dict", {0: (None, ("dict", {0: (None, None)}))}) + } + response = client.endpoints.object.get_and_return_with_map_of_map( + map_={"string": {"string": "string"}} + ) validate_response(response, expected_response, expected_types) async_response = await async_client.endpoints.object.get_and_return_with_map_of_map( @@ -157,23 +175,25 @@ async def test_get_and_return_nested_with_optional_field( ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.object.get_and_return_nested_with_optional_field( - string="string", - nested_object=ObjectWithOptionalField( + async_response = ( + await async_client.endpoints.object.get_and_return_nested_with_optional_field( string="string", - integer=1, - long_=1000000, - double=1.1, - bool_=True, - datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), - date=datetime.date.fromisoformat("2023-01-15"), - uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), - base_64="SGVsbG8gd29ybGQh", - list_=["string"], - set_={"string"}, - map_={1: "string"}, - bigint="123456789123456789", - ), + nested_object=ObjectWithOptionalField( + string="string", + integer=1, + long_=1000000, + double=1.1, + bool_=True, + datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), + date=datetime.date.fromisoformat("2023-01-15"), + uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + base_64="SGVsbG8gd29ybGQh", + list_=["string"], + set_={"string"}, + map_={1: "string"}, + bigint="123456789123456789", + ), + ) ) validate_response(async_response, expected_response, expected_types) @@ -238,24 +258,26 @@ async def test_get_and_return_nested_with_required_field( ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.object.get_and_return_nested_with_required_field( - string_="string", - string="string", - nested_object=ObjectWithOptionalField( + async_response = ( + await async_client.endpoints.object.get_and_return_nested_with_required_field( + string_="string", string="string", - integer=1, - long_=1000000, - double=1.1, - bool_=True, - datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), - date=datetime.date.fromisoformat("2023-01-15"), - uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), - base_64="SGVsbG8gd29ybGQh", - list_=["string"], - set_={"string"}, - map_={1: "string"}, - bigint="123456789123456789", - ), + nested_object=ObjectWithOptionalField( + string="string", + integer=1, + long_=1000000, + double=1.1, + bool_=True, + datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), + date=datetime.date.fromisoformat("2023-01-15"), + uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + base_64="SGVsbG8gd29ybGQh", + list_=["string"], + set_={"string"}, + map_={1: "string"}, + bigint="123456789123456789", + ), + ) ) validate_response(async_response, expected_response, expected_types) @@ -299,27 +321,31 @@ async def test_get_and_return_nested_with_required_field_as_list( "bigint": None, }, } - response = client.endpoints.object.get_and_return_nested_with_required_field_as_list( - request=[ - NestedObjectWithRequiredField( - string="string", - nested_object=ObjectWithOptionalField( + response = ( + client.endpoints.object.get_and_return_nested_with_required_field_as_list( + request=[ + NestedObjectWithRequiredField( string="string", - integer=1, - long_=1000000, - double=1.1, - bool_=True, - datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), - date=datetime.date.fromisoformat("2023-01-15"), - uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), - base_64="SGVsbG8gd29ybGQh", - list_=["string"], - set_={"string"}, - map_={1: "string"}, - bigint="123456789123456789", - ), - ) - ] + nested_object=ObjectWithOptionalField( + string="string", + integer=1, + long_=1000000, + double=1.1, + bool_=True, + datetime=datetime.datetime.fromisoformat( + "2024-01-15 09:30:00+00:00" + ), + date=datetime.date.fromisoformat("2023-01-15"), + uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + base_64="SGVsbG8gd29ybGQh", + list_=["string"], + set_={"string"}, + map_={1: "string"}, + bigint="123456789123456789", + ), + ) + ] + ) ) validate_response(response, expected_response, expected_types) @@ -333,7 +359,9 @@ async def test_get_and_return_nested_with_required_field_as_list( long_=1000000, double=1.1, bool_=True, - datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), + datetime=datetime.datetime.fromisoformat( + "2024-01-15 09:30:00+00:00" + ), date=datetime.date.fromisoformat("2023-01-15"), uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), base_64="SGVsbG8gd29ybGQh", diff --git a/seed/python-sdk/exhaustive/deps_with_min_python_version/tests/endpoints/test_params.py b/seed/python-sdk/exhaustive/deps_with_min_python_version/tests/endpoints/test_params.py index 163d7b9161d..d8ffb00c0a0 100644 --- a/seed/python-sdk/exhaustive/deps_with_min_python_version/tests/endpoints/test_params.py +++ b/seed/python-sdk/exhaustive/deps_with_min_python_version/tests/endpoints/test_params.py @@ -1,13 +1,14 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing - -from seed import AsyncSeedExhaustive, SeedExhaustive - from ..utilities import validate_response -async def test_get_with_path(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_with_path( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "string" expected_types: typing.Any = None response = client.endpoints.params.get_with_path(param="string") @@ -17,32 +18,63 @@ async def test_get_with_path(client: SeedExhaustive, async_client: AsyncSeedExha validate_response(async_response, expected_response, expected_types) -async def test_get_with_query(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_with_query( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: # Type ignore to avoid mypy complaining about the function not being meant to return a value assert client.endpoints.params.get_with_query(query="string", number=1) is None # type: ignore[func-returns-value] - assert await async_client.endpoints.params.get_with_query(query="string", number=1) is None # type: ignore[func-returns-value] + assert ( + await async_client.endpoints.params.get_with_query(query="string", number=1) + is None + ) # type: ignore[func-returns-value] -async def test_get_with_allow_multiple_query(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_with_allow_multiple_query( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: # Type ignore to avoid mypy complaining about the function not being meant to return a value - assert client.endpoints.params.get_with_allow_multiple_query(query="string", numer=1) is None # type: ignore[func-returns-value] - - assert await async_client.endpoints.params.get_with_allow_multiple_query(query="string", numer=1) is None # type: ignore[func-returns-value] - - -async def test_get_with_path_and_query(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: + assert ( + client.endpoints.params.get_with_allow_multiple_query(query="string", numer=1) + is None + ) # type: ignore[func-returns-value] + + assert ( + await async_client.endpoints.params.get_with_allow_multiple_query( + query="string", numer=1 + ) + is None + ) # type: ignore[func-returns-value] + + +async def test_get_with_path_and_query( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: # Type ignore to avoid mypy complaining about the function not being meant to return a value - assert client.endpoints.params.get_with_path_and_query(param="string", query="string") is None # type: ignore[func-returns-value] - - assert await async_client.endpoints.params.get_with_path_and_query(param="string", query="string") is None # type: ignore[func-returns-value] - - -async def test_modify_with_path(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: + assert ( + client.endpoints.params.get_with_path_and_query(param="string", query="string") + is None + ) # type: ignore[func-returns-value] + + assert ( + await async_client.endpoints.params.get_with_path_and_query( + param="string", query="string" + ) + is None + ) # type: ignore[func-returns-value] + + +async def test_modify_with_path( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "string" expected_types: typing.Any = None - response = client.endpoints.params.modify_with_path(param="string", request="string") + response = client.endpoints.params.modify_with_path( + param="string", request="string" + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.params.modify_with_path(param="string", request="string") + async_response = await async_client.endpoints.params.modify_with_path( + param="string", request="string" + ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/exhaustive/deps_with_min_python_version/tests/endpoints/test_primitive.py b/seed/python-sdk/exhaustive/deps_with_min_python_version/tests/endpoints/test_primitive.py index ba3bc7e29e5..26cbcf45d2f 100644 --- a/seed/python-sdk/exhaustive/deps_with_min_python_version/tests/endpoints/test_primitive.py +++ b/seed/python-sdk/exhaustive/deps_with_min_python_version/tests/endpoints/test_primitive.py @@ -1,65 +1,86 @@ # This file was auto-generated by Fern from our API Definition. -import datetime +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing -import uuid - -from seed import AsyncSeedExhaustive, SeedExhaustive - from ..utilities import validate_response +import datetime +import uuid -async def test_get_and_return_string(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_string( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "string" expected_types: typing.Any = None response = client.endpoints.primitive.get_and_return_string(request="string") validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.primitive.get_and_return_string(request="string") + async_response = await async_client.endpoints.primitive.get_and_return_string( + request="string" + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_int(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_int( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = 1 expected_types: typing.Any = "integer" response = client.endpoints.primitive.get_and_return_int(request=1) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.primitive.get_and_return_int(request=1) + async_response = await async_client.endpoints.primitive.get_and_return_int( + request=1 + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_long(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_long( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = 1000000 expected_types: typing.Any = None response = client.endpoints.primitive.get_and_return_long(request=1000000) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.primitive.get_and_return_long(request=1000000) + async_response = await async_client.endpoints.primitive.get_and_return_long( + request=1000000 + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_double(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_double( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = 1.1 expected_types: typing.Any = None response = client.endpoints.primitive.get_and_return_double(request=1.1) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.primitive.get_and_return_double(request=1.1) + async_response = await async_client.endpoints.primitive.get_and_return_double( + request=1.1 + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_bool(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_bool( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = True expected_types: typing.Any = None response = client.endpoints.primitive.get_and_return_bool(request=True) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.primitive.get_and_return_bool(request=True) + async_response = await async_client.endpoints.primitive.get_and_return_bool( + request=True + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_datetime(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_datetime( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "2024-01-15T09:30:00Z" expected_types: typing.Any = "datetime" response = client.endpoints.primitive.get_and_return_datetime( @@ -73,10 +94,14 @@ async def test_get_and_return_datetime(client: SeedExhaustive, async_client: Asy validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_date(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_date( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "2023-01-15" expected_types: typing.Any = "date" - response = client.endpoints.primitive.get_and_return_date(request=datetime.date.fromisoformat("2023-01-15")) + response = client.endpoints.primitive.get_and_return_date( + request=datetime.date.fromisoformat("2023-01-15") + ) validate_response(response, expected_response, expected_types) async_response = await async_client.endpoints.primitive.get_and_return_date( @@ -85,10 +110,14 @@ async def test_get_and_return_date(client: SeedExhaustive, async_client: AsyncSe validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_uuid(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_uuid( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32" expected_types: typing.Any = "uuid" - response = client.endpoints.primitive.get_and_return_uuid(request=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32")) + response = client.endpoints.primitive.get_and_return_uuid( + request=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32") + ) validate_response(response, expected_response, expected_types) async_response = await async_client.endpoints.primitive.get_and_return_uuid( @@ -97,11 +126,17 @@ async def test_get_and_return_uuid(client: SeedExhaustive, async_client: AsyncSe validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_base_64(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_base_64( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "SGVsbG8gd29ybGQh" expected_types: typing.Any = None - response = client.endpoints.primitive.get_and_return_base_64(request="SGVsbG8gd29ybGQh") + response = client.endpoints.primitive.get_and_return_base_64( + request="SGVsbG8gd29ybGQh" + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.primitive.get_and_return_base_64(request="SGVsbG8gd29ybGQh") + async_response = await async_client.endpoints.primitive.get_and_return_base_64( + request="SGVsbG8gd29ybGQh" + ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/exhaustive/deps_with_min_python_version/tests/endpoints/test_union.py b/seed/python-sdk/exhaustive/deps_with_min_python_version/tests/endpoints/test_union.py index 14e34c2a6df..ceb84928cd9 100644 --- a/seed/python-sdk/exhaustive/deps_with_min_python_version/tests/endpoints/test_union.py +++ b/seed/python-sdk/exhaustive/deps_with_min_python_version/tests/endpoints/test_union.py @@ -1,17 +1,24 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing - -from seed import AsyncSeedExhaustive, SeedExhaustive from seed.types.union import Animal_Dog - from ..utilities import validate_response -async def test_get_and_return_union(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: - expected_response: typing.Any = {"animal": "dog", "name": "string", "likesToWoof": True} +async def test_get_and_return_union( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: + expected_response: typing.Any = { + "animal": "dog", + "name": "string", + "likesToWoof": True, + } expected_types: typing.Any = "no_validate" - response = client.endpoints.union.get_and_return_union(request=Animal_Dog(name="string", likes_to_woof=True)) + response = client.endpoints.union.get_and_return_union( + request=Animal_Dog(name="string", likes_to_woof=True) + ) validate_response(response, expected_response, expected_types) async_response = await async_client.endpoints.union.get_and_return_union( diff --git a/seed/python-sdk/exhaustive/deps_with_min_python_version/tests/test_inlined_requests.py b/seed/python-sdk/exhaustive/deps_with_min_python_version/tests/test_inlined_requests.py index bb9390d3845..03f46b31cc9 100644 --- a/seed/python-sdk/exhaustive/deps_with_min_python_version/tests/test_inlined_requests.py +++ b/seed/python-sdk/exhaustive/deps_with_min_python_version/tests/test_inlined_requests.py @@ -1,16 +1,17 @@ # This file was auto-generated by Fern from our API Definition. -import datetime +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing -import uuid - -from seed import AsyncSeedExhaustive, SeedExhaustive from seed.types.object import ObjectWithOptionalField - +import datetime +import uuid from .utilities import validate_response -async def test_post_with_object_bodyand_response(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_post_with_object_bodyand_response( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = { "string": "string", "integer": 1, @@ -62,23 +63,25 @@ async def test_post_with_object_bodyand_response(client: SeedExhaustive, async_c ) validate_response(response, expected_response, expected_types) - async_response = await async_client.inlined_requests.post_with_object_bodyand_response( - string="string", - integer=1, - nested_object=ObjectWithOptionalField( + async_response = ( + await async_client.inlined_requests.post_with_object_bodyand_response( string="string", integer=1, - long_=1000000, - double=1.1, - bool_=True, - datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), - date=datetime.date.fromisoformat("2023-01-15"), - uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), - base_64="SGVsbG8gd29ybGQh", - list_=["string"], - set_={"string"}, - map_={1: "string"}, - bigint="123456789123456789", - ), + nested_object=ObjectWithOptionalField( + string="string", + integer=1, + long_=1000000, + double=1.1, + bool_=True, + datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), + date=datetime.date.fromisoformat("2023-01-15"), + uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + base_64="SGVsbG8gd29ybGQh", + list_=["string"], + set_={"string"}, + map_={1: "string"}, + bigint="123456789123456789", + ), + ) ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/exhaustive/deps_with_min_python_version/tests/test_no_auth.py b/seed/python-sdk/exhaustive/deps_with_min_python_version/tests/test_no_auth.py index 3328661bb48..fc475f4b6fb 100644 --- a/seed/python-sdk/exhaustive/deps_with_min_python_version/tests/test_no_auth.py +++ b/seed/python-sdk/exhaustive/deps_with_min_python_version/tests/test_no_auth.py @@ -1,17 +1,20 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing - -from seed import AsyncSeedExhaustive, SeedExhaustive - from .utilities import validate_response -async def test_post_with_no_auth(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_post_with_no_auth( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = True expected_types: typing.Any = None response = client.no_auth.post_with_no_auth(request={"key": "value"}) validate_response(response, expected_response, expected_types) - async_response = await async_client.no_auth.post_with_no_auth(request={"key": "value"}) + async_response = await async_client.no_auth.post_with_no_auth( + request={"key": "value"} + ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/exhaustive/deps_with_min_python_version/tests/test_no_req_body.py b/seed/python-sdk/exhaustive/deps_with_min_python_version/tests/test_no_req_body.py index 73abac9d2d8..07061a0e99e 100644 --- a/seed/python-sdk/exhaustive/deps_with_min_python_version/tests/test_no_req_body.py +++ b/seed/python-sdk/exhaustive/deps_with_min_python_version/tests/test_no_req_body.py @@ -1,13 +1,14 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing - -from seed import AsyncSeedExhaustive, SeedExhaustive - from .utilities import validate_response -async def test_get_with_no_request_body(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_with_no_request_body( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = { "string": "string", "integer": 1, @@ -45,7 +46,9 @@ async def test_get_with_no_request_body(client: SeedExhaustive, async_client: As validate_response(async_response, expected_response, expected_types) -async def test_post_with_no_request_body(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_post_with_no_request_body( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "string" expected_types: typing.Any = None response = client.no_req_body.post_with_no_request_body() diff --git a/seed/python-sdk/exhaustive/deps_with_min_python_version/tests/test_req_with_headers.py b/seed/python-sdk/exhaustive/deps_with_min_python_version/tests/test_req_with_headers.py index bba3b5b5507..75ce9d00c03 100644 --- a/seed/python-sdk/exhaustive/deps_with_min_python_version/tests/test_req_with_headers.py +++ b/seed/python-sdk/exhaustive/deps_with_min_python_version/tests/test_req_with_headers.py @@ -1,10 +1,27 @@ # This file was auto-generated by Fern from our API Definition. -from seed import AsyncSeedExhaustive, SeedExhaustive +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive -async def test_get_with_custom_header(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_with_custom_header( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: # Type ignore to avoid mypy complaining about the function not being meant to return a value - assert client.req_with_headers.get_with_custom_header(x_test_service_header="string", x_test_endpoint_header="string", request="string") is None # type: ignore[func-returns-value] + assert ( + client.req_with_headers.get_with_custom_header( + x_test_service_header="string", + x_test_endpoint_header="string", + request="string", + ) + is None + ) # type: ignore[func-returns-value] - assert await async_client.req_with_headers.get_with_custom_header(x_test_service_header="string", x_test_endpoint_header="string", request="string") is None # type: ignore[func-returns-value] + assert ( + await async_client.req_with_headers.get_with_custom_header( + x_test_service_header="string", + x_test_endpoint_header="string", + request="string", + ) + is None + ) # type: ignore[func-returns-value] diff --git a/seed/python-sdk/exhaustive/deps_with_min_python_version/tests/utilities.py b/seed/python-sdk/exhaustive/deps_with_min_python_version/tests/utilities.py index 13da208eb3a..e8f4472564c 100644 --- a/seed/python-sdk/exhaustive/deps_with_min_python_version/tests/utilities.py +++ b/seed/python-sdk/exhaustive/deps_with_min_python_version/tests/utilities.py @@ -3,11 +3,14 @@ import typing import uuid -import pydantic from dateutil import parser +import pydantic + -def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> typing.Any: +def cast_field( + json_expectation: typing.Any, type_expectation: typing.Any +) -> typing.Any: # Cast these specific types which come through as string and expect our # models to cast to the correct type. if type_expectation == "uuid": @@ -25,7 +28,9 @@ def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> ty return json_expectation -def validate_field(response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any) -> None: +def validate_field( + response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectation == "no_validate": return @@ -44,7 +49,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(entry_expectation, dict): is_container_of_complex_type = True validate_response( - response=response[idx], json_expectation=ex, type_expectations=entry_expectation + response=response[idx], + json_expectation=ex, + type_expectations=entry_expectation, ) else: cast_json_expectation.append(cast_field(ex, entry_expectation)) @@ -56,7 +63,10 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # if any of the values of the set have a type_expectation of a dict, we're assuming it's a pydantic # model and keeping it a list. if container_expectation != "set" or not any( - map(lambda value: isinstance(value, dict), list(contents_expectation.values())) + map( + lambda value: isinstance(value, dict), + list(contents_expectation.values()), + ) ): json_expectation = cast_field(json_expectation, container_expectation) elif isinstance(type_expectation, tuple): @@ -65,9 +75,15 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(contents_expectation, dict): json_expectation = { cast_field( - key, contents_expectation.get(idx)[0] if contents_expectation.get(idx) is not None else None # type: ignore + key, + contents_expectation.get(idx)[0] + if contents_expectation.get(idx) is not None + else None, # type: ignore ): cast_field( - value, contents_expectation.get(idx)[1] if contents_expectation.get(idx) is not None else None # type: ignore + value, + contents_expectation.get(idx)[1] + if contents_expectation.get(idx) is not None + else None, # type: ignore ) for idx, (key, value) in enumerate(json_expectation.items()) } @@ -86,7 +102,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # Arg type_expectations is a deeply nested structure that matches the response, but with the values replaced with the expected types -def validate_response(response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any) -> None: +def validate_response( + response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectations == "no_validate": return @@ -96,11 +114,17 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e and not isinstance(response, dict) and not issubclass(type(response), pydantic.BaseModel) ): - validate_field(response=response, json_expectation=json_expectation, type_expectation=type_expectations) + validate_field( + response=response, + json_expectation=json_expectation, + type_expectation=type_expectations, + ) return if isinstance(response, list): - assert len(response) == len(json_expectation), "Length mismatch, expected: {0}, Actual: {1}".format( + assert len(response) == len( + json_expectation + ), "Length mismatch, expected: {0}, Actual: {1}".format( len(response), len(json_expectation) ) content_expectation = type_expectations @@ -108,7 +132,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e content_expectation = type_expectations[1] for idx, item in enumerate(response): validate_response( - response=item, json_expectation=json_expectation[idx], type_expectations=content_expectation[idx] + response=item, + json_expectation=json_expectation[idx], + type_expectations=content_expectation[idx], ) else: response_json = response @@ -116,7 +142,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e response_json = response.dict(by_alias=True) for key, value in json_expectation.items(): - assert key in response_json, "Field {0} not found within the response object: {1}".format( + assert ( + key in response_json + ), "Field {0} not found within the response object: {1}".format( key, response_json ) @@ -128,11 +156,19 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e # Otherwise, we're just validating a single field that's a pydantic model. if isinstance(value, dict) and not isinstance(type_expectation, tuple): validate_response( - response=response_json[key], json_expectation=value, type_expectations=type_expectation + response=response_json[key], + json_expectation=value, + type_expectations=type_expectation, ) else: - validate_field(response=response_json[key], json_expectation=value, type_expectation=type_expectation) + validate_field( + response=response_json[key], + json_expectation=value, + type_expectation=type_expectation, + ) # Ensure there are no additional fields here either del response_json[key] - assert len(response_json) == 0, "Additional fields found, expected None: {0}".format(response_json) + assert ( + len(response_json) == 0 + ), "Additional fields found, expected None: {0}".format(response_json) diff --git a/seed/python-sdk/exhaustive/deps_with_min_python_version/tests/utils/assets/models/__init__.py b/seed/python-sdk/exhaustive/deps_with_min_python_version/tests/utils/assets/models/__init__.py index 2cf01263529..3a1c852e71e 100644 --- a/seed/python-sdk/exhaustive/deps_with_min_python_version/tests/utils/assets/models/__init__.py +++ b/seed/python-sdk/exhaustive/deps_with_min_python_version/tests/utils/assets/models/__init__.py @@ -5,7 +5,7 @@ from .circle import CircleParams from .object_with_defaults import ObjectWithDefaultsParams from .object_with_optional_field import ObjectWithOptionalFieldParams -from .shape import Shape_CircleParams, Shape_SquareParams, ShapeParams +from .shape import ShapeParams, Shape_CircleParams, Shape_SquareParams from .square import SquareParams from .undiscriminated_shape import UndiscriminatedShapeParams diff --git a/seed/python-sdk/exhaustive/deps_with_min_python_version/tests/utils/assets/models/circle.py b/seed/python-sdk/exhaustive/deps_with_min_python_version/tests/utils/assets/models/circle.py index af7a1bf8a8e..253f12d38b3 100644 --- a/seed/python-sdk/exhaustive/deps_with_min_python_version/tests/utils/assets/models/circle.py +++ b/seed/python-sdk/exhaustive/deps_with_min_python_version/tests/utils/assets/models/circle.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class CircleParams(typing_extensions.TypedDict): - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] diff --git a/seed/python-sdk/exhaustive/deps_with_min_python_version/tests/utils/assets/models/object_with_optional_field.py b/seed/python-sdk/exhaustive/deps_with_min_python_version/tests/utils/assets/models/object_with_optional_field.py index 3ad93d5f305..ebe7dc80547 100644 --- a/seed/python-sdk/exhaustive/deps_with_min_python_version/tests/utils/assets/models/object_with_optional_field.py +++ b/seed/python-sdk/exhaustive/deps_with_min_python_version/tests/utils/assets/models/object_with_optional_field.py @@ -7,8 +7,8 @@ import uuid import typing_extensions -from seed.core.serialization import FieldMetadata +from seed.core.serialization import FieldMetadata from .color import Color from .shape import ShapeParams from .undiscriminated_shape import UndiscriminatedShapeParams @@ -18,16 +18,30 @@ class ObjectWithOptionalFieldParams(typing_extensions.TypedDict): literal: typing.Literal["lit_one"] string: typing_extensions.NotRequired[str] integer: typing_extensions.NotRequired[int] - long_: typing_extensions.NotRequired[typing_extensions.Annotated[int, FieldMetadata(alias="long")]] + long_: typing_extensions.NotRequired[ + typing_extensions.Annotated[int, FieldMetadata(alias="long")] + ] double: typing_extensions.NotRequired[float] - bool_: typing_extensions.NotRequired[typing_extensions.Annotated[bool, FieldMetadata(alias="bool")]] + bool_: typing_extensions.NotRequired[ + typing_extensions.Annotated[bool, FieldMetadata(alias="bool")] + ] datetime: typing_extensions.NotRequired[dt.datetime] date: typing_extensions.NotRequired[dt.date] - uuid_: typing_extensions.NotRequired[typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")]] - base_64: typing_extensions.NotRequired[typing_extensions.Annotated[str, FieldMetadata(alias="base64")]] - list_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")]] - set_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")]] - map_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")]] + uuid_: typing_extensions.NotRequired[ + typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")] + ] + base_64: typing_extensions.NotRequired[ + typing_extensions.Annotated[str, FieldMetadata(alias="base64")] + ] + list_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")] + ] + set_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")] + ] + map_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")] + ] enum: typing_extensions.NotRequired[Color] union: typing_extensions.NotRequired[ShapeParams] second_union: typing_extensions.NotRequired[ShapeParams] diff --git a/seed/python-sdk/exhaustive/deps_with_min_python_version/tests/utils/assets/models/shape.py b/seed/python-sdk/exhaustive/deps_with_min_python_version/tests/utils/assets/models/shape.py index 2c33c877951..816ffc51bdc 100644 --- a/seed/python-sdk/exhaustive/deps_with_min_python_version/tests/utils/assets/models/shape.py +++ b/seed/python-sdk/exhaustive/deps_with_min_python_version/tests/utils/assets/models/shape.py @@ -7,6 +7,7 @@ import typing import typing_extensions + from seed.core.serialization import FieldMetadata @@ -15,13 +16,21 @@ class Base(typing_extensions.TypedDict): class Shape_CircleParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["circle"], FieldMetadata(alias="shapeType")] - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["circle"], FieldMetadata(alias="shapeType") + ] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] class Shape_SquareParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["square"], FieldMetadata(alias="shapeType")] - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["square"], FieldMetadata(alias="shapeType") + ] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] ShapeParams = typing.Union[Shape_CircleParams, Shape_SquareParams] diff --git a/seed/python-sdk/exhaustive/deps_with_min_python_version/tests/utils/assets/models/square.py b/seed/python-sdk/exhaustive/deps_with_min_python_version/tests/utils/assets/models/square.py index b9b7dd319bc..bcf08a723c5 100644 --- a/seed/python-sdk/exhaustive/deps_with_min_python_version/tests/utils/assets/models/square.py +++ b/seed/python-sdk/exhaustive/deps_with_min_python_version/tests/utils/assets/models/square.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class SquareParams(typing_extensions.TypedDict): - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] diff --git a/seed/python-sdk/exhaustive/deps_with_min_python_version/tests/utils/test_http_client.py b/seed/python-sdk/exhaustive/deps_with_min_python_version/tests/utils/test_http_client.py index edd11ca7afb..f5a874a75f3 100644 --- a/seed/python-sdk/exhaustive/deps_with_min_python_version/tests/utils/test_http_client.py +++ b/seed/python-sdk/exhaustive/deps_with_min_python_version/tests/utils/test_http_client.py @@ -9,12 +9,17 @@ def get_request_options() -> RequestOptions: def test_get_json_request_body() -> None: - json_body, data_body = get_request_body(json={"hello": "world"}, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json={"hello": "world"}, data=None, request_options=None, omit=None + ) assert json_body == {"hello": "world"} assert data_body is None json_body_extras, data_body_extras = get_request_body( - json={"goodbye": "world"}, data=None, request_options=get_request_options(), omit=None + json={"goodbye": "world"}, + data=None, + request_options=get_request_options(), + omit=None, ) assert json_body_extras == {"goodbye": "world", "see you": "later"} @@ -22,12 +27,17 @@ def test_get_json_request_body() -> None: def test_get_files_request_body() -> None: - json_body, data_body = get_request_body(json=None, data={"hello": "world"}, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data={"hello": "world"}, request_options=None, omit=None + ) assert data_body == {"hello": "world"} assert json_body is None json_body_extras, data_body_extras = get_request_body( - json=None, data={"goodbye": "world"}, request_options=get_request_options(), omit=None + json=None, + data={"goodbye": "world"}, + request_options=get_request_options(), + omit=None, ) assert data_body_extras == {"goodbye": "world", "see you": "later"} @@ -35,7 +45,9 @@ def test_get_files_request_body() -> None: def test_get_none_request_body() -> None: - json_body, data_body = get_request_body(json=None, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data=None, request_options=None, omit=None + ) assert data_body is None assert json_body is None diff --git a/seed/python-sdk/exhaustive/deps_with_min_python_version/tests/utils/test_query_encoding.py b/seed/python-sdk/exhaustive/deps_with_min_python_version/tests/utils/test_query_encoding.py index 247e1551b46..fbc8f402167 100644 --- a/seed/python-sdk/exhaustive/deps_with_min_python_version/tests/utils/test_query_encoding.py +++ b/seed/python-sdk/exhaustive/deps_with_min_python_version/tests/utils/test_query_encoding.py @@ -4,9 +4,15 @@ def test_query_encoding() -> None: - assert encode_query({"hello world": "hello world"}) == {"hello world": "hello world"} - assert encode_query({"hello_world": {"hello": "world"}}) == {"hello_world[hello]": "world"} - assert encode_query({"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"}) == { + assert encode_query({"hello world": "hello world"}) == { + "hello world": "hello world" + } + assert encode_query({"hello_world": {"hello": "world"}}) == { + "hello_world[hello]": "world" + } + assert encode_query( + {"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"} + ) == { "hello_world[hello][world]": "today", "hello_world[test]": "this", "hi": "there", diff --git a/seed/python-sdk/exhaustive/deps_with_min_python_version/tests/utils/test_serialization.py b/seed/python-sdk/exhaustive/deps_with_min_python_version/tests/utils/test_serialization.py index 58b1ed66e6d..5ca956916dd 100644 --- a/seed/python-sdk/exhaustive/deps_with_min_python_version/tests/utils/test_serialization.py +++ b/seed/python-sdk/exhaustive/deps_with_min_python_version/tests/utils/test_serialization.py @@ -1,10 +1,12 @@ # This file was auto-generated by Fern from our API Definition. -from typing import Any, List +from typing import List, Any -from seed.core.serialization import convert_and_respect_annotation_metadata +from seed.core.serialization import ( + convert_and_respect_annotation_metadata, +) +from .assets.models import ShapeParams, ObjectWithOptionalFieldParams -from .assets.models import ObjectWithOptionalFieldParams, ShapeParams UNION_TEST: ShapeParams = {"radius_measurement": 1.0, "shape_type": "circle", "id": "1"} UNION_TEST_CONVERTED = {"shapeType": "circle", "radiusMeasurement": 1.0, "id": "1"} @@ -18,20 +20,54 @@ def test_convert_and_respect_annotation_metadata() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) - assert converted == {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"} + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) + assert converted == { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + } def test_convert_and_respect_annotation_metadata_in_list() -> None: data: List[ObjectWithOptionalFieldParams] = [ - {"string": "string", "long_": 12345, "bool_": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long_": 67890, "list_": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long_": 12345, + "bool_": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long_": 67890, + "list_": [], + "literal": "lit_one", + "any": "any", + }, ] - converted = convert_and_respect_annotation_metadata(object_=data, annotation=List[ObjectWithOptionalFieldParams]) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=List[ObjectWithOptionalFieldParams] + ) assert converted == [ - {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long": 67890, "list": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long": 67890, + "list": [], + "literal": "lit_one", + "any": "any", + }, ] @@ -43,7 +79,9 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) assert converted == { "string": "string", @@ -55,12 +93,16 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: def test_convert_and_respect_annotation_metadata_in_union() -> None: - converted = convert_and_respect_annotation_metadata(object_=UNION_TEST, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=UNION_TEST, annotation=ShapeParams + ) assert converted == UNION_TEST_CONVERTED def test_convert_and_respect_annotation_metadata_with_empty_object() -> None: data: Any = {} - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ShapeParams + ) assert converted == data diff --git a/seed/python-sdk/exhaustive/extra_dependencies/pyproject.toml b/seed/python-sdk/exhaustive/extra_dependencies/pyproject.toml index 8529702ea71..3b6a5cf604f 100644 --- a/seed/python-sdk/exhaustive/extra_dependencies/pyproject.toml +++ b/seed/python-sdk/exhaustive/extra_dependencies/pyproject.toml @@ -45,6 +45,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/python-sdk/exhaustive/extra_dependencies/src/seed/__init__.py b/seed/python-sdk/exhaustive/extra_dependencies/src/seed/__init__.py index eb56b0ce275..dc1ef03a650 100644 --- a/seed/python-sdk/exhaustive/extra_dependencies/src/seed/__init__.py +++ b/seed/python-sdk/exhaustive/extra_dependencies/src/seed/__init__.py @@ -1,6 +1,14 @@ # This file was auto-generated by Fern from our API Definition. -from . import endpoints, general_errors, inlined_requests, no_auth, no_req_body, req_with_headers, types +from . import ( + endpoints, + general_errors, + inlined_requests, + no_auth, + no_req_body, + req_with_headers, + types, +) from .client import AsyncSeedExhaustive, SeedExhaustive from .general_errors import BadObjectRequestInfo, BadRequestBody from .version import __version__ diff --git a/seed/python-sdk/exhaustive/extra_dependencies/src/seed/client.py b/seed/python-sdk/exhaustive/extra_dependencies/src/seed/client.py index b1b9764c7a7..f5ab292af6b 100644 --- a/seed/python-sdk/exhaustive/extra_dependencies/src/seed/client.py +++ b/seed/python-sdk/exhaustive/extra_dependencies/src/seed/client.py @@ -1,15 +1,19 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from .endpoints.client import AsyncEndpointsClient, EndpointsClient -from .inlined_requests.client import AsyncInlinedRequestsClient, InlinedRequestsClient -from .no_auth.client import AsyncNoAuthClient, NoAuthClient -from .no_req_body.client import AsyncNoReqBodyClient, NoReqBodyClient -from .req_with_headers.client import AsyncReqWithHeadersClient, ReqWithHeadersClient +from .core.client_wrapper import SyncClientWrapper +from .endpoints.client import EndpointsClient +from .inlined_requests.client import InlinedRequestsClient +from .no_auth.client import NoAuthClient +from .no_req_body.client import NoReqBodyClient +from .req_with_headers.client import ReqWithHeadersClient +from .core.client_wrapper import AsyncClientWrapper +from .endpoints.client import AsyncEndpointsClient +from .inlined_requests.client import AsyncInlinedRequestsClient +from .no_auth.client import AsyncNoAuthClient +from .no_req_body.client import AsyncNoReqBodyClient +from .req_with_headers.client import AsyncReqWithHeadersClient class SeedExhaustive: @@ -48,24 +52,32 @@ def __init__( token: typing.Optional[typing.Union[str, typing.Callable[[], str]]] = None, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.Client] = None + httpx_client: typing.Optional[httpx.Client] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = SyncClientWrapper( base_url=base_url, token=token, httpx_client=httpx_client if httpx_client is not None - else httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.Client( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.Client(timeout=_defaulted_timeout), timeout=_defaulted_timeout, ) self.endpoints = EndpointsClient(client_wrapper=self._client_wrapper) - self.inlined_requests = InlinedRequestsClient(client_wrapper=self._client_wrapper) + self.inlined_requests = InlinedRequestsClient( + client_wrapper=self._client_wrapper + ) self.no_auth = NoAuthClient(client_wrapper=self._client_wrapper) self.no_req_body = NoReqBodyClient(client_wrapper=self._client_wrapper) - self.req_with_headers = ReqWithHeadersClient(client_wrapper=self._client_wrapper) + self.req_with_headers = ReqWithHeadersClient( + client_wrapper=self._client_wrapper + ) class AsyncSeedExhaustive: @@ -104,21 +116,29 @@ def __init__( token: typing.Optional[typing.Union[str, typing.Callable[[], str]]] = None, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.AsyncClient] = None + httpx_client: typing.Optional[httpx.AsyncClient] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = AsyncClientWrapper( base_url=base_url, token=token, httpx_client=httpx_client if httpx_client is not None - else httpx.AsyncClient(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.AsyncClient( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.AsyncClient(timeout=_defaulted_timeout), timeout=_defaulted_timeout, ) self.endpoints = AsyncEndpointsClient(client_wrapper=self._client_wrapper) - self.inlined_requests = AsyncInlinedRequestsClient(client_wrapper=self._client_wrapper) + self.inlined_requests = AsyncInlinedRequestsClient( + client_wrapper=self._client_wrapper + ) self.no_auth = AsyncNoAuthClient(client_wrapper=self._client_wrapper) self.no_req_body = AsyncNoReqBodyClient(client_wrapper=self._client_wrapper) - self.req_with_headers = AsyncReqWithHeadersClient(client_wrapper=self._client_wrapper) + self.req_with_headers = AsyncReqWithHeadersClient( + client_wrapper=self._client_wrapper + ) diff --git a/seed/python-sdk/exhaustive/extra_dependencies/src/seed/core/api_error.py b/seed/python-sdk/exhaustive/extra_dependencies/src/seed/core/api_error.py index 2e9fc5431cd..da734b58068 100644 --- a/seed/python-sdk/exhaustive/extra_dependencies/src/seed/core/api_error.py +++ b/seed/python-sdk/exhaustive/extra_dependencies/src/seed/core/api_error.py @@ -7,7 +7,9 @@ class ApiError(Exception): status_code: typing.Optional[int] body: typing.Any - def __init__(self, *, status_code: typing.Optional[int] = None, body: typing.Any = None): + def __init__( + self, *, status_code: typing.Optional[int] = None, body: typing.Any = None + ): self.status_code = status_code self.body = body diff --git a/seed/python-sdk/exhaustive/extra_dependencies/src/seed/core/client_wrapper.py b/seed/python-sdk/exhaustive/extra_dependencies/src/seed/core/client_wrapper.py index 8d01b584b82..d037184a816 100644 --- a/seed/python-sdk/exhaustive/extra_dependencies/src/seed/core/client_wrapper.py +++ b/seed/python-sdk/exhaustive/extra_dependencies/src/seed/core/client_wrapper.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .http_client import AsyncHttpClient, HttpClient +from .http_client import HttpClient +from .http_client import AsyncHttpClient class BaseClientWrapper: diff --git a/seed/python-sdk/exhaustive/extra_dependencies/src/seed/core/datetime_utils.py b/seed/python-sdk/exhaustive/extra_dependencies/src/seed/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/python-sdk/exhaustive/extra_dependencies/src/seed/core/datetime_utils.py +++ b/seed/python-sdk/exhaustive/extra_dependencies/src/seed/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/python-sdk/exhaustive/extra_dependencies/src/seed/core/file.py b/seed/python-sdk/exhaustive/extra_dependencies/src/seed/core/file.py index cb0d40bbbf3..6e0f92bfcb1 100644 --- a/seed/python-sdk/exhaustive/extra_dependencies/src/seed/core/file.py +++ b/seed/python-sdk/exhaustive/extra_dependencies/src/seed/core/file.py @@ -13,12 +13,17 @@ # (filename, file (or bytes), content_type) typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str]], # (filename, file (or bytes), content_type, headers) - typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str], typing.Mapping[str, str]], + typing.Tuple[ + typing.Optional[str], + FileContent, + typing.Optional[str], + typing.Mapping[str, str], + ], ] def convert_file_dict_to_httpx_tuples( - d: typing.Dict[str, typing.Union[File, typing.List[File]]] + d: typing.Dict[str, typing.Union[File, typing.List[File]]], ) -> typing.List[typing.Tuple[str, File]]: """ The format we use is a list of tuples, where the first element is the diff --git a/seed/python-sdk/exhaustive/extra_dependencies/src/seed/core/http_client.py b/seed/python-sdk/exhaustive/extra_dependencies/src/seed/core/http_client.py index 9333d8a7f15..091f71bc185 100644 --- a/seed/python-sdk/exhaustive/extra_dependencies/src/seed/core/http_client.py +++ b/seed/python-sdk/exhaustive/extra_dependencies/src/seed/core/http_client.py @@ -77,7 +77,9 @@ def _retry_timeout(response: httpx.Response, retries: int) -> float: return retry_after # Apply exponential backoff, capped at MAX_RETRY_DELAY_SECONDS. - retry_delay = min(INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS) + retry_delay = min( + INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS + ) # Add a randomness / jitter to the retry delay to avoid overwhelming the server with retries. timeout = retry_delay * (1 - 0.25 * random()) @@ -90,7 +92,8 @@ def _should_retry(response: httpx.Response) -> bool: def remove_omit_from_dict( - original: typing.Dict[str, typing.Optional[typing.Any]], omit: typing.Optional[typing.Any] + original: typing.Dict[str, typing.Optional[typing.Any]], + omit: typing.Optional[typing.Any], ) -> typing.Dict[str, typing.Any]: if omit is None: return original @@ -108,7 +111,8 @@ def maybe_filter_request_body( ) -> typing.Optional[typing.Any]: if data is None: return ( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else None ) @@ -118,7 +122,8 @@ def maybe_filter_request_body( data_content = { **(jsonable_encoder(remove_omit_from_dict(data, omit))), # type: ignore **( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else {} ), @@ -162,7 +167,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url def request( @@ -174,8 +181,12 @@ def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -184,11 +195,14 @@ def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) response = self.httpx_client.request( method=method, @@ -198,7 +212,11 @@ def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -209,7 +227,10 @@ def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -222,11 +243,15 @@ def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: time.sleep(_retry_timeout(response=response, retries=retries)) @@ -256,8 +281,12 @@ def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -266,11 +295,14 @@ def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) with self.httpx_client.stream( method=method, @@ -280,7 +312,11 @@ def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -291,7 +327,9 @@ def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -304,7 +342,9 @@ def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream @@ -327,7 +367,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url async def request( @@ -339,8 +381,12 @@ async def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -349,11 +395,14 @@ async def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) # Add the input to each of these and do None-safety checks response = await self.httpx_client.request( @@ -364,7 +413,11 @@ async def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -375,7 +428,10 @@ async def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -388,11 +444,15 @@ async def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: await asyncio.sleep(_retry_timeout(response=response, retries=retries)) @@ -421,8 +481,12 @@ async def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -431,11 +495,14 @@ async def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) async with self.httpx_client.stream( method=method, @@ -445,7 +512,11 @@ async def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -456,7 +527,9 @@ async def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -469,7 +542,9 @@ async def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream diff --git a/seed/python-sdk/exhaustive/extra_dependencies/src/seed/core/jsonable_encoder.py b/seed/python-sdk/exhaustive/extra_dependencies/src/seed/core/jsonable_encoder.py index d3fd328fd41..12a8b52fc22 100644 --- a/seed/python-sdk/exhaustive/extra_dependencies/src/seed/core/jsonable_encoder.py +++ b/seed/python-sdk/exhaustive/extra_dependencies/src/seed/core/jsonable_encoder.py @@ -19,13 +19,19 @@ import pydantic from .datetime_utils import serialize_datetime -from .pydantic_utilities import IS_PYDANTIC_V2, encode_by_type, to_jsonable_with_fallback +from .pydantic_utilities import ( + IS_PYDANTIC_V2, + encode_by_type, + to_jsonable_with_fallback, +) SetIntStr = Set[Union[int, str]] DictIntStrAny = Dict[Union[int, str], Any] -def jsonable_encoder(obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None) -> Any: +def jsonable_encoder( + obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None +) -> Any: custom_encoder = custom_encoder or {} if custom_encoder: if type(obj) in custom_encoder: diff --git a/seed/python-sdk/exhaustive/extra_dependencies/src/seed/core/pydantic_utilities.py b/seed/python-sdk/exhaustive/extra_dependencies/src/seed/core/pydantic_utilities.py index 170a563d6eb..c63935c32a2 100644 --- a/seed/python-sdk/exhaustive/extra_dependencies/src/seed/core/pydantic_utilities.py +++ b/seed/python-sdk/exhaustive/extra_dependencies/src/seed/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) # type: ignore # Pydantic v1 diff --git a/seed/python-sdk/exhaustive/extra_dependencies/src/seed/core/query_encoder.py b/seed/python-sdk/exhaustive/extra_dependencies/src/seed/core/query_encoder.py index 24076d72ee9..7cb98f52cd7 100644 --- a/seed/python-sdk/exhaustive/extra_dependencies/src/seed/core/query_encoder.py +++ b/seed/python-sdk/exhaustive/extra_dependencies/src/seed/core/query_encoder.py @@ -7,7 +7,9 @@ # Flattens dicts to be of the form {"key[subkey][subkey2]": value} where value is not a dict -def traverse_query_dict(dict_flat: Dict[str, Any], key_prefix: Optional[str] = None) -> Dict[str, Any]: +def traverse_query_dict( + dict_flat: Dict[str, Any], key_prefix: Optional[str] = None +) -> Dict[str, Any]: result = {} for k, v in dict_flat.items(): key = f"{key_prefix}[{k}]" if key_prefix is not None else k @@ -30,4 +32,8 @@ def single_query_encoder(query_key: str, query_value: Any) -> Dict[str, Any]: def encode_query(query: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: - return dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) if query is not None else None + return ( + dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) + if query is not None + else None + ) diff --git a/seed/python-sdk/exhaustive/extra_dependencies/src/seed/core/serialization.py b/seed/python-sdk/exhaustive/extra_dependencies/src/seed/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/python-sdk/exhaustive/extra_dependencies/src/seed/core/serialization.py +++ b/seed/python-sdk/exhaustive/extra_dependencies/src/seed/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/python-sdk/exhaustive/extra_dependencies/src/seed/endpoints/__init__.py b/seed/python-sdk/exhaustive/extra_dependencies/src/seed/endpoints/__init__.py index 92307cab7fe..a9496ece178 100644 --- a/seed/python-sdk/exhaustive/extra_dependencies/src/seed/endpoints/__init__.py +++ b/seed/python-sdk/exhaustive/extra_dependencies/src/seed/endpoints/__init__.py @@ -2,4 +2,12 @@ from . import container, enum, http_methods, object, params, primitive, union -__all__ = ["container", "enum", "http_methods", "object", "params", "primitive", "union"] +__all__ = [ + "container", + "enum", + "http_methods", + "object", + "params", + "primitive", + "union", +] diff --git a/seed/python-sdk/exhaustive/extra_dependencies/src/seed/endpoints/client.py b/seed/python-sdk/exhaustive/extra_dependencies/src/seed/endpoints/client.py index 18dc397fdf1..69930de54d7 100644 --- a/seed/python-sdk/exhaustive/extra_dependencies/src/seed/endpoints/client.py +++ b/seed/python-sdk/exhaustive/extra_dependencies/src/seed/endpoints/client.py @@ -1,13 +1,21 @@ # This file was auto-generated by Fern from our API Definition. -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from .container.client import AsyncContainerClient, ContainerClient -from .enum.client import AsyncEnumClient, EnumClient -from .http_methods.client import AsyncHttpMethodsClient, HttpMethodsClient -from .object.client import AsyncObjectClient, ObjectClient -from .params.client import AsyncParamsClient, ParamsClient -from .primitive.client import AsyncPrimitiveClient, PrimitiveClient -from .union.client import AsyncUnionClient, UnionClient +from ..core.client_wrapper import SyncClientWrapper +from .container.client import ContainerClient +from .enum.client import EnumClient +from .http_methods.client import HttpMethodsClient +from .object.client import ObjectClient +from .params.client import ParamsClient +from .primitive.client import PrimitiveClient +from .union.client import UnionClient +from ..core.client_wrapper import AsyncClientWrapper +from .container.client import AsyncContainerClient +from .enum.client import AsyncEnumClient +from .http_methods.client import AsyncHttpMethodsClient +from .object.client import AsyncObjectClient +from .params.client import AsyncParamsClient +from .primitive.client import AsyncPrimitiveClient +from .union.client import AsyncUnionClient class EndpointsClient: diff --git a/seed/python-sdk/exhaustive/extra_dependencies/src/seed/endpoints/container/client.py b/seed/python-sdk/exhaustive/extra_dependencies/src/seed/endpoints/container/client.py index c6cf14f63ac..4af9c12d534 100644 --- a/seed/python-sdk/exhaustive/extra_dependencies/src/seed/endpoints/container/client.py +++ b/seed/python-sdk/exhaustive/extra_dependencies/src/seed/endpoints/container/client.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. import typing +from ...core.client_wrapper import SyncClientWrapper +from ...core.request_options import RequestOptions +from ...core.pydantic_utilities import parse_obj_as from json.decoder import JSONDecodeError - from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ...core.pydantic_utilities import parse_obj_as -from ...core.request_options import RequestOptions from ...types.object.types.object_with_required_field import ObjectWithRequiredField +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -18,7 +18,10 @@ def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper def get_and_return_list_of_primitives( - self, *, request: typing.Sequence[str], request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Sequence[str], + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[str]: """ Parameters @@ -45,11 +48,18 @@ def get_and_return_list_of_primitives( ) """ _response = self._client_wrapper.httpx_client.request( - "container/list-of-primitives", method="POST", json=request, request_options=request_options, omit=OMIT + "container/list-of-primitives", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.List[str], parse_obj_as(type_=typing.List[str], object_=_response.json())) # type: ignore + return typing.cast( + typing.List[str], + parse_obj_as(type_=typing.List[str], object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -59,7 +69,7 @@ def get_and_return_list_of_objects( self, *, request: typing.Sequence[ObjectWithRequiredField], - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[ObjectWithRequiredField]: """ Parameters @@ -91,18 +101,31 @@ def get_and_return_list_of_objects( ) """ _response = self._client_wrapper.httpx_client.request( - "container/list-of-objects", method="POST", json=request, request_options=request_options, omit=OMIT + "container/list-of-objects", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.List[ObjectWithRequiredField], parse_obj_as(type_=typing.List[ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.List[ObjectWithRequiredField], + parse_obj_as( + type_=typing.List[ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_and_return_set_of_primitives( - self, *, request: typing.Set[str], request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Set[str], + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Set[str]: """ Parameters @@ -129,11 +152,18 @@ def get_and_return_set_of_primitives( ) """ _response = self._client_wrapper.httpx_client.request( - "container/set-of-primitives", method="POST", json=request, request_options=request_options, omit=OMIT + "container/set-of-primitives", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Set[str], parse_obj_as(type_=typing.Set[str], object_=_response.json())) # type: ignore + return typing.cast( + typing.Set[str], + parse_obj_as(type_=typing.Set[str], object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -143,7 +173,7 @@ def get_and_return_set_of_objects( self, *, request: typing.Sequence[ObjectWithRequiredField], - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[ObjectWithRequiredField]: """ Parameters @@ -175,18 +205,31 @@ def get_and_return_set_of_objects( ) """ _response = self._client_wrapper.httpx_client.request( - "container/set-of-objects", method="POST", json=request, request_options=request_options, omit=OMIT + "container/set-of-objects", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.List[ObjectWithRequiredField], parse_obj_as(type_=typing.List[ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.List[ObjectWithRequiredField], + parse_obj_as( + type_=typing.List[ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_and_return_map_prim_to_prim( - self, *, request: typing.Dict[str, str], request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Dict[str, str], + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Dict[str, str]: """ Parameters @@ -213,11 +256,18 @@ def get_and_return_map_prim_to_prim( ) """ _response = self._client_wrapper.httpx_client.request( - "container/map-prim-to-prim", method="POST", json=request, request_options=request_options, omit=OMIT + "container/map-prim-to-prim", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Dict[str, str], parse_obj_as(type_=typing.Dict[str, str], object_=_response.json())) # type: ignore + return typing.cast( + typing.Dict[str, str], + parse_obj_as(type_=typing.Dict[str, str], object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -227,7 +277,7 @@ def get_and_return_map_of_prim_to_object( self, *, request: typing.Dict[str, ObjectWithRequiredField], - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Dict[str, ObjectWithRequiredField]: """ Parameters @@ -259,11 +309,21 @@ def get_and_return_map_of_prim_to_object( ) """ _response = self._client_wrapper.httpx_client.request( - "container/map-prim-to-object", method="POST", json=request, request_options=request_options, omit=OMIT + "container/map-prim-to-object", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Dict[str, ObjectWithRequiredField], parse_obj_as(type_=typing.Dict[str, ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.Dict[str, ObjectWithRequiredField], + parse_obj_as( + type_=typing.Dict[str, ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -273,7 +333,7 @@ def get_and_return_optional( self, *, request: typing.Optional[ObjectWithRequiredField] = None, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Optional[ObjectWithRequiredField]: """ Parameters @@ -303,11 +363,21 @@ def get_and_return_optional( ) """ _response = self._client_wrapper.httpx_client.request( - "container/opt-objects", method="POST", json=request, request_options=request_options, omit=OMIT + "container/opt-objects", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Optional[ObjectWithRequiredField], parse_obj_as(type_=typing.Optional[ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.Optional[ObjectWithRequiredField], + parse_obj_as( + type_=typing.Optional[ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -319,7 +389,10 @@ def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper async def get_and_return_list_of_primitives( - self, *, request: typing.Sequence[str], request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Sequence[str], + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[str]: """ Parameters @@ -354,11 +427,18 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/list-of-primitives", method="POST", json=request, request_options=request_options, omit=OMIT + "container/list-of-primitives", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.List[str], parse_obj_as(type_=typing.List[str], object_=_response.json())) # type: ignore + return typing.cast( + typing.List[str], + parse_obj_as(type_=typing.List[str], object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -368,7 +448,7 @@ async def get_and_return_list_of_objects( self, *, request: typing.Sequence[ObjectWithRequiredField], - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[ObjectWithRequiredField]: """ Parameters @@ -408,18 +488,31 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/list-of-objects", method="POST", json=request, request_options=request_options, omit=OMIT + "container/list-of-objects", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.List[ObjectWithRequiredField], parse_obj_as(type_=typing.List[ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.List[ObjectWithRequiredField], + parse_obj_as( + type_=typing.List[ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_and_return_set_of_primitives( - self, *, request: typing.Set[str], request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Set[str], + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Set[str]: """ Parameters @@ -454,11 +547,18 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/set-of-primitives", method="POST", json=request, request_options=request_options, omit=OMIT + "container/set-of-primitives", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Set[str], parse_obj_as(type_=typing.Set[str], object_=_response.json())) # type: ignore + return typing.cast( + typing.Set[str], + parse_obj_as(type_=typing.Set[str], object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -468,7 +568,7 @@ async def get_and_return_set_of_objects( self, *, request: typing.Sequence[ObjectWithRequiredField], - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[ObjectWithRequiredField]: """ Parameters @@ -508,18 +608,31 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/set-of-objects", method="POST", json=request, request_options=request_options, omit=OMIT + "container/set-of-objects", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.List[ObjectWithRequiredField], parse_obj_as(type_=typing.List[ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.List[ObjectWithRequiredField], + parse_obj_as( + type_=typing.List[ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_and_return_map_prim_to_prim( - self, *, request: typing.Dict[str, str], request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Dict[str, str], + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Dict[str, str]: """ Parameters @@ -554,11 +667,18 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/map-prim-to-prim", method="POST", json=request, request_options=request_options, omit=OMIT + "container/map-prim-to-prim", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Dict[str, str], parse_obj_as(type_=typing.Dict[str, str], object_=_response.json())) # type: ignore + return typing.cast( + typing.Dict[str, str], + parse_obj_as(type_=typing.Dict[str, str], object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -568,7 +688,7 @@ async def get_and_return_map_of_prim_to_object( self, *, request: typing.Dict[str, ObjectWithRequiredField], - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Dict[str, ObjectWithRequiredField]: """ Parameters @@ -608,11 +728,21 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/map-prim-to-object", method="POST", json=request, request_options=request_options, omit=OMIT + "container/map-prim-to-object", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Dict[str, ObjectWithRequiredField], parse_obj_as(type_=typing.Dict[str, ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.Dict[str, ObjectWithRequiredField], + parse_obj_as( + type_=typing.Dict[str, ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -622,7 +752,7 @@ async def get_and_return_optional( self, *, request: typing.Optional[ObjectWithRequiredField] = None, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Optional[ObjectWithRequiredField]: """ Parameters @@ -660,11 +790,21 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/opt-objects", method="POST", json=request, request_options=request_options, omit=OMIT + "container/opt-objects", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Optional[ObjectWithRequiredField], parse_obj_as(type_=typing.Optional[ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.Optional[ObjectWithRequiredField], + parse_obj_as( + type_=typing.Optional[ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/extra_dependencies/src/seed/endpoints/enum/client.py b/seed/python-sdk/exhaustive/extra_dependencies/src/seed/endpoints/enum/client.py index 44e2690ff6c..3e3208e3bcf 100644 --- a/seed/python-sdk/exhaustive/extra_dependencies/src/seed/endpoints/enum/client.py +++ b/seed/python-sdk/exhaustive/extra_dependencies/src/seed/endpoints/enum/client.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. import typing +from ...core.client_wrapper import SyncClientWrapper +from ...types.enum.types.weather_report import WeatherReport +from ...core.request_options import RequestOptions +from ...core.pydantic_utilities import parse_obj_as from json.decoder import JSONDecodeError - from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ...core.pydantic_utilities import parse_obj_as -from ...core.request_options import RequestOptions -from ...types.enum.types.weather_report import WeatherReport +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -18,7 +18,10 @@ def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper def get_and_return_enum( - self, *, request: WeatherReport, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: WeatherReport, + request_options: typing.Optional[RequestOptions] = None, ) -> WeatherReport: """ Parameters @@ -45,11 +48,18 @@ def get_and_return_enum( ) """ _response = self._client_wrapper.httpx_client.request( - "enum", method="POST", json=request, request_options=request_options, omit=OMIT + "enum", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(WeatherReport, parse_obj_as(type_=WeatherReport, object_=_response.json())) # type: ignore + return typing.cast( + WeatherReport, + parse_obj_as(type_=WeatherReport, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -61,7 +71,10 @@ def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper async def get_and_return_enum( - self, *, request: WeatherReport, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: WeatherReport, + request_options: typing.Optional[RequestOptions] = None, ) -> WeatherReport: """ Parameters @@ -96,11 +109,18 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "enum", method="POST", json=request, request_options=request_options, omit=OMIT + "enum", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(WeatherReport, parse_obj_as(type_=WeatherReport, object_=_response.json())) # type: ignore + return typing.cast( + WeatherReport, + parse_obj_as(type_=WeatherReport, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/extra_dependencies/src/seed/endpoints/http_methods/client.py b/seed/python-sdk/exhaustive/extra_dependencies/src/seed/endpoints/http_methods/client.py index a2549280a1b..570a227844f 100644 --- a/seed/python-sdk/exhaustive/extra_dependencies/src/seed/endpoints/http_methods/client.py +++ b/seed/python-sdk/exhaustive/extra_dependencies/src/seed/endpoints/http_methods/client.py @@ -1,16 +1,16 @@ # This file was auto-generated by Fern from our API Definition. -import datetime as dt import typing -import uuid -from json.decoder import JSONDecodeError - -from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper +from ...core.client_wrapper import SyncClientWrapper +from ...core.request_options import RequestOptions from ...core.jsonable_encoder import jsonable_encoder from ...core.pydantic_utilities import parse_obj_as -from ...core.request_options import RequestOptions +from json.decoder import JSONDecodeError +from ...core.api_error import ApiError from ...types.object.types.object_with_optional_field import ObjectWithOptionalField +import datetime as dt +import uuid +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -20,7 +20,9 @@ class HttpMethodsClient: def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper - def test_get(self, id: str, *, request_options: typing.Optional[RequestOptions] = None) -> str: + def test_get( + self, id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -46,11 +48,15 @@ def test_get(self, id: str, *, request_options: typing.Optional[RequestOptions] ) """ _response = self._client_wrapper.httpx_client.request( - f"http-methods/{jsonable_encoder(id)}", method="GET", request_options=request_options + f"http-methods/{jsonable_encoder(id)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -84,18 +90,33 @@ def test_post( ) """ _response = self._client_wrapper.httpx_client.request( - "http-methods", method="POST", json={"string": string}, request_options=request_options, omit=OMIT + "http-methods", + method="POST", + json={ + "string": string, + }, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def test_put( - self, id: str, *, string: str, request_options: typing.Optional[RequestOptions] = None + self, + id: str, + *, + string: str, + request_options: typing.Optional[RequestOptions] = None, ) -> ObjectWithOptionalField: """ Parameters @@ -127,13 +148,20 @@ def test_put( _response = self._client_wrapper.httpx_client.request( f"http-methods/{jsonable_encoder(id)}", method="PUT", - json={"string": string}, + json={ + "string": string, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -254,13 +282,20 @@ def test_patch( ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def test_delete(self, id: str, *, request_options: typing.Optional[RequestOptions] = None) -> bool: + def test_delete( + self, id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> bool: """ Parameters ---------- @@ -286,11 +321,15 @@ def test_delete(self, id: str, *, request_options: typing.Optional[RequestOption ) """ _response = self._client_wrapper.httpx_client.request( - f"http-methods/{jsonable_encoder(id)}", method="DELETE", request_options=request_options + f"http-methods/{jsonable_encoder(id)}", + method="DELETE", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -301,7 +340,9 @@ class AsyncHttpMethodsClient: def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper - async def test_get(self, id: str, *, request_options: typing.Optional[RequestOptions] = None) -> str: + async def test_get( + self, id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -335,11 +376,15 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - f"http-methods/{jsonable_encoder(id)}", method="GET", request_options=request_options + f"http-methods/{jsonable_encoder(id)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -381,18 +426,33 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "http-methods", method="POST", json={"string": string}, request_options=request_options, omit=OMIT + "http-methods", + method="POST", + json={ + "string": string, + }, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def test_put( - self, id: str, *, string: str, request_options: typing.Optional[RequestOptions] = None + self, + id: str, + *, + string: str, + request_options: typing.Optional[RequestOptions] = None, ) -> ObjectWithOptionalField: """ Parameters @@ -432,13 +492,20 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( f"http-methods/{jsonable_encoder(id)}", method="PUT", - json={"string": string}, + json={ + "string": string, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -566,13 +633,20 @@ async def main() -> None: ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - async def test_delete(self, id: str, *, request_options: typing.Optional[RequestOptions] = None) -> bool: + async def test_delete( + self, id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> bool: """ Parameters ---------- @@ -606,11 +680,15 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - f"http-methods/{jsonable_encoder(id)}", method="DELETE", request_options=request_options + f"http-methods/{jsonable_encoder(id)}", + method="DELETE", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/extra_dependencies/src/seed/endpoints/object/client.py b/seed/python-sdk/exhaustive/extra_dependencies/src/seed/endpoints/object/client.py index a724f959193..dcb1324b74b 100644 --- a/seed/python-sdk/exhaustive/extra_dependencies/src/seed/endpoints/object/client.py +++ b/seed/python-sdk/exhaustive/extra_dependencies/src/seed/endpoints/object/client.py @@ -1,20 +1,24 @@ # This file was auto-generated by Fern from our API Definition. -import datetime as dt import typing +from ...core.client_wrapper import SyncClientWrapper +import datetime as dt import uuid -from json.decoder import JSONDecodeError - -from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ...core.jsonable_encoder import jsonable_encoder -from ...core.pydantic_utilities import parse_obj_as from ...core.request_options import RequestOptions -from ...types.object.types.nested_object_with_optional_field import NestedObjectWithOptionalField -from ...types.object.types.nested_object_with_required_field import NestedObjectWithRequiredField -from ...types.object.types.object_with_map_of_map import ObjectWithMapOfMap from ...types.object.types.object_with_optional_field import ObjectWithOptionalField +from ...core.pydantic_utilities import parse_obj_as +from json.decoder import JSONDecodeError +from ...core.api_error import ApiError from ...types.object.types.object_with_required_field import ObjectWithRequiredField +from ...types.object.types.object_with_map_of_map import ObjectWithMapOfMap +from ...types.object.types.nested_object_with_optional_field import ( + NestedObjectWithOptionalField, +) +from ...types.object.types.nested_object_with_required_field import ( + NestedObjectWithRequiredField, +) +from ...core.jsonable_encoder import jsonable_encoder +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -135,7 +139,12 @@ def get_and_return_with_optional_field( ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -171,20 +180,30 @@ def get_and_return_with_required_field( _response = self._client_wrapper.httpx_client.request( "object/get-and-return-with-required-field", method="POST", - json={"string": string}, + json={ + "string": string, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithRequiredField, parse_obj_as(type_=ObjectWithRequiredField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithRequiredField, + parse_obj_as( + type_=ObjectWithRequiredField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_and_return_with_map_of_map( - self, *, map_: typing.Dict[str, typing.Dict[str, str]], request_options: typing.Optional[RequestOptions] = None + self, + *, + map_: typing.Dict[str, typing.Dict[str, str]], + request_options: typing.Optional[RequestOptions] = None, ) -> ObjectWithMapOfMap: """ Parameters @@ -213,13 +232,18 @@ def get_and_return_with_map_of_map( _response = self._client_wrapper.httpx_client.request( "object/get-and-return-with-map-of-map", method="POST", - json={"map": map_}, + json={ + "map": map_, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithMapOfMap, parse_obj_as(type_=ObjectWithMapOfMap, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithMapOfMap, + parse_obj_as(type_=ObjectWithMapOfMap, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -286,13 +310,21 @@ def get_and_return_nested_with_optional_field( _response = self._client_wrapper.httpx_client.request( "object/get-and-return-nested-with-optional-field", method="POST", - json={"string": string, "NestedObject": nested_object}, + json={ + "string": string, + "NestedObject": nested_object, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(NestedObjectWithOptionalField, parse_obj_as(type_=NestedObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + NestedObjectWithOptionalField, + parse_obj_as( + type_=NestedObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -363,13 +395,21 @@ def get_and_return_nested_with_required_field( _response = self._client_wrapper.httpx_client.request( f"object/get-and-return-nested-with-required-field/{jsonable_encoder(string_)}", method="POST", - json={"string": string, "NestedObject": nested_object}, + json={ + "string": string, + "NestedObject": nested_object, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(NestedObjectWithRequiredField, parse_obj_as(type_=NestedObjectWithRequiredField, object_=_response.json())) # type: ignore + return typing.cast( + NestedObjectWithRequiredField, + parse_obj_as( + type_=NestedObjectWithRequiredField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -446,7 +486,12 @@ def get_and_return_nested_with_required_field_as_list( ) try: if 200 <= _response.status_code < 300: - return typing.cast(NestedObjectWithRequiredField, parse_obj_as(type_=NestedObjectWithRequiredField, object_=_response.json())) # type: ignore + return typing.cast( + NestedObjectWithRequiredField, + parse_obj_as( + type_=NestedObjectWithRequiredField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -575,7 +620,12 @@ async def main() -> None: ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -619,20 +669,30 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( "object/get-and-return-with-required-field", method="POST", - json={"string": string}, + json={ + "string": string, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithRequiredField, parse_obj_as(type_=ObjectWithRequiredField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithRequiredField, + parse_obj_as( + type_=ObjectWithRequiredField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_and_return_with_map_of_map( - self, *, map_: typing.Dict[str, typing.Dict[str, str]], request_options: typing.Optional[RequestOptions] = None + self, + *, + map_: typing.Dict[str, typing.Dict[str, str]], + request_options: typing.Optional[RequestOptions] = None, ) -> ObjectWithMapOfMap: """ Parameters @@ -669,13 +729,18 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( "object/get-and-return-with-map-of-map", method="POST", - json={"map": map_}, + json={ + "map": map_, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithMapOfMap, parse_obj_as(type_=ObjectWithMapOfMap, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithMapOfMap, + parse_obj_as(type_=ObjectWithMapOfMap, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -749,13 +814,21 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( "object/get-and-return-nested-with-optional-field", method="POST", - json={"string": string, "NestedObject": nested_object}, + json={ + "string": string, + "NestedObject": nested_object, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(NestedObjectWithOptionalField, parse_obj_as(type_=NestedObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + NestedObjectWithOptionalField, + parse_obj_as( + type_=NestedObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -833,13 +906,21 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( f"object/get-and-return-nested-with-required-field/{jsonable_encoder(string_)}", method="POST", - json={"string": string, "NestedObject": nested_object}, + json={ + "string": string, + "NestedObject": nested_object, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(NestedObjectWithRequiredField, parse_obj_as(type_=NestedObjectWithRequiredField, object_=_response.json())) # type: ignore + return typing.cast( + NestedObjectWithRequiredField, + parse_obj_as( + type_=NestedObjectWithRequiredField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -923,7 +1004,12 @@ async def main() -> None: ) try: if 200 <= _response.status_code < 300: - return typing.cast(NestedObjectWithRequiredField, parse_obj_as(type_=NestedObjectWithRequiredField, object_=_response.json())) # type: ignore + return typing.cast( + NestedObjectWithRequiredField, + parse_obj_as( + type_=NestedObjectWithRequiredField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/extra_dependencies/src/seed/endpoints/params/client.py b/seed/python-sdk/exhaustive/extra_dependencies/src/seed/endpoints/params/client.py index 5cd7ceef42a..a9187ac94b8 100644 --- a/seed/python-sdk/exhaustive/extra_dependencies/src/seed/endpoints/params/client.py +++ b/seed/python-sdk/exhaustive/extra_dependencies/src/seed/endpoints/params/client.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. import typing -from json.decoder import JSONDecodeError - -from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper +from ...core.client_wrapper import SyncClientWrapper +from ...core.request_options import RequestOptions from ...core.jsonable_encoder import jsonable_encoder from ...core.pydantic_utilities import parse_obj_as -from ...core.request_options import RequestOptions +from json.decoder import JSONDecodeError +from ...core.api_error import ApiError +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -17,7 +17,9 @@ class ParamsClient: def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper - def get_with_path(self, param: str, *, request_options: typing.Optional[RequestOptions] = None) -> str: + def get_with_path( + self, param: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ GET with path param @@ -45,18 +47,26 @@ def get_with_path(self, param: str, *, request_options: typing.Optional[RequestO ) """ _response = self._client_wrapper.httpx_client.request( - f"params/path/{jsonable_encoder(param)}", method="GET", request_options=request_options + f"params/path/{jsonable_encoder(param)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_with_query( - self, *, query: str, number: int, request_options: typing.Optional[RequestOptions] = None + self, + *, + query: str, + number: int, + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ GET with query param @@ -88,7 +98,13 @@ def get_with_query( ) """ _response = self._client_wrapper.httpx_client.request( - "params", method="GET", params={"query": query, "number": number}, request_options=request_options + "params", + method="GET", + params={ + "query": query, + "number": number, + }, + request_options=request_options, ) try: if 200 <= _response.status_code < 300: @@ -135,7 +151,13 @@ def get_with_allow_multiple_query( ) """ _response = self._client_wrapper.httpx_client.request( - "params", method="GET", params={"query": query, "numer": numer}, request_options=request_options + "params", + method="GET", + params={ + "query": query, + "numer": numer, + }, + request_options=request_options, ) try: if 200 <= _response.status_code < 300: @@ -146,7 +168,11 @@ def get_with_allow_multiple_query( raise ApiError(status_code=_response.status_code, body=_response_json) def get_with_path_and_query( - self, param: str, *, query: str, request_options: typing.Optional[RequestOptions] = None + self, + param: str, + *, + query: str, + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ GET with path and query params @@ -180,7 +206,9 @@ def get_with_path_and_query( _response = self._client_wrapper.httpx_client.request( f"params/path-query/{jsonable_encoder(param)}", method="GET", - params={"query": query}, + params={ + "query": query, + }, request_options=request_options, ) try: @@ -192,7 +220,11 @@ def get_with_path_and_query( raise ApiError(status_code=_response.status_code, body=_response_json) def modify_with_path( - self, param: str, *, request: str, request_options: typing.Optional[RequestOptions] = None + self, + param: str, + *, + request: str, + request_options: typing.Optional[RequestOptions] = None, ) -> str: """ PUT to update with path param @@ -232,7 +264,9 @@ def modify_with_path( ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -243,7 +277,9 @@ class AsyncParamsClient: def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper - async def get_with_path(self, param: str, *, request_options: typing.Optional[RequestOptions] = None) -> str: + async def get_with_path( + self, param: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ GET with path param @@ -279,18 +315,26 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - f"params/path/{jsonable_encoder(param)}", method="GET", request_options=request_options + f"params/path/{jsonable_encoder(param)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_with_query( - self, *, query: str, number: int, request_options: typing.Optional[RequestOptions] = None + self, + *, + query: str, + number: int, + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ GET with query param @@ -330,7 +374,13 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "params", method="GET", params={"query": query, "number": number}, request_options=request_options + "params", + method="GET", + params={ + "query": query, + "number": number, + }, + request_options=request_options, ) try: if 200 <= _response.status_code < 300: @@ -385,7 +435,13 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "params", method="GET", params={"query": query, "numer": numer}, request_options=request_options + "params", + method="GET", + params={ + "query": query, + "numer": numer, + }, + request_options=request_options, ) try: if 200 <= _response.status_code < 300: @@ -396,7 +452,11 @@ async def main() -> None: raise ApiError(status_code=_response.status_code, body=_response_json) async def get_with_path_and_query( - self, param: str, *, query: str, request_options: typing.Optional[RequestOptions] = None + self, + param: str, + *, + query: str, + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ GET with path and query params @@ -438,7 +498,9 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( f"params/path-query/{jsonable_encoder(param)}", method="GET", - params={"query": query}, + params={ + "query": query, + }, request_options=request_options, ) try: @@ -450,7 +512,11 @@ async def main() -> None: raise ApiError(status_code=_response.status_code, body=_response_json) async def modify_with_path( - self, param: str, *, request: str, request_options: typing.Optional[RequestOptions] = None + self, + param: str, + *, + request: str, + request_options: typing.Optional[RequestOptions] = None, ) -> str: """ PUT to update with path param @@ -498,7 +564,9 @@ async def main() -> None: ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/extra_dependencies/src/seed/endpoints/primitive/client.py b/seed/python-sdk/exhaustive/extra_dependencies/src/seed/endpoints/primitive/client.py index 844b6a782f0..20a66f049b4 100644 --- a/seed/python-sdk/exhaustive/extra_dependencies/src/seed/endpoints/primitive/client.py +++ b/seed/python-sdk/exhaustive/extra_dependencies/src/seed/endpoints/primitive/client.py @@ -1,14 +1,14 @@ # This file was auto-generated by Fern from our API Definition. -import datetime as dt import typing -import uuid +from ...core.client_wrapper import SyncClientWrapper +from ...core.request_options import RequestOptions +from ...core.pydantic_utilities import parse_obj_as from json.decoder import JSONDecodeError - from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ...core.pydantic_utilities import parse_obj_as -from ...core.request_options import RequestOptions +import datetime as dt +import uuid +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -18,7 +18,9 @@ class PrimitiveClient: def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper - def get_and_return_string(self, *, request: str, request_options: typing.Optional[RequestOptions] = None) -> str: + def get_and_return_string( + self, *, request: str, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -44,17 +46,25 @@ def get_and_return_string(self, *, request: str, request_options: typing.Optiona ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/string", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/string", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def get_and_return_int(self, *, request: int, request_options: typing.Optional[RequestOptions] = None) -> int: + def get_and_return_int( + self, *, request: int, request_options: typing.Optional[RequestOptions] = None + ) -> int: """ Parameters ---------- @@ -80,17 +90,25 @@ def get_and_return_int(self, *, request: int, request_options: typing.Optional[R ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/integer", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/integer", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(int, parse_obj_as(type_=int, object_=_response.json())) # type: ignore + return typing.cast( + int, parse_obj_as(type_=int, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def get_and_return_long(self, *, request: int, request_options: typing.Optional[RequestOptions] = None) -> int: + def get_and_return_long( + self, *, request: int, request_options: typing.Optional[RequestOptions] = None + ) -> int: """ Parameters ---------- @@ -116,11 +134,17 @@ def get_and_return_long(self, *, request: int, request_options: typing.Optional[ ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/long", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/long", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(int, parse_obj_as(type_=int, object_=_response.json())) # type: ignore + return typing.cast( + int, parse_obj_as(type_=int, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -154,17 +178,25 @@ def get_and_return_double( ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/double", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/double", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(float, parse_obj_as(type_=float, object_=_response.json())) # type: ignore + return typing.cast( + float, parse_obj_as(type_=float, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def get_and_return_bool(self, *, request: bool, request_options: typing.Optional[RequestOptions] = None) -> bool: + def get_and_return_bool( + self, *, request: bool, request_options: typing.Optional[RequestOptions] = None + ) -> bool: """ Parameters ---------- @@ -190,18 +222,27 @@ def get_and_return_bool(self, *, request: bool, request_options: typing.Optional ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/boolean", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/boolean", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_and_return_datetime( - self, *, request: dt.datetime, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: dt.datetime, + request_options: typing.Optional[RequestOptions] = None, ) -> dt.datetime: """ Parameters @@ -232,18 +273,28 @@ def get_and_return_datetime( ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/datetime", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/datetime", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(dt.datetime, parse_obj_as(type_=dt.datetime, object_=_response.json())) # type: ignore + return typing.cast( + dt.datetime, + parse_obj_as(type_=dt.datetime, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_and_return_date( - self, *, request: dt.date, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: dt.date, + request_options: typing.Optional[RequestOptions] = None, ) -> dt.date: """ Parameters @@ -274,18 +325,27 @@ def get_and_return_date( ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/date", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/date", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(dt.date, parse_obj_as(type_=dt.date, object_=_response.json())) # type: ignore + return typing.cast( + dt.date, parse_obj_as(type_=dt.date, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_and_return_uuid( - self, *, request: uuid.UUID, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: uuid.UUID, + request_options: typing.Optional[RequestOptions] = None, ) -> uuid.UUID: """ Parameters @@ -316,17 +376,25 @@ def get_and_return_uuid( ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/uuid", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/uuid", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(uuid.UUID, parse_obj_as(type_=uuid.UUID, object_=_response.json())) # type: ignore + return typing.cast( + uuid.UUID, parse_obj_as(type_=uuid.UUID, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def get_and_return_base_64(self, *, request: str, request_options: typing.Optional[RequestOptions] = None) -> str: + def get_and_return_base_64( + self, *, request: str, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -352,11 +420,17 @@ def get_and_return_base_64(self, *, request: str, request_options: typing.Option ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/base64", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/base64", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -403,17 +477,25 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/string", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/string", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - async def get_and_return_int(self, *, request: int, request_options: typing.Optional[RequestOptions] = None) -> int: + async def get_and_return_int( + self, *, request: int, request_options: typing.Optional[RequestOptions] = None + ) -> int: """ Parameters ---------- @@ -447,11 +529,17 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/integer", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/integer", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(int, parse_obj_as(type_=int, object_=_response.json())) # type: ignore + return typing.cast( + int, parse_obj_as(type_=int, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -493,11 +581,17 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/long", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/long", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(int, parse_obj_as(type_=int, object_=_response.json())) # type: ignore + return typing.cast( + int, parse_obj_as(type_=int, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -539,11 +633,17 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/double", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/double", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(float, parse_obj_as(type_=float, object_=_response.json())) # type: ignore + return typing.cast( + float, parse_obj_as(type_=float, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -585,18 +685,27 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/boolean", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/boolean", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_and_return_datetime( - self, *, request: dt.datetime, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: dt.datetime, + request_options: typing.Optional[RequestOptions] = None, ) -> dt.datetime: """ Parameters @@ -634,18 +743,28 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/datetime", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/datetime", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(dt.datetime, parse_obj_as(type_=dt.datetime, object_=_response.json())) # type: ignore + return typing.cast( + dt.datetime, + parse_obj_as(type_=dt.datetime, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_and_return_date( - self, *, request: dt.date, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: dt.date, + request_options: typing.Optional[RequestOptions] = None, ) -> dt.date: """ Parameters @@ -683,18 +802,27 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/date", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/date", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(dt.date, parse_obj_as(type_=dt.date, object_=_response.json())) # type: ignore + return typing.cast( + dt.date, parse_obj_as(type_=dt.date, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_and_return_uuid( - self, *, request: uuid.UUID, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: uuid.UUID, + request_options: typing.Optional[RequestOptions] = None, ) -> uuid.UUID: """ Parameters @@ -732,11 +860,17 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/uuid", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/uuid", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(uuid.UUID, parse_obj_as(type_=uuid.UUID, object_=_response.json())) # type: ignore + return typing.cast( + uuid.UUID, parse_obj_as(type_=uuid.UUID, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -778,11 +912,17 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/base64", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/base64", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/extra_dependencies/src/seed/endpoints/union/client.py b/seed/python-sdk/exhaustive/extra_dependencies/src/seed/endpoints/union/client.py index 77153587a27..f4c3d9312de 100644 --- a/seed/python-sdk/exhaustive/extra_dependencies/src/seed/endpoints/union/client.py +++ b/seed/python-sdk/exhaustive/extra_dependencies/src/seed/endpoints/union/client.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. import typing +from ...core.client_wrapper import SyncClientWrapper +from ...types.union.types.animal import Animal +from ...core.request_options import RequestOptions +from ...core.pydantic_utilities import parse_obj_as from json.decoder import JSONDecodeError - from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ...core.pydantic_utilities import parse_obj_as -from ...core.request_options import RequestOptions -from ...types.union.types.animal import Animal +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -18,7 +18,10 @@ def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper def get_and_return_union( - self, *, request: Animal, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: Animal, + request_options: typing.Optional[RequestOptions] = None, ) -> Animal: """ Parameters @@ -49,11 +52,17 @@ def get_and_return_union( ) """ _response = self._client_wrapper.httpx_client.request( - "union", method="POST", json=request, request_options=request_options, omit=OMIT + "union", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(Animal, parse_obj_as(type_=Animal, object_=_response.json())) # type: ignore + return typing.cast( + Animal, parse_obj_as(type_=Animal, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -65,7 +74,10 @@ def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper async def get_and_return_union( - self, *, request: Animal, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: Animal, + request_options: typing.Optional[RequestOptions] = None, ) -> Animal: """ Parameters @@ -104,11 +116,17 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "union", method="POST", json=request, request_options=request_options, omit=OMIT + "union", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(Animal, parse_obj_as(type_=Animal, object_=_response.json())) # type: ignore + return typing.cast( + Animal, parse_obj_as(type_=Animal, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/extra_dependencies/src/seed/general_errors/types/bad_object_request_info.py b/seed/python-sdk/exhaustive/extra_dependencies/src/seed/general_errors/types/bad_object_request_info.py index 7f03429e922..73c44b89531 100644 --- a/seed/python-sdk/exhaustive/extra_dependencies/src/seed/general_errors/types/bad_object_request_info.py +++ b/seed/python-sdk/exhaustive/extra_dependencies/src/seed/general_errors/types/bad_object_request_info.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class BadObjectRequestInfo(UniversalBaseModel): message: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/extra_dependencies/src/seed/inlined_requests/client.py b/seed/python-sdk/exhaustive/extra_dependencies/src/seed/inlined_requests/client.py index f7c46698eb9..39e0c8fe637 100644 --- a/seed/python-sdk/exhaustive/extra_dependencies/src/seed/inlined_requests/client.py +++ b/seed/python-sdk/exhaustive/extra_dependencies/src/seed/inlined_requests/client.py @@ -1,15 +1,15 @@ # This file was auto-generated by Fern from our API Definition. import typing -from json.decoder import JSONDecodeError - -from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.pydantic_utilities import parse_obj_as +from ..core.client_wrapper import SyncClientWrapper +from ..types.object.types.object_with_optional_field import ObjectWithOptionalField from ..core.request_options import RequestOptions +from ..core.pydantic_utilities import parse_obj_as from ..general_errors.errors.bad_request_body import BadRequestBody from ..general_errors.types.bad_object_request_info import BadObjectRequestInfo -from ..types.object.types.object_with_optional_field import ObjectWithOptionalField +from json.decoder import JSONDecodeError +from ..core.api_error import ApiError +from ..core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -25,7 +25,7 @@ def post_with_object_bodyand_response( string: str, integer: int, nested_object: ObjectWithOptionalField, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> ObjectWithOptionalField: """ POST with custom object in request body, response is an object @@ -86,16 +86,30 @@ def post_with_object_bodyand_response( _response = self._client_wrapper.httpx_client.request( "req-bodies/object", method="POST", - json={"string": string, "integer": integer, "NestedObject": nested_object}, + json={ + "string": string, + "integer": integer, + "NestedObject": nested_object, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore if _response.status_code == 400: raise BadRequestBody( - typing.cast(BadObjectRequestInfo, parse_obj_as(type_=BadObjectRequestInfo, object_=_response.json())) # type: ignore + typing.cast( + BadObjectRequestInfo, + parse_obj_as( + type_=BadObjectRequestInfo, object_=_response.json() + ), + ) # type: ignore ) _response_json = _response.json() except JSONDecodeError: @@ -113,7 +127,7 @@ async def post_with_object_bodyand_response( string: str, integer: int, nested_object: ObjectWithOptionalField, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> ObjectWithOptionalField: """ POST with custom object in request body, response is an object @@ -181,16 +195,30 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( "req-bodies/object", method="POST", - json={"string": string, "integer": integer, "NestedObject": nested_object}, + json={ + "string": string, + "integer": integer, + "NestedObject": nested_object, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore if _response.status_code == 400: raise BadRequestBody( - typing.cast(BadObjectRequestInfo, parse_obj_as(type_=BadObjectRequestInfo, object_=_response.json())) # type: ignore + typing.cast( + BadObjectRequestInfo, + parse_obj_as( + type_=BadObjectRequestInfo, object_=_response.json() + ), + ) # type: ignore ) _response_json = _response.json() except JSONDecodeError: diff --git a/seed/python-sdk/exhaustive/extra_dependencies/src/seed/no_auth/client.py b/seed/python-sdk/exhaustive/extra_dependencies/src/seed/no_auth/client.py index 3d203bcea34..e5590cde0df 100644 --- a/seed/python-sdk/exhaustive/extra_dependencies/src/seed/no_auth/client.py +++ b/seed/python-sdk/exhaustive/extra_dependencies/src/seed/no_auth/client.py @@ -1,14 +1,14 @@ # This file was auto-generated by Fern from our API Definition. import typing -from json.decoder import JSONDecodeError - -from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.pydantic_utilities import parse_obj_as +from ..core.client_wrapper import SyncClientWrapper from ..core.request_options import RequestOptions +from ..core.pydantic_utilities import parse_obj_as from ..general_errors.errors.bad_request_body import BadRequestBody from ..general_errors.types.bad_object_request_info import BadObjectRequestInfo +from json.decoder import JSONDecodeError +from ..core.api_error import ApiError +from ..core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -19,7 +19,10 @@ def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper def post_with_no_auth( - self, *, request: typing.Any, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Any, + request_options: typing.Optional[RequestOptions] = None, ) -> bool: """ POST request with no auth @@ -48,14 +51,25 @@ def post_with_no_auth( ) """ _response = self._client_wrapper.httpx_client.request( - "no-auth", method="POST", json=request, request_options=request_options, omit=OMIT + "no-auth", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore if _response.status_code == 400: raise BadRequestBody( - typing.cast(BadObjectRequestInfo, parse_obj_as(type_=BadObjectRequestInfo, object_=_response.json())) # type: ignore + typing.cast( + BadObjectRequestInfo, + parse_obj_as( + type_=BadObjectRequestInfo, object_=_response.json() + ), + ) # type: ignore ) _response_json = _response.json() except JSONDecodeError: @@ -68,7 +82,10 @@ def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper async def post_with_no_auth( - self, *, request: typing.Any, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Any, + request_options: typing.Optional[RequestOptions] = None, ) -> bool: """ POST request with no auth @@ -105,14 +122,25 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "no-auth", method="POST", json=request, request_options=request_options, omit=OMIT + "no-auth", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore if _response.status_code == 400: raise BadRequestBody( - typing.cast(BadObjectRequestInfo, parse_obj_as(type_=BadObjectRequestInfo, object_=_response.json())) # type: ignore + typing.cast( + BadObjectRequestInfo, + parse_obj_as( + type_=BadObjectRequestInfo, object_=_response.json() + ), + ) # type: ignore ) _response_json = _response.json() except JSONDecodeError: diff --git a/seed/python-sdk/exhaustive/extra_dependencies/src/seed/no_req_body/client.py b/seed/python-sdk/exhaustive/extra_dependencies/src/seed/no_req_body/client.py index 33fa0c77d27..5afdd703fdc 100644 --- a/seed/python-sdk/exhaustive/extra_dependencies/src/seed/no_req_body/client.py +++ b/seed/python-sdk/exhaustive/extra_dependencies/src/seed/no_req_body/client.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. +from ..core.client_wrapper import SyncClientWrapper import typing -from json.decoder import JSONDecodeError - -from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.pydantic_utilities import parse_obj_as from ..core.request_options import RequestOptions from ..types.object.types.object_with_optional_field import ObjectWithOptionalField +from ..core.pydantic_utilities import parse_obj_as +from json.decoder import JSONDecodeError +from ..core.api_error import ApiError +from ..core.client_wrapper import AsyncClientWrapper class NoReqBodyClient: @@ -38,17 +38,26 @@ def get_with_no_request_body( client.no_req_body.get_with_no_request_body() """ _response = self._client_wrapper.httpx_client.request( - "no-req-body", method="GET", request_options=request_options + "no-req-body", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def post_with_no_request_body(self, *, request_options: typing.Optional[RequestOptions] = None) -> str: + def post_with_no_request_body( + self, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -70,11 +79,15 @@ def post_with_no_request_body(self, *, request_options: typing.Optional[RequestO client.no_req_body.post_with_no_request_body() """ _response = self._client_wrapper.httpx_client.request( - "no-req-body", method="POST", request_options=request_options + "no-req-body", + method="POST", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -117,17 +130,26 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "no-req-body", method="GET", request_options=request_options + "no-req-body", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - async def post_with_no_request_body(self, *, request_options: typing.Optional[RequestOptions] = None) -> str: + async def post_with_no_request_body( + self, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -157,11 +179,15 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "no-req-body", method="POST", request_options=request_options + "no-req-body", + method="POST", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/extra_dependencies/src/seed/req_with_headers/client.py b/seed/python-sdk/exhaustive/extra_dependencies/src/seed/req_with_headers/client.py index 655402249e9..984428516e3 100644 --- a/seed/python-sdk/exhaustive/extra_dependencies/src/seed/req_with_headers/client.py +++ b/seed/python-sdk/exhaustive/extra_dependencies/src/seed/req_with_headers/client.py @@ -1,11 +1,11 @@ # This file was auto-generated by Fern from our API Definition. import typing +from ..core.client_wrapper import SyncClientWrapper +from ..core.request_options import RequestOptions from json.decoder import JSONDecodeError - from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.request_options import RequestOptions +from ..core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -21,7 +21,7 @@ def get_with_custom_header( x_test_service_header: str, x_test_endpoint_header: str, request: str, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ Parameters @@ -58,8 +58,12 @@ def get_with_custom_header( method="POST", json=request, headers={ - "X-TEST-SERVICE-HEADER": str(x_test_service_header) if x_test_service_header is not None else None, - "X-TEST-ENDPOINT-HEADER": str(x_test_endpoint_header) if x_test_endpoint_header is not None else None, + "X-TEST-SERVICE-HEADER": str(x_test_service_header) + if x_test_service_header is not None + else None, + "X-TEST-ENDPOINT-HEADER": str(x_test_endpoint_header) + if x_test_endpoint_header is not None + else None, }, request_options=request_options, omit=OMIT, @@ -83,7 +87,7 @@ async def get_with_custom_header( x_test_service_header: str, x_test_endpoint_header: str, request: str, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ Parameters @@ -128,8 +132,12 @@ async def main() -> None: method="POST", json=request, headers={ - "X-TEST-SERVICE-HEADER": str(x_test_service_header) if x_test_service_header is not None else None, - "X-TEST-ENDPOINT-HEADER": str(x_test_endpoint_header) if x_test_endpoint_header is not None else None, + "X-TEST-SERVICE-HEADER": str(x_test_service_header) + if x_test_service_header is not None + else None, + "X-TEST-ENDPOINT-HEADER": str(x_test_endpoint_header) + if x_test_endpoint_header is not None + else None, }, request_options=request_options, omit=OMIT, diff --git a/seed/python-sdk/exhaustive/extra_dependencies/src/seed/types/enum/types/weather_report.py b/seed/python-sdk/exhaustive/extra_dependencies/src/seed/types/enum/types/weather_report.py index 2d54965dc22..84017ef161d 100644 --- a/seed/python-sdk/exhaustive/extra_dependencies/src/seed/types/enum/types/weather_report.py +++ b/seed/python-sdk/exhaustive/extra_dependencies/src/seed/types/enum/types/weather_report.py @@ -2,4 +2,6 @@ import typing -WeatherReport = typing.Union[typing.Literal["SUNNY", "CLOUDY", "RAINING", "SNOWING"], typing.Any] +WeatherReport = typing.Union[ + typing.Literal["SUNNY", "CLOUDY", "RAINING", "SNOWING"], typing.Any +] diff --git a/seed/python-sdk/exhaustive/extra_dependencies/src/seed/types/object/types/double_optional.py b/seed/python-sdk/exhaustive/extra_dependencies/src/seed/types/object/types/double_optional.py index ddf165b13bd..ed236347357 100644 --- a/seed/python-sdk/exhaustive/extra_dependencies/src/seed/types/object/types/double_optional.py +++ b/seed/python-sdk/exhaustive/extra_dependencies/src/seed/types/object/types/double_optional.py @@ -1,18 +1,21 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .optional_alias import OptionalAlias +import pydantic +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class DoubleOptional(UniversalBaseModel): - optional_alias: typing.Optional[OptionalAlias] = pydantic.Field(alias="optionalAlias", default=None) + optional_alias: typing.Optional[OptionalAlias] = pydantic.Field( + alias="optionalAlias", default=None + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/extra_dependencies/src/seed/types/object/types/nested_object_with_optional_field.py b/seed/python-sdk/exhaustive/extra_dependencies/src/seed/types/object/types/nested_object_with_optional_field.py index 81669c0dd39..20a4d40a714 100644 --- a/seed/python-sdk/exhaustive/extra_dependencies/src/seed/types/object/types/nested_object_with_optional_field.py +++ b/seed/python-sdk/exhaustive/extra_dependencies/src/seed/types/object/types/nested_object_with_optional_field.py @@ -1,19 +1,22 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .object_with_optional_field import ObjectWithOptionalField +import pydantic +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class NestedObjectWithOptionalField(UniversalBaseModel): string: typing.Optional[str] = None - nested_object: typing.Optional[ObjectWithOptionalField] = pydantic.Field(alias="NestedObject", default=None) + nested_object: typing.Optional[ObjectWithOptionalField] = pydantic.Field( + alias="NestedObject", default=None + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/extra_dependencies/src/seed/types/object/types/nested_object_with_required_field.py b/seed/python-sdk/exhaustive/extra_dependencies/src/seed/types/object/types/nested_object_with_required_field.py index 1a621942c6c..a6ca8781190 100644 --- a/seed/python-sdk/exhaustive/extra_dependencies/src/seed/types/object/types/nested_object_with_required_field.py +++ b/seed/python-sdk/exhaustive/extra_dependencies/src/seed/types/object/types/nested_object_with_required_field.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import UniversalBaseModel from .object_with_optional_field import ObjectWithOptionalField +import pydantic +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class NestedObjectWithRequiredField(UniversalBaseModel): @@ -13,7 +12,9 @@ class NestedObjectWithRequiredField(UniversalBaseModel): nested_object: ObjectWithOptionalField = pydantic.Field(alias="NestedObject") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/extra_dependencies/src/seed/types/object/types/object_with_map_of_map.py b/seed/python-sdk/exhaustive/extra_dependencies/src/seed/types/object/types/object_with_map_of_map.py index 8883cc1d498..313cd25ceb8 100644 --- a/seed/python-sdk/exhaustive/extra_dependencies/src/seed/types/object/types/object_with_map_of_map.py +++ b/seed/python-sdk/exhaustive/extra_dependencies/src/seed/types/object/types/object_with_map_of_map.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class ObjectWithMapOfMap(UniversalBaseModel): map_: typing.Dict[str, typing.Dict[str, str]] = pydantic.Field(alias="map") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/extra_dependencies/src/seed/types/object/types/object_with_optional_field.py b/seed/python-sdk/exhaustive/extra_dependencies/src/seed/types/object/types/object_with_optional_field.py index 6aab170be0c..9131f0e91d7 100644 --- a/seed/python-sdk/exhaustive/extra_dependencies/src/seed/types/object/types/object_with_optional_field.py +++ b/seed/python-sdk/exhaustive/extra_dependencies/src/seed/types/object/types/object_with_optional_field.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. -import datetime as dt +from ....core.pydantic_utilities import UniversalBaseModel import typing -import uuid - import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +import datetime as dt +import uuid +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class ObjectWithOptionalField(UniversalBaseModel): @@ -23,13 +22,19 @@ class ObjectWithOptionalField(UniversalBaseModel): date: typing.Optional[dt.date] = None uuid_: typing.Optional[uuid.UUID] = pydantic.Field(alias="uuid", default=None) base_64: typing.Optional[str] = pydantic.Field(alias="base64", default=None) - list_: typing.Optional[typing.List[str]] = pydantic.Field(alias="list", default=None) + list_: typing.Optional[typing.List[str]] = pydantic.Field( + alias="list", default=None + ) set_: typing.Optional[typing.Set[str]] = pydantic.Field(alias="set", default=None) - map_: typing.Optional[typing.Dict[int, str]] = pydantic.Field(alias="map", default=None) + map_: typing.Optional[typing.Dict[int, str]] = pydantic.Field( + alias="map", default=None + ) bigint: typing.Optional[str] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/extra_dependencies/src/seed/types/object/types/object_with_required_field.py b/seed/python-sdk/exhaustive/extra_dependencies/src/seed/types/object/types/object_with_required_field.py index 61b98867984..24db26a3cf8 100644 --- a/seed/python-sdk/exhaustive/extra_dependencies/src/seed/types/object/types/object_with_required_field.py +++ b/seed/python-sdk/exhaustive/extra_dependencies/src/seed/types/object/types/object_with_required_field.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class ObjectWithRequiredField(UniversalBaseModel): string: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/extra_dependencies/src/seed/types/union/types/animal.py b/seed/python-sdk/exhaustive/extra_dependencies/src/seed/types/union/types/animal.py index 1ae43d1663e..84c71d2009a 100644 --- a/seed/python-sdk/exhaustive/extra_dependencies/src/seed/types/union/types/animal.py +++ b/seed/python-sdk/exhaustive/extra_dependencies/src/seed/types/union/types/animal.py @@ -1,12 +1,10 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ....core.pydantic_utilities import UniversalBaseModel import typing - import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class Animal_Dog(UniversalBaseModel): @@ -15,7 +13,9 @@ class Animal_Dog(UniversalBaseModel): likes_to_woof: bool = pydantic.Field(alias="likesToWoof") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: @@ -30,7 +30,9 @@ class Animal_Cat(UniversalBaseModel): likes_to_meow: bool = pydantic.Field(alias="likesToMeow") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/extra_dependencies/src/seed/types/union/types/cat.py b/seed/python-sdk/exhaustive/extra_dependencies/src/seed/types/union/types/cat.py index 61fc5527b1f..c59b78523c9 100644 --- a/seed/python-sdk/exhaustive/extra_dependencies/src/seed/types/union/types/cat.py +++ b/seed/python-sdk/exhaustive/extra_dependencies/src/seed/types/union/types/cat.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ....core.pydantic_utilities import UniversalBaseModel import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class Cat(UniversalBaseModel): @@ -12,7 +11,9 @@ class Cat(UniversalBaseModel): likes_to_meow: bool = pydantic.Field(alias="likesToMeow") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/extra_dependencies/src/seed/types/union/types/dog.py b/seed/python-sdk/exhaustive/extra_dependencies/src/seed/types/union/types/dog.py index c1ff5339dfe..e250c72edef 100644 --- a/seed/python-sdk/exhaustive/extra_dependencies/src/seed/types/union/types/dog.py +++ b/seed/python-sdk/exhaustive/extra_dependencies/src/seed/types/union/types/dog.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ....core.pydantic_utilities import UniversalBaseModel import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class Dog(UniversalBaseModel): @@ -12,7 +11,9 @@ class Dog(UniversalBaseModel): likes_to_woof: bool = pydantic.Field(alias="likesToWoof") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/extra_dependencies/src/seed/version.py b/seed/python-sdk/exhaustive/extra_dependencies/src/seed/version.py index 63ba170685a..ac44536abdb 100644 --- a/seed/python-sdk/exhaustive/extra_dependencies/src/seed/version.py +++ b/seed/python-sdk/exhaustive/extra_dependencies/src/seed/version.py @@ -1,4 +1,3 @@ - from importlib import metadata __version__ = metadata.version("fern_exhaustive") diff --git a/seed/python-sdk/exhaustive/extra_dependencies/tests/conftest.py b/seed/python-sdk/exhaustive/extra_dependencies/tests/conftest.py index b5b50383b94..86cb2b41af8 100644 --- a/seed/python-sdk/exhaustive/extra_dependencies/tests/conftest.py +++ b/seed/python-sdk/exhaustive/extra_dependencies/tests/conftest.py @@ -1,16 +1,22 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive import os - import pytest -from seed import AsyncSeedExhaustive, SeedExhaustive +from seed import AsyncSeedExhaustive @pytest.fixture def client() -> SeedExhaustive: - return SeedExhaustive(token=os.getenv("ENV_TOKEN", "token"), base_url=os.getenv("TESTS_BASE_URL", "base_url")) + return SeedExhaustive( + token=os.getenv("ENV_TOKEN", "token"), + base_url=os.getenv("TESTS_BASE_URL", "base_url"), + ) @pytest.fixture def async_client() -> AsyncSeedExhaustive: - return AsyncSeedExhaustive(token=os.getenv("ENV_TOKEN", "token"), base_url=os.getenv("TESTS_BASE_URL", "base_url")) + return AsyncSeedExhaustive( + token=os.getenv("ENV_TOKEN", "token"), + base_url=os.getenv("TESTS_BASE_URL", "base_url"), + ) diff --git a/seed/python-sdk/exhaustive/extra_dependencies/tests/custom/test_client.py b/seed/python-sdk/exhaustive/extra_dependencies/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/python-sdk/exhaustive/extra_dependencies/tests/custom/test_client.py +++ b/seed/python-sdk/exhaustive/extra_dependencies/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/python-sdk/exhaustive/extra_dependencies/tests/endpoints/test_container.py b/seed/python-sdk/exhaustive/extra_dependencies/tests/endpoints/test_container.py index 17d9d75240d..240f16f2a8c 100644 --- a/seed/python-sdk/exhaustive/extra_dependencies/tests/endpoints/test_container.py +++ b/seed/python-sdk/exhaustive/extra_dependencies/tests/endpoints/test_container.py @@ -1,91 +1,137 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing - -from seed import AsyncSeedExhaustive, SeedExhaustive -from seed.types.object import ObjectWithRequiredField - from ..utilities import validate_response +from seed.types.object import ObjectWithRequiredField -async def test_get_and_return_list_of_primitives(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_list_of_primitives( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = ["string"] expected_types: typing.Tuple[typing.Any, typing.Any] = ("list", {0: None}) - response = client.endpoints.container.get_and_return_list_of_primitives(request=["string"]) + response = client.endpoints.container.get_and_return_list_of_primitives( + request=["string"] + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.container.get_and_return_list_of_primitives(request=["string"]) + async_response = ( + await async_client.endpoints.container.get_and_return_list_of_primitives( + request=["string"] + ) + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_list_of_objects(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_list_of_objects( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = [{"string": "string"}] - expected_types: typing.Tuple[typing.Any, typing.Any] = ("list", {0: {"string": None}}) + expected_types: typing.Tuple[typing.Any, typing.Any] = ( + "list", + {0: {"string": None}}, + ) response = client.endpoints.container.get_and_return_list_of_objects( request=[ObjectWithRequiredField(string="string")] ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.container.get_and_return_list_of_objects( - request=[ObjectWithRequiredField(string="string")] + async_response = ( + await async_client.endpoints.container.get_and_return_list_of_objects( + request=[ObjectWithRequiredField(string="string")] + ) ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_set_of_primitives(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_set_of_primitives( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = ["string"] expected_types: typing.Tuple[typing.Any, typing.Any] = ("set", {0: None}) - response = client.endpoints.container.get_and_return_set_of_primitives(request={"string"}) + response = client.endpoints.container.get_and_return_set_of_primitives( + request={"string"} + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.container.get_and_return_set_of_primitives(request={"string"}) + async_response = ( + await async_client.endpoints.container.get_and_return_set_of_primitives( + request={"string"} + ) + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_set_of_objects(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_set_of_objects( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = [{"string": "string"}] - expected_types: typing.Tuple[typing.Any, typing.Any] = ("set", {0: {"string": None}}) + expected_types: typing.Tuple[typing.Any, typing.Any] = ( + "set", + {0: {"string": None}}, + ) response = client.endpoints.container.get_and_return_set_of_objects( request=[ObjectWithRequiredField(string="string")] ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.container.get_and_return_set_of_objects( - request=[ObjectWithRequiredField(string="string")] + async_response = ( + await async_client.endpoints.container.get_and_return_set_of_objects( + request=[ObjectWithRequiredField(string="string")] + ) ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_map_prim_to_prim(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_map_prim_to_prim( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = {"string": "string"} expected_types: typing.Tuple[typing.Any, typing.Any] = ("dict", {0: (None, None)}) - response = client.endpoints.container.get_and_return_map_prim_to_prim(request={"string": "string"}) + response = client.endpoints.container.get_and_return_map_prim_to_prim( + request={"string": "string"} + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.container.get_and_return_map_prim_to_prim( - request={"string": "string"} + async_response = ( + await async_client.endpoints.container.get_and_return_map_prim_to_prim( + request={"string": "string"} + ) ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_map_of_prim_to_object(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_map_of_prim_to_object( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = {"string": {"string": "string"}} - expected_types: typing.Tuple[typing.Any, typing.Any] = ("dict", {0: (None, {"string": None})}) + expected_types: typing.Tuple[typing.Any, typing.Any] = ( + "dict", + {0: (None, {"string": None})}, + ) response = client.endpoints.container.get_and_return_map_of_prim_to_object( request={"string": ObjectWithRequiredField(string="string")} ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.container.get_and_return_map_of_prim_to_object( - request={"string": ObjectWithRequiredField(string="string")} + async_response = ( + await async_client.endpoints.container.get_and_return_map_of_prim_to_object( + request={"string": ObjectWithRequiredField(string="string")} + ) ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_optional(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_optional( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = {"string": "string"} expected_types: typing.Any = {"string": None} - response = client.endpoints.container.get_and_return_optional(request=ObjectWithRequiredField(string="string")) + response = client.endpoints.container.get_and_return_optional( + request=ObjectWithRequiredField(string="string") + ) validate_response(response, expected_response, expected_types) async_response = await async_client.endpoints.container.get_and_return_optional( diff --git a/seed/python-sdk/exhaustive/extra_dependencies/tests/endpoints/test_enum.py b/seed/python-sdk/exhaustive/extra_dependencies/tests/endpoints/test_enum.py index 890aada5ce4..ca3fca30b5a 100644 --- a/seed/python-sdk/exhaustive/extra_dependencies/tests/endpoints/test_enum.py +++ b/seed/python-sdk/exhaustive/extra_dependencies/tests/endpoints/test_enum.py @@ -1,17 +1,20 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing - -from seed import AsyncSeedExhaustive, SeedExhaustive - from ..utilities import validate_response -async def test_get_and_return_enum(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_enum( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "SUNNY" expected_types: typing.Any = None response = client.endpoints.enum.get_and_return_enum(request="SUNNY") validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.enum.get_and_return_enum(request="SUNNY") + async_response = await async_client.endpoints.enum.get_and_return_enum( + request="SUNNY" + ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/exhaustive/extra_dependencies/tests/endpoints/test_http_methods.py b/seed/python-sdk/exhaustive/extra_dependencies/tests/endpoints/test_http_methods.py index dc01bafcf6f..77131fc6e8b 100644 --- a/seed/python-sdk/exhaustive/extra_dependencies/tests/endpoints/test_http_methods.py +++ b/seed/python-sdk/exhaustive/extra_dependencies/tests/endpoints/test_http_methods.py @@ -1,15 +1,16 @@ # This file was auto-generated by Fern from our API Definition. -import datetime +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing -import uuid - -from seed import AsyncSeedExhaustive, SeedExhaustive - from ..utilities import validate_response +import datetime +import uuid -async def test_test_get(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_test_get( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "string" expected_types: typing.Any = None response = client.endpoints.http_methods.test_get(id="string") @@ -19,7 +20,9 @@ async def test_test_get(client: SeedExhaustive, async_client: AsyncSeedExhaustiv validate_response(async_response, expected_response, expected_types) -async def test_test_post(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_test_post( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = { "string": "string", "integer": 1, @@ -53,11 +56,15 @@ async def test_test_post(client: SeedExhaustive, async_client: AsyncSeedExhausti response = client.endpoints.http_methods.test_post(string="string") validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.http_methods.test_post(string="string") + async_response = await async_client.endpoints.http_methods.test_post( + string="string" + ) validate_response(async_response, expected_response, expected_types) -async def test_test_put(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_test_put( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = { "string": "string", "integer": 1, @@ -91,11 +98,15 @@ async def test_test_put(client: SeedExhaustive, async_client: AsyncSeedExhaustiv response = client.endpoints.http_methods.test_put(id="string", string="string") validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.http_methods.test_put(id="string", string="string") + async_response = await async_client.endpoints.http_methods.test_put( + id="string", string="string" + ) validate_response(async_response, expected_response, expected_types) -async def test_test_patch(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_test_patch( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = { "string": "string", "integer": 1, @@ -163,7 +174,9 @@ async def test_test_patch(client: SeedExhaustive, async_client: AsyncSeedExhaust validate_response(async_response, expected_response, expected_types) -async def test_test_delete(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_test_delete( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = True expected_types: typing.Any = None response = client.endpoints.http_methods.test_delete(id="string") diff --git a/seed/python-sdk/exhaustive/extra_dependencies/tests/endpoints/test_object.py b/seed/python-sdk/exhaustive/extra_dependencies/tests/endpoints/test_object.py index a9098b6e9ef..c48c4332b22 100644 --- a/seed/python-sdk/exhaustive/extra_dependencies/tests/endpoints/test_object.py +++ b/seed/python-sdk/exhaustive/extra_dependencies/tests/endpoints/test_object.py @@ -1,16 +1,18 @@ # This file was auto-generated by Fern from our API Definition. -import datetime +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing +import datetime import uuid - -from seed import AsyncSeedExhaustive, SeedExhaustive -from seed.types.object import NestedObjectWithRequiredField, ObjectWithOptionalField - from ..utilities import validate_response +from seed.types.object import ObjectWithOptionalField +from seed.types.object import NestedObjectWithRequiredField -async def test_get_and_return_with_optional_field(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_with_optional_field( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = { "string": "string", "integer": 1, @@ -58,38 +60,54 @@ async def test_get_and_return_with_optional_field(client: SeedExhaustive, async_ ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.object.get_and_return_with_optional_field( - string="string", - integer=1, - long_=1000000, - double=1.1, - bool_=True, - datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), - date=datetime.date.fromisoformat("2023-01-15"), - uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), - base_64="SGVsbG8gd29ybGQh", - list_=["string"], - set_={"string"}, - map_={1: "string"}, - bigint="123456789123456789", + async_response = ( + await async_client.endpoints.object.get_and_return_with_optional_field( + string="string", + integer=1, + long_=1000000, + double=1.1, + bool_=True, + datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), + date=datetime.date.fromisoformat("2023-01-15"), + uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + base_64="SGVsbG8gd29ybGQh", + list_=["string"], + set_={"string"}, + map_={1: "string"}, + bigint="123456789123456789", + ) ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_with_required_field(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_with_required_field( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = {"string": "string"} expected_types: typing.Any = {"string": None} - response = client.endpoints.object.get_and_return_with_required_field(string="string") + response = client.endpoints.object.get_and_return_with_required_field( + string="string" + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.object.get_and_return_with_required_field(string="string") + async_response = ( + await async_client.endpoints.object.get_and_return_with_required_field( + string="string" + ) + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_with_map_of_map(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_with_map_of_map( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = {"map": {"string": {"string": "string"}}} - expected_types: typing.Any = {"map": ("dict", {0: (None, ("dict", {0: (None, None)}))})} - response = client.endpoints.object.get_and_return_with_map_of_map(map_={"string": {"string": "string"}}) + expected_types: typing.Any = { + "map": ("dict", {0: (None, ("dict", {0: (None, None)}))}) + } + response = client.endpoints.object.get_and_return_with_map_of_map( + map_={"string": {"string": "string"}} + ) validate_response(response, expected_response, expected_types) async_response = await async_client.endpoints.object.get_and_return_with_map_of_map( @@ -157,23 +175,25 @@ async def test_get_and_return_nested_with_optional_field( ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.object.get_and_return_nested_with_optional_field( - string="string", - nested_object=ObjectWithOptionalField( + async_response = ( + await async_client.endpoints.object.get_and_return_nested_with_optional_field( string="string", - integer=1, - long_=1000000, - double=1.1, - bool_=True, - datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), - date=datetime.date.fromisoformat("2023-01-15"), - uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), - base_64="SGVsbG8gd29ybGQh", - list_=["string"], - set_={"string"}, - map_={1: "string"}, - bigint="123456789123456789", - ), + nested_object=ObjectWithOptionalField( + string="string", + integer=1, + long_=1000000, + double=1.1, + bool_=True, + datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), + date=datetime.date.fromisoformat("2023-01-15"), + uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + base_64="SGVsbG8gd29ybGQh", + list_=["string"], + set_={"string"}, + map_={1: "string"}, + bigint="123456789123456789", + ), + ) ) validate_response(async_response, expected_response, expected_types) @@ -238,24 +258,26 @@ async def test_get_and_return_nested_with_required_field( ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.object.get_and_return_nested_with_required_field( - string_="string", - string="string", - nested_object=ObjectWithOptionalField( + async_response = ( + await async_client.endpoints.object.get_and_return_nested_with_required_field( + string_="string", string="string", - integer=1, - long_=1000000, - double=1.1, - bool_=True, - datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), - date=datetime.date.fromisoformat("2023-01-15"), - uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), - base_64="SGVsbG8gd29ybGQh", - list_=["string"], - set_={"string"}, - map_={1: "string"}, - bigint="123456789123456789", - ), + nested_object=ObjectWithOptionalField( + string="string", + integer=1, + long_=1000000, + double=1.1, + bool_=True, + datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), + date=datetime.date.fromisoformat("2023-01-15"), + uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + base_64="SGVsbG8gd29ybGQh", + list_=["string"], + set_={"string"}, + map_={1: "string"}, + bigint="123456789123456789", + ), + ) ) validate_response(async_response, expected_response, expected_types) @@ -299,27 +321,31 @@ async def test_get_and_return_nested_with_required_field_as_list( "bigint": None, }, } - response = client.endpoints.object.get_and_return_nested_with_required_field_as_list( - request=[ - NestedObjectWithRequiredField( - string="string", - nested_object=ObjectWithOptionalField( + response = ( + client.endpoints.object.get_and_return_nested_with_required_field_as_list( + request=[ + NestedObjectWithRequiredField( string="string", - integer=1, - long_=1000000, - double=1.1, - bool_=True, - datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), - date=datetime.date.fromisoformat("2023-01-15"), - uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), - base_64="SGVsbG8gd29ybGQh", - list_=["string"], - set_={"string"}, - map_={1: "string"}, - bigint="123456789123456789", - ), - ) - ] + nested_object=ObjectWithOptionalField( + string="string", + integer=1, + long_=1000000, + double=1.1, + bool_=True, + datetime=datetime.datetime.fromisoformat( + "2024-01-15 09:30:00+00:00" + ), + date=datetime.date.fromisoformat("2023-01-15"), + uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + base_64="SGVsbG8gd29ybGQh", + list_=["string"], + set_={"string"}, + map_={1: "string"}, + bigint="123456789123456789", + ), + ) + ] + ) ) validate_response(response, expected_response, expected_types) @@ -333,7 +359,9 @@ async def test_get_and_return_nested_with_required_field_as_list( long_=1000000, double=1.1, bool_=True, - datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), + datetime=datetime.datetime.fromisoformat( + "2024-01-15 09:30:00+00:00" + ), date=datetime.date.fromisoformat("2023-01-15"), uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), base_64="SGVsbG8gd29ybGQh", diff --git a/seed/python-sdk/exhaustive/extra_dependencies/tests/endpoints/test_params.py b/seed/python-sdk/exhaustive/extra_dependencies/tests/endpoints/test_params.py index 163d7b9161d..d8ffb00c0a0 100644 --- a/seed/python-sdk/exhaustive/extra_dependencies/tests/endpoints/test_params.py +++ b/seed/python-sdk/exhaustive/extra_dependencies/tests/endpoints/test_params.py @@ -1,13 +1,14 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing - -from seed import AsyncSeedExhaustive, SeedExhaustive - from ..utilities import validate_response -async def test_get_with_path(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_with_path( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "string" expected_types: typing.Any = None response = client.endpoints.params.get_with_path(param="string") @@ -17,32 +18,63 @@ async def test_get_with_path(client: SeedExhaustive, async_client: AsyncSeedExha validate_response(async_response, expected_response, expected_types) -async def test_get_with_query(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_with_query( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: # Type ignore to avoid mypy complaining about the function not being meant to return a value assert client.endpoints.params.get_with_query(query="string", number=1) is None # type: ignore[func-returns-value] - assert await async_client.endpoints.params.get_with_query(query="string", number=1) is None # type: ignore[func-returns-value] + assert ( + await async_client.endpoints.params.get_with_query(query="string", number=1) + is None + ) # type: ignore[func-returns-value] -async def test_get_with_allow_multiple_query(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_with_allow_multiple_query( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: # Type ignore to avoid mypy complaining about the function not being meant to return a value - assert client.endpoints.params.get_with_allow_multiple_query(query="string", numer=1) is None # type: ignore[func-returns-value] - - assert await async_client.endpoints.params.get_with_allow_multiple_query(query="string", numer=1) is None # type: ignore[func-returns-value] - - -async def test_get_with_path_and_query(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: + assert ( + client.endpoints.params.get_with_allow_multiple_query(query="string", numer=1) + is None + ) # type: ignore[func-returns-value] + + assert ( + await async_client.endpoints.params.get_with_allow_multiple_query( + query="string", numer=1 + ) + is None + ) # type: ignore[func-returns-value] + + +async def test_get_with_path_and_query( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: # Type ignore to avoid mypy complaining about the function not being meant to return a value - assert client.endpoints.params.get_with_path_and_query(param="string", query="string") is None # type: ignore[func-returns-value] - - assert await async_client.endpoints.params.get_with_path_and_query(param="string", query="string") is None # type: ignore[func-returns-value] - - -async def test_modify_with_path(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: + assert ( + client.endpoints.params.get_with_path_and_query(param="string", query="string") + is None + ) # type: ignore[func-returns-value] + + assert ( + await async_client.endpoints.params.get_with_path_and_query( + param="string", query="string" + ) + is None + ) # type: ignore[func-returns-value] + + +async def test_modify_with_path( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "string" expected_types: typing.Any = None - response = client.endpoints.params.modify_with_path(param="string", request="string") + response = client.endpoints.params.modify_with_path( + param="string", request="string" + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.params.modify_with_path(param="string", request="string") + async_response = await async_client.endpoints.params.modify_with_path( + param="string", request="string" + ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/exhaustive/extra_dependencies/tests/endpoints/test_primitive.py b/seed/python-sdk/exhaustive/extra_dependencies/tests/endpoints/test_primitive.py index ba3bc7e29e5..26cbcf45d2f 100644 --- a/seed/python-sdk/exhaustive/extra_dependencies/tests/endpoints/test_primitive.py +++ b/seed/python-sdk/exhaustive/extra_dependencies/tests/endpoints/test_primitive.py @@ -1,65 +1,86 @@ # This file was auto-generated by Fern from our API Definition. -import datetime +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing -import uuid - -from seed import AsyncSeedExhaustive, SeedExhaustive - from ..utilities import validate_response +import datetime +import uuid -async def test_get_and_return_string(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_string( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "string" expected_types: typing.Any = None response = client.endpoints.primitive.get_and_return_string(request="string") validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.primitive.get_and_return_string(request="string") + async_response = await async_client.endpoints.primitive.get_and_return_string( + request="string" + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_int(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_int( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = 1 expected_types: typing.Any = "integer" response = client.endpoints.primitive.get_and_return_int(request=1) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.primitive.get_and_return_int(request=1) + async_response = await async_client.endpoints.primitive.get_and_return_int( + request=1 + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_long(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_long( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = 1000000 expected_types: typing.Any = None response = client.endpoints.primitive.get_and_return_long(request=1000000) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.primitive.get_and_return_long(request=1000000) + async_response = await async_client.endpoints.primitive.get_and_return_long( + request=1000000 + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_double(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_double( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = 1.1 expected_types: typing.Any = None response = client.endpoints.primitive.get_and_return_double(request=1.1) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.primitive.get_and_return_double(request=1.1) + async_response = await async_client.endpoints.primitive.get_and_return_double( + request=1.1 + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_bool(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_bool( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = True expected_types: typing.Any = None response = client.endpoints.primitive.get_and_return_bool(request=True) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.primitive.get_and_return_bool(request=True) + async_response = await async_client.endpoints.primitive.get_and_return_bool( + request=True + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_datetime(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_datetime( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "2024-01-15T09:30:00Z" expected_types: typing.Any = "datetime" response = client.endpoints.primitive.get_and_return_datetime( @@ -73,10 +94,14 @@ async def test_get_and_return_datetime(client: SeedExhaustive, async_client: Asy validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_date(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_date( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "2023-01-15" expected_types: typing.Any = "date" - response = client.endpoints.primitive.get_and_return_date(request=datetime.date.fromisoformat("2023-01-15")) + response = client.endpoints.primitive.get_and_return_date( + request=datetime.date.fromisoformat("2023-01-15") + ) validate_response(response, expected_response, expected_types) async_response = await async_client.endpoints.primitive.get_and_return_date( @@ -85,10 +110,14 @@ async def test_get_and_return_date(client: SeedExhaustive, async_client: AsyncSe validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_uuid(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_uuid( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32" expected_types: typing.Any = "uuid" - response = client.endpoints.primitive.get_and_return_uuid(request=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32")) + response = client.endpoints.primitive.get_and_return_uuid( + request=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32") + ) validate_response(response, expected_response, expected_types) async_response = await async_client.endpoints.primitive.get_and_return_uuid( @@ -97,11 +126,17 @@ async def test_get_and_return_uuid(client: SeedExhaustive, async_client: AsyncSe validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_base_64(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_base_64( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "SGVsbG8gd29ybGQh" expected_types: typing.Any = None - response = client.endpoints.primitive.get_and_return_base_64(request="SGVsbG8gd29ybGQh") + response = client.endpoints.primitive.get_and_return_base_64( + request="SGVsbG8gd29ybGQh" + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.primitive.get_and_return_base_64(request="SGVsbG8gd29ybGQh") + async_response = await async_client.endpoints.primitive.get_and_return_base_64( + request="SGVsbG8gd29ybGQh" + ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/exhaustive/extra_dependencies/tests/endpoints/test_union.py b/seed/python-sdk/exhaustive/extra_dependencies/tests/endpoints/test_union.py index 14e34c2a6df..ceb84928cd9 100644 --- a/seed/python-sdk/exhaustive/extra_dependencies/tests/endpoints/test_union.py +++ b/seed/python-sdk/exhaustive/extra_dependencies/tests/endpoints/test_union.py @@ -1,17 +1,24 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing - -from seed import AsyncSeedExhaustive, SeedExhaustive from seed.types.union import Animal_Dog - from ..utilities import validate_response -async def test_get_and_return_union(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: - expected_response: typing.Any = {"animal": "dog", "name": "string", "likesToWoof": True} +async def test_get_and_return_union( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: + expected_response: typing.Any = { + "animal": "dog", + "name": "string", + "likesToWoof": True, + } expected_types: typing.Any = "no_validate" - response = client.endpoints.union.get_and_return_union(request=Animal_Dog(name="string", likes_to_woof=True)) + response = client.endpoints.union.get_and_return_union( + request=Animal_Dog(name="string", likes_to_woof=True) + ) validate_response(response, expected_response, expected_types) async_response = await async_client.endpoints.union.get_and_return_union( diff --git a/seed/python-sdk/exhaustive/extra_dependencies/tests/test_inlined_requests.py b/seed/python-sdk/exhaustive/extra_dependencies/tests/test_inlined_requests.py index bb9390d3845..03f46b31cc9 100644 --- a/seed/python-sdk/exhaustive/extra_dependencies/tests/test_inlined_requests.py +++ b/seed/python-sdk/exhaustive/extra_dependencies/tests/test_inlined_requests.py @@ -1,16 +1,17 @@ # This file was auto-generated by Fern from our API Definition. -import datetime +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing -import uuid - -from seed import AsyncSeedExhaustive, SeedExhaustive from seed.types.object import ObjectWithOptionalField - +import datetime +import uuid from .utilities import validate_response -async def test_post_with_object_bodyand_response(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_post_with_object_bodyand_response( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = { "string": "string", "integer": 1, @@ -62,23 +63,25 @@ async def test_post_with_object_bodyand_response(client: SeedExhaustive, async_c ) validate_response(response, expected_response, expected_types) - async_response = await async_client.inlined_requests.post_with_object_bodyand_response( - string="string", - integer=1, - nested_object=ObjectWithOptionalField( + async_response = ( + await async_client.inlined_requests.post_with_object_bodyand_response( string="string", integer=1, - long_=1000000, - double=1.1, - bool_=True, - datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), - date=datetime.date.fromisoformat("2023-01-15"), - uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), - base_64="SGVsbG8gd29ybGQh", - list_=["string"], - set_={"string"}, - map_={1: "string"}, - bigint="123456789123456789", - ), + nested_object=ObjectWithOptionalField( + string="string", + integer=1, + long_=1000000, + double=1.1, + bool_=True, + datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), + date=datetime.date.fromisoformat("2023-01-15"), + uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + base_64="SGVsbG8gd29ybGQh", + list_=["string"], + set_={"string"}, + map_={1: "string"}, + bigint="123456789123456789", + ), + ) ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/exhaustive/extra_dependencies/tests/test_no_auth.py b/seed/python-sdk/exhaustive/extra_dependencies/tests/test_no_auth.py index 3328661bb48..fc475f4b6fb 100644 --- a/seed/python-sdk/exhaustive/extra_dependencies/tests/test_no_auth.py +++ b/seed/python-sdk/exhaustive/extra_dependencies/tests/test_no_auth.py @@ -1,17 +1,20 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing - -from seed import AsyncSeedExhaustive, SeedExhaustive - from .utilities import validate_response -async def test_post_with_no_auth(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_post_with_no_auth( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = True expected_types: typing.Any = None response = client.no_auth.post_with_no_auth(request={"key": "value"}) validate_response(response, expected_response, expected_types) - async_response = await async_client.no_auth.post_with_no_auth(request={"key": "value"}) + async_response = await async_client.no_auth.post_with_no_auth( + request={"key": "value"} + ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/exhaustive/extra_dependencies/tests/test_no_req_body.py b/seed/python-sdk/exhaustive/extra_dependencies/tests/test_no_req_body.py index 73abac9d2d8..07061a0e99e 100644 --- a/seed/python-sdk/exhaustive/extra_dependencies/tests/test_no_req_body.py +++ b/seed/python-sdk/exhaustive/extra_dependencies/tests/test_no_req_body.py @@ -1,13 +1,14 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing - -from seed import AsyncSeedExhaustive, SeedExhaustive - from .utilities import validate_response -async def test_get_with_no_request_body(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_with_no_request_body( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = { "string": "string", "integer": 1, @@ -45,7 +46,9 @@ async def test_get_with_no_request_body(client: SeedExhaustive, async_client: As validate_response(async_response, expected_response, expected_types) -async def test_post_with_no_request_body(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_post_with_no_request_body( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "string" expected_types: typing.Any = None response = client.no_req_body.post_with_no_request_body() diff --git a/seed/python-sdk/exhaustive/extra_dependencies/tests/test_req_with_headers.py b/seed/python-sdk/exhaustive/extra_dependencies/tests/test_req_with_headers.py index bba3b5b5507..75ce9d00c03 100644 --- a/seed/python-sdk/exhaustive/extra_dependencies/tests/test_req_with_headers.py +++ b/seed/python-sdk/exhaustive/extra_dependencies/tests/test_req_with_headers.py @@ -1,10 +1,27 @@ # This file was auto-generated by Fern from our API Definition. -from seed import AsyncSeedExhaustive, SeedExhaustive +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive -async def test_get_with_custom_header(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_with_custom_header( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: # Type ignore to avoid mypy complaining about the function not being meant to return a value - assert client.req_with_headers.get_with_custom_header(x_test_service_header="string", x_test_endpoint_header="string", request="string") is None # type: ignore[func-returns-value] + assert ( + client.req_with_headers.get_with_custom_header( + x_test_service_header="string", + x_test_endpoint_header="string", + request="string", + ) + is None + ) # type: ignore[func-returns-value] - assert await async_client.req_with_headers.get_with_custom_header(x_test_service_header="string", x_test_endpoint_header="string", request="string") is None # type: ignore[func-returns-value] + assert ( + await async_client.req_with_headers.get_with_custom_header( + x_test_service_header="string", + x_test_endpoint_header="string", + request="string", + ) + is None + ) # type: ignore[func-returns-value] diff --git a/seed/python-sdk/exhaustive/extra_dependencies/tests/utilities.py b/seed/python-sdk/exhaustive/extra_dependencies/tests/utilities.py index 13da208eb3a..e8f4472564c 100644 --- a/seed/python-sdk/exhaustive/extra_dependencies/tests/utilities.py +++ b/seed/python-sdk/exhaustive/extra_dependencies/tests/utilities.py @@ -3,11 +3,14 @@ import typing import uuid -import pydantic from dateutil import parser +import pydantic + -def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> typing.Any: +def cast_field( + json_expectation: typing.Any, type_expectation: typing.Any +) -> typing.Any: # Cast these specific types which come through as string and expect our # models to cast to the correct type. if type_expectation == "uuid": @@ -25,7 +28,9 @@ def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> ty return json_expectation -def validate_field(response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any) -> None: +def validate_field( + response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectation == "no_validate": return @@ -44,7 +49,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(entry_expectation, dict): is_container_of_complex_type = True validate_response( - response=response[idx], json_expectation=ex, type_expectations=entry_expectation + response=response[idx], + json_expectation=ex, + type_expectations=entry_expectation, ) else: cast_json_expectation.append(cast_field(ex, entry_expectation)) @@ -56,7 +63,10 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # if any of the values of the set have a type_expectation of a dict, we're assuming it's a pydantic # model and keeping it a list. if container_expectation != "set" or not any( - map(lambda value: isinstance(value, dict), list(contents_expectation.values())) + map( + lambda value: isinstance(value, dict), + list(contents_expectation.values()), + ) ): json_expectation = cast_field(json_expectation, container_expectation) elif isinstance(type_expectation, tuple): @@ -65,9 +75,15 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(contents_expectation, dict): json_expectation = { cast_field( - key, contents_expectation.get(idx)[0] if contents_expectation.get(idx) is not None else None # type: ignore + key, + contents_expectation.get(idx)[0] + if contents_expectation.get(idx) is not None + else None, # type: ignore ): cast_field( - value, contents_expectation.get(idx)[1] if contents_expectation.get(idx) is not None else None # type: ignore + value, + contents_expectation.get(idx)[1] + if contents_expectation.get(idx) is not None + else None, # type: ignore ) for idx, (key, value) in enumerate(json_expectation.items()) } @@ -86,7 +102,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # Arg type_expectations is a deeply nested structure that matches the response, but with the values replaced with the expected types -def validate_response(response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any) -> None: +def validate_response( + response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectations == "no_validate": return @@ -96,11 +114,17 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e and not isinstance(response, dict) and not issubclass(type(response), pydantic.BaseModel) ): - validate_field(response=response, json_expectation=json_expectation, type_expectation=type_expectations) + validate_field( + response=response, + json_expectation=json_expectation, + type_expectation=type_expectations, + ) return if isinstance(response, list): - assert len(response) == len(json_expectation), "Length mismatch, expected: {0}, Actual: {1}".format( + assert len(response) == len( + json_expectation + ), "Length mismatch, expected: {0}, Actual: {1}".format( len(response), len(json_expectation) ) content_expectation = type_expectations @@ -108,7 +132,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e content_expectation = type_expectations[1] for idx, item in enumerate(response): validate_response( - response=item, json_expectation=json_expectation[idx], type_expectations=content_expectation[idx] + response=item, + json_expectation=json_expectation[idx], + type_expectations=content_expectation[idx], ) else: response_json = response @@ -116,7 +142,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e response_json = response.dict(by_alias=True) for key, value in json_expectation.items(): - assert key in response_json, "Field {0} not found within the response object: {1}".format( + assert ( + key in response_json + ), "Field {0} not found within the response object: {1}".format( key, response_json ) @@ -128,11 +156,19 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e # Otherwise, we're just validating a single field that's a pydantic model. if isinstance(value, dict) and not isinstance(type_expectation, tuple): validate_response( - response=response_json[key], json_expectation=value, type_expectations=type_expectation + response=response_json[key], + json_expectation=value, + type_expectations=type_expectation, ) else: - validate_field(response=response_json[key], json_expectation=value, type_expectation=type_expectation) + validate_field( + response=response_json[key], + json_expectation=value, + type_expectation=type_expectation, + ) # Ensure there are no additional fields here either del response_json[key] - assert len(response_json) == 0, "Additional fields found, expected None: {0}".format(response_json) + assert ( + len(response_json) == 0 + ), "Additional fields found, expected None: {0}".format(response_json) diff --git a/seed/python-sdk/exhaustive/extra_dependencies/tests/utils/assets/models/__init__.py b/seed/python-sdk/exhaustive/extra_dependencies/tests/utils/assets/models/__init__.py index 2cf01263529..3a1c852e71e 100644 --- a/seed/python-sdk/exhaustive/extra_dependencies/tests/utils/assets/models/__init__.py +++ b/seed/python-sdk/exhaustive/extra_dependencies/tests/utils/assets/models/__init__.py @@ -5,7 +5,7 @@ from .circle import CircleParams from .object_with_defaults import ObjectWithDefaultsParams from .object_with_optional_field import ObjectWithOptionalFieldParams -from .shape import Shape_CircleParams, Shape_SquareParams, ShapeParams +from .shape import ShapeParams, Shape_CircleParams, Shape_SquareParams from .square import SquareParams from .undiscriminated_shape import UndiscriminatedShapeParams diff --git a/seed/python-sdk/exhaustive/extra_dependencies/tests/utils/assets/models/circle.py b/seed/python-sdk/exhaustive/extra_dependencies/tests/utils/assets/models/circle.py index af7a1bf8a8e..253f12d38b3 100644 --- a/seed/python-sdk/exhaustive/extra_dependencies/tests/utils/assets/models/circle.py +++ b/seed/python-sdk/exhaustive/extra_dependencies/tests/utils/assets/models/circle.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class CircleParams(typing_extensions.TypedDict): - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] diff --git a/seed/python-sdk/exhaustive/extra_dependencies/tests/utils/assets/models/object_with_optional_field.py b/seed/python-sdk/exhaustive/extra_dependencies/tests/utils/assets/models/object_with_optional_field.py index 3ad93d5f305..ebe7dc80547 100644 --- a/seed/python-sdk/exhaustive/extra_dependencies/tests/utils/assets/models/object_with_optional_field.py +++ b/seed/python-sdk/exhaustive/extra_dependencies/tests/utils/assets/models/object_with_optional_field.py @@ -7,8 +7,8 @@ import uuid import typing_extensions -from seed.core.serialization import FieldMetadata +from seed.core.serialization import FieldMetadata from .color import Color from .shape import ShapeParams from .undiscriminated_shape import UndiscriminatedShapeParams @@ -18,16 +18,30 @@ class ObjectWithOptionalFieldParams(typing_extensions.TypedDict): literal: typing.Literal["lit_one"] string: typing_extensions.NotRequired[str] integer: typing_extensions.NotRequired[int] - long_: typing_extensions.NotRequired[typing_extensions.Annotated[int, FieldMetadata(alias="long")]] + long_: typing_extensions.NotRequired[ + typing_extensions.Annotated[int, FieldMetadata(alias="long")] + ] double: typing_extensions.NotRequired[float] - bool_: typing_extensions.NotRequired[typing_extensions.Annotated[bool, FieldMetadata(alias="bool")]] + bool_: typing_extensions.NotRequired[ + typing_extensions.Annotated[bool, FieldMetadata(alias="bool")] + ] datetime: typing_extensions.NotRequired[dt.datetime] date: typing_extensions.NotRequired[dt.date] - uuid_: typing_extensions.NotRequired[typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")]] - base_64: typing_extensions.NotRequired[typing_extensions.Annotated[str, FieldMetadata(alias="base64")]] - list_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")]] - set_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")]] - map_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")]] + uuid_: typing_extensions.NotRequired[ + typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")] + ] + base_64: typing_extensions.NotRequired[ + typing_extensions.Annotated[str, FieldMetadata(alias="base64")] + ] + list_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")] + ] + set_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")] + ] + map_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")] + ] enum: typing_extensions.NotRequired[Color] union: typing_extensions.NotRequired[ShapeParams] second_union: typing_extensions.NotRequired[ShapeParams] diff --git a/seed/python-sdk/exhaustive/extra_dependencies/tests/utils/assets/models/shape.py b/seed/python-sdk/exhaustive/extra_dependencies/tests/utils/assets/models/shape.py index 2c33c877951..816ffc51bdc 100644 --- a/seed/python-sdk/exhaustive/extra_dependencies/tests/utils/assets/models/shape.py +++ b/seed/python-sdk/exhaustive/extra_dependencies/tests/utils/assets/models/shape.py @@ -7,6 +7,7 @@ import typing import typing_extensions + from seed.core.serialization import FieldMetadata @@ -15,13 +16,21 @@ class Base(typing_extensions.TypedDict): class Shape_CircleParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["circle"], FieldMetadata(alias="shapeType")] - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["circle"], FieldMetadata(alias="shapeType") + ] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] class Shape_SquareParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["square"], FieldMetadata(alias="shapeType")] - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["square"], FieldMetadata(alias="shapeType") + ] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] ShapeParams = typing.Union[Shape_CircleParams, Shape_SquareParams] diff --git a/seed/python-sdk/exhaustive/extra_dependencies/tests/utils/assets/models/square.py b/seed/python-sdk/exhaustive/extra_dependencies/tests/utils/assets/models/square.py index b9b7dd319bc..bcf08a723c5 100644 --- a/seed/python-sdk/exhaustive/extra_dependencies/tests/utils/assets/models/square.py +++ b/seed/python-sdk/exhaustive/extra_dependencies/tests/utils/assets/models/square.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class SquareParams(typing_extensions.TypedDict): - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] diff --git a/seed/python-sdk/exhaustive/extra_dependencies/tests/utils/test_http_client.py b/seed/python-sdk/exhaustive/extra_dependencies/tests/utils/test_http_client.py index edd11ca7afb..f5a874a75f3 100644 --- a/seed/python-sdk/exhaustive/extra_dependencies/tests/utils/test_http_client.py +++ b/seed/python-sdk/exhaustive/extra_dependencies/tests/utils/test_http_client.py @@ -9,12 +9,17 @@ def get_request_options() -> RequestOptions: def test_get_json_request_body() -> None: - json_body, data_body = get_request_body(json={"hello": "world"}, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json={"hello": "world"}, data=None, request_options=None, omit=None + ) assert json_body == {"hello": "world"} assert data_body is None json_body_extras, data_body_extras = get_request_body( - json={"goodbye": "world"}, data=None, request_options=get_request_options(), omit=None + json={"goodbye": "world"}, + data=None, + request_options=get_request_options(), + omit=None, ) assert json_body_extras == {"goodbye": "world", "see you": "later"} @@ -22,12 +27,17 @@ def test_get_json_request_body() -> None: def test_get_files_request_body() -> None: - json_body, data_body = get_request_body(json=None, data={"hello": "world"}, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data={"hello": "world"}, request_options=None, omit=None + ) assert data_body == {"hello": "world"} assert json_body is None json_body_extras, data_body_extras = get_request_body( - json=None, data={"goodbye": "world"}, request_options=get_request_options(), omit=None + json=None, + data={"goodbye": "world"}, + request_options=get_request_options(), + omit=None, ) assert data_body_extras == {"goodbye": "world", "see you": "later"} @@ -35,7 +45,9 @@ def test_get_files_request_body() -> None: def test_get_none_request_body() -> None: - json_body, data_body = get_request_body(json=None, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data=None, request_options=None, omit=None + ) assert data_body is None assert json_body is None diff --git a/seed/python-sdk/exhaustive/extra_dependencies/tests/utils/test_query_encoding.py b/seed/python-sdk/exhaustive/extra_dependencies/tests/utils/test_query_encoding.py index 247e1551b46..fbc8f402167 100644 --- a/seed/python-sdk/exhaustive/extra_dependencies/tests/utils/test_query_encoding.py +++ b/seed/python-sdk/exhaustive/extra_dependencies/tests/utils/test_query_encoding.py @@ -4,9 +4,15 @@ def test_query_encoding() -> None: - assert encode_query({"hello world": "hello world"}) == {"hello world": "hello world"} - assert encode_query({"hello_world": {"hello": "world"}}) == {"hello_world[hello]": "world"} - assert encode_query({"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"}) == { + assert encode_query({"hello world": "hello world"}) == { + "hello world": "hello world" + } + assert encode_query({"hello_world": {"hello": "world"}}) == { + "hello_world[hello]": "world" + } + assert encode_query( + {"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"} + ) == { "hello_world[hello][world]": "today", "hello_world[test]": "this", "hi": "there", diff --git a/seed/python-sdk/exhaustive/extra_dependencies/tests/utils/test_serialization.py b/seed/python-sdk/exhaustive/extra_dependencies/tests/utils/test_serialization.py index 58b1ed66e6d..5ca956916dd 100644 --- a/seed/python-sdk/exhaustive/extra_dependencies/tests/utils/test_serialization.py +++ b/seed/python-sdk/exhaustive/extra_dependencies/tests/utils/test_serialization.py @@ -1,10 +1,12 @@ # This file was auto-generated by Fern from our API Definition. -from typing import Any, List +from typing import List, Any -from seed.core.serialization import convert_and_respect_annotation_metadata +from seed.core.serialization import ( + convert_and_respect_annotation_metadata, +) +from .assets.models import ShapeParams, ObjectWithOptionalFieldParams -from .assets.models import ObjectWithOptionalFieldParams, ShapeParams UNION_TEST: ShapeParams = {"radius_measurement": 1.0, "shape_type": "circle", "id": "1"} UNION_TEST_CONVERTED = {"shapeType": "circle", "radiusMeasurement": 1.0, "id": "1"} @@ -18,20 +20,54 @@ def test_convert_and_respect_annotation_metadata() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) - assert converted == {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"} + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) + assert converted == { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + } def test_convert_and_respect_annotation_metadata_in_list() -> None: data: List[ObjectWithOptionalFieldParams] = [ - {"string": "string", "long_": 12345, "bool_": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long_": 67890, "list_": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long_": 12345, + "bool_": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long_": 67890, + "list_": [], + "literal": "lit_one", + "any": "any", + }, ] - converted = convert_and_respect_annotation_metadata(object_=data, annotation=List[ObjectWithOptionalFieldParams]) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=List[ObjectWithOptionalFieldParams] + ) assert converted == [ - {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long": 67890, "list": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long": 67890, + "list": [], + "literal": "lit_one", + "any": "any", + }, ] @@ -43,7 +79,9 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) assert converted == { "string": "string", @@ -55,12 +93,16 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: def test_convert_and_respect_annotation_metadata_in_union() -> None: - converted = convert_and_respect_annotation_metadata(object_=UNION_TEST, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=UNION_TEST, annotation=ShapeParams + ) assert converted == UNION_TEST_CONVERTED def test_convert_and_respect_annotation_metadata_with_empty_object() -> None: data: Any = {} - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ShapeParams + ) assert converted == data diff --git a/seed/python-sdk/exhaustive/extra_dev_dependencies/pyproject.toml b/seed/python-sdk/exhaustive/extra_dev_dependencies/pyproject.toml index ac81dc261b7..7181885035d 100644 --- a/seed/python-sdk/exhaustive/extra_dev_dependencies/pyproject.toml +++ b/seed/python-sdk/exhaustive/extra_dev_dependencies/pyproject.toml @@ -45,6 +45,7 @@ pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" requests_mock = "1.12.1" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/__init__.py b/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/__init__.py index eb56b0ce275..dc1ef03a650 100644 --- a/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/__init__.py +++ b/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/__init__.py @@ -1,6 +1,14 @@ # This file was auto-generated by Fern from our API Definition. -from . import endpoints, general_errors, inlined_requests, no_auth, no_req_body, req_with_headers, types +from . import ( + endpoints, + general_errors, + inlined_requests, + no_auth, + no_req_body, + req_with_headers, + types, +) from .client import AsyncSeedExhaustive, SeedExhaustive from .general_errors import BadObjectRequestInfo, BadRequestBody from .version import __version__ diff --git a/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/client.py b/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/client.py index b1b9764c7a7..f5ab292af6b 100644 --- a/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/client.py +++ b/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/client.py @@ -1,15 +1,19 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from .endpoints.client import AsyncEndpointsClient, EndpointsClient -from .inlined_requests.client import AsyncInlinedRequestsClient, InlinedRequestsClient -from .no_auth.client import AsyncNoAuthClient, NoAuthClient -from .no_req_body.client import AsyncNoReqBodyClient, NoReqBodyClient -from .req_with_headers.client import AsyncReqWithHeadersClient, ReqWithHeadersClient +from .core.client_wrapper import SyncClientWrapper +from .endpoints.client import EndpointsClient +from .inlined_requests.client import InlinedRequestsClient +from .no_auth.client import NoAuthClient +from .no_req_body.client import NoReqBodyClient +from .req_with_headers.client import ReqWithHeadersClient +from .core.client_wrapper import AsyncClientWrapper +from .endpoints.client import AsyncEndpointsClient +from .inlined_requests.client import AsyncInlinedRequestsClient +from .no_auth.client import AsyncNoAuthClient +from .no_req_body.client import AsyncNoReqBodyClient +from .req_with_headers.client import AsyncReqWithHeadersClient class SeedExhaustive: @@ -48,24 +52,32 @@ def __init__( token: typing.Optional[typing.Union[str, typing.Callable[[], str]]] = None, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.Client] = None + httpx_client: typing.Optional[httpx.Client] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = SyncClientWrapper( base_url=base_url, token=token, httpx_client=httpx_client if httpx_client is not None - else httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.Client( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.Client(timeout=_defaulted_timeout), timeout=_defaulted_timeout, ) self.endpoints = EndpointsClient(client_wrapper=self._client_wrapper) - self.inlined_requests = InlinedRequestsClient(client_wrapper=self._client_wrapper) + self.inlined_requests = InlinedRequestsClient( + client_wrapper=self._client_wrapper + ) self.no_auth = NoAuthClient(client_wrapper=self._client_wrapper) self.no_req_body = NoReqBodyClient(client_wrapper=self._client_wrapper) - self.req_with_headers = ReqWithHeadersClient(client_wrapper=self._client_wrapper) + self.req_with_headers = ReqWithHeadersClient( + client_wrapper=self._client_wrapper + ) class AsyncSeedExhaustive: @@ -104,21 +116,29 @@ def __init__( token: typing.Optional[typing.Union[str, typing.Callable[[], str]]] = None, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.AsyncClient] = None + httpx_client: typing.Optional[httpx.AsyncClient] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = AsyncClientWrapper( base_url=base_url, token=token, httpx_client=httpx_client if httpx_client is not None - else httpx.AsyncClient(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.AsyncClient( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.AsyncClient(timeout=_defaulted_timeout), timeout=_defaulted_timeout, ) self.endpoints = AsyncEndpointsClient(client_wrapper=self._client_wrapper) - self.inlined_requests = AsyncInlinedRequestsClient(client_wrapper=self._client_wrapper) + self.inlined_requests = AsyncInlinedRequestsClient( + client_wrapper=self._client_wrapper + ) self.no_auth = AsyncNoAuthClient(client_wrapper=self._client_wrapper) self.no_req_body = AsyncNoReqBodyClient(client_wrapper=self._client_wrapper) - self.req_with_headers = AsyncReqWithHeadersClient(client_wrapper=self._client_wrapper) + self.req_with_headers = AsyncReqWithHeadersClient( + client_wrapper=self._client_wrapper + ) diff --git a/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/core/api_error.py b/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/core/api_error.py index 2e9fc5431cd..da734b58068 100644 --- a/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/core/api_error.py +++ b/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/core/api_error.py @@ -7,7 +7,9 @@ class ApiError(Exception): status_code: typing.Optional[int] body: typing.Any - def __init__(self, *, status_code: typing.Optional[int] = None, body: typing.Any = None): + def __init__( + self, *, status_code: typing.Optional[int] = None, body: typing.Any = None + ): self.status_code = status_code self.body = body diff --git a/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/core/client_wrapper.py b/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/core/client_wrapper.py index 8d01b584b82..d037184a816 100644 --- a/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/core/client_wrapper.py +++ b/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/core/client_wrapper.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .http_client import AsyncHttpClient, HttpClient +from .http_client import HttpClient +from .http_client import AsyncHttpClient class BaseClientWrapper: diff --git a/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/core/datetime_utils.py b/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/core/datetime_utils.py +++ b/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/core/file.py b/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/core/file.py index cb0d40bbbf3..6e0f92bfcb1 100644 --- a/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/core/file.py +++ b/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/core/file.py @@ -13,12 +13,17 @@ # (filename, file (or bytes), content_type) typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str]], # (filename, file (or bytes), content_type, headers) - typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str], typing.Mapping[str, str]], + typing.Tuple[ + typing.Optional[str], + FileContent, + typing.Optional[str], + typing.Mapping[str, str], + ], ] def convert_file_dict_to_httpx_tuples( - d: typing.Dict[str, typing.Union[File, typing.List[File]]] + d: typing.Dict[str, typing.Union[File, typing.List[File]]], ) -> typing.List[typing.Tuple[str, File]]: """ The format we use is a list of tuples, where the first element is the diff --git a/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/core/http_client.py b/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/core/http_client.py index 9333d8a7f15..091f71bc185 100644 --- a/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/core/http_client.py +++ b/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/core/http_client.py @@ -77,7 +77,9 @@ def _retry_timeout(response: httpx.Response, retries: int) -> float: return retry_after # Apply exponential backoff, capped at MAX_RETRY_DELAY_SECONDS. - retry_delay = min(INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS) + retry_delay = min( + INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS + ) # Add a randomness / jitter to the retry delay to avoid overwhelming the server with retries. timeout = retry_delay * (1 - 0.25 * random()) @@ -90,7 +92,8 @@ def _should_retry(response: httpx.Response) -> bool: def remove_omit_from_dict( - original: typing.Dict[str, typing.Optional[typing.Any]], omit: typing.Optional[typing.Any] + original: typing.Dict[str, typing.Optional[typing.Any]], + omit: typing.Optional[typing.Any], ) -> typing.Dict[str, typing.Any]: if omit is None: return original @@ -108,7 +111,8 @@ def maybe_filter_request_body( ) -> typing.Optional[typing.Any]: if data is None: return ( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else None ) @@ -118,7 +122,8 @@ def maybe_filter_request_body( data_content = { **(jsonable_encoder(remove_omit_from_dict(data, omit))), # type: ignore **( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else {} ), @@ -162,7 +167,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url def request( @@ -174,8 +181,12 @@ def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -184,11 +195,14 @@ def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) response = self.httpx_client.request( method=method, @@ -198,7 +212,11 @@ def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -209,7 +227,10 @@ def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -222,11 +243,15 @@ def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: time.sleep(_retry_timeout(response=response, retries=retries)) @@ -256,8 +281,12 @@ def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -266,11 +295,14 @@ def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) with self.httpx_client.stream( method=method, @@ -280,7 +312,11 @@ def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -291,7 +327,9 @@ def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -304,7 +342,9 @@ def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream @@ -327,7 +367,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url async def request( @@ -339,8 +381,12 @@ async def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -349,11 +395,14 @@ async def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) # Add the input to each of these and do None-safety checks response = await self.httpx_client.request( @@ -364,7 +413,11 @@ async def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -375,7 +428,10 @@ async def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -388,11 +444,15 @@ async def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: await asyncio.sleep(_retry_timeout(response=response, retries=retries)) @@ -421,8 +481,12 @@ async def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -431,11 +495,14 @@ async def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) async with self.httpx_client.stream( method=method, @@ -445,7 +512,11 @@ async def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -456,7 +527,9 @@ async def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -469,7 +542,9 @@ async def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream diff --git a/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/core/jsonable_encoder.py b/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/core/jsonable_encoder.py index d3fd328fd41..12a8b52fc22 100644 --- a/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/core/jsonable_encoder.py +++ b/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/core/jsonable_encoder.py @@ -19,13 +19,19 @@ import pydantic from .datetime_utils import serialize_datetime -from .pydantic_utilities import IS_PYDANTIC_V2, encode_by_type, to_jsonable_with_fallback +from .pydantic_utilities import ( + IS_PYDANTIC_V2, + encode_by_type, + to_jsonable_with_fallback, +) SetIntStr = Set[Union[int, str]] DictIntStrAny = Dict[Union[int, str], Any] -def jsonable_encoder(obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None) -> Any: +def jsonable_encoder( + obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None +) -> Any: custom_encoder = custom_encoder or {} if custom_encoder: if type(obj) in custom_encoder: diff --git a/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/core/pydantic_utilities.py b/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/core/pydantic_utilities.py index 170a563d6eb..c63935c32a2 100644 --- a/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/core/pydantic_utilities.py +++ b/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) # type: ignore # Pydantic v1 diff --git a/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/core/query_encoder.py b/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/core/query_encoder.py index 24076d72ee9..7cb98f52cd7 100644 --- a/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/core/query_encoder.py +++ b/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/core/query_encoder.py @@ -7,7 +7,9 @@ # Flattens dicts to be of the form {"key[subkey][subkey2]": value} where value is not a dict -def traverse_query_dict(dict_flat: Dict[str, Any], key_prefix: Optional[str] = None) -> Dict[str, Any]: +def traverse_query_dict( + dict_flat: Dict[str, Any], key_prefix: Optional[str] = None +) -> Dict[str, Any]: result = {} for k, v in dict_flat.items(): key = f"{key_prefix}[{k}]" if key_prefix is not None else k @@ -30,4 +32,8 @@ def single_query_encoder(query_key: str, query_value: Any) -> Dict[str, Any]: def encode_query(query: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: - return dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) if query is not None else None + return ( + dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) + if query is not None + else None + ) diff --git a/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/core/serialization.py b/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/core/serialization.py +++ b/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/endpoints/__init__.py b/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/endpoints/__init__.py index 92307cab7fe..a9496ece178 100644 --- a/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/endpoints/__init__.py +++ b/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/endpoints/__init__.py @@ -2,4 +2,12 @@ from . import container, enum, http_methods, object, params, primitive, union -__all__ = ["container", "enum", "http_methods", "object", "params", "primitive", "union"] +__all__ = [ + "container", + "enum", + "http_methods", + "object", + "params", + "primitive", + "union", +] diff --git a/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/endpoints/client.py b/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/endpoints/client.py index 18dc397fdf1..69930de54d7 100644 --- a/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/endpoints/client.py +++ b/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/endpoints/client.py @@ -1,13 +1,21 @@ # This file was auto-generated by Fern from our API Definition. -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from .container.client import AsyncContainerClient, ContainerClient -from .enum.client import AsyncEnumClient, EnumClient -from .http_methods.client import AsyncHttpMethodsClient, HttpMethodsClient -from .object.client import AsyncObjectClient, ObjectClient -from .params.client import AsyncParamsClient, ParamsClient -from .primitive.client import AsyncPrimitiveClient, PrimitiveClient -from .union.client import AsyncUnionClient, UnionClient +from ..core.client_wrapper import SyncClientWrapper +from .container.client import ContainerClient +from .enum.client import EnumClient +from .http_methods.client import HttpMethodsClient +from .object.client import ObjectClient +from .params.client import ParamsClient +from .primitive.client import PrimitiveClient +from .union.client import UnionClient +from ..core.client_wrapper import AsyncClientWrapper +from .container.client import AsyncContainerClient +from .enum.client import AsyncEnumClient +from .http_methods.client import AsyncHttpMethodsClient +from .object.client import AsyncObjectClient +from .params.client import AsyncParamsClient +from .primitive.client import AsyncPrimitiveClient +from .union.client import AsyncUnionClient class EndpointsClient: diff --git a/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/endpoints/container/client.py b/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/endpoints/container/client.py index c6cf14f63ac..4af9c12d534 100644 --- a/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/endpoints/container/client.py +++ b/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/endpoints/container/client.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. import typing +from ...core.client_wrapper import SyncClientWrapper +from ...core.request_options import RequestOptions +from ...core.pydantic_utilities import parse_obj_as from json.decoder import JSONDecodeError - from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ...core.pydantic_utilities import parse_obj_as -from ...core.request_options import RequestOptions from ...types.object.types.object_with_required_field import ObjectWithRequiredField +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -18,7 +18,10 @@ def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper def get_and_return_list_of_primitives( - self, *, request: typing.Sequence[str], request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Sequence[str], + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[str]: """ Parameters @@ -45,11 +48,18 @@ def get_and_return_list_of_primitives( ) """ _response = self._client_wrapper.httpx_client.request( - "container/list-of-primitives", method="POST", json=request, request_options=request_options, omit=OMIT + "container/list-of-primitives", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.List[str], parse_obj_as(type_=typing.List[str], object_=_response.json())) # type: ignore + return typing.cast( + typing.List[str], + parse_obj_as(type_=typing.List[str], object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -59,7 +69,7 @@ def get_and_return_list_of_objects( self, *, request: typing.Sequence[ObjectWithRequiredField], - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[ObjectWithRequiredField]: """ Parameters @@ -91,18 +101,31 @@ def get_and_return_list_of_objects( ) """ _response = self._client_wrapper.httpx_client.request( - "container/list-of-objects", method="POST", json=request, request_options=request_options, omit=OMIT + "container/list-of-objects", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.List[ObjectWithRequiredField], parse_obj_as(type_=typing.List[ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.List[ObjectWithRequiredField], + parse_obj_as( + type_=typing.List[ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_and_return_set_of_primitives( - self, *, request: typing.Set[str], request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Set[str], + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Set[str]: """ Parameters @@ -129,11 +152,18 @@ def get_and_return_set_of_primitives( ) """ _response = self._client_wrapper.httpx_client.request( - "container/set-of-primitives", method="POST", json=request, request_options=request_options, omit=OMIT + "container/set-of-primitives", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Set[str], parse_obj_as(type_=typing.Set[str], object_=_response.json())) # type: ignore + return typing.cast( + typing.Set[str], + parse_obj_as(type_=typing.Set[str], object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -143,7 +173,7 @@ def get_and_return_set_of_objects( self, *, request: typing.Sequence[ObjectWithRequiredField], - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[ObjectWithRequiredField]: """ Parameters @@ -175,18 +205,31 @@ def get_and_return_set_of_objects( ) """ _response = self._client_wrapper.httpx_client.request( - "container/set-of-objects", method="POST", json=request, request_options=request_options, omit=OMIT + "container/set-of-objects", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.List[ObjectWithRequiredField], parse_obj_as(type_=typing.List[ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.List[ObjectWithRequiredField], + parse_obj_as( + type_=typing.List[ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_and_return_map_prim_to_prim( - self, *, request: typing.Dict[str, str], request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Dict[str, str], + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Dict[str, str]: """ Parameters @@ -213,11 +256,18 @@ def get_and_return_map_prim_to_prim( ) """ _response = self._client_wrapper.httpx_client.request( - "container/map-prim-to-prim", method="POST", json=request, request_options=request_options, omit=OMIT + "container/map-prim-to-prim", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Dict[str, str], parse_obj_as(type_=typing.Dict[str, str], object_=_response.json())) # type: ignore + return typing.cast( + typing.Dict[str, str], + parse_obj_as(type_=typing.Dict[str, str], object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -227,7 +277,7 @@ def get_and_return_map_of_prim_to_object( self, *, request: typing.Dict[str, ObjectWithRequiredField], - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Dict[str, ObjectWithRequiredField]: """ Parameters @@ -259,11 +309,21 @@ def get_and_return_map_of_prim_to_object( ) """ _response = self._client_wrapper.httpx_client.request( - "container/map-prim-to-object", method="POST", json=request, request_options=request_options, omit=OMIT + "container/map-prim-to-object", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Dict[str, ObjectWithRequiredField], parse_obj_as(type_=typing.Dict[str, ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.Dict[str, ObjectWithRequiredField], + parse_obj_as( + type_=typing.Dict[str, ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -273,7 +333,7 @@ def get_and_return_optional( self, *, request: typing.Optional[ObjectWithRequiredField] = None, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Optional[ObjectWithRequiredField]: """ Parameters @@ -303,11 +363,21 @@ def get_and_return_optional( ) """ _response = self._client_wrapper.httpx_client.request( - "container/opt-objects", method="POST", json=request, request_options=request_options, omit=OMIT + "container/opt-objects", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Optional[ObjectWithRequiredField], parse_obj_as(type_=typing.Optional[ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.Optional[ObjectWithRequiredField], + parse_obj_as( + type_=typing.Optional[ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -319,7 +389,10 @@ def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper async def get_and_return_list_of_primitives( - self, *, request: typing.Sequence[str], request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Sequence[str], + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[str]: """ Parameters @@ -354,11 +427,18 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/list-of-primitives", method="POST", json=request, request_options=request_options, omit=OMIT + "container/list-of-primitives", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.List[str], parse_obj_as(type_=typing.List[str], object_=_response.json())) # type: ignore + return typing.cast( + typing.List[str], + parse_obj_as(type_=typing.List[str], object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -368,7 +448,7 @@ async def get_and_return_list_of_objects( self, *, request: typing.Sequence[ObjectWithRequiredField], - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[ObjectWithRequiredField]: """ Parameters @@ -408,18 +488,31 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/list-of-objects", method="POST", json=request, request_options=request_options, omit=OMIT + "container/list-of-objects", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.List[ObjectWithRequiredField], parse_obj_as(type_=typing.List[ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.List[ObjectWithRequiredField], + parse_obj_as( + type_=typing.List[ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_and_return_set_of_primitives( - self, *, request: typing.Set[str], request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Set[str], + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Set[str]: """ Parameters @@ -454,11 +547,18 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/set-of-primitives", method="POST", json=request, request_options=request_options, omit=OMIT + "container/set-of-primitives", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Set[str], parse_obj_as(type_=typing.Set[str], object_=_response.json())) # type: ignore + return typing.cast( + typing.Set[str], + parse_obj_as(type_=typing.Set[str], object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -468,7 +568,7 @@ async def get_and_return_set_of_objects( self, *, request: typing.Sequence[ObjectWithRequiredField], - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[ObjectWithRequiredField]: """ Parameters @@ -508,18 +608,31 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/set-of-objects", method="POST", json=request, request_options=request_options, omit=OMIT + "container/set-of-objects", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.List[ObjectWithRequiredField], parse_obj_as(type_=typing.List[ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.List[ObjectWithRequiredField], + parse_obj_as( + type_=typing.List[ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_and_return_map_prim_to_prim( - self, *, request: typing.Dict[str, str], request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Dict[str, str], + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Dict[str, str]: """ Parameters @@ -554,11 +667,18 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/map-prim-to-prim", method="POST", json=request, request_options=request_options, omit=OMIT + "container/map-prim-to-prim", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Dict[str, str], parse_obj_as(type_=typing.Dict[str, str], object_=_response.json())) # type: ignore + return typing.cast( + typing.Dict[str, str], + parse_obj_as(type_=typing.Dict[str, str], object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -568,7 +688,7 @@ async def get_and_return_map_of_prim_to_object( self, *, request: typing.Dict[str, ObjectWithRequiredField], - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Dict[str, ObjectWithRequiredField]: """ Parameters @@ -608,11 +728,21 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/map-prim-to-object", method="POST", json=request, request_options=request_options, omit=OMIT + "container/map-prim-to-object", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Dict[str, ObjectWithRequiredField], parse_obj_as(type_=typing.Dict[str, ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.Dict[str, ObjectWithRequiredField], + parse_obj_as( + type_=typing.Dict[str, ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -622,7 +752,7 @@ async def get_and_return_optional( self, *, request: typing.Optional[ObjectWithRequiredField] = None, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Optional[ObjectWithRequiredField]: """ Parameters @@ -660,11 +790,21 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/opt-objects", method="POST", json=request, request_options=request_options, omit=OMIT + "container/opt-objects", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Optional[ObjectWithRequiredField], parse_obj_as(type_=typing.Optional[ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.Optional[ObjectWithRequiredField], + parse_obj_as( + type_=typing.Optional[ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/endpoints/enum/client.py b/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/endpoints/enum/client.py index 44e2690ff6c..3e3208e3bcf 100644 --- a/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/endpoints/enum/client.py +++ b/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/endpoints/enum/client.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. import typing +from ...core.client_wrapper import SyncClientWrapper +from ...types.enum.types.weather_report import WeatherReport +from ...core.request_options import RequestOptions +from ...core.pydantic_utilities import parse_obj_as from json.decoder import JSONDecodeError - from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ...core.pydantic_utilities import parse_obj_as -from ...core.request_options import RequestOptions -from ...types.enum.types.weather_report import WeatherReport +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -18,7 +18,10 @@ def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper def get_and_return_enum( - self, *, request: WeatherReport, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: WeatherReport, + request_options: typing.Optional[RequestOptions] = None, ) -> WeatherReport: """ Parameters @@ -45,11 +48,18 @@ def get_and_return_enum( ) """ _response = self._client_wrapper.httpx_client.request( - "enum", method="POST", json=request, request_options=request_options, omit=OMIT + "enum", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(WeatherReport, parse_obj_as(type_=WeatherReport, object_=_response.json())) # type: ignore + return typing.cast( + WeatherReport, + parse_obj_as(type_=WeatherReport, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -61,7 +71,10 @@ def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper async def get_and_return_enum( - self, *, request: WeatherReport, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: WeatherReport, + request_options: typing.Optional[RequestOptions] = None, ) -> WeatherReport: """ Parameters @@ -96,11 +109,18 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "enum", method="POST", json=request, request_options=request_options, omit=OMIT + "enum", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(WeatherReport, parse_obj_as(type_=WeatherReport, object_=_response.json())) # type: ignore + return typing.cast( + WeatherReport, + parse_obj_as(type_=WeatherReport, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/endpoints/http_methods/client.py b/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/endpoints/http_methods/client.py index a2549280a1b..570a227844f 100644 --- a/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/endpoints/http_methods/client.py +++ b/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/endpoints/http_methods/client.py @@ -1,16 +1,16 @@ # This file was auto-generated by Fern from our API Definition. -import datetime as dt import typing -import uuid -from json.decoder import JSONDecodeError - -from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper +from ...core.client_wrapper import SyncClientWrapper +from ...core.request_options import RequestOptions from ...core.jsonable_encoder import jsonable_encoder from ...core.pydantic_utilities import parse_obj_as -from ...core.request_options import RequestOptions +from json.decoder import JSONDecodeError +from ...core.api_error import ApiError from ...types.object.types.object_with_optional_field import ObjectWithOptionalField +import datetime as dt +import uuid +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -20,7 +20,9 @@ class HttpMethodsClient: def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper - def test_get(self, id: str, *, request_options: typing.Optional[RequestOptions] = None) -> str: + def test_get( + self, id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -46,11 +48,15 @@ def test_get(self, id: str, *, request_options: typing.Optional[RequestOptions] ) """ _response = self._client_wrapper.httpx_client.request( - f"http-methods/{jsonable_encoder(id)}", method="GET", request_options=request_options + f"http-methods/{jsonable_encoder(id)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -84,18 +90,33 @@ def test_post( ) """ _response = self._client_wrapper.httpx_client.request( - "http-methods", method="POST", json={"string": string}, request_options=request_options, omit=OMIT + "http-methods", + method="POST", + json={ + "string": string, + }, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def test_put( - self, id: str, *, string: str, request_options: typing.Optional[RequestOptions] = None + self, + id: str, + *, + string: str, + request_options: typing.Optional[RequestOptions] = None, ) -> ObjectWithOptionalField: """ Parameters @@ -127,13 +148,20 @@ def test_put( _response = self._client_wrapper.httpx_client.request( f"http-methods/{jsonable_encoder(id)}", method="PUT", - json={"string": string}, + json={ + "string": string, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -254,13 +282,20 @@ def test_patch( ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def test_delete(self, id: str, *, request_options: typing.Optional[RequestOptions] = None) -> bool: + def test_delete( + self, id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> bool: """ Parameters ---------- @@ -286,11 +321,15 @@ def test_delete(self, id: str, *, request_options: typing.Optional[RequestOption ) """ _response = self._client_wrapper.httpx_client.request( - f"http-methods/{jsonable_encoder(id)}", method="DELETE", request_options=request_options + f"http-methods/{jsonable_encoder(id)}", + method="DELETE", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -301,7 +340,9 @@ class AsyncHttpMethodsClient: def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper - async def test_get(self, id: str, *, request_options: typing.Optional[RequestOptions] = None) -> str: + async def test_get( + self, id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -335,11 +376,15 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - f"http-methods/{jsonable_encoder(id)}", method="GET", request_options=request_options + f"http-methods/{jsonable_encoder(id)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -381,18 +426,33 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "http-methods", method="POST", json={"string": string}, request_options=request_options, omit=OMIT + "http-methods", + method="POST", + json={ + "string": string, + }, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def test_put( - self, id: str, *, string: str, request_options: typing.Optional[RequestOptions] = None + self, + id: str, + *, + string: str, + request_options: typing.Optional[RequestOptions] = None, ) -> ObjectWithOptionalField: """ Parameters @@ -432,13 +492,20 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( f"http-methods/{jsonable_encoder(id)}", method="PUT", - json={"string": string}, + json={ + "string": string, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -566,13 +633,20 @@ async def main() -> None: ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - async def test_delete(self, id: str, *, request_options: typing.Optional[RequestOptions] = None) -> bool: + async def test_delete( + self, id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> bool: """ Parameters ---------- @@ -606,11 +680,15 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - f"http-methods/{jsonable_encoder(id)}", method="DELETE", request_options=request_options + f"http-methods/{jsonable_encoder(id)}", + method="DELETE", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/endpoints/object/client.py b/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/endpoints/object/client.py index a724f959193..dcb1324b74b 100644 --- a/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/endpoints/object/client.py +++ b/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/endpoints/object/client.py @@ -1,20 +1,24 @@ # This file was auto-generated by Fern from our API Definition. -import datetime as dt import typing +from ...core.client_wrapper import SyncClientWrapper +import datetime as dt import uuid -from json.decoder import JSONDecodeError - -from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ...core.jsonable_encoder import jsonable_encoder -from ...core.pydantic_utilities import parse_obj_as from ...core.request_options import RequestOptions -from ...types.object.types.nested_object_with_optional_field import NestedObjectWithOptionalField -from ...types.object.types.nested_object_with_required_field import NestedObjectWithRequiredField -from ...types.object.types.object_with_map_of_map import ObjectWithMapOfMap from ...types.object.types.object_with_optional_field import ObjectWithOptionalField +from ...core.pydantic_utilities import parse_obj_as +from json.decoder import JSONDecodeError +from ...core.api_error import ApiError from ...types.object.types.object_with_required_field import ObjectWithRequiredField +from ...types.object.types.object_with_map_of_map import ObjectWithMapOfMap +from ...types.object.types.nested_object_with_optional_field import ( + NestedObjectWithOptionalField, +) +from ...types.object.types.nested_object_with_required_field import ( + NestedObjectWithRequiredField, +) +from ...core.jsonable_encoder import jsonable_encoder +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -135,7 +139,12 @@ def get_and_return_with_optional_field( ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -171,20 +180,30 @@ def get_and_return_with_required_field( _response = self._client_wrapper.httpx_client.request( "object/get-and-return-with-required-field", method="POST", - json={"string": string}, + json={ + "string": string, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithRequiredField, parse_obj_as(type_=ObjectWithRequiredField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithRequiredField, + parse_obj_as( + type_=ObjectWithRequiredField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_and_return_with_map_of_map( - self, *, map_: typing.Dict[str, typing.Dict[str, str]], request_options: typing.Optional[RequestOptions] = None + self, + *, + map_: typing.Dict[str, typing.Dict[str, str]], + request_options: typing.Optional[RequestOptions] = None, ) -> ObjectWithMapOfMap: """ Parameters @@ -213,13 +232,18 @@ def get_and_return_with_map_of_map( _response = self._client_wrapper.httpx_client.request( "object/get-and-return-with-map-of-map", method="POST", - json={"map": map_}, + json={ + "map": map_, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithMapOfMap, parse_obj_as(type_=ObjectWithMapOfMap, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithMapOfMap, + parse_obj_as(type_=ObjectWithMapOfMap, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -286,13 +310,21 @@ def get_and_return_nested_with_optional_field( _response = self._client_wrapper.httpx_client.request( "object/get-and-return-nested-with-optional-field", method="POST", - json={"string": string, "NestedObject": nested_object}, + json={ + "string": string, + "NestedObject": nested_object, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(NestedObjectWithOptionalField, parse_obj_as(type_=NestedObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + NestedObjectWithOptionalField, + parse_obj_as( + type_=NestedObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -363,13 +395,21 @@ def get_and_return_nested_with_required_field( _response = self._client_wrapper.httpx_client.request( f"object/get-and-return-nested-with-required-field/{jsonable_encoder(string_)}", method="POST", - json={"string": string, "NestedObject": nested_object}, + json={ + "string": string, + "NestedObject": nested_object, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(NestedObjectWithRequiredField, parse_obj_as(type_=NestedObjectWithRequiredField, object_=_response.json())) # type: ignore + return typing.cast( + NestedObjectWithRequiredField, + parse_obj_as( + type_=NestedObjectWithRequiredField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -446,7 +486,12 @@ def get_and_return_nested_with_required_field_as_list( ) try: if 200 <= _response.status_code < 300: - return typing.cast(NestedObjectWithRequiredField, parse_obj_as(type_=NestedObjectWithRequiredField, object_=_response.json())) # type: ignore + return typing.cast( + NestedObjectWithRequiredField, + parse_obj_as( + type_=NestedObjectWithRequiredField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -575,7 +620,12 @@ async def main() -> None: ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -619,20 +669,30 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( "object/get-and-return-with-required-field", method="POST", - json={"string": string}, + json={ + "string": string, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithRequiredField, parse_obj_as(type_=ObjectWithRequiredField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithRequiredField, + parse_obj_as( + type_=ObjectWithRequiredField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_and_return_with_map_of_map( - self, *, map_: typing.Dict[str, typing.Dict[str, str]], request_options: typing.Optional[RequestOptions] = None + self, + *, + map_: typing.Dict[str, typing.Dict[str, str]], + request_options: typing.Optional[RequestOptions] = None, ) -> ObjectWithMapOfMap: """ Parameters @@ -669,13 +729,18 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( "object/get-and-return-with-map-of-map", method="POST", - json={"map": map_}, + json={ + "map": map_, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithMapOfMap, parse_obj_as(type_=ObjectWithMapOfMap, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithMapOfMap, + parse_obj_as(type_=ObjectWithMapOfMap, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -749,13 +814,21 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( "object/get-and-return-nested-with-optional-field", method="POST", - json={"string": string, "NestedObject": nested_object}, + json={ + "string": string, + "NestedObject": nested_object, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(NestedObjectWithOptionalField, parse_obj_as(type_=NestedObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + NestedObjectWithOptionalField, + parse_obj_as( + type_=NestedObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -833,13 +906,21 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( f"object/get-and-return-nested-with-required-field/{jsonable_encoder(string_)}", method="POST", - json={"string": string, "NestedObject": nested_object}, + json={ + "string": string, + "NestedObject": nested_object, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(NestedObjectWithRequiredField, parse_obj_as(type_=NestedObjectWithRequiredField, object_=_response.json())) # type: ignore + return typing.cast( + NestedObjectWithRequiredField, + parse_obj_as( + type_=NestedObjectWithRequiredField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -923,7 +1004,12 @@ async def main() -> None: ) try: if 200 <= _response.status_code < 300: - return typing.cast(NestedObjectWithRequiredField, parse_obj_as(type_=NestedObjectWithRequiredField, object_=_response.json())) # type: ignore + return typing.cast( + NestedObjectWithRequiredField, + parse_obj_as( + type_=NestedObjectWithRequiredField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/endpoints/params/client.py b/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/endpoints/params/client.py index 5cd7ceef42a..a9187ac94b8 100644 --- a/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/endpoints/params/client.py +++ b/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/endpoints/params/client.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. import typing -from json.decoder import JSONDecodeError - -from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper +from ...core.client_wrapper import SyncClientWrapper +from ...core.request_options import RequestOptions from ...core.jsonable_encoder import jsonable_encoder from ...core.pydantic_utilities import parse_obj_as -from ...core.request_options import RequestOptions +from json.decoder import JSONDecodeError +from ...core.api_error import ApiError +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -17,7 +17,9 @@ class ParamsClient: def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper - def get_with_path(self, param: str, *, request_options: typing.Optional[RequestOptions] = None) -> str: + def get_with_path( + self, param: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ GET with path param @@ -45,18 +47,26 @@ def get_with_path(self, param: str, *, request_options: typing.Optional[RequestO ) """ _response = self._client_wrapper.httpx_client.request( - f"params/path/{jsonable_encoder(param)}", method="GET", request_options=request_options + f"params/path/{jsonable_encoder(param)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_with_query( - self, *, query: str, number: int, request_options: typing.Optional[RequestOptions] = None + self, + *, + query: str, + number: int, + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ GET with query param @@ -88,7 +98,13 @@ def get_with_query( ) """ _response = self._client_wrapper.httpx_client.request( - "params", method="GET", params={"query": query, "number": number}, request_options=request_options + "params", + method="GET", + params={ + "query": query, + "number": number, + }, + request_options=request_options, ) try: if 200 <= _response.status_code < 300: @@ -135,7 +151,13 @@ def get_with_allow_multiple_query( ) """ _response = self._client_wrapper.httpx_client.request( - "params", method="GET", params={"query": query, "numer": numer}, request_options=request_options + "params", + method="GET", + params={ + "query": query, + "numer": numer, + }, + request_options=request_options, ) try: if 200 <= _response.status_code < 300: @@ -146,7 +168,11 @@ def get_with_allow_multiple_query( raise ApiError(status_code=_response.status_code, body=_response_json) def get_with_path_and_query( - self, param: str, *, query: str, request_options: typing.Optional[RequestOptions] = None + self, + param: str, + *, + query: str, + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ GET with path and query params @@ -180,7 +206,9 @@ def get_with_path_and_query( _response = self._client_wrapper.httpx_client.request( f"params/path-query/{jsonable_encoder(param)}", method="GET", - params={"query": query}, + params={ + "query": query, + }, request_options=request_options, ) try: @@ -192,7 +220,11 @@ def get_with_path_and_query( raise ApiError(status_code=_response.status_code, body=_response_json) def modify_with_path( - self, param: str, *, request: str, request_options: typing.Optional[RequestOptions] = None + self, + param: str, + *, + request: str, + request_options: typing.Optional[RequestOptions] = None, ) -> str: """ PUT to update with path param @@ -232,7 +264,9 @@ def modify_with_path( ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -243,7 +277,9 @@ class AsyncParamsClient: def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper - async def get_with_path(self, param: str, *, request_options: typing.Optional[RequestOptions] = None) -> str: + async def get_with_path( + self, param: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ GET with path param @@ -279,18 +315,26 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - f"params/path/{jsonable_encoder(param)}", method="GET", request_options=request_options + f"params/path/{jsonable_encoder(param)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_with_query( - self, *, query: str, number: int, request_options: typing.Optional[RequestOptions] = None + self, + *, + query: str, + number: int, + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ GET with query param @@ -330,7 +374,13 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "params", method="GET", params={"query": query, "number": number}, request_options=request_options + "params", + method="GET", + params={ + "query": query, + "number": number, + }, + request_options=request_options, ) try: if 200 <= _response.status_code < 300: @@ -385,7 +435,13 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "params", method="GET", params={"query": query, "numer": numer}, request_options=request_options + "params", + method="GET", + params={ + "query": query, + "numer": numer, + }, + request_options=request_options, ) try: if 200 <= _response.status_code < 300: @@ -396,7 +452,11 @@ async def main() -> None: raise ApiError(status_code=_response.status_code, body=_response_json) async def get_with_path_and_query( - self, param: str, *, query: str, request_options: typing.Optional[RequestOptions] = None + self, + param: str, + *, + query: str, + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ GET with path and query params @@ -438,7 +498,9 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( f"params/path-query/{jsonable_encoder(param)}", method="GET", - params={"query": query}, + params={ + "query": query, + }, request_options=request_options, ) try: @@ -450,7 +512,11 @@ async def main() -> None: raise ApiError(status_code=_response.status_code, body=_response_json) async def modify_with_path( - self, param: str, *, request: str, request_options: typing.Optional[RequestOptions] = None + self, + param: str, + *, + request: str, + request_options: typing.Optional[RequestOptions] = None, ) -> str: """ PUT to update with path param @@ -498,7 +564,9 @@ async def main() -> None: ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/endpoints/primitive/client.py b/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/endpoints/primitive/client.py index 844b6a782f0..20a66f049b4 100644 --- a/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/endpoints/primitive/client.py +++ b/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/endpoints/primitive/client.py @@ -1,14 +1,14 @@ # This file was auto-generated by Fern from our API Definition. -import datetime as dt import typing -import uuid +from ...core.client_wrapper import SyncClientWrapper +from ...core.request_options import RequestOptions +from ...core.pydantic_utilities import parse_obj_as from json.decoder import JSONDecodeError - from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ...core.pydantic_utilities import parse_obj_as -from ...core.request_options import RequestOptions +import datetime as dt +import uuid +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -18,7 +18,9 @@ class PrimitiveClient: def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper - def get_and_return_string(self, *, request: str, request_options: typing.Optional[RequestOptions] = None) -> str: + def get_and_return_string( + self, *, request: str, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -44,17 +46,25 @@ def get_and_return_string(self, *, request: str, request_options: typing.Optiona ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/string", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/string", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def get_and_return_int(self, *, request: int, request_options: typing.Optional[RequestOptions] = None) -> int: + def get_and_return_int( + self, *, request: int, request_options: typing.Optional[RequestOptions] = None + ) -> int: """ Parameters ---------- @@ -80,17 +90,25 @@ def get_and_return_int(self, *, request: int, request_options: typing.Optional[R ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/integer", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/integer", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(int, parse_obj_as(type_=int, object_=_response.json())) # type: ignore + return typing.cast( + int, parse_obj_as(type_=int, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def get_and_return_long(self, *, request: int, request_options: typing.Optional[RequestOptions] = None) -> int: + def get_and_return_long( + self, *, request: int, request_options: typing.Optional[RequestOptions] = None + ) -> int: """ Parameters ---------- @@ -116,11 +134,17 @@ def get_and_return_long(self, *, request: int, request_options: typing.Optional[ ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/long", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/long", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(int, parse_obj_as(type_=int, object_=_response.json())) # type: ignore + return typing.cast( + int, parse_obj_as(type_=int, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -154,17 +178,25 @@ def get_and_return_double( ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/double", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/double", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(float, parse_obj_as(type_=float, object_=_response.json())) # type: ignore + return typing.cast( + float, parse_obj_as(type_=float, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def get_and_return_bool(self, *, request: bool, request_options: typing.Optional[RequestOptions] = None) -> bool: + def get_and_return_bool( + self, *, request: bool, request_options: typing.Optional[RequestOptions] = None + ) -> bool: """ Parameters ---------- @@ -190,18 +222,27 @@ def get_and_return_bool(self, *, request: bool, request_options: typing.Optional ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/boolean", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/boolean", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_and_return_datetime( - self, *, request: dt.datetime, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: dt.datetime, + request_options: typing.Optional[RequestOptions] = None, ) -> dt.datetime: """ Parameters @@ -232,18 +273,28 @@ def get_and_return_datetime( ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/datetime", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/datetime", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(dt.datetime, parse_obj_as(type_=dt.datetime, object_=_response.json())) # type: ignore + return typing.cast( + dt.datetime, + parse_obj_as(type_=dt.datetime, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_and_return_date( - self, *, request: dt.date, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: dt.date, + request_options: typing.Optional[RequestOptions] = None, ) -> dt.date: """ Parameters @@ -274,18 +325,27 @@ def get_and_return_date( ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/date", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/date", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(dt.date, parse_obj_as(type_=dt.date, object_=_response.json())) # type: ignore + return typing.cast( + dt.date, parse_obj_as(type_=dt.date, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_and_return_uuid( - self, *, request: uuid.UUID, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: uuid.UUID, + request_options: typing.Optional[RequestOptions] = None, ) -> uuid.UUID: """ Parameters @@ -316,17 +376,25 @@ def get_and_return_uuid( ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/uuid", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/uuid", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(uuid.UUID, parse_obj_as(type_=uuid.UUID, object_=_response.json())) # type: ignore + return typing.cast( + uuid.UUID, parse_obj_as(type_=uuid.UUID, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def get_and_return_base_64(self, *, request: str, request_options: typing.Optional[RequestOptions] = None) -> str: + def get_and_return_base_64( + self, *, request: str, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -352,11 +420,17 @@ def get_and_return_base_64(self, *, request: str, request_options: typing.Option ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/base64", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/base64", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -403,17 +477,25 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/string", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/string", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - async def get_and_return_int(self, *, request: int, request_options: typing.Optional[RequestOptions] = None) -> int: + async def get_and_return_int( + self, *, request: int, request_options: typing.Optional[RequestOptions] = None + ) -> int: """ Parameters ---------- @@ -447,11 +529,17 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/integer", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/integer", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(int, parse_obj_as(type_=int, object_=_response.json())) # type: ignore + return typing.cast( + int, parse_obj_as(type_=int, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -493,11 +581,17 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/long", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/long", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(int, parse_obj_as(type_=int, object_=_response.json())) # type: ignore + return typing.cast( + int, parse_obj_as(type_=int, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -539,11 +633,17 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/double", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/double", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(float, parse_obj_as(type_=float, object_=_response.json())) # type: ignore + return typing.cast( + float, parse_obj_as(type_=float, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -585,18 +685,27 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/boolean", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/boolean", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_and_return_datetime( - self, *, request: dt.datetime, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: dt.datetime, + request_options: typing.Optional[RequestOptions] = None, ) -> dt.datetime: """ Parameters @@ -634,18 +743,28 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/datetime", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/datetime", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(dt.datetime, parse_obj_as(type_=dt.datetime, object_=_response.json())) # type: ignore + return typing.cast( + dt.datetime, + parse_obj_as(type_=dt.datetime, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_and_return_date( - self, *, request: dt.date, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: dt.date, + request_options: typing.Optional[RequestOptions] = None, ) -> dt.date: """ Parameters @@ -683,18 +802,27 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/date", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/date", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(dt.date, parse_obj_as(type_=dt.date, object_=_response.json())) # type: ignore + return typing.cast( + dt.date, parse_obj_as(type_=dt.date, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_and_return_uuid( - self, *, request: uuid.UUID, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: uuid.UUID, + request_options: typing.Optional[RequestOptions] = None, ) -> uuid.UUID: """ Parameters @@ -732,11 +860,17 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/uuid", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/uuid", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(uuid.UUID, parse_obj_as(type_=uuid.UUID, object_=_response.json())) # type: ignore + return typing.cast( + uuid.UUID, parse_obj_as(type_=uuid.UUID, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -778,11 +912,17 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/base64", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/base64", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/endpoints/union/client.py b/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/endpoints/union/client.py index 77153587a27..f4c3d9312de 100644 --- a/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/endpoints/union/client.py +++ b/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/endpoints/union/client.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. import typing +from ...core.client_wrapper import SyncClientWrapper +from ...types.union.types.animal import Animal +from ...core.request_options import RequestOptions +from ...core.pydantic_utilities import parse_obj_as from json.decoder import JSONDecodeError - from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ...core.pydantic_utilities import parse_obj_as -from ...core.request_options import RequestOptions -from ...types.union.types.animal import Animal +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -18,7 +18,10 @@ def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper def get_and_return_union( - self, *, request: Animal, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: Animal, + request_options: typing.Optional[RequestOptions] = None, ) -> Animal: """ Parameters @@ -49,11 +52,17 @@ def get_and_return_union( ) """ _response = self._client_wrapper.httpx_client.request( - "union", method="POST", json=request, request_options=request_options, omit=OMIT + "union", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(Animal, parse_obj_as(type_=Animal, object_=_response.json())) # type: ignore + return typing.cast( + Animal, parse_obj_as(type_=Animal, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -65,7 +74,10 @@ def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper async def get_and_return_union( - self, *, request: Animal, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: Animal, + request_options: typing.Optional[RequestOptions] = None, ) -> Animal: """ Parameters @@ -104,11 +116,17 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "union", method="POST", json=request, request_options=request_options, omit=OMIT + "union", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(Animal, parse_obj_as(type_=Animal, object_=_response.json())) # type: ignore + return typing.cast( + Animal, parse_obj_as(type_=Animal, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/general_errors/types/bad_object_request_info.py b/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/general_errors/types/bad_object_request_info.py index 7f03429e922..73c44b89531 100644 --- a/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/general_errors/types/bad_object_request_info.py +++ b/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/general_errors/types/bad_object_request_info.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class BadObjectRequestInfo(UniversalBaseModel): message: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/inlined_requests/client.py b/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/inlined_requests/client.py index f7c46698eb9..39e0c8fe637 100644 --- a/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/inlined_requests/client.py +++ b/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/inlined_requests/client.py @@ -1,15 +1,15 @@ # This file was auto-generated by Fern from our API Definition. import typing -from json.decoder import JSONDecodeError - -from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.pydantic_utilities import parse_obj_as +from ..core.client_wrapper import SyncClientWrapper +from ..types.object.types.object_with_optional_field import ObjectWithOptionalField from ..core.request_options import RequestOptions +from ..core.pydantic_utilities import parse_obj_as from ..general_errors.errors.bad_request_body import BadRequestBody from ..general_errors.types.bad_object_request_info import BadObjectRequestInfo -from ..types.object.types.object_with_optional_field import ObjectWithOptionalField +from json.decoder import JSONDecodeError +from ..core.api_error import ApiError +from ..core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -25,7 +25,7 @@ def post_with_object_bodyand_response( string: str, integer: int, nested_object: ObjectWithOptionalField, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> ObjectWithOptionalField: """ POST with custom object in request body, response is an object @@ -86,16 +86,30 @@ def post_with_object_bodyand_response( _response = self._client_wrapper.httpx_client.request( "req-bodies/object", method="POST", - json={"string": string, "integer": integer, "NestedObject": nested_object}, + json={ + "string": string, + "integer": integer, + "NestedObject": nested_object, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore if _response.status_code == 400: raise BadRequestBody( - typing.cast(BadObjectRequestInfo, parse_obj_as(type_=BadObjectRequestInfo, object_=_response.json())) # type: ignore + typing.cast( + BadObjectRequestInfo, + parse_obj_as( + type_=BadObjectRequestInfo, object_=_response.json() + ), + ) # type: ignore ) _response_json = _response.json() except JSONDecodeError: @@ -113,7 +127,7 @@ async def post_with_object_bodyand_response( string: str, integer: int, nested_object: ObjectWithOptionalField, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> ObjectWithOptionalField: """ POST with custom object in request body, response is an object @@ -181,16 +195,30 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( "req-bodies/object", method="POST", - json={"string": string, "integer": integer, "NestedObject": nested_object}, + json={ + "string": string, + "integer": integer, + "NestedObject": nested_object, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore if _response.status_code == 400: raise BadRequestBody( - typing.cast(BadObjectRequestInfo, parse_obj_as(type_=BadObjectRequestInfo, object_=_response.json())) # type: ignore + typing.cast( + BadObjectRequestInfo, + parse_obj_as( + type_=BadObjectRequestInfo, object_=_response.json() + ), + ) # type: ignore ) _response_json = _response.json() except JSONDecodeError: diff --git a/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/no_auth/client.py b/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/no_auth/client.py index 3d203bcea34..e5590cde0df 100644 --- a/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/no_auth/client.py +++ b/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/no_auth/client.py @@ -1,14 +1,14 @@ # This file was auto-generated by Fern from our API Definition. import typing -from json.decoder import JSONDecodeError - -from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.pydantic_utilities import parse_obj_as +from ..core.client_wrapper import SyncClientWrapper from ..core.request_options import RequestOptions +from ..core.pydantic_utilities import parse_obj_as from ..general_errors.errors.bad_request_body import BadRequestBody from ..general_errors.types.bad_object_request_info import BadObjectRequestInfo +from json.decoder import JSONDecodeError +from ..core.api_error import ApiError +from ..core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -19,7 +19,10 @@ def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper def post_with_no_auth( - self, *, request: typing.Any, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Any, + request_options: typing.Optional[RequestOptions] = None, ) -> bool: """ POST request with no auth @@ -48,14 +51,25 @@ def post_with_no_auth( ) """ _response = self._client_wrapper.httpx_client.request( - "no-auth", method="POST", json=request, request_options=request_options, omit=OMIT + "no-auth", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore if _response.status_code == 400: raise BadRequestBody( - typing.cast(BadObjectRequestInfo, parse_obj_as(type_=BadObjectRequestInfo, object_=_response.json())) # type: ignore + typing.cast( + BadObjectRequestInfo, + parse_obj_as( + type_=BadObjectRequestInfo, object_=_response.json() + ), + ) # type: ignore ) _response_json = _response.json() except JSONDecodeError: @@ -68,7 +82,10 @@ def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper async def post_with_no_auth( - self, *, request: typing.Any, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Any, + request_options: typing.Optional[RequestOptions] = None, ) -> bool: """ POST request with no auth @@ -105,14 +122,25 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "no-auth", method="POST", json=request, request_options=request_options, omit=OMIT + "no-auth", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore if _response.status_code == 400: raise BadRequestBody( - typing.cast(BadObjectRequestInfo, parse_obj_as(type_=BadObjectRequestInfo, object_=_response.json())) # type: ignore + typing.cast( + BadObjectRequestInfo, + parse_obj_as( + type_=BadObjectRequestInfo, object_=_response.json() + ), + ) # type: ignore ) _response_json = _response.json() except JSONDecodeError: diff --git a/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/no_req_body/client.py b/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/no_req_body/client.py index 33fa0c77d27..5afdd703fdc 100644 --- a/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/no_req_body/client.py +++ b/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/no_req_body/client.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. +from ..core.client_wrapper import SyncClientWrapper import typing -from json.decoder import JSONDecodeError - -from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.pydantic_utilities import parse_obj_as from ..core.request_options import RequestOptions from ..types.object.types.object_with_optional_field import ObjectWithOptionalField +from ..core.pydantic_utilities import parse_obj_as +from json.decoder import JSONDecodeError +from ..core.api_error import ApiError +from ..core.client_wrapper import AsyncClientWrapper class NoReqBodyClient: @@ -38,17 +38,26 @@ def get_with_no_request_body( client.no_req_body.get_with_no_request_body() """ _response = self._client_wrapper.httpx_client.request( - "no-req-body", method="GET", request_options=request_options + "no-req-body", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def post_with_no_request_body(self, *, request_options: typing.Optional[RequestOptions] = None) -> str: + def post_with_no_request_body( + self, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -70,11 +79,15 @@ def post_with_no_request_body(self, *, request_options: typing.Optional[RequestO client.no_req_body.post_with_no_request_body() """ _response = self._client_wrapper.httpx_client.request( - "no-req-body", method="POST", request_options=request_options + "no-req-body", + method="POST", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -117,17 +130,26 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "no-req-body", method="GET", request_options=request_options + "no-req-body", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - async def post_with_no_request_body(self, *, request_options: typing.Optional[RequestOptions] = None) -> str: + async def post_with_no_request_body( + self, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -157,11 +179,15 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "no-req-body", method="POST", request_options=request_options + "no-req-body", + method="POST", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/req_with_headers/client.py b/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/req_with_headers/client.py index 655402249e9..984428516e3 100644 --- a/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/req_with_headers/client.py +++ b/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/req_with_headers/client.py @@ -1,11 +1,11 @@ # This file was auto-generated by Fern from our API Definition. import typing +from ..core.client_wrapper import SyncClientWrapper +from ..core.request_options import RequestOptions from json.decoder import JSONDecodeError - from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.request_options import RequestOptions +from ..core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -21,7 +21,7 @@ def get_with_custom_header( x_test_service_header: str, x_test_endpoint_header: str, request: str, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ Parameters @@ -58,8 +58,12 @@ def get_with_custom_header( method="POST", json=request, headers={ - "X-TEST-SERVICE-HEADER": str(x_test_service_header) if x_test_service_header is not None else None, - "X-TEST-ENDPOINT-HEADER": str(x_test_endpoint_header) if x_test_endpoint_header is not None else None, + "X-TEST-SERVICE-HEADER": str(x_test_service_header) + if x_test_service_header is not None + else None, + "X-TEST-ENDPOINT-HEADER": str(x_test_endpoint_header) + if x_test_endpoint_header is not None + else None, }, request_options=request_options, omit=OMIT, @@ -83,7 +87,7 @@ async def get_with_custom_header( x_test_service_header: str, x_test_endpoint_header: str, request: str, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ Parameters @@ -128,8 +132,12 @@ async def main() -> None: method="POST", json=request, headers={ - "X-TEST-SERVICE-HEADER": str(x_test_service_header) if x_test_service_header is not None else None, - "X-TEST-ENDPOINT-HEADER": str(x_test_endpoint_header) if x_test_endpoint_header is not None else None, + "X-TEST-SERVICE-HEADER": str(x_test_service_header) + if x_test_service_header is not None + else None, + "X-TEST-ENDPOINT-HEADER": str(x_test_endpoint_header) + if x_test_endpoint_header is not None + else None, }, request_options=request_options, omit=OMIT, diff --git a/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/types/enum/types/weather_report.py b/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/types/enum/types/weather_report.py index 2d54965dc22..84017ef161d 100644 --- a/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/types/enum/types/weather_report.py +++ b/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/types/enum/types/weather_report.py @@ -2,4 +2,6 @@ import typing -WeatherReport = typing.Union[typing.Literal["SUNNY", "CLOUDY", "RAINING", "SNOWING"], typing.Any] +WeatherReport = typing.Union[ + typing.Literal["SUNNY", "CLOUDY", "RAINING", "SNOWING"], typing.Any +] diff --git a/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/types/object/types/double_optional.py b/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/types/object/types/double_optional.py index ddf165b13bd..ed236347357 100644 --- a/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/types/object/types/double_optional.py +++ b/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/types/object/types/double_optional.py @@ -1,18 +1,21 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .optional_alias import OptionalAlias +import pydantic +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class DoubleOptional(UniversalBaseModel): - optional_alias: typing.Optional[OptionalAlias] = pydantic.Field(alias="optionalAlias", default=None) + optional_alias: typing.Optional[OptionalAlias] = pydantic.Field( + alias="optionalAlias", default=None + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/types/object/types/nested_object_with_optional_field.py b/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/types/object/types/nested_object_with_optional_field.py index 81669c0dd39..20a4d40a714 100644 --- a/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/types/object/types/nested_object_with_optional_field.py +++ b/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/types/object/types/nested_object_with_optional_field.py @@ -1,19 +1,22 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .object_with_optional_field import ObjectWithOptionalField +import pydantic +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class NestedObjectWithOptionalField(UniversalBaseModel): string: typing.Optional[str] = None - nested_object: typing.Optional[ObjectWithOptionalField] = pydantic.Field(alias="NestedObject", default=None) + nested_object: typing.Optional[ObjectWithOptionalField] = pydantic.Field( + alias="NestedObject", default=None + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/types/object/types/nested_object_with_required_field.py b/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/types/object/types/nested_object_with_required_field.py index 1a621942c6c..a6ca8781190 100644 --- a/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/types/object/types/nested_object_with_required_field.py +++ b/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/types/object/types/nested_object_with_required_field.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import UniversalBaseModel from .object_with_optional_field import ObjectWithOptionalField +import pydantic +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class NestedObjectWithRequiredField(UniversalBaseModel): @@ -13,7 +12,9 @@ class NestedObjectWithRequiredField(UniversalBaseModel): nested_object: ObjectWithOptionalField = pydantic.Field(alias="NestedObject") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/types/object/types/object_with_map_of_map.py b/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/types/object/types/object_with_map_of_map.py index 8883cc1d498..313cd25ceb8 100644 --- a/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/types/object/types/object_with_map_of_map.py +++ b/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/types/object/types/object_with_map_of_map.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class ObjectWithMapOfMap(UniversalBaseModel): map_: typing.Dict[str, typing.Dict[str, str]] = pydantic.Field(alias="map") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/types/object/types/object_with_optional_field.py b/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/types/object/types/object_with_optional_field.py index 6aab170be0c..9131f0e91d7 100644 --- a/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/types/object/types/object_with_optional_field.py +++ b/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/types/object/types/object_with_optional_field.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. -import datetime as dt +from ....core.pydantic_utilities import UniversalBaseModel import typing -import uuid - import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +import datetime as dt +import uuid +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class ObjectWithOptionalField(UniversalBaseModel): @@ -23,13 +22,19 @@ class ObjectWithOptionalField(UniversalBaseModel): date: typing.Optional[dt.date] = None uuid_: typing.Optional[uuid.UUID] = pydantic.Field(alias="uuid", default=None) base_64: typing.Optional[str] = pydantic.Field(alias="base64", default=None) - list_: typing.Optional[typing.List[str]] = pydantic.Field(alias="list", default=None) + list_: typing.Optional[typing.List[str]] = pydantic.Field( + alias="list", default=None + ) set_: typing.Optional[typing.Set[str]] = pydantic.Field(alias="set", default=None) - map_: typing.Optional[typing.Dict[int, str]] = pydantic.Field(alias="map", default=None) + map_: typing.Optional[typing.Dict[int, str]] = pydantic.Field( + alias="map", default=None + ) bigint: typing.Optional[str] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/types/object/types/object_with_required_field.py b/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/types/object/types/object_with_required_field.py index 61b98867984..24db26a3cf8 100644 --- a/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/types/object/types/object_with_required_field.py +++ b/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/types/object/types/object_with_required_field.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class ObjectWithRequiredField(UniversalBaseModel): string: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/types/union/types/animal.py b/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/types/union/types/animal.py index 1ae43d1663e..84c71d2009a 100644 --- a/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/types/union/types/animal.py +++ b/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/types/union/types/animal.py @@ -1,12 +1,10 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ....core.pydantic_utilities import UniversalBaseModel import typing - import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class Animal_Dog(UniversalBaseModel): @@ -15,7 +13,9 @@ class Animal_Dog(UniversalBaseModel): likes_to_woof: bool = pydantic.Field(alias="likesToWoof") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: @@ -30,7 +30,9 @@ class Animal_Cat(UniversalBaseModel): likes_to_meow: bool = pydantic.Field(alias="likesToMeow") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/types/union/types/cat.py b/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/types/union/types/cat.py index 61fc5527b1f..c59b78523c9 100644 --- a/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/types/union/types/cat.py +++ b/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/types/union/types/cat.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ....core.pydantic_utilities import UniversalBaseModel import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class Cat(UniversalBaseModel): @@ -12,7 +11,9 @@ class Cat(UniversalBaseModel): likes_to_meow: bool = pydantic.Field(alias="likesToMeow") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/types/union/types/dog.py b/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/types/union/types/dog.py index c1ff5339dfe..e250c72edef 100644 --- a/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/types/union/types/dog.py +++ b/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/types/union/types/dog.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ....core.pydantic_utilities import UniversalBaseModel import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class Dog(UniversalBaseModel): @@ -12,7 +11,9 @@ class Dog(UniversalBaseModel): likes_to_woof: bool = pydantic.Field(alias="likesToWoof") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/version.py b/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/version.py index 63ba170685a..ac44536abdb 100644 --- a/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/version.py +++ b/seed/python-sdk/exhaustive/extra_dev_dependencies/src/seed/version.py @@ -1,4 +1,3 @@ - from importlib import metadata __version__ = metadata.version("fern_exhaustive") diff --git a/seed/python-sdk/exhaustive/extra_dev_dependencies/tests/conftest.py b/seed/python-sdk/exhaustive/extra_dev_dependencies/tests/conftest.py index b5b50383b94..86cb2b41af8 100644 --- a/seed/python-sdk/exhaustive/extra_dev_dependencies/tests/conftest.py +++ b/seed/python-sdk/exhaustive/extra_dev_dependencies/tests/conftest.py @@ -1,16 +1,22 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive import os - import pytest -from seed import AsyncSeedExhaustive, SeedExhaustive +from seed import AsyncSeedExhaustive @pytest.fixture def client() -> SeedExhaustive: - return SeedExhaustive(token=os.getenv("ENV_TOKEN", "token"), base_url=os.getenv("TESTS_BASE_URL", "base_url")) + return SeedExhaustive( + token=os.getenv("ENV_TOKEN", "token"), + base_url=os.getenv("TESTS_BASE_URL", "base_url"), + ) @pytest.fixture def async_client() -> AsyncSeedExhaustive: - return AsyncSeedExhaustive(token=os.getenv("ENV_TOKEN", "token"), base_url=os.getenv("TESTS_BASE_URL", "base_url")) + return AsyncSeedExhaustive( + token=os.getenv("ENV_TOKEN", "token"), + base_url=os.getenv("TESTS_BASE_URL", "base_url"), + ) diff --git a/seed/python-sdk/exhaustive/extra_dev_dependencies/tests/custom/test_client.py b/seed/python-sdk/exhaustive/extra_dev_dependencies/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/python-sdk/exhaustive/extra_dev_dependencies/tests/custom/test_client.py +++ b/seed/python-sdk/exhaustive/extra_dev_dependencies/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/python-sdk/exhaustive/extra_dev_dependencies/tests/endpoints/test_container.py b/seed/python-sdk/exhaustive/extra_dev_dependencies/tests/endpoints/test_container.py index 17d9d75240d..240f16f2a8c 100644 --- a/seed/python-sdk/exhaustive/extra_dev_dependencies/tests/endpoints/test_container.py +++ b/seed/python-sdk/exhaustive/extra_dev_dependencies/tests/endpoints/test_container.py @@ -1,91 +1,137 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing - -from seed import AsyncSeedExhaustive, SeedExhaustive -from seed.types.object import ObjectWithRequiredField - from ..utilities import validate_response +from seed.types.object import ObjectWithRequiredField -async def test_get_and_return_list_of_primitives(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_list_of_primitives( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = ["string"] expected_types: typing.Tuple[typing.Any, typing.Any] = ("list", {0: None}) - response = client.endpoints.container.get_and_return_list_of_primitives(request=["string"]) + response = client.endpoints.container.get_and_return_list_of_primitives( + request=["string"] + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.container.get_and_return_list_of_primitives(request=["string"]) + async_response = ( + await async_client.endpoints.container.get_and_return_list_of_primitives( + request=["string"] + ) + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_list_of_objects(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_list_of_objects( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = [{"string": "string"}] - expected_types: typing.Tuple[typing.Any, typing.Any] = ("list", {0: {"string": None}}) + expected_types: typing.Tuple[typing.Any, typing.Any] = ( + "list", + {0: {"string": None}}, + ) response = client.endpoints.container.get_and_return_list_of_objects( request=[ObjectWithRequiredField(string="string")] ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.container.get_and_return_list_of_objects( - request=[ObjectWithRequiredField(string="string")] + async_response = ( + await async_client.endpoints.container.get_and_return_list_of_objects( + request=[ObjectWithRequiredField(string="string")] + ) ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_set_of_primitives(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_set_of_primitives( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = ["string"] expected_types: typing.Tuple[typing.Any, typing.Any] = ("set", {0: None}) - response = client.endpoints.container.get_and_return_set_of_primitives(request={"string"}) + response = client.endpoints.container.get_and_return_set_of_primitives( + request={"string"} + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.container.get_and_return_set_of_primitives(request={"string"}) + async_response = ( + await async_client.endpoints.container.get_and_return_set_of_primitives( + request={"string"} + ) + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_set_of_objects(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_set_of_objects( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = [{"string": "string"}] - expected_types: typing.Tuple[typing.Any, typing.Any] = ("set", {0: {"string": None}}) + expected_types: typing.Tuple[typing.Any, typing.Any] = ( + "set", + {0: {"string": None}}, + ) response = client.endpoints.container.get_and_return_set_of_objects( request=[ObjectWithRequiredField(string="string")] ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.container.get_and_return_set_of_objects( - request=[ObjectWithRequiredField(string="string")] + async_response = ( + await async_client.endpoints.container.get_and_return_set_of_objects( + request=[ObjectWithRequiredField(string="string")] + ) ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_map_prim_to_prim(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_map_prim_to_prim( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = {"string": "string"} expected_types: typing.Tuple[typing.Any, typing.Any] = ("dict", {0: (None, None)}) - response = client.endpoints.container.get_and_return_map_prim_to_prim(request={"string": "string"}) + response = client.endpoints.container.get_and_return_map_prim_to_prim( + request={"string": "string"} + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.container.get_and_return_map_prim_to_prim( - request={"string": "string"} + async_response = ( + await async_client.endpoints.container.get_and_return_map_prim_to_prim( + request={"string": "string"} + ) ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_map_of_prim_to_object(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_map_of_prim_to_object( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = {"string": {"string": "string"}} - expected_types: typing.Tuple[typing.Any, typing.Any] = ("dict", {0: (None, {"string": None})}) + expected_types: typing.Tuple[typing.Any, typing.Any] = ( + "dict", + {0: (None, {"string": None})}, + ) response = client.endpoints.container.get_and_return_map_of_prim_to_object( request={"string": ObjectWithRequiredField(string="string")} ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.container.get_and_return_map_of_prim_to_object( - request={"string": ObjectWithRequiredField(string="string")} + async_response = ( + await async_client.endpoints.container.get_and_return_map_of_prim_to_object( + request={"string": ObjectWithRequiredField(string="string")} + ) ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_optional(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_optional( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = {"string": "string"} expected_types: typing.Any = {"string": None} - response = client.endpoints.container.get_and_return_optional(request=ObjectWithRequiredField(string="string")) + response = client.endpoints.container.get_and_return_optional( + request=ObjectWithRequiredField(string="string") + ) validate_response(response, expected_response, expected_types) async_response = await async_client.endpoints.container.get_and_return_optional( diff --git a/seed/python-sdk/exhaustive/extra_dev_dependencies/tests/endpoints/test_enum.py b/seed/python-sdk/exhaustive/extra_dev_dependencies/tests/endpoints/test_enum.py index 890aada5ce4..ca3fca30b5a 100644 --- a/seed/python-sdk/exhaustive/extra_dev_dependencies/tests/endpoints/test_enum.py +++ b/seed/python-sdk/exhaustive/extra_dev_dependencies/tests/endpoints/test_enum.py @@ -1,17 +1,20 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing - -from seed import AsyncSeedExhaustive, SeedExhaustive - from ..utilities import validate_response -async def test_get_and_return_enum(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_enum( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "SUNNY" expected_types: typing.Any = None response = client.endpoints.enum.get_and_return_enum(request="SUNNY") validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.enum.get_and_return_enum(request="SUNNY") + async_response = await async_client.endpoints.enum.get_and_return_enum( + request="SUNNY" + ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/exhaustive/extra_dev_dependencies/tests/endpoints/test_http_methods.py b/seed/python-sdk/exhaustive/extra_dev_dependencies/tests/endpoints/test_http_methods.py index dc01bafcf6f..77131fc6e8b 100644 --- a/seed/python-sdk/exhaustive/extra_dev_dependencies/tests/endpoints/test_http_methods.py +++ b/seed/python-sdk/exhaustive/extra_dev_dependencies/tests/endpoints/test_http_methods.py @@ -1,15 +1,16 @@ # This file was auto-generated by Fern from our API Definition. -import datetime +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing -import uuid - -from seed import AsyncSeedExhaustive, SeedExhaustive - from ..utilities import validate_response +import datetime +import uuid -async def test_test_get(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_test_get( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "string" expected_types: typing.Any = None response = client.endpoints.http_methods.test_get(id="string") @@ -19,7 +20,9 @@ async def test_test_get(client: SeedExhaustive, async_client: AsyncSeedExhaustiv validate_response(async_response, expected_response, expected_types) -async def test_test_post(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_test_post( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = { "string": "string", "integer": 1, @@ -53,11 +56,15 @@ async def test_test_post(client: SeedExhaustive, async_client: AsyncSeedExhausti response = client.endpoints.http_methods.test_post(string="string") validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.http_methods.test_post(string="string") + async_response = await async_client.endpoints.http_methods.test_post( + string="string" + ) validate_response(async_response, expected_response, expected_types) -async def test_test_put(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_test_put( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = { "string": "string", "integer": 1, @@ -91,11 +98,15 @@ async def test_test_put(client: SeedExhaustive, async_client: AsyncSeedExhaustiv response = client.endpoints.http_methods.test_put(id="string", string="string") validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.http_methods.test_put(id="string", string="string") + async_response = await async_client.endpoints.http_methods.test_put( + id="string", string="string" + ) validate_response(async_response, expected_response, expected_types) -async def test_test_patch(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_test_patch( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = { "string": "string", "integer": 1, @@ -163,7 +174,9 @@ async def test_test_patch(client: SeedExhaustive, async_client: AsyncSeedExhaust validate_response(async_response, expected_response, expected_types) -async def test_test_delete(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_test_delete( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = True expected_types: typing.Any = None response = client.endpoints.http_methods.test_delete(id="string") diff --git a/seed/python-sdk/exhaustive/extra_dev_dependencies/tests/endpoints/test_object.py b/seed/python-sdk/exhaustive/extra_dev_dependencies/tests/endpoints/test_object.py index a9098b6e9ef..c48c4332b22 100644 --- a/seed/python-sdk/exhaustive/extra_dev_dependencies/tests/endpoints/test_object.py +++ b/seed/python-sdk/exhaustive/extra_dev_dependencies/tests/endpoints/test_object.py @@ -1,16 +1,18 @@ # This file was auto-generated by Fern from our API Definition. -import datetime +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing +import datetime import uuid - -from seed import AsyncSeedExhaustive, SeedExhaustive -from seed.types.object import NestedObjectWithRequiredField, ObjectWithOptionalField - from ..utilities import validate_response +from seed.types.object import ObjectWithOptionalField +from seed.types.object import NestedObjectWithRequiredField -async def test_get_and_return_with_optional_field(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_with_optional_field( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = { "string": "string", "integer": 1, @@ -58,38 +60,54 @@ async def test_get_and_return_with_optional_field(client: SeedExhaustive, async_ ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.object.get_and_return_with_optional_field( - string="string", - integer=1, - long_=1000000, - double=1.1, - bool_=True, - datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), - date=datetime.date.fromisoformat("2023-01-15"), - uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), - base_64="SGVsbG8gd29ybGQh", - list_=["string"], - set_={"string"}, - map_={1: "string"}, - bigint="123456789123456789", + async_response = ( + await async_client.endpoints.object.get_and_return_with_optional_field( + string="string", + integer=1, + long_=1000000, + double=1.1, + bool_=True, + datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), + date=datetime.date.fromisoformat("2023-01-15"), + uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + base_64="SGVsbG8gd29ybGQh", + list_=["string"], + set_={"string"}, + map_={1: "string"}, + bigint="123456789123456789", + ) ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_with_required_field(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_with_required_field( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = {"string": "string"} expected_types: typing.Any = {"string": None} - response = client.endpoints.object.get_and_return_with_required_field(string="string") + response = client.endpoints.object.get_and_return_with_required_field( + string="string" + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.object.get_and_return_with_required_field(string="string") + async_response = ( + await async_client.endpoints.object.get_and_return_with_required_field( + string="string" + ) + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_with_map_of_map(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_with_map_of_map( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = {"map": {"string": {"string": "string"}}} - expected_types: typing.Any = {"map": ("dict", {0: (None, ("dict", {0: (None, None)}))})} - response = client.endpoints.object.get_and_return_with_map_of_map(map_={"string": {"string": "string"}}) + expected_types: typing.Any = { + "map": ("dict", {0: (None, ("dict", {0: (None, None)}))}) + } + response = client.endpoints.object.get_and_return_with_map_of_map( + map_={"string": {"string": "string"}} + ) validate_response(response, expected_response, expected_types) async_response = await async_client.endpoints.object.get_and_return_with_map_of_map( @@ -157,23 +175,25 @@ async def test_get_and_return_nested_with_optional_field( ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.object.get_and_return_nested_with_optional_field( - string="string", - nested_object=ObjectWithOptionalField( + async_response = ( + await async_client.endpoints.object.get_and_return_nested_with_optional_field( string="string", - integer=1, - long_=1000000, - double=1.1, - bool_=True, - datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), - date=datetime.date.fromisoformat("2023-01-15"), - uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), - base_64="SGVsbG8gd29ybGQh", - list_=["string"], - set_={"string"}, - map_={1: "string"}, - bigint="123456789123456789", - ), + nested_object=ObjectWithOptionalField( + string="string", + integer=1, + long_=1000000, + double=1.1, + bool_=True, + datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), + date=datetime.date.fromisoformat("2023-01-15"), + uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + base_64="SGVsbG8gd29ybGQh", + list_=["string"], + set_={"string"}, + map_={1: "string"}, + bigint="123456789123456789", + ), + ) ) validate_response(async_response, expected_response, expected_types) @@ -238,24 +258,26 @@ async def test_get_and_return_nested_with_required_field( ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.object.get_and_return_nested_with_required_field( - string_="string", - string="string", - nested_object=ObjectWithOptionalField( + async_response = ( + await async_client.endpoints.object.get_and_return_nested_with_required_field( + string_="string", string="string", - integer=1, - long_=1000000, - double=1.1, - bool_=True, - datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), - date=datetime.date.fromisoformat("2023-01-15"), - uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), - base_64="SGVsbG8gd29ybGQh", - list_=["string"], - set_={"string"}, - map_={1: "string"}, - bigint="123456789123456789", - ), + nested_object=ObjectWithOptionalField( + string="string", + integer=1, + long_=1000000, + double=1.1, + bool_=True, + datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), + date=datetime.date.fromisoformat("2023-01-15"), + uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + base_64="SGVsbG8gd29ybGQh", + list_=["string"], + set_={"string"}, + map_={1: "string"}, + bigint="123456789123456789", + ), + ) ) validate_response(async_response, expected_response, expected_types) @@ -299,27 +321,31 @@ async def test_get_and_return_nested_with_required_field_as_list( "bigint": None, }, } - response = client.endpoints.object.get_and_return_nested_with_required_field_as_list( - request=[ - NestedObjectWithRequiredField( - string="string", - nested_object=ObjectWithOptionalField( + response = ( + client.endpoints.object.get_and_return_nested_with_required_field_as_list( + request=[ + NestedObjectWithRequiredField( string="string", - integer=1, - long_=1000000, - double=1.1, - bool_=True, - datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), - date=datetime.date.fromisoformat("2023-01-15"), - uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), - base_64="SGVsbG8gd29ybGQh", - list_=["string"], - set_={"string"}, - map_={1: "string"}, - bigint="123456789123456789", - ), - ) - ] + nested_object=ObjectWithOptionalField( + string="string", + integer=1, + long_=1000000, + double=1.1, + bool_=True, + datetime=datetime.datetime.fromisoformat( + "2024-01-15 09:30:00+00:00" + ), + date=datetime.date.fromisoformat("2023-01-15"), + uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + base_64="SGVsbG8gd29ybGQh", + list_=["string"], + set_={"string"}, + map_={1: "string"}, + bigint="123456789123456789", + ), + ) + ] + ) ) validate_response(response, expected_response, expected_types) @@ -333,7 +359,9 @@ async def test_get_and_return_nested_with_required_field_as_list( long_=1000000, double=1.1, bool_=True, - datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), + datetime=datetime.datetime.fromisoformat( + "2024-01-15 09:30:00+00:00" + ), date=datetime.date.fromisoformat("2023-01-15"), uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), base_64="SGVsbG8gd29ybGQh", diff --git a/seed/python-sdk/exhaustive/extra_dev_dependencies/tests/endpoints/test_params.py b/seed/python-sdk/exhaustive/extra_dev_dependencies/tests/endpoints/test_params.py index 163d7b9161d..d8ffb00c0a0 100644 --- a/seed/python-sdk/exhaustive/extra_dev_dependencies/tests/endpoints/test_params.py +++ b/seed/python-sdk/exhaustive/extra_dev_dependencies/tests/endpoints/test_params.py @@ -1,13 +1,14 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing - -from seed import AsyncSeedExhaustive, SeedExhaustive - from ..utilities import validate_response -async def test_get_with_path(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_with_path( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "string" expected_types: typing.Any = None response = client.endpoints.params.get_with_path(param="string") @@ -17,32 +18,63 @@ async def test_get_with_path(client: SeedExhaustive, async_client: AsyncSeedExha validate_response(async_response, expected_response, expected_types) -async def test_get_with_query(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_with_query( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: # Type ignore to avoid mypy complaining about the function not being meant to return a value assert client.endpoints.params.get_with_query(query="string", number=1) is None # type: ignore[func-returns-value] - assert await async_client.endpoints.params.get_with_query(query="string", number=1) is None # type: ignore[func-returns-value] + assert ( + await async_client.endpoints.params.get_with_query(query="string", number=1) + is None + ) # type: ignore[func-returns-value] -async def test_get_with_allow_multiple_query(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_with_allow_multiple_query( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: # Type ignore to avoid mypy complaining about the function not being meant to return a value - assert client.endpoints.params.get_with_allow_multiple_query(query="string", numer=1) is None # type: ignore[func-returns-value] - - assert await async_client.endpoints.params.get_with_allow_multiple_query(query="string", numer=1) is None # type: ignore[func-returns-value] - - -async def test_get_with_path_and_query(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: + assert ( + client.endpoints.params.get_with_allow_multiple_query(query="string", numer=1) + is None + ) # type: ignore[func-returns-value] + + assert ( + await async_client.endpoints.params.get_with_allow_multiple_query( + query="string", numer=1 + ) + is None + ) # type: ignore[func-returns-value] + + +async def test_get_with_path_and_query( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: # Type ignore to avoid mypy complaining about the function not being meant to return a value - assert client.endpoints.params.get_with_path_and_query(param="string", query="string") is None # type: ignore[func-returns-value] - - assert await async_client.endpoints.params.get_with_path_and_query(param="string", query="string") is None # type: ignore[func-returns-value] - - -async def test_modify_with_path(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: + assert ( + client.endpoints.params.get_with_path_and_query(param="string", query="string") + is None + ) # type: ignore[func-returns-value] + + assert ( + await async_client.endpoints.params.get_with_path_and_query( + param="string", query="string" + ) + is None + ) # type: ignore[func-returns-value] + + +async def test_modify_with_path( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "string" expected_types: typing.Any = None - response = client.endpoints.params.modify_with_path(param="string", request="string") + response = client.endpoints.params.modify_with_path( + param="string", request="string" + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.params.modify_with_path(param="string", request="string") + async_response = await async_client.endpoints.params.modify_with_path( + param="string", request="string" + ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/exhaustive/extra_dev_dependencies/tests/endpoints/test_primitive.py b/seed/python-sdk/exhaustive/extra_dev_dependencies/tests/endpoints/test_primitive.py index ba3bc7e29e5..26cbcf45d2f 100644 --- a/seed/python-sdk/exhaustive/extra_dev_dependencies/tests/endpoints/test_primitive.py +++ b/seed/python-sdk/exhaustive/extra_dev_dependencies/tests/endpoints/test_primitive.py @@ -1,65 +1,86 @@ # This file was auto-generated by Fern from our API Definition. -import datetime +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing -import uuid - -from seed import AsyncSeedExhaustive, SeedExhaustive - from ..utilities import validate_response +import datetime +import uuid -async def test_get_and_return_string(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_string( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "string" expected_types: typing.Any = None response = client.endpoints.primitive.get_and_return_string(request="string") validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.primitive.get_and_return_string(request="string") + async_response = await async_client.endpoints.primitive.get_and_return_string( + request="string" + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_int(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_int( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = 1 expected_types: typing.Any = "integer" response = client.endpoints.primitive.get_and_return_int(request=1) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.primitive.get_and_return_int(request=1) + async_response = await async_client.endpoints.primitive.get_and_return_int( + request=1 + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_long(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_long( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = 1000000 expected_types: typing.Any = None response = client.endpoints.primitive.get_and_return_long(request=1000000) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.primitive.get_and_return_long(request=1000000) + async_response = await async_client.endpoints.primitive.get_and_return_long( + request=1000000 + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_double(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_double( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = 1.1 expected_types: typing.Any = None response = client.endpoints.primitive.get_and_return_double(request=1.1) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.primitive.get_and_return_double(request=1.1) + async_response = await async_client.endpoints.primitive.get_and_return_double( + request=1.1 + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_bool(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_bool( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = True expected_types: typing.Any = None response = client.endpoints.primitive.get_and_return_bool(request=True) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.primitive.get_and_return_bool(request=True) + async_response = await async_client.endpoints.primitive.get_and_return_bool( + request=True + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_datetime(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_datetime( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "2024-01-15T09:30:00Z" expected_types: typing.Any = "datetime" response = client.endpoints.primitive.get_and_return_datetime( @@ -73,10 +94,14 @@ async def test_get_and_return_datetime(client: SeedExhaustive, async_client: Asy validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_date(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_date( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "2023-01-15" expected_types: typing.Any = "date" - response = client.endpoints.primitive.get_and_return_date(request=datetime.date.fromisoformat("2023-01-15")) + response = client.endpoints.primitive.get_and_return_date( + request=datetime.date.fromisoformat("2023-01-15") + ) validate_response(response, expected_response, expected_types) async_response = await async_client.endpoints.primitive.get_and_return_date( @@ -85,10 +110,14 @@ async def test_get_and_return_date(client: SeedExhaustive, async_client: AsyncSe validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_uuid(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_uuid( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32" expected_types: typing.Any = "uuid" - response = client.endpoints.primitive.get_and_return_uuid(request=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32")) + response = client.endpoints.primitive.get_and_return_uuid( + request=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32") + ) validate_response(response, expected_response, expected_types) async_response = await async_client.endpoints.primitive.get_and_return_uuid( @@ -97,11 +126,17 @@ async def test_get_and_return_uuid(client: SeedExhaustive, async_client: AsyncSe validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_base_64(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_base_64( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "SGVsbG8gd29ybGQh" expected_types: typing.Any = None - response = client.endpoints.primitive.get_and_return_base_64(request="SGVsbG8gd29ybGQh") + response = client.endpoints.primitive.get_and_return_base_64( + request="SGVsbG8gd29ybGQh" + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.primitive.get_and_return_base_64(request="SGVsbG8gd29ybGQh") + async_response = await async_client.endpoints.primitive.get_and_return_base_64( + request="SGVsbG8gd29ybGQh" + ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/exhaustive/extra_dev_dependencies/tests/endpoints/test_union.py b/seed/python-sdk/exhaustive/extra_dev_dependencies/tests/endpoints/test_union.py index 14e34c2a6df..ceb84928cd9 100644 --- a/seed/python-sdk/exhaustive/extra_dev_dependencies/tests/endpoints/test_union.py +++ b/seed/python-sdk/exhaustive/extra_dev_dependencies/tests/endpoints/test_union.py @@ -1,17 +1,24 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing - -from seed import AsyncSeedExhaustive, SeedExhaustive from seed.types.union import Animal_Dog - from ..utilities import validate_response -async def test_get_and_return_union(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: - expected_response: typing.Any = {"animal": "dog", "name": "string", "likesToWoof": True} +async def test_get_and_return_union( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: + expected_response: typing.Any = { + "animal": "dog", + "name": "string", + "likesToWoof": True, + } expected_types: typing.Any = "no_validate" - response = client.endpoints.union.get_and_return_union(request=Animal_Dog(name="string", likes_to_woof=True)) + response = client.endpoints.union.get_and_return_union( + request=Animal_Dog(name="string", likes_to_woof=True) + ) validate_response(response, expected_response, expected_types) async_response = await async_client.endpoints.union.get_and_return_union( diff --git a/seed/python-sdk/exhaustive/extra_dev_dependencies/tests/test_inlined_requests.py b/seed/python-sdk/exhaustive/extra_dev_dependencies/tests/test_inlined_requests.py index bb9390d3845..03f46b31cc9 100644 --- a/seed/python-sdk/exhaustive/extra_dev_dependencies/tests/test_inlined_requests.py +++ b/seed/python-sdk/exhaustive/extra_dev_dependencies/tests/test_inlined_requests.py @@ -1,16 +1,17 @@ # This file was auto-generated by Fern from our API Definition. -import datetime +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing -import uuid - -from seed import AsyncSeedExhaustive, SeedExhaustive from seed.types.object import ObjectWithOptionalField - +import datetime +import uuid from .utilities import validate_response -async def test_post_with_object_bodyand_response(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_post_with_object_bodyand_response( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = { "string": "string", "integer": 1, @@ -62,23 +63,25 @@ async def test_post_with_object_bodyand_response(client: SeedExhaustive, async_c ) validate_response(response, expected_response, expected_types) - async_response = await async_client.inlined_requests.post_with_object_bodyand_response( - string="string", - integer=1, - nested_object=ObjectWithOptionalField( + async_response = ( + await async_client.inlined_requests.post_with_object_bodyand_response( string="string", integer=1, - long_=1000000, - double=1.1, - bool_=True, - datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), - date=datetime.date.fromisoformat("2023-01-15"), - uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), - base_64="SGVsbG8gd29ybGQh", - list_=["string"], - set_={"string"}, - map_={1: "string"}, - bigint="123456789123456789", - ), + nested_object=ObjectWithOptionalField( + string="string", + integer=1, + long_=1000000, + double=1.1, + bool_=True, + datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), + date=datetime.date.fromisoformat("2023-01-15"), + uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + base_64="SGVsbG8gd29ybGQh", + list_=["string"], + set_={"string"}, + map_={1: "string"}, + bigint="123456789123456789", + ), + ) ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/exhaustive/extra_dev_dependencies/tests/test_no_auth.py b/seed/python-sdk/exhaustive/extra_dev_dependencies/tests/test_no_auth.py index 3328661bb48..fc475f4b6fb 100644 --- a/seed/python-sdk/exhaustive/extra_dev_dependencies/tests/test_no_auth.py +++ b/seed/python-sdk/exhaustive/extra_dev_dependencies/tests/test_no_auth.py @@ -1,17 +1,20 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing - -from seed import AsyncSeedExhaustive, SeedExhaustive - from .utilities import validate_response -async def test_post_with_no_auth(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_post_with_no_auth( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = True expected_types: typing.Any = None response = client.no_auth.post_with_no_auth(request={"key": "value"}) validate_response(response, expected_response, expected_types) - async_response = await async_client.no_auth.post_with_no_auth(request={"key": "value"}) + async_response = await async_client.no_auth.post_with_no_auth( + request={"key": "value"} + ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/exhaustive/extra_dev_dependencies/tests/test_no_req_body.py b/seed/python-sdk/exhaustive/extra_dev_dependencies/tests/test_no_req_body.py index 73abac9d2d8..07061a0e99e 100644 --- a/seed/python-sdk/exhaustive/extra_dev_dependencies/tests/test_no_req_body.py +++ b/seed/python-sdk/exhaustive/extra_dev_dependencies/tests/test_no_req_body.py @@ -1,13 +1,14 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing - -from seed import AsyncSeedExhaustive, SeedExhaustive - from .utilities import validate_response -async def test_get_with_no_request_body(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_with_no_request_body( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = { "string": "string", "integer": 1, @@ -45,7 +46,9 @@ async def test_get_with_no_request_body(client: SeedExhaustive, async_client: As validate_response(async_response, expected_response, expected_types) -async def test_post_with_no_request_body(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_post_with_no_request_body( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "string" expected_types: typing.Any = None response = client.no_req_body.post_with_no_request_body() diff --git a/seed/python-sdk/exhaustive/extra_dev_dependencies/tests/test_req_with_headers.py b/seed/python-sdk/exhaustive/extra_dev_dependencies/tests/test_req_with_headers.py index bba3b5b5507..75ce9d00c03 100644 --- a/seed/python-sdk/exhaustive/extra_dev_dependencies/tests/test_req_with_headers.py +++ b/seed/python-sdk/exhaustive/extra_dev_dependencies/tests/test_req_with_headers.py @@ -1,10 +1,27 @@ # This file was auto-generated by Fern from our API Definition. -from seed import AsyncSeedExhaustive, SeedExhaustive +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive -async def test_get_with_custom_header(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_with_custom_header( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: # Type ignore to avoid mypy complaining about the function not being meant to return a value - assert client.req_with_headers.get_with_custom_header(x_test_service_header="string", x_test_endpoint_header="string", request="string") is None # type: ignore[func-returns-value] + assert ( + client.req_with_headers.get_with_custom_header( + x_test_service_header="string", + x_test_endpoint_header="string", + request="string", + ) + is None + ) # type: ignore[func-returns-value] - assert await async_client.req_with_headers.get_with_custom_header(x_test_service_header="string", x_test_endpoint_header="string", request="string") is None # type: ignore[func-returns-value] + assert ( + await async_client.req_with_headers.get_with_custom_header( + x_test_service_header="string", + x_test_endpoint_header="string", + request="string", + ) + is None + ) # type: ignore[func-returns-value] diff --git a/seed/python-sdk/exhaustive/extra_dev_dependencies/tests/utilities.py b/seed/python-sdk/exhaustive/extra_dev_dependencies/tests/utilities.py index 13da208eb3a..e8f4472564c 100644 --- a/seed/python-sdk/exhaustive/extra_dev_dependencies/tests/utilities.py +++ b/seed/python-sdk/exhaustive/extra_dev_dependencies/tests/utilities.py @@ -3,11 +3,14 @@ import typing import uuid -import pydantic from dateutil import parser +import pydantic + -def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> typing.Any: +def cast_field( + json_expectation: typing.Any, type_expectation: typing.Any +) -> typing.Any: # Cast these specific types which come through as string and expect our # models to cast to the correct type. if type_expectation == "uuid": @@ -25,7 +28,9 @@ def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> ty return json_expectation -def validate_field(response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any) -> None: +def validate_field( + response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectation == "no_validate": return @@ -44,7 +49,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(entry_expectation, dict): is_container_of_complex_type = True validate_response( - response=response[idx], json_expectation=ex, type_expectations=entry_expectation + response=response[idx], + json_expectation=ex, + type_expectations=entry_expectation, ) else: cast_json_expectation.append(cast_field(ex, entry_expectation)) @@ -56,7 +63,10 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # if any of the values of the set have a type_expectation of a dict, we're assuming it's a pydantic # model and keeping it a list. if container_expectation != "set" or not any( - map(lambda value: isinstance(value, dict), list(contents_expectation.values())) + map( + lambda value: isinstance(value, dict), + list(contents_expectation.values()), + ) ): json_expectation = cast_field(json_expectation, container_expectation) elif isinstance(type_expectation, tuple): @@ -65,9 +75,15 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(contents_expectation, dict): json_expectation = { cast_field( - key, contents_expectation.get(idx)[0] if contents_expectation.get(idx) is not None else None # type: ignore + key, + contents_expectation.get(idx)[0] + if contents_expectation.get(idx) is not None + else None, # type: ignore ): cast_field( - value, contents_expectation.get(idx)[1] if contents_expectation.get(idx) is not None else None # type: ignore + value, + contents_expectation.get(idx)[1] + if contents_expectation.get(idx) is not None + else None, # type: ignore ) for idx, (key, value) in enumerate(json_expectation.items()) } @@ -86,7 +102,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # Arg type_expectations is a deeply nested structure that matches the response, but with the values replaced with the expected types -def validate_response(response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any) -> None: +def validate_response( + response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectations == "no_validate": return @@ -96,11 +114,17 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e and not isinstance(response, dict) and not issubclass(type(response), pydantic.BaseModel) ): - validate_field(response=response, json_expectation=json_expectation, type_expectation=type_expectations) + validate_field( + response=response, + json_expectation=json_expectation, + type_expectation=type_expectations, + ) return if isinstance(response, list): - assert len(response) == len(json_expectation), "Length mismatch, expected: {0}, Actual: {1}".format( + assert len(response) == len( + json_expectation + ), "Length mismatch, expected: {0}, Actual: {1}".format( len(response), len(json_expectation) ) content_expectation = type_expectations @@ -108,7 +132,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e content_expectation = type_expectations[1] for idx, item in enumerate(response): validate_response( - response=item, json_expectation=json_expectation[idx], type_expectations=content_expectation[idx] + response=item, + json_expectation=json_expectation[idx], + type_expectations=content_expectation[idx], ) else: response_json = response @@ -116,7 +142,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e response_json = response.dict(by_alias=True) for key, value in json_expectation.items(): - assert key in response_json, "Field {0} not found within the response object: {1}".format( + assert ( + key in response_json + ), "Field {0} not found within the response object: {1}".format( key, response_json ) @@ -128,11 +156,19 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e # Otherwise, we're just validating a single field that's a pydantic model. if isinstance(value, dict) and not isinstance(type_expectation, tuple): validate_response( - response=response_json[key], json_expectation=value, type_expectations=type_expectation + response=response_json[key], + json_expectation=value, + type_expectations=type_expectation, ) else: - validate_field(response=response_json[key], json_expectation=value, type_expectation=type_expectation) + validate_field( + response=response_json[key], + json_expectation=value, + type_expectation=type_expectation, + ) # Ensure there are no additional fields here either del response_json[key] - assert len(response_json) == 0, "Additional fields found, expected None: {0}".format(response_json) + assert ( + len(response_json) == 0 + ), "Additional fields found, expected None: {0}".format(response_json) diff --git a/seed/python-sdk/exhaustive/extra_dev_dependencies/tests/utils/assets/models/__init__.py b/seed/python-sdk/exhaustive/extra_dev_dependencies/tests/utils/assets/models/__init__.py index 2cf01263529..3a1c852e71e 100644 --- a/seed/python-sdk/exhaustive/extra_dev_dependencies/tests/utils/assets/models/__init__.py +++ b/seed/python-sdk/exhaustive/extra_dev_dependencies/tests/utils/assets/models/__init__.py @@ -5,7 +5,7 @@ from .circle import CircleParams from .object_with_defaults import ObjectWithDefaultsParams from .object_with_optional_field import ObjectWithOptionalFieldParams -from .shape import Shape_CircleParams, Shape_SquareParams, ShapeParams +from .shape import ShapeParams, Shape_CircleParams, Shape_SquareParams from .square import SquareParams from .undiscriminated_shape import UndiscriminatedShapeParams diff --git a/seed/python-sdk/exhaustive/extra_dev_dependencies/tests/utils/assets/models/circle.py b/seed/python-sdk/exhaustive/extra_dev_dependencies/tests/utils/assets/models/circle.py index af7a1bf8a8e..253f12d38b3 100644 --- a/seed/python-sdk/exhaustive/extra_dev_dependencies/tests/utils/assets/models/circle.py +++ b/seed/python-sdk/exhaustive/extra_dev_dependencies/tests/utils/assets/models/circle.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class CircleParams(typing_extensions.TypedDict): - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] diff --git a/seed/python-sdk/exhaustive/extra_dev_dependencies/tests/utils/assets/models/object_with_optional_field.py b/seed/python-sdk/exhaustive/extra_dev_dependencies/tests/utils/assets/models/object_with_optional_field.py index 3ad93d5f305..ebe7dc80547 100644 --- a/seed/python-sdk/exhaustive/extra_dev_dependencies/tests/utils/assets/models/object_with_optional_field.py +++ b/seed/python-sdk/exhaustive/extra_dev_dependencies/tests/utils/assets/models/object_with_optional_field.py @@ -7,8 +7,8 @@ import uuid import typing_extensions -from seed.core.serialization import FieldMetadata +from seed.core.serialization import FieldMetadata from .color import Color from .shape import ShapeParams from .undiscriminated_shape import UndiscriminatedShapeParams @@ -18,16 +18,30 @@ class ObjectWithOptionalFieldParams(typing_extensions.TypedDict): literal: typing.Literal["lit_one"] string: typing_extensions.NotRequired[str] integer: typing_extensions.NotRequired[int] - long_: typing_extensions.NotRequired[typing_extensions.Annotated[int, FieldMetadata(alias="long")]] + long_: typing_extensions.NotRequired[ + typing_extensions.Annotated[int, FieldMetadata(alias="long")] + ] double: typing_extensions.NotRequired[float] - bool_: typing_extensions.NotRequired[typing_extensions.Annotated[bool, FieldMetadata(alias="bool")]] + bool_: typing_extensions.NotRequired[ + typing_extensions.Annotated[bool, FieldMetadata(alias="bool")] + ] datetime: typing_extensions.NotRequired[dt.datetime] date: typing_extensions.NotRequired[dt.date] - uuid_: typing_extensions.NotRequired[typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")]] - base_64: typing_extensions.NotRequired[typing_extensions.Annotated[str, FieldMetadata(alias="base64")]] - list_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")]] - set_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")]] - map_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")]] + uuid_: typing_extensions.NotRequired[ + typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")] + ] + base_64: typing_extensions.NotRequired[ + typing_extensions.Annotated[str, FieldMetadata(alias="base64")] + ] + list_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")] + ] + set_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")] + ] + map_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")] + ] enum: typing_extensions.NotRequired[Color] union: typing_extensions.NotRequired[ShapeParams] second_union: typing_extensions.NotRequired[ShapeParams] diff --git a/seed/python-sdk/exhaustive/extra_dev_dependencies/tests/utils/assets/models/shape.py b/seed/python-sdk/exhaustive/extra_dev_dependencies/tests/utils/assets/models/shape.py index 2c33c877951..816ffc51bdc 100644 --- a/seed/python-sdk/exhaustive/extra_dev_dependencies/tests/utils/assets/models/shape.py +++ b/seed/python-sdk/exhaustive/extra_dev_dependencies/tests/utils/assets/models/shape.py @@ -7,6 +7,7 @@ import typing import typing_extensions + from seed.core.serialization import FieldMetadata @@ -15,13 +16,21 @@ class Base(typing_extensions.TypedDict): class Shape_CircleParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["circle"], FieldMetadata(alias="shapeType")] - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["circle"], FieldMetadata(alias="shapeType") + ] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] class Shape_SquareParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["square"], FieldMetadata(alias="shapeType")] - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["square"], FieldMetadata(alias="shapeType") + ] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] ShapeParams = typing.Union[Shape_CircleParams, Shape_SquareParams] diff --git a/seed/python-sdk/exhaustive/extra_dev_dependencies/tests/utils/assets/models/square.py b/seed/python-sdk/exhaustive/extra_dev_dependencies/tests/utils/assets/models/square.py index b9b7dd319bc..bcf08a723c5 100644 --- a/seed/python-sdk/exhaustive/extra_dev_dependencies/tests/utils/assets/models/square.py +++ b/seed/python-sdk/exhaustive/extra_dev_dependencies/tests/utils/assets/models/square.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class SquareParams(typing_extensions.TypedDict): - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] diff --git a/seed/python-sdk/exhaustive/extra_dev_dependencies/tests/utils/test_http_client.py b/seed/python-sdk/exhaustive/extra_dev_dependencies/tests/utils/test_http_client.py index edd11ca7afb..f5a874a75f3 100644 --- a/seed/python-sdk/exhaustive/extra_dev_dependencies/tests/utils/test_http_client.py +++ b/seed/python-sdk/exhaustive/extra_dev_dependencies/tests/utils/test_http_client.py @@ -9,12 +9,17 @@ def get_request_options() -> RequestOptions: def test_get_json_request_body() -> None: - json_body, data_body = get_request_body(json={"hello": "world"}, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json={"hello": "world"}, data=None, request_options=None, omit=None + ) assert json_body == {"hello": "world"} assert data_body is None json_body_extras, data_body_extras = get_request_body( - json={"goodbye": "world"}, data=None, request_options=get_request_options(), omit=None + json={"goodbye": "world"}, + data=None, + request_options=get_request_options(), + omit=None, ) assert json_body_extras == {"goodbye": "world", "see you": "later"} @@ -22,12 +27,17 @@ def test_get_json_request_body() -> None: def test_get_files_request_body() -> None: - json_body, data_body = get_request_body(json=None, data={"hello": "world"}, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data={"hello": "world"}, request_options=None, omit=None + ) assert data_body == {"hello": "world"} assert json_body is None json_body_extras, data_body_extras = get_request_body( - json=None, data={"goodbye": "world"}, request_options=get_request_options(), omit=None + json=None, + data={"goodbye": "world"}, + request_options=get_request_options(), + omit=None, ) assert data_body_extras == {"goodbye": "world", "see you": "later"} @@ -35,7 +45,9 @@ def test_get_files_request_body() -> None: def test_get_none_request_body() -> None: - json_body, data_body = get_request_body(json=None, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data=None, request_options=None, omit=None + ) assert data_body is None assert json_body is None diff --git a/seed/python-sdk/exhaustive/extra_dev_dependencies/tests/utils/test_query_encoding.py b/seed/python-sdk/exhaustive/extra_dev_dependencies/tests/utils/test_query_encoding.py index 247e1551b46..fbc8f402167 100644 --- a/seed/python-sdk/exhaustive/extra_dev_dependencies/tests/utils/test_query_encoding.py +++ b/seed/python-sdk/exhaustive/extra_dev_dependencies/tests/utils/test_query_encoding.py @@ -4,9 +4,15 @@ def test_query_encoding() -> None: - assert encode_query({"hello world": "hello world"}) == {"hello world": "hello world"} - assert encode_query({"hello_world": {"hello": "world"}}) == {"hello_world[hello]": "world"} - assert encode_query({"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"}) == { + assert encode_query({"hello world": "hello world"}) == { + "hello world": "hello world" + } + assert encode_query({"hello_world": {"hello": "world"}}) == { + "hello_world[hello]": "world" + } + assert encode_query( + {"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"} + ) == { "hello_world[hello][world]": "today", "hello_world[test]": "this", "hi": "there", diff --git a/seed/python-sdk/exhaustive/extra_dev_dependencies/tests/utils/test_serialization.py b/seed/python-sdk/exhaustive/extra_dev_dependencies/tests/utils/test_serialization.py index 58b1ed66e6d..5ca956916dd 100644 --- a/seed/python-sdk/exhaustive/extra_dev_dependencies/tests/utils/test_serialization.py +++ b/seed/python-sdk/exhaustive/extra_dev_dependencies/tests/utils/test_serialization.py @@ -1,10 +1,12 @@ # This file was auto-generated by Fern from our API Definition. -from typing import Any, List +from typing import List, Any -from seed.core.serialization import convert_and_respect_annotation_metadata +from seed.core.serialization import ( + convert_and_respect_annotation_metadata, +) +from .assets.models import ShapeParams, ObjectWithOptionalFieldParams -from .assets.models import ObjectWithOptionalFieldParams, ShapeParams UNION_TEST: ShapeParams = {"radius_measurement": 1.0, "shape_type": "circle", "id": "1"} UNION_TEST_CONVERTED = {"shapeType": "circle", "radiusMeasurement": 1.0, "id": "1"} @@ -18,20 +20,54 @@ def test_convert_and_respect_annotation_metadata() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) - assert converted == {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"} + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) + assert converted == { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + } def test_convert_and_respect_annotation_metadata_in_list() -> None: data: List[ObjectWithOptionalFieldParams] = [ - {"string": "string", "long_": 12345, "bool_": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long_": 67890, "list_": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long_": 12345, + "bool_": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long_": 67890, + "list_": [], + "literal": "lit_one", + "any": "any", + }, ] - converted = convert_and_respect_annotation_metadata(object_=data, annotation=List[ObjectWithOptionalFieldParams]) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=List[ObjectWithOptionalFieldParams] + ) assert converted == [ - {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long": 67890, "list": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long": 67890, + "list": [], + "literal": "lit_one", + "any": "any", + }, ] @@ -43,7 +79,9 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) assert converted == { "string": "string", @@ -55,12 +93,16 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: def test_convert_and_respect_annotation_metadata_in_union() -> None: - converted = convert_and_respect_annotation_metadata(object_=UNION_TEST, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=UNION_TEST, annotation=ShapeParams + ) assert converted == UNION_TEST_CONVERTED def test_convert_and_respect_annotation_metadata_with_empty_object() -> None: data: Any = {} - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ShapeParams + ) assert converted == data diff --git a/seed/python-sdk/exhaustive/five-second-timeout/pyproject.toml b/seed/python-sdk/exhaustive/five-second-timeout/pyproject.toml index c6cd3a2b7b9..fc29a237334 100644 --- a/seed/python-sdk/exhaustive/five-second-timeout/pyproject.toml +++ b/seed/python-sdk/exhaustive/five-second-timeout/pyproject.toml @@ -43,6 +43,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/python-sdk/exhaustive/five-second-timeout/src/seed/__init__.py b/seed/python-sdk/exhaustive/five-second-timeout/src/seed/__init__.py index eb56b0ce275..dc1ef03a650 100644 --- a/seed/python-sdk/exhaustive/five-second-timeout/src/seed/__init__.py +++ b/seed/python-sdk/exhaustive/five-second-timeout/src/seed/__init__.py @@ -1,6 +1,14 @@ # This file was auto-generated by Fern from our API Definition. -from . import endpoints, general_errors, inlined_requests, no_auth, no_req_body, req_with_headers, types +from . import ( + endpoints, + general_errors, + inlined_requests, + no_auth, + no_req_body, + req_with_headers, + types, +) from .client import AsyncSeedExhaustive, SeedExhaustive from .general_errors import BadObjectRequestInfo, BadRequestBody from .version import __version__ diff --git a/seed/python-sdk/exhaustive/five-second-timeout/src/seed/client.py b/seed/python-sdk/exhaustive/five-second-timeout/src/seed/client.py index 801287e59cb..b3155401041 100644 --- a/seed/python-sdk/exhaustive/five-second-timeout/src/seed/client.py +++ b/seed/python-sdk/exhaustive/five-second-timeout/src/seed/client.py @@ -1,15 +1,19 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from .endpoints.client import AsyncEndpointsClient, EndpointsClient -from .inlined_requests.client import AsyncInlinedRequestsClient, InlinedRequestsClient -from .no_auth.client import AsyncNoAuthClient, NoAuthClient -from .no_req_body.client import AsyncNoReqBodyClient, NoReqBodyClient -from .req_with_headers.client import AsyncReqWithHeadersClient, ReqWithHeadersClient +from .core.client_wrapper import SyncClientWrapper +from .endpoints.client import EndpointsClient +from .inlined_requests.client import InlinedRequestsClient +from .no_auth.client import NoAuthClient +from .no_req_body.client import NoReqBodyClient +from .req_with_headers.client import ReqWithHeadersClient +from .core.client_wrapper import AsyncClientWrapper +from .endpoints.client import AsyncEndpointsClient +from .inlined_requests.client import AsyncInlinedRequestsClient +from .no_auth.client import AsyncNoAuthClient +from .no_req_body.client import AsyncNoReqBodyClient +from .req_with_headers.client import AsyncReqWithHeadersClient class SeedExhaustive: @@ -48,24 +52,32 @@ def __init__( token: typing.Optional[typing.Union[str, typing.Callable[[], str]]] = None, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.Client] = None + httpx_client: typing.Optional[httpx.Client] = None, ): - _defaulted_timeout = timeout if timeout is not None else 5 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 5 if httpx_client is None else None + ) self._client_wrapper = SyncClientWrapper( base_url=base_url, token=token, httpx_client=httpx_client if httpx_client is not None - else httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.Client( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.Client(timeout=_defaulted_timeout), timeout=_defaulted_timeout, ) self.endpoints = EndpointsClient(client_wrapper=self._client_wrapper) - self.inlined_requests = InlinedRequestsClient(client_wrapper=self._client_wrapper) + self.inlined_requests = InlinedRequestsClient( + client_wrapper=self._client_wrapper + ) self.no_auth = NoAuthClient(client_wrapper=self._client_wrapper) self.no_req_body = NoReqBodyClient(client_wrapper=self._client_wrapper) - self.req_with_headers = ReqWithHeadersClient(client_wrapper=self._client_wrapper) + self.req_with_headers = ReqWithHeadersClient( + client_wrapper=self._client_wrapper + ) class AsyncSeedExhaustive: @@ -104,21 +116,29 @@ def __init__( token: typing.Optional[typing.Union[str, typing.Callable[[], str]]] = None, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.AsyncClient] = None + httpx_client: typing.Optional[httpx.AsyncClient] = None, ): - _defaulted_timeout = timeout if timeout is not None else 5 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 5 if httpx_client is None else None + ) self._client_wrapper = AsyncClientWrapper( base_url=base_url, token=token, httpx_client=httpx_client if httpx_client is not None - else httpx.AsyncClient(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.AsyncClient( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.AsyncClient(timeout=_defaulted_timeout), timeout=_defaulted_timeout, ) self.endpoints = AsyncEndpointsClient(client_wrapper=self._client_wrapper) - self.inlined_requests = AsyncInlinedRequestsClient(client_wrapper=self._client_wrapper) + self.inlined_requests = AsyncInlinedRequestsClient( + client_wrapper=self._client_wrapper + ) self.no_auth = AsyncNoAuthClient(client_wrapper=self._client_wrapper) self.no_req_body = AsyncNoReqBodyClient(client_wrapper=self._client_wrapper) - self.req_with_headers = AsyncReqWithHeadersClient(client_wrapper=self._client_wrapper) + self.req_with_headers = AsyncReqWithHeadersClient( + client_wrapper=self._client_wrapper + ) diff --git a/seed/python-sdk/exhaustive/five-second-timeout/src/seed/core/api_error.py b/seed/python-sdk/exhaustive/five-second-timeout/src/seed/core/api_error.py index 2e9fc5431cd..da734b58068 100644 --- a/seed/python-sdk/exhaustive/five-second-timeout/src/seed/core/api_error.py +++ b/seed/python-sdk/exhaustive/five-second-timeout/src/seed/core/api_error.py @@ -7,7 +7,9 @@ class ApiError(Exception): status_code: typing.Optional[int] body: typing.Any - def __init__(self, *, status_code: typing.Optional[int] = None, body: typing.Any = None): + def __init__( + self, *, status_code: typing.Optional[int] = None, body: typing.Any = None + ): self.status_code = status_code self.body = body diff --git a/seed/python-sdk/exhaustive/five-second-timeout/src/seed/core/client_wrapper.py b/seed/python-sdk/exhaustive/five-second-timeout/src/seed/core/client_wrapper.py index 8d01b584b82..d037184a816 100644 --- a/seed/python-sdk/exhaustive/five-second-timeout/src/seed/core/client_wrapper.py +++ b/seed/python-sdk/exhaustive/five-second-timeout/src/seed/core/client_wrapper.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .http_client import AsyncHttpClient, HttpClient +from .http_client import HttpClient +from .http_client import AsyncHttpClient class BaseClientWrapper: diff --git a/seed/python-sdk/exhaustive/five-second-timeout/src/seed/core/datetime_utils.py b/seed/python-sdk/exhaustive/five-second-timeout/src/seed/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/python-sdk/exhaustive/five-second-timeout/src/seed/core/datetime_utils.py +++ b/seed/python-sdk/exhaustive/five-second-timeout/src/seed/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/python-sdk/exhaustive/five-second-timeout/src/seed/core/file.py b/seed/python-sdk/exhaustive/five-second-timeout/src/seed/core/file.py index cb0d40bbbf3..6e0f92bfcb1 100644 --- a/seed/python-sdk/exhaustive/five-second-timeout/src/seed/core/file.py +++ b/seed/python-sdk/exhaustive/five-second-timeout/src/seed/core/file.py @@ -13,12 +13,17 @@ # (filename, file (or bytes), content_type) typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str]], # (filename, file (or bytes), content_type, headers) - typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str], typing.Mapping[str, str]], + typing.Tuple[ + typing.Optional[str], + FileContent, + typing.Optional[str], + typing.Mapping[str, str], + ], ] def convert_file_dict_to_httpx_tuples( - d: typing.Dict[str, typing.Union[File, typing.List[File]]] + d: typing.Dict[str, typing.Union[File, typing.List[File]]], ) -> typing.List[typing.Tuple[str, File]]: """ The format we use is a list of tuples, where the first element is the diff --git a/seed/python-sdk/exhaustive/five-second-timeout/src/seed/core/http_client.py b/seed/python-sdk/exhaustive/five-second-timeout/src/seed/core/http_client.py index 9333d8a7f15..091f71bc185 100644 --- a/seed/python-sdk/exhaustive/five-second-timeout/src/seed/core/http_client.py +++ b/seed/python-sdk/exhaustive/five-second-timeout/src/seed/core/http_client.py @@ -77,7 +77,9 @@ def _retry_timeout(response: httpx.Response, retries: int) -> float: return retry_after # Apply exponential backoff, capped at MAX_RETRY_DELAY_SECONDS. - retry_delay = min(INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS) + retry_delay = min( + INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS + ) # Add a randomness / jitter to the retry delay to avoid overwhelming the server with retries. timeout = retry_delay * (1 - 0.25 * random()) @@ -90,7 +92,8 @@ def _should_retry(response: httpx.Response) -> bool: def remove_omit_from_dict( - original: typing.Dict[str, typing.Optional[typing.Any]], omit: typing.Optional[typing.Any] + original: typing.Dict[str, typing.Optional[typing.Any]], + omit: typing.Optional[typing.Any], ) -> typing.Dict[str, typing.Any]: if omit is None: return original @@ -108,7 +111,8 @@ def maybe_filter_request_body( ) -> typing.Optional[typing.Any]: if data is None: return ( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else None ) @@ -118,7 +122,8 @@ def maybe_filter_request_body( data_content = { **(jsonable_encoder(remove_omit_from_dict(data, omit))), # type: ignore **( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else {} ), @@ -162,7 +167,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url def request( @@ -174,8 +181,12 @@ def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -184,11 +195,14 @@ def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) response = self.httpx_client.request( method=method, @@ -198,7 +212,11 @@ def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -209,7 +227,10 @@ def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -222,11 +243,15 @@ def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: time.sleep(_retry_timeout(response=response, retries=retries)) @@ -256,8 +281,12 @@ def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -266,11 +295,14 @@ def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) with self.httpx_client.stream( method=method, @@ -280,7 +312,11 @@ def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -291,7 +327,9 @@ def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -304,7 +342,9 @@ def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream @@ -327,7 +367,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url async def request( @@ -339,8 +381,12 @@ async def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -349,11 +395,14 @@ async def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) # Add the input to each of these and do None-safety checks response = await self.httpx_client.request( @@ -364,7 +413,11 @@ async def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -375,7 +428,10 @@ async def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -388,11 +444,15 @@ async def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: await asyncio.sleep(_retry_timeout(response=response, retries=retries)) @@ -421,8 +481,12 @@ async def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -431,11 +495,14 @@ async def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) async with self.httpx_client.stream( method=method, @@ -445,7 +512,11 @@ async def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -456,7 +527,9 @@ async def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -469,7 +542,9 @@ async def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream diff --git a/seed/python-sdk/exhaustive/five-second-timeout/src/seed/core/jsonable_encoder.py b/seed/python-sdk/exhaustive/five-second-timeout/src/seed/core/jsonable_encoder.py index d3fd328fd41..12a8b52fc22 100644 --- a/seed/python-sdk/exhaustive/five-second-timeout/src/seed/core/jsonable_encoder.py +++ b/seed/python-sdk/exhaustive/five-second-timeout/src/seed/core/jsonable_encoder.py @@ -19,13 +19,19 @@ import pydantic from .datetime_utils import serialize_datetime -from .pydantic_utilities import IS_PYDANTIC_V2, encode_by_type, to_jsonable_with_fallback +from .pydantic_utilities import ( + IS_PYDANTIC_V2, + encode_by_type, + to_jsonable_with_fallback, +) SetIntStr = Set[Union[int, str]] DictIntStrAny = Dict[Union[int, str], Any] -def jsonable_encoder(obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None) -> Any: +def jsonable_encoder( + obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None +) -> Any: custom_encoder = custom_encoder or {} if custom_encoder: if type(obj) in custom_encoder: diff --git a/seed/python-sdk/exhaustive/five-second-timeout/src/seed/core/pydantic_utilities.py b/seed/python-sdk/exhaustive/five-second-timeout/src/seed/core/pydantic_utilities.py index 170a563d6eb..c63935c32a2 100644 --- a/seed/python-sdk/exhaustive/five-second-timeout/src/seed/core/pydantic_utilities.py +++ b/seed/python-sdk/exhaustive/five-second-timeout/src/seed/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) # type: ignore # Pydantic v1 diff --git a/seed/python-sdk/exhaustive/five-second-timeout/src/seed/core/query_encoder.py b/seed/python-sdk/exhaustive/five-second-timeout/src/seed/core/query_encoder.py index 24076d72ee9..7cb98f52cd7 100644 --- a/seed/python-sdk/exhaustive/five-second-timeout/src/seed/core/query_encoder.py +++ b/seed/python-sdk/exhaustive/five-second-timeout/src/seed/core/query_encoder.py @@ -7,7 +7,9 @@ # Flattens dicts to be of the form {"key[subkey][subkey2]": value} where value is not a dict -def traverse_query_dict(dict_flat: Dict[str, Any], key_prefix: Optional[str] = None) -> Dict[str, Any]: +def traverse_query_dict( + dict_flat: Dict[str, Any], key_prefix: Optional[str] = None +) -> Dict[str, Any]: result = {} for k, v in dict_flat.items(): key = f"{key_prefix}[{k}]" if key_prefix is not None else k @@ -30,4 +32,8 @@ def single_query_encoder(query_key: str, query_value: Any) -> Dict[str, Any]: def encode_query(query: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: - return dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) if query is not None else None + return ( + dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) + if query is not None + else None + ) diff --git a/seed/python-sdk/exhaustive/five-second-timeout/src/seed/core/serialization.py b/seed/python-sdk/exhaustive/five-second-timeout/src/seed/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/python-sdk/exhaustive/five-second-timeout/src/seed/core/serialization.py +++ b/seed/python-sdk/exhaustive/five-second-timeout/src/seed/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/python-sdk/exhaustive/five-second-timeout/src/seed/endpoints/__init__.py b/seed/python-sdk/exhaustive/five-second-timeout/src/seed/endpoints/__init__.py index 92307cab7fe..a9496ece178 100644 --- a/seed/python-sdk/exhaustive/five-second-timeout/src/seed/endpoints/__init__.py +++ b/seed/python-sdk/exhaustive/five-second-timeout/src/seed/endpoints/__init__.py @@ -2,4 +2,12 @@ from . import container, enum, http_methods, object, params, primitive, union -__all__ = ["container", "enum", "http_methods", "object", "params", "primitive", "union"] +__all__ = [ + "container", + "enum", + "http_methods", + "object", + "params", + "primitive", + "union", +] diff --git a/seed/python-sdk/exhaustive/five-second-timeout/src/seed/endpoints/client.py b/seed/python-sdk/exhaustive/five-second-timeout/src/seed/endpoints/client.py index 18dc397fdf1..69930de54d7 100644 --- a/seed/python-sdk/exhaustive/five-second-timeout/src/seed/endpoints/client.py +++ b/seed/python-sdk/exhaustive/five-second-timeout/src/seed/endpoints/client.py @@ -1,13 +1,21 @@ # This file was auto-generated by Fern from our API Definition. -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from .container.client import AsyncContainerClient, ContainerClient -from .enum.client import AsyncEnumClient, EnumClient -from .http_methods.client import AsyncHttpMethodsClient, HttpMethodsClient -from .object.client import AsyncObjectClient, ObjectClient -from .params.client import AsyncParamsClient, ParamsClient -from .primitive.client import AsyncPrimitiveClient, PrimitiveClient -from .union.client import AsyncUnionClient, UnionClient +from ..core.client_wrapper import SyncClientWrapper +from .container.client import ContainerClient +from .enum.client import EnumClient +from .http_methods.client import HttpMethodsClient +from .object.client import ObjectClient +from .params.client import ParamsClient +from .primitive.client import PrimitiveClient +from .union.client import UnionClient +from ..core.client_wrapper import AsyncClientWrapper +from .container.client import AsyncContainerClient +from .enum.client import AsyncEnumClient +from .http_methods.client import AsyncHttpMethodsClient +from .object.client import AsyncObjectClient +from .params.client import AsyncParamsClient +from .primitive.client import AsyncPrimitiveClient +from .union.client import AsyncUnionClient class EndpointsClient: diff --git a/seed/python-sdk/exhaustive/five-second-timeout/src/seed/endpoints/container/client.py b/seed/python-sdk/exhaustive/five-second-timeout/src/seed/endpoints/container/client.py index c6cf14f63ac..4af9c12d534 100644 --- a/seed/python-sdk/exhaustive/five-second-timeout/src/seed/endpoints/container/client.py +++ b/seed/python-sdk/exhaustive/five-second-timeout/src/seed/endpoints/container/client.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. import typing +from ...core.client_wrapper import SyncClientWrapper +from ...core.request_options import RequestOptions +from ...core.pydantic_utilities import parse_obj_as from json.decoder import JSONDecodeError - from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ...core.pydantic_utilities import parse_obj_as -from ...core.request_options import RequestOptions from ...types.object.types.object_with_required_field import ObjectWithRequiredField +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -18,7 +18,10 @@ def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper def get_and_return_list_of_primitives( - self, *, request: typing.Sequence[str], request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Sequence[str], + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[str]: """ Parameters @@ -45,11 +48,18 @@ def get_and_return_list_of_primitives( ) """ _response = self._client_wrapper.httpx_client.request( - "container/list-of-primitives", method="POST", json=request, request_options=request_options, omit=OMIT + "container/list-of-primitives", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.List[str], parse_obj_as(type_=typing.List[str], object_=_response.json())) # type: ignore + return typing.cast( + typing.List[str], + parse_obj_as(type_=typing.List[str], object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -59,7 +69,7 @@ def get_and_return_list_of_objects( self, *, request: typing.Sequence[ObjectWithRequiredField], - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[ObjectWithRequiredField]: """ Parameters @@ -91,18 +101,31 @@ def get_and_return_list_of_objects( ) """ _response = self._client_wrapper.httpx_client.request( - "container/list-of-objects", method="POST", json=request, request_options=request_options, omit=OMIT + "container/list-of-objects", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.List[ObjectWithRequiredField], parse_obj_as(type_=typing.List[ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.List[ObjectWithRequiredField], + parse_obj_as( + type_=typing.List[ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_and_return_set_of_primitives( - self, *, request: typing.Set[str], request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Set[str], + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Set[str]: """ Parameters @@ -129,11 +152,18 @@ def get_and_return_set_of_primitives( ) """ _response = self._client_wrapper.httpx_client.request( - "container/set-of-primitives", method="POST", json=request, request_options=request_options, omit=OMIT + "container/set-of-primitives", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Set[str], parse_obj_as(type_=typing.Set[str], object_=_response.json())) # type: ignore + return typing.cast( + typing.Set[str], + parse_obj_as(type_=typing.Set[str], object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -143,7 +173,7 @@ def get_and_return_set_of_objects( self, *, request: typing.Sequence[ObjectWithRequiredField], - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[ObjectWithRequiredField]: """ Parameters @@ -175,18 +205,31 @@ def get_and_return_set_of_objects( ) """ _response = self._client_wrapper.httpx_client.request( - "container/set-of-objects", method="POST", json=request, request_options=request_options, omit=OMIT + "container/set-of-objects", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.List[ObjectWithRequiredField], parse_obj_as(type_=typing.List[ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.List[ObjectWithRequiredField], + parse_obj_as( + type_=typing.List[ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_and_return_map_prim_to_prim( - self, *, request: typing.Dict[str, str], request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Dict[str, str], + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Dict[str, str]: """ Parameters @@ -213,11 +256,18 @@ def get_and_return_map_prim_to_prim( ) """ _response = self._client_wrapper.httpx_client.request( - "container/map-prim-to-prim", method="POST", json=request, request_options=request_options, omit=OMIT + "container/map-prim-to-prim", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Dict[str, str], parse_obj_as(type_=typing.Dict[str, str], object_=_response.json())) # type: ignore + return typing.cast( + typing.Dict[str, str], + parse_obj_as(type_=typing.Dict[str, str], object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -227,7 +277,7 @@ def get_and_return_map_of_prim_to_object( self, *, request: typing.Dict[str, ObjectWithRequiredField], - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Dict[str, ObjectWithRequiredField]: """ Parameters @@ -259,11 +309,21 @@ def get_and_return_map_of_prim_to_object( ) """ _response = self._client_wrapper.httpx_client.request( - "container/map-prim-to-object", method="POST", json=request, request_options=request_options, omit=OMIT + "container/map-prim-to-object", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Dict[str, ObjectWithRequiredField], parse_obj_as(type_=typing.Dict[str, ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.Dict[str, ObjectWithRequiredField], + parse_obj_as( + type_=typing.Dict[str, ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -273,7 +333,7 @@ def get_and_return_optional( self, *, request: typing.Optional[ObjectWithRequiredField] = None, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Optional[ObjectWithRequiredField]: """ Parameters @@ -303,11 +363,21 @@ def get_and_return_optional( ) """ _response = self._client_wrapper.httpx_client.request( - "container/opt-objects", method="POST", json=request, request_options=request_options, omit=OMIT + "container/opt-objects", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Optional[ObjectWithRequiredField], parse_obj_as(type_=typing.Optional[ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.Optional[ObjectWithRequiredField], + parse_obj_as( + type_=typing.Optional[ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -319,7 +389,10 @@ def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper async def get_and_return_list_of_primitives( - self, *, request: typing.Sequence[str], request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Sequence[str], + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[str]: """ Parameters @@ -354,11 +427,18 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/list-of-primitives", method="POST", json=request, request_options=request_options, omit=OMIT + "container/list-of-primitives", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.List[str], parse_obj_as(type_=typing.List[str], object_=_response.json())) # type: ignore + return typing.cast( + typing.List[str], + parse_obj_as(type_=typing.List[str], object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -368,7 +448,7 @@ async def get_and_return_list_of_objects( self, *, request: typing.Sequence[ObjectWithRequiredField], - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[ObjectWithRequiredField]: """ Parameters @@ -408,18 +488,31 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/list-of-objects", method="POST", json=request, request_options=request_options, omit=OMIT + "container/list-of-objects", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.List[ObjectWithRequiredField], parse_obj_as(type_=typing.List[ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.List[ObjectWithRequiredField], + parse_obj_as( + type_=typing.List[ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_and_return_set_of_primitives( - self, *, request: typing.Set[str], request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Set[str], + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Set[str]: """ Parameters @@ -454,11 +547,18 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/set-of-primitives", method="POST", json=request, request_options=request_options, omit=OMIT + "container/set-of-primitives", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Set[str], parse_obj_as(type_=typing.Set[str], object_=_response.json())) # type: ignore + return typing.cast( + typing.Set[str], + parse_obj_as(type_=typing.Set[str], object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -468,7 +568,7 @@ async def get_and_return_set_of_objects( self, *, request: typing.Sequence[ObjectWithRequiredField], - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[ObjectWithRequiredField]: """ Parameters @@ -508,18 +608,31 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/set-of-objects", method="POST", json=request, request_options=request_options, omit=OMIT + "container/set-of-objects", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.List[ObjectWithRequiredField], parse_obj_as(type_=typing.List[ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.List[ObjectWithRequiredField], + parse_obj_as( + type_=typing.List[ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_and_return_map_prim_to_prim( - self, *, request: typing.Dict[str, str], request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Dict[str, str], + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Dict[str, str]: """ Parameters @@ -554,11 +667,18 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/map-prim-to-prim", method="POST", json=request, request_options=request_options, omit=OMIT + "container/map-prim-to-prim", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Dict[str, str], parse_obj_as(type_=typing.Dict[str, str], object_=_response.json())) # type: ignore + return typing.cast( + typing.Dict[str, str], + parse_obj_as(type_=typing.Dict[str, str], object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -568,7 +688,7 @@ async def get_and_return_map_of_prim_to_object( self, *, request: typing.Dict[str, ObjectWithRequiredField], - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Dict[str, ObjectWithRequiredField]: """ Parameters @@ -608,11 +728,21 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/map-prim-to-object", method="POST", json=request, request_options=request_options, omit=OMIT + "container/map-prim-to-object", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Dict[str, ObjectWithRequiredField], parse_obj_as(type_=typing.Dict[str, ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.Dict[str, ObjectWithRequiredField], + parse_obj_as( + type_=typing.Dict[str, ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -622,7 +752,7 @@ async def get_and_return_optional( self, *, request: typing.Optional[ObjectWithRequiredField] = None, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Optional[ObjectWithRequiredField]: """ Parameters @@ -660,11 +790,21 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/opt-objects", method="POST", json=request, request_options=request_options, omit=OMIT + "container/opt-objects", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Optional[ObjectWithRequiredField], parse_obj_as(type_=typing.Optional[ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.Optional[ObjectWithRequiredField], + parse_obj_as( + type_=typing.Optional[ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/five-second-timeout/src/seed/endpoints/enum/client.py b/seed/python-sdk/exhaustive/five-second-timeout/src/seed/endpoints/enum/client.py index 44e2690ff6c..3e3208e3bcf 100644 --- a/seed/python-sdk/exhaustive/five-second-timeout/src/seed/endpoints/enum/client.py +++ b/seed/python-sdk/exhaustive/five-second-timeout/src/seed/endpoints/enum/client.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. import typing +from ...core.client_wrapper import SyncClientWrapper +from ...types.enum.types.weather_report import WeatherReport +from ...core.request_options import RequestOptions +from ...core.pydantic_utilities import parse_obj_as from json.decoder import JSONDecodeError - from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ...core.pydantic_utilities import parse_obj_as -from ...core.request_options import RequestOptions -from ...types.enum.types.weather_report import WeatherReport +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -18,7 +18,10 @@ def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper def get_and_return_enum( - self, *, request: WeatherReport, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: WeatherReport, + request_options: typing.Optional[RequestOptions] = None, ) -> WeatherReport: """ Parameters @@ -45,11 +48,18 @@ def get_and_return_enum( ) """ _response = self._client_wrapper.httpx_client.request( - "enum", method="POST", json=request, request_options=request_options, omit=OMIT + "enum", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(WeatherReport, parse_obj_as(type_=WeatherReport, object_=_response.json())) # type: ignore + return typing.cast( + WeatherReport, + parse_obj_as(type_=WeatherReport, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -61,7 +71,10 @@ def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper async def get_and_return_enum( - self, *, request: WeatherReport, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: WeatherReport, + request_options: typing.Optional[RequestOptions] = None, ) -> WeatherReport: """ Parameters @@ -96,11 +109,18 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "enum", method="POST", json=request, request_options=request_options, omit=OMIT + "enum", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(WeatherReport, parse_obj_as(type_=WeatherReport, object_=_response.json())) # type: ignore + return typing.cast( + WeatherReport, + parse_obj_as(type_=WeatherReport, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/five-second-timeout/src/seed/endpoints/http_methods/client.py b/seed/python-sdk/exhaustive/five-second-timeout/src/seed/endpoints/http_methods/client.py index a2549280a1b..570a227844f 100644 --- a/seed/python-sdk/exhaustive/five-second-timeout/src/seed/endpoints/http_methods/client.py +++ b/seed/python-sdk/exhaustive/five-second-timeout/src/seed/endpoints/http_methods/client.py @@ -1,16 +1,16 @@ # This file was auto-generated by Fern from our API Definition. -import datetime as dt import typing -import uuid -from json.decoder import JSONDecodeError - -from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper +from ...core.client_wrapper import SyncClientWrapper +from ...core.request_options import RequestOptions from ...core.jsonable_encoder import jsonable_encoder from ...core.pydantic_utilities import parse_obj_as -from ...core.request_options import RequestOptions +from json.decoder import JSONDecodeError +from ...core.api_error import ApiError from ...types.object.types.object_with_optional_field import ObjectWithOptionalField +import datetime as dt +import uuid +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -20,7 +20,9 @@ class HttpMethodsClient: def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper - def test_get(self, id: str, *, request_options: typing.Optional[RequestOptions] = None) -> str: + def test_get( + self, id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -46,11 +48,15 @@ def test_get(self, id: str, *, request_options: typing.Optional[RequestOptions] ) """ _response = self._client_wrapper.httpx_client.request( - f"http-methods/{jsonable_encoder(id)}", method="GET", request_options=request_options + f"http-methods/{jsonable_encoder(id)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -84,18 +90,33 @@ def test_post( ) """ _response = self._client_wrapper.httpx_client.request( - "http-methods", method="POST", json={"string": string}, request_options=request_options, omit=OMIT + "http-methods", + method="POST", + json={ + "string": string, + }, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def test_put( - self, id: str, *, string: str, request_options: typing.Optional[RequestOptions] = None + self, + id: str, + *, + string: str, + request_options: typing.Optional[RequestOptions] = None, ) -> ObjectWithOptionalField: """ Parameters @@ -127,13 +148,20 @@ def test_put( _response = self._client_wrapper.httpx_client.request( f"http-methods/{jsonable_encoder(id)}", method="PUT", - json={"string": string}, + json={ + "string": string, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -254,13 +282,20 @@ def test_patch( ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def test_delete(self, id: str, *, request_options: typing.Optional[RequestOptions] = None) -> bool: + def test_delete( + self, id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> bool: """ Parameters ---------- @@ -286,11 +321,15 @@ def test_delete(self, id: str, *, request_options: typing.Optional[RequestOption ) """ _response = self._client_wrapper.httpx_client.request( - f"http-methods/{jsonable_encoder(id)}", method="DELETE", request_options=request_options + f"http-methods/{jsonable_encoder(id)}", + method="DELETE", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -301,7 +340,9 @@ class AsyncHttpMethodsClient: def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper - async def test_get(self, id: str, *, request_options: typing.Optional[RequestOptions] = None) -> str: + async def test_get( + self, id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -335,11 +376,15 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - f"http-methods/{jsonable_encoder(id)}", method="GET", request_options=request_options + f"http-methods/{jsonable_encoder(id)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -381,18 +426,33 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "http-methods", method="POST", json={"string": string}, request_options=request_options, omit=OMIT + "http-methods", + method="POST", + json={ + "string": string, + }, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def test_put( - self, id: str, *, string: str, request_options: typing.Optional[RequestOptions] = None + self, + id: str, + *, + string: str, + request_options: typing.Optional[RequestOptions] = None, ) -> ObjectWithOptionalField: """ Parameters @@ -432,13 +492,20 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( f"http-methods/{jsonable_encoder(id)}", method="PUT", - json={"string": string}, + json={ + "string": string, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -566,13 +633,20 @@ async def main() -> None: ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - async def test_delete(self, id: str, *, request_options: typing.Optional[RequestOptions] = None) -> bool: + async def test_delete( + self, id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> bool: """ Parameters ---------- @@ -606,11 +680,15 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - f"http-methods/{jsonable_encoder(id)}", method="DELETE", request_options=request_options + f"http-methods/{jsonable_encoder(id)}", + method="DELETE", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/five-second-timeout/src/seed/endpoints/object/client.py b/seed/python-sdk/exhaustive/five-second-timeout/src/seed/endpoints/object/client.py index a724f959193..dcb1324b74b 100644 --- a/seed/python-sdk/exhaustive/five-second-timeout/src/seed/endpoints/object/client.py +++ b/seed/python-sdk/exhaustive/five-second-timeout/src/seed/endpoints/object/client.py @@ -1,20 +1,24 @@ # This file was auto-generated by Fern from our API Definition. -import datetime as dt import typing +from ...core.client_wrapper import SyncClientWrapper +import datetime as dt import uuid -from json.decoder import JSONDecodeError - -from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ...core.jsonable_encoder import jsonable_encoder -from ...core.pydantic_utilities import parse_obj_as from ...core.request_options import RequestOptions -from ...types.object.types.nested_object_with_optional_field import NestedObjectWithOptionalField -from ...types.object.types.nested_object_with_required_field import NestedObjectWithRequiredField -from ...types.object.types.object_with_map_of_map import ObjectWithMapOfMap from ...types.object.types.object_with_optional_field import ObjectWithOptionalField +from ...core.pydantic_utilities import parse_obj_as +from json.decoder import JSONDecodeError +from ...core.api_error import ApiError from ...types.object.types.object_with_required_field import ObjectWithRequiredField +from ...types.object.types.object_with_map_of_map import ObjectWithMapOfMap +from ...types.object.types.nested_object_with_optional_field import ( + NestedObjectWithOptionalField, +) +from ...types.object.types.nested_object_with_required_field import ( + NestedObjectWithRequiredField, +) +from ...core.jsonable_encoder import jsonable_encoder +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -135,7 +139,12 @@ def get_and_return_with_optional_field( ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -171,20 +180,30 @@ def get_and_return_with_required_field( _response = self._client_wrapper.httpx_client.request( "object/get-and-return-with-required-field", method="POST", - json={"string": string}, + json={ + "string": string, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithRequiredField, parse_obj_as(type_=ObjectWithRequiredField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithRequiredField, + parse_obj_as( + type_=ObjectWithRequiredField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_and_return_with_map_of_map( - self, *, map_: typing.Dict[str, typing.Dict[str, str]], request_options: typing.Optional[RequestOptions] = None + self, + *, + map_: typing.Dict[str, typing.Dict[str, str]], + request_options: typing.Optional[RequestOptions] = None, ) -> ObjectWithMapOfMap: """ Parameters @@ -213,13 +232,18 @@ def get_and_return_with_map_of_map( _response = self._client_wrapper.httpx_client.request( "object/get-and-return-with-map-of-map", method="POST", - json={"map": map_}, + json={ + "map": map_, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithMapOfMap, parse_obj_as(type_=ObjectWithMapOfMap, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithMapOfMap, + parse_obj_as(type_=ObjectWithMapOfMap, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -286,13 +310,21 @@ def get_and_return_nested_with_optional_field( _response = self._client_wrapper.httpx_client.request( "object/get-and-return-nested-with-optional-field", method="POST", - json={"string": string, "NestedObject": nested_object}, + json={ + "string": string, + "NestedObject": nested_object, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(NestedObjectWithOptionalField, parse_obj_as(type_=NestedObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + NestedObjectWithOptionalField, + parse_obj_as( + type_=NestedObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -363,13 +395,21 @@ def get_and_return_nested_with_required_field( _response = self._client_wrapper.httpx_client.request( f"object/get-and-return-nested-with-required-field/{jsonable_encoder(string_)}", method="POST", - json={"string": string, "NestedObject": nested_object}, + json={ + "string": string, + "NestedObject": nested_object, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(NestedObjectWithRequiredField, parse_obj_as(type_=NestedObjectWithRequiredField, object_=_response.json())) # type: ignore + return typing.cast( + NestedObjectWithRequiredField, + parse_obj_as( + type_=NestedObjectWithRequiredField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -446,7 +486,12 @@ def get_and_return_nested_with_required_field_as_list( ) try: if 200 <= _response.status_code < 300: - return typing.cast(NestedObjectWithRequiredField, parse_obj_as(type_=NestedObjectWithRequiredField, object_=_response.json())) # type: ignore + return typing.cast( + NestedObjectWithRequiredField, + parse_obj_as( + type_=NestedObjectWithRequiredField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -575,7 +620,12 @@ async def main() -> None: ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -619,20 +669,30 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( "object/get-and-return-with-required-field", method="POST", - json={"string": string}, + json={ + "string": string, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithRequiredField, parse_obj_as(type_=ObjectWithRequiredField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithRequiredField, + parse_obj_as( + type_=ObjectWithRequiredField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_and_return_with_map_of_map( - self, *, map_: typing.Dict[str, typing.Dict[str, str]], request_options: typing.Optional[RequestOptions] = None + self, + *, + map_: typing.Dict[str, typing.Dict[str, str]], + request_options: typing.Optional[RequestOptions] = None, ) -> ObjectWithMapOfMap: """ Parameters @@ -669,13 +729,18 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( "object/get-and-return-with-map-of-map", method="POST", - json={"map": map_}, + json={ + "map": map_, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithMapOfMap, parse_obj_as(type_=ObjectWithMapOfMap, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithMapOfMap, + parse_obj_as(type_=ObjectWithMapOfMap, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -749,13 +814,21 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( "object/get-and-return-nested-with-optional-field", method="POST", - json={"string": string, "NestedObject": nested_object}, + json={ + "string": string, + "NestedObject": nested_object, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(NestedObjectWithOptionalField, parse_obj_as(type_=NestedObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + NestedObjectWithOptionalField, + parse_obj_as( + type_=NestedObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -833,13 +906,21 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( f"object/get-and-return-nested-with-required-field/{jsonable_encoder(string_)}", method="POST", - json={"string": string, "NestedObject": nested_object}, + json={ + "string": string, + "NestedObject": nested_object, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(NestedObjectWithRequiredField, parse_obj_as(type_=NestedObjectWithRequiredField, object_=_response.json())) # type: ignore + return typing.cast( + NestedObjectWithRequiredField, + parse_obj_as( + type_=NestedObjectWithRequiredField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -923,7 +1004,12 @@ async def main() -> None: ) try: if 200 <= _response.status_code < 300: - return typing.cast(NestedObjectWithRequiredField, parse_obj_as(type_=NestedObjectWithRequiredField, object_=_response.json())) # type: ignore + return typing.cast( + NestedObjectWithRequiredField, + parse_obj_as( + type_=NestedObjectWithRequiredField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/five-second-timeout/src/seed/endpoints/params/client.py b/seed/python-sdk/exhaustive/five-second-timeout/src/seed/endpoints/params/client.py index 5cd7ceef42a..a9187ac94b8 100644 --- a/seed/python-sdk/exhaustive/five-second-timeout/src/seed/endpoints/params/client.py +++ b/seed/python-sdk/exhaustive/five-second-timeout/src/seed/endpoints/params/client.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. import typing -from json.decoder import JSONDecodeError - -from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper +from ...core.client_wrapper import SyncClientWrapper +from ...core.request_options import RequestOptions from ...core.jsonable_encoder import jsonable_encoder from ...core.pydantic_utilities import parse_obj_as -from ...core.request_options import RequestOptions +from json.decoder import JSONDecodeError +from ...core.api_error import ApiError +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -17,7 +17,9 @@ class ParamsClient: def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper - def get_with_path(self, param: str, *, request_options: typing.Optional[RequestOptions] = None) -> str: + def get_with_path( + self, param: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ GET with path param @@ -45,18 +47,26 @@ def get_with_path(self, param: str, *, request_options: typing.Optional[RequestO ) """ _response = self._client_wrapper.httpx_client.request( - f"params/path/{jsonable_encoder(param)}", method="GET", request_options=request_options + f"params/path/{jsonable_encoder(param)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_with_query( - self, *, query: str, number: int, request_options: typing.Optional[RequestOptions] = None + self, + *, + query: str, + number: int, + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ GET with query param @@ -88,7 +98,13 @@ def get_with_query( ) """ _response = self._client_wrapper.httpx_client.request( - "params", method="GET", params={"query": query, "number": number}, request_options=request_options + "params", + method="GET", + params={ + "query": query, + "number": number, + }, + request_options=request_options, ) try: if 200 <= _response.status_code < 300: @@ -135,7 +151,13 @@ def get_with_allow_multiple_query( ) """ _response = self._client_wrapper.httpx_client.request( - "params", method="GET", params={"query": query, "numer": numer}, request_options=request_options + "params", + method="GET", + params={ + "query": query, + "numer": numer, + }, + request_options=request_options, ) try: if 200 <= _response.status_code < 300: @@ -146,7 +168,11 @@ def get_with_allow_multiple_query( raise ApiError(status_code=_response.status_code, body=_response_json) def get_with_path_and_query( - self, param: str, *, query: str, request_options: typing.Optional[RequestOptions] = None + self, + param: str, + *, + query: str, + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ GET with path and query params @@ -180,7 +206,9 @@ def get_with_path_and_query( _response = self._client_wrapper.httpx_client.request( f"params/path-query/{jsonable_encoder(param)}", method="GET", - params={"query": query}, + params={ + "query": query, + }, request_options=request_options, ) try: @@ -192,7 +220,11 @@ def get_with_path_and_query( raise ApiError(status_code=_response.status_code, body=_response_json) def modify_with_path( - self, param: str, *, request: str, request_options: typing.Optional[RequestOptions] = None + self, + param: str, + *, + request: str, + request_options: typing.Optional[RequestOptions] = None, ) -> str: """ PUT to update with path param @@ -232,7 +264,9 @@ def modify_with_path( ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -243,7 +277,9 @@ class AsyncParamsClient: def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper - async def get_with_path(self, param: str, *, request_options: typing.Optional[RequestOptions] = None) -> str: + async def get_with_path( + self, param: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ GET with path param @@ -279,18 +315,26 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - f"params/path/{jsonable_encoder(param)}", method="GET", request_options=request_options + f"params/path/{jsonable_encoder(param)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_with_query( - self, *, query: str, number: int, request_options: typing.Optional[RequestOptions] = None + self, + *, + query: str, + number: int, + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ GET with query param @@ -330,7 +374,13 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "params", method="GET", params={"query": query, "number": number}, request_options=request_options + "params", + method="GET", + params={ + "query": query, + "number": number, + }, + request_options=request_options, ) try: if 200 <= _response.status_code < 300: @@ -385,7 +435,13 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "params", method="GET", params={"query": query, "numer": numer}, request_options=request_options + "params", + method="GET", + params={ + "query": query, + "numer": numer, + }, + request_options=request_options, ) try: if 200 <= _response.status_code < 300: @@ -396,7 +452,11 @@ async def main() -> None: raise ApiError(status_code=_response.status_code, body=_response_json) async def get_with_path_and_query( - self, param: str, *, query: str, request_options: typing.Optional[RequestOptions] = None + self, + param: str, + *, + query: str, + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ GET with path and query params @@ -438,7 +498,9 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( f"params/path-query/{jsonable_encoder(param)}", method="GET", - params={"query": query}, + params={ + "query": query, + }, request_options=request_options, ) try: @@ -450,7 +512,11 @@ async def main() -> None: raise ApiError(status_code=_response.status_code, body=_response_json) async def modify_with_path( - self, param: str, *, request: str, request_options: typing.Optional[RequestOptions] = None + self, + param: str, + *, + request: str, + request_options: typing.Optional[RequestOptions] = None, ) -> str: """ PUT to update with path param @@ -498,7 +564,9 @@ async def main() -> None: ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/five-second-timeout/src/seed/endpoints/primitive/client.py b/seed/python-sdk/exhaustive/five-second-timeout/src/seed/endpoints/primitive/client.py index 844b6a782f0..20a66f049b4 100644 --- a/seed/python-sdk/exhaustive/five-second-timeout/src/seed/endpoints/primitive/client.py +++ b/seed/python-sdk/exhaustive/five-second-timeout/src/seed/endpoints/primitive/client.py @@ -1,14 +1,14 @@ # This file was auto-generated by Fern from our API Definition. -import datetime as dt import typing -import uuid +from ...core.client_wrapper import SyncClientWrapper +from ...core.request_options import RequestOptions +from ...core.pydantic_utilities import parse_obj_as from json.decoder import JSONDecodeError - from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ...core.pydantic_utilities import parse_obj_as -from ...core.request_options import RequestOptions +import datetime as dt +import uuid +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -18,7 +18,9 @@ class PrimitiveClient: def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper - def get_and_return_string(self, *, request: str, request_options: typing.Optional[RequestOptions] = None) -> str: + def get_and_return_string( + self, *, request: str, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -44,17 +46,25 @@ def get_and_return_string(self, *, request: str, request_options: typing.Optiona ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/string", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/string", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def get_and_return_int(self, *, request: int, request_options: typing.Optional[RequestOptions] = None) -> int: + def get_and_return_int( + self, *, request: int, request_options: typing.Optional[RequestOptions] = None + ) -> int: """ Parameters ---------- @@ -80,17 +90,25 @@ def get_and_return_int(self, *, request: int, request_options: typing.Optional[R ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/integer", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/integer", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(int, parse_obj_as(type_=int, object_=_response.json())) # type: ignore + return typing.cast( + int, parse_obj_as(type_=int, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def get_and_return_long(self, *, request: int, request_options: typing.Optional[RequestOptions] = None) -> int: + def get_and_return_long( + self, *, request: int, request_options: typing.Optional[RequestOptions] = None + ) -> int: """ Parameters ---------- @@ -116,11 +134,17 @@ def get_and_return_long(self, *, request: int, request_options: typing.Optional[ ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/long", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/long", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(int, parse_obj_as(type_=int, object_=_response.json())) # type: ignore + return typing.cast( + int, parse_obj_as(type_=int, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -154,17 +178,25 @@ def get_and_return_double( ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/double", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/double", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(float, parse_obj_as(type_=float, object_=_response.json())) # type: ignore + return typing.cast( + float, parse_obj_as(type_=float, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def get_and_return_bool(self, *, request: bool, request_options: typing.Optional[RequestOptions] = None) -> bool: + def get_and_return_bool( + self, *, request: bool, request_options: typing.Optional[RequestOptions] = None + ) -> bool: """ Parameters ---------- @@ -190,18 +222,27 @@ def get_and_return_bool(self, *, request: bool, request_options: typing.Optional ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/boolean", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/boolean", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_and_return_datetime( - self, *, request: dt.datetime, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: dt.datetime, + request_options: typing.Optional[RequestOptions] = None, ) -> dt.datetime: """ Parameters @@ -232,18 +273,28 @@ def get_and_return_datetime( ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/datetime", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/datetime", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(dt.datetime, parse_obj_as(type_=dt.datetime, object_=_response.json())) # type: ignore + return typing.cast( + dt.datetime, + parse_obj_as(type_=dt.datetime, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_and_return_date( - self, *, request: dt.date, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: dt.date, + request_options: typing.Optional[RequestOptions] = None, ) -> dt.date: """ Parameters @@ -274,18 +325,27 @@ def get_and_return_date( ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/date", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/date", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(dt.date, parse_obj_as(type_=dt.date, object_=_response.json())) # type: ignore + return typing.cast( + dt.date, parse_obj_as(type_=dt.date, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_and_return_uuid( - self, *, request: uuid.UUID, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: uuid.UUID, + request_options: typing.Optional[RequestOptions] = None, ) -> uuid.UUID: """ Parameters @@ -316,17 +376,25 @@ def get_and_return_uuid( ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/uuid", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/uuid", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(uuid.UUID, parse_obj_as(type_=uuid.UUID, object_=_response.json())) # type: ignore + return typing.cast( + uuid.UUID, parse_obj_as(type_=uuid.UUID, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def get_and_return_base_64(self, *, request: str, request_options: typing.Optional[RequestOptions] = None) -> str: + def get_and_return_base_64( + self, *, request: str, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -352,11 +420,17 @@ def get_and_return_base_64(self, *, request: str, request_options: typing.Option ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/base64", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/base64", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -403,17 +477,25 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/string", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/string", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - async def get_and_return_int(self, *, request: int, request_options: typing.Optional[RequestOptions] = None) -> int: + async def get_and_return_int( + self, *, request: int, request_options: typing.Optional[RequestOptions] = None + ) -> int: """ Parameters ---------- @@ -447,11 +529,17 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/integer", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/integer", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(int, parse_obj_as(type_=int, object_=_response.json())) # type: ignore + return typing.cast( + int, parse_obj_as(type_=int, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -493,11 +581,17 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/long", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/long", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(int, parse_obj_as(type_=int, object_=_response.json())) # type: ignore + return typing.cast( + int, parse_obj_as(type_=int, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -539,11 +633,17 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/double", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/double", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(float, parse_obj_as(type_=float, object_=_response.json())) # type: ignore + return typing.cast( + float, parse_obj_as(type_=float, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -585,18 +685,27 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/boolean", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/boolean", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_and_return_datetime( - self, *, request: dt.datetime, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: dt.datetime, + request_options: typing.Optional[RequestOptions] = None, ) -> dt.datetime: """ Parameters @@ -634,18 +743,28 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/datetime", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/datetime", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(dt.datetime, parse_obj_as(type_=dt.datetime, object_=_response.json())) # type: ignore + return typing.cast( + dt.datetime, + parse_obj_as(type_=dt.datetime, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_and_return_date( - self, *, request: dt.date, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: dt.date, + request_options: typing.Optional[RequestOptions] = None, ) -> dt.date: """ Parameters @@ -683,18 +802,27 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/date", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/date", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(dt.date, parse_obj_as(type_=dt.date, object_=_response.json())) # type: ignore + return typing.cast( + dt.date, parse_obj_as(type_=dt.date, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_and_return_uuid( - self, *, request: uuid.UUID, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: uuid.UUID, + request_options: typing.Optional[RequestOptions] = None, ) -> uuid.UUID: """ Parameters @@ -732,11 +860,17 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/uuid", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/uuid", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(uuid.UUID, parse_obj_as(type_=uuid.UUID, object_=_response.json())) # type: ignore + return typing.cast( + uuid.UUID, parse_obj_as(type_=uuid.UUID, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -778,11 +912,17 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/base64", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/base64", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/five-second-timeout/src/seed/endpoints/union/client.py b/seed/python-sdk/exhaustive/five-second-timeout/src/seed/endpoints/union/client.py index 77153587a27..f4c3d9312de 100644 --- a/seed/python-sdk/exhaustive/five-second-timeout/src/seed/endpoints/union/client.py +++ b/seed/python-sdk/exhaustive/five-second-timeout/src/seed/endpoints/union/client.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. import typing +from ...core.client_wrapper import SyncClientWrapper +from ...types.union.types.animal import Animal +from ...core.request_options import RequestOptions +from ...core.pydantic_utilities import parse_obj_as from json.decoder import JSONDecodeError - from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ...core.pydantic_utilities import parse_obj_as -from ...core.request_options import RequestOptions -from ...types.union.types.animal import Animal +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -18,7 +18,10 @@ def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper def get_and_return_union( - self, *, request: Animal, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: Animal, + request_options: typing.Optional[RequestOptions] = None, ) -> Animal: """ Parameters @@ -49,11 +52,17 @@ def get_and_return_union( ) """ _response = self._client_wrapper.httpx_client.request( - "union", method="POST", json=request, request_options=request_options, omit=OMIT + "union", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(Animal, parse_obj_as(type_=Animal, object_=_response.json())) # type: ignore + return typing.cast( + Animal, parse_obj_as(type_=Animal, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -65,7 +74,10 @@ def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper async def get_and_return_union( - self, *, request: Animal, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: Animal, + request_options: typing.Optional[RequestOptions] = None, ) -> Animal: """ Parameters @@ -104,11 +116,17 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "union", method="POST", json=request, request_options=request_options, omit=OMIT + "union", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(Animal, parse_obj_as(type_=Animal, object_=_response.json())) # type: ignore + return typing.cast( + Animal, parse_obj_as(type_=Animal, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/five-second-timeout/src/seed/general_errors/types/bad_object_request_info.py b/seed/python-sdk/exhaustive/five-second-timeout/src/seed/general_errors/types/bad_object_request_info.py index 7f03429e922..73c44b89531 100644 --- a/seed/python-sdk/exhaustive/five-second-timeout/src/seed/general_errors/types/bad_object_request_info.py +++ b/seed/python-sdk/exhaustive/five-second-timeout/src/seed/general_errors/types/bad_object_request_info.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class BadObjectRequestInfo(UniversalBaseModel): message: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/five-second-timeout/src/seed/inlined_requests/client.py b/seed/python-sdk/exhaustive/five-second-timeout/src/seed/inlined_requests/client.py index f7c46698eb9..39e0c8fe637 100644 --- a/seed/python-sdk/exhaustive/five-second-timeout/src/seed/inlined_requests/client.py +++ b/seed/python-sdk/exhaustive/five-second-timeout/src/seed/inlined_requests/client.py @@ -1,15 +1,15 @@ # This file was auto-generated by Fern from our API Definition. import typing -from json.decoder import JSONDecodeError - -from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.pydantic_utilities import parse_obj_as +from ..core.client_wrapper import SyncClientWrapper +from ..types.object.types.object_with_optional_field import ObjectWithOptionalField from ..core.request_options import RequestOptions +from ..core.pydantic_utilities import parse_obj_as from ..general_errors.errors.bad_request_body import BadRequestBody from ..general_errors.types.bad_object_request_info import BadObjectRequestInfo -from ..types.object.types.object_with_optional_field import ObjectWithOptionalField +from json.decoder import JSONDecodeError +from ..core.api_error import ApiError +from ..core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -25,7 +25,7 @@ def post_with_object_bodyand_response( string: str, integer: int, nested_object: ObjectWithOptionalField, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> ObjectWithOptionalField: """ POST with custom object in request body, response is an object @@ -86,16 +86,30 @@ def post_with_object_bodyand_response( _response = self._client_wrapper.httpx_client.request( "req-bodies/object", method="POST", - json={"string": string, "integer": integer, "NestedObject": nested_object}, + json={ + "string": string, + "integer": integer, + "NestedObject": nested_object, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore if _response.status_code == 400: raise BadRequestBody( - typing.cast(BadObjectRequestInfo, parse_obj_as(type_=BadObjectRequestInfo, object_=_response.json())) # type: ignore + typing.cast( + BadObjectRequestInfo, + parse_obj_as( + type_=BadObjectRequestInfo, object_=_response.json() + ), + ) # type: ignore ) _response_json = _response.json() except JSONDecodeError: @@ -113,7 +127,7 @@ async def post_with_object_bodyand_response( string: str, integer: int, nested_object: ObjectWithOptionalField, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> ObjectWithOptionalField: """ POST with custom object in request body, response is an object @@ -181,16 +195,30 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( "req-bodies/object", method="POST", - json={"string": string, "integer": integer, "NestedObject": nested_object}, + json={ + "string": string, + "integer": integer, + "NestedObject": nested_object, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore if _response.status_code == 400: raise BadRequestBody( - typing.cast(BadObjectRequestInfo, parse_obj_as(type_=BadObjectRequestInfo, object_=_response.json())) # type: ignore + typing.cast( + BadObjectRequestInfo, + parse_obj_as( + type_=BadObjectRequestInfo, object_=_response.json() + ), + ) # type: ignore ) _response_json = _response.json() except JSONDecodeError: diff --git a/seed/python-sdk/exhaustive/five-second-timeout/src/seed/no_auth/client.py b/seed/python-sdk/exhaustive/five-second-timeout/src/seed/no_auth/client.py index 3d203bcea34..e5590cde0df 100644 --- a/seed/python-sdk/exhaustive/five-second-timeout/src/seed/no_auth/client.py +++ b/seed/python-sdk/exhaustive/five-second-timeout/src/seed/no_auth/client.py @@ -1,14 +1,14 @@ # This file was auto-generated by Fern from our API Definition. import typing -from json.decoder import JSONDecodeError - -from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.pydantic_utilities import parse_obj_as +from ..core.client_wrapper import SyncClientWrapper from ..core.request_options import RequestOptions +from ..core.pydantic_utilities import parse_obj_as from ..general_errors.errors.bad_request_body import BadRequestBody from ..general_errors.types.bad_object_request_info import BadObjectRequestInfo +from json.decoder import JSONDecodeError +from ..core.api_error import ApiError +from ..core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -19,7 +19,10 @@ def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper def post_with_no_auth( - self, *, request: typing.Any, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Any, + request_options: typing.Optional[RequestOptions] = None, ) -> bool: """ POST request with no auth @@ -48,14 +51,25 @@ def post_with_no_auth( ) """ _response = self._client_wrapper.httpx_client.request( - "no-auth", method="POST", json=request, request_options=request_options, omit=OMIT + "no-auth", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore if _response.status_code == 400: raise BadRequestBody( - typing.cast(BadObjectRequestInfo, parse_obj_as(type_=BadObjectRequestInfo, object_=_response.json())) # type: ignore + typing.cast( + BadObjectRequestInfo, + parse_obj_as( + type_=BadObjectRequestInfo, object_=_response.json() + ), + ) # type: ignore ) _response_json = _response.json() except JSONDecodeError: @@ -68,7 +82,10 @@ def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper async def post_with_no_auth( - self, *, request: typing.Any, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Any, + request_options: typing.Optional[RequestOptions] = None, ) -> bool: """ POST request with no auth @@ -105,14 +122,25 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "no-auth", method="POST", json=request, request_options=request_options, omit=OMIT + "no-auth", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore if _response.status_code == 400: raise BadRequestBody( - typing.cast(BadObjectRequestInfo, parse_obj_as(type_=BadObjectRequestInfo, object_=_response.json())) # type: ignore + typing.cast( + BadObjectRequestInfo, + parse_obj_as( + type_=BadObjectRequestInfo, object_=_response.json() + ), + ) # type: ignore ) _response_json = _response.json() except JSONDecodeError: diff --git a/seed/python-sdk/exhaustive/five-second-timeout/src/seed/no_req_body/client.py b/seed/python-sdk/exhaustive/five-second-timeout/src/seed/no_req_body/client.py index 33fa0c77d27..5afdd703fdc 100644 --- a/seed/python-sdk/exhaustive/five-second-timeout/src/seed/no_req_body/client.py +++ b/seed/python-sdk/exhaustive/five-second-timeout/src/seed/no_req_body/client.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. +from ..core.client_wrapper import SyncClientWrapper import typing -from json.decoder import JSONDecodeError - -from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.pydantic_utilities import parse_obj_as from ..core.request_options import RequestOptions from ..types.object.types.object_with_optional_field import ObjectWithOptionalField +from ..core.pydantic_utilities import parse_obj_as +from json.decoder import JSONDecodeError +from ..core.api_error import ApiError +from ..core.client_wrapper import AsyncClientWrapper class NoReqBodyClient: @@ -38,17 +38,26 @@ def get_with_no_request_body( client.no_req_body.get_with_no_request_body() """ _response = self._client_wrapper.httpx_client.request( - "no-req-body", method="GET", request_options=request_options + "no-req-body", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def post_with_no_request_body(self, *, request_options: typing.Optional[RequestOptions] = None) -> str: + def post_with_no_request_body( + self, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -70,11 +79,15 @@ def post_with_no_request_body(self, *, request_options: typing.Optional[RequestO client.no_req_body.post_with_no_request_body() """ _response = self._client_wrapper.httpx_client.request( - "no-req-body", method="POST", request_options=request_options + "no-req-body", + method="POST", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -117,17 +130,26 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "no-req-body", method="GET", request_options=request_options + "no-req-body", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - async def post_with_no_request_body(self, *, request_options: typing.Optional[RequestOptions] = None) -> str: + async def post_with_no_request_body( + self, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -157,11 +179,15 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "no-req-body", method="POST", request_options=request_options + "no-req-body", + method="POST", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/five-second-timeout/src/seed/req_with_headers/client.py b/seed/python-sdk/exhaustive/five-second-timeout/src/seed/req_with_headers/client.py index 655402249e9..984428516e3 100644 --- a/seed/python-sdk/exhaustive/five-second-timeout/src/seed/req_with_headers/client.py +++ b/seed/python-sdk/exhaustive/five-second-timeout/src/seed/req_with_headers/client.py @@ -1,11 +1,11 @@ # This file was auto-generated by Fern from our API Definition. import typing +from ..core.client_wrapper import SyncClientWrapper +from ..core.request_options import RequestOptions from json.decoder import JSONDecodeError - from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.request_options import RequestOptions +from ..core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -21,7 +21,7 @@ def get_with_custom_header( x_test_service_header: str, x_test_endpoint_header: str, request: str, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ Parameters @@ -58,8 +58,12 @@ def get_with_custom_header( method="POST", json=request, headers={ - "X-TEST-SERVICE-HEADER": str(x_test_service_header) if x_test_service_header is not None else None, - "X-TEST-ENDPOINT-HEADER": str(x_test_endpoint_header) if x_test_endpoint_header is not None else None, + "X-TEST-SERVICE-HEADER": str(x_test_service_header) + if x_test_service_header is not None + else None, + "X-TEST-ENDPOINT-HEADER": str(x_test_endpoint_header) + if x_test_endpoint_header is not None + else None, }, request_options=request_options, omit=OMIT, @@ -83,7 +87,7 @@ async def get_with_custom_header( x_test_service_header: str, x_test_endpoint_header: str, request: str, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ Parameters @@ -128,8 +132,12 @@ async def main() -> None: method="POST", json=request, headers={ - "X-TEST-SERVICE-HEADER": str(x_test_service_header) if x_test_service_header is not None else None, - "X-TEST-ENDPOINT-HEADER": str(x_test_endpoint_header) if x_test_endpoint_header is not None else None, + "X-TEST-SERVICE-HEADER": str(x_test_service_header) + if x_test_service_header is not None + else None, + "X-TEST-ENDPOINT-HEADER": str(x_test_endpoint_header) + if x_test_endpoint_header is not None + else None, }, request_options=request_options, omit=OMIT, diff --git a/seed/python-sdk/exhaustive/five-second-timeout/src/seed/types/enum/types/weather_report.py b/seed/python-sdk/exhaustive/five-second-timeout/src/seed/types/enum/types/weather_report.py index 2d54965dc22..84017ef161d 100644 --- a/seed/python-sdk/exhaustive/five-second-timeout/src/seed/types/enum/types/weather_report.py +++ b/seed/python-sdk/exhaustive/five-second-timeout/src/seed/types/enum/types/weather_report.py @@ -2,4 +2,6 @@ import typing -WeatherReport = typing.Union[typing.Literal["SUNNY", "CLOUDY", "RAINING", "SNOWING"], typing.Any] +WeatherReport = typing.Union[ + typing.Literal["SUNNY", "CLOUDY", "RAINING", "SNOWING"], typing.Any +] diff --git a/seed/python-sdk/exhaustive/five-second-timeout/src/seed/types/object/types/double_optional.py b/seed/python-sdk/exhaustive/five-second-timeout/src/seed/types/object/types/double_optional.py index ddf165b13bd..ed236347357 100644 --- a/seed/python-sdk/exhaustive/five-second-timeout/src/seed/types/object/types/double_optional.py +++ b/seed/python-sdk/exhaustive/five-second-timeout/src/seed/types/object/types/double_optional.py @@ -1,18 +1,21 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .optional_alias import OptionalAlias +import pydantic +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class DoubleOptional(UniversalBaseModel): - optional_alias: typing.Optional[OptionalAlias] = pydantic.Field(alias="optionalAlias", default=None) + optional_alias: typing.Optional[OptionalAlias] = pydantic.Field( + alias="optionalAlias", default=None + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/five-second-timeout/src/seed/types/object/types/nested_object_with_optional_field.py b/seed/python-sdk/exhaustive/five-second-timeout/src/seed/types/object/types/nested_object_with_optional_field.py index 81669c0dd39..20a4d40a714 100644 --- a/seed/python-sdk/exhaustive/five-second-timeout/src/seed/types/object/types/nested_object_with_optional_field.py +++ b/seed/python-sdk/exhaustive/five-second-timeout/src/seed/types/object/types/nested_object_with_optional_field.py @@ -1,19 +1,22 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .object_with_optional_field import ObjectWithOptionalField +import pydantic +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class NestedObjectWithOptionalField(UniversalBaseModel): string: typing.Optional[str] = None - nested_object: typing.Optional[ObjectWithOptionalField] = pydantic.Field(alias="NestedObject", default=None) + nested_object: typing.Optional[ObjectWithOptionalField] = pydantic.Field( + alias="NestedObject", default=None + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/five-second-timeout/src/seed/types/object/types/nested_object_with_required_field.py b/seed/python-sdk/exhaustive/five-second-timeout/src/seed/types/object/types/nested_object_with_required_field.py index 1a621942c6c..a6ca8781190 100644 --- a/seed/python-sdk/exhaustive/five-second-timeout/src/seed/types/object/types/nested_object_with_required_field.py +++ b/seed/python-sdk/exhaustive/five-second-timeout/src/seed/types/object/types/nested_object_with_required_field.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import UniversalBaseModel from .object_with_optional_field import ObjectWithOptionalField +import pydantic +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class NestedObjectWithRequiredField(UniversalBaseModel): @@ -13,7 +12,9 @@ class NestedObjectWithRequiredField(UniversalBaseModel): nested_object: ObjectWithOptionalField = pydantic.Field(alias="NestedObject") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/five-second-timeout/src/seed/types/object/types/object_with_map_of_map.py b/seed/python-sdk/exhaustive/five-second-timeout/src/seed/types/object/types/object_with_map_of_map.py index 8883cc1d498..313cd25ceb8 100644 --- a/seed/python-sdk/exhaustive/five-second-timeout/src/seed/types/object/types/object_with_map_of_map.py +++ b/seed/python-sdk/exhaustive/five-second-timeout/src/seed/types/object/types/object_with_map_of_map.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class ObjectWithMapOfMap(UniversalBaseModel): map_: typing.Dict[str, typing.Dict[str, str]] = pydantic.Field(alias="map") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/five-second-timeout/src/seed/types/object/types/object_with_optional_field.py b/seed/python-sdk/exhaustive/five-second-timeout/src/seed/types/object/types/object_with_optional_field.py index 6aab170be0c..9131f0e91d7 100644 --- a/seed/python-sdk/exhaustive/five-second-timeout/src/seed/types/object/types/object_with_optional_field.py +++ b/seed/python-sdk/exhaustive/five-second-timeout/src/seed/types/object/types/object_with_optional_field.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. -import datetime as dt +from ....core.pydantic_utilities import UniversalBaseModel import typing -import uuid - import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +import datetime as dt +import uuid +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class ObjectWithOptionalField(UniversalBaseModel): @@ -23,13 +22,19 @@ class ObjectWithOptionalField(UniversalBaseModel): date: typing.Optional[dt.date] = None uuid_: typing.Optional[uuid.UUID] = pydantic.Field(alias="uuid", default=None) base_64: typing.Optional[str] = pydantic.Field(alias="base64", default=None) - list_: typing.Optional[typing.List[str]] = pydantic.Field(alias="list", default=None) + list_: typing.Optional[typing.List[str]] = pydantic.Field( + alias="list", default=None + ) set_: typing.Optional[typing.Set[str]] = pydantic.Field(alias="set", default=None) - map_: typing.Optional[typing.Dict[int, str]] = pydantic.Field(alias="map", default=None) + map_: typing.Optional[typing.Dict[int, str]] = pydantic.Field( + alias="map", default=None + ) bigint: typing.Optional[str] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/five-second-timeout/src/seed/types/object/types/object_with_required_field.py b/seed/python-sdk/exhaustive/five-second-timeout/src/seed/types/object/types/object_with_required_field.py index 61b98867984..24db26a3cf8 100644 --- a/seed/python-sdk/exhaustive/five-second-timeout/src/seed/types/object/types/object_with_required_field.py +++ b/seed/python-sdk/exhaustive/five-second-timeout/src/seed/types/object/types/object_with_required_field.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class ObjectWithRequiredField(UniversalBaseModel): string: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/five-second-timeout/src/seed/types/union/types/animal.py b/seed/python-sdk/exhaustive/five-second-timeout/src/seed/types/union/types/animal.py index 1ae43d1663e..84c71d2009a 100644 --- a/seed/python-sdk/exhaustive/five-second-timeout/src/seed/types/union/types/animal.py +++ b/seed/python-sdk/exhaustive/five-second-timeout/src/seed/types/union/types/animal.py @@ -1,12 +1,10 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ....core.pydantic_utilities import UniversalBaseModel import typing - import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class Animal_Dog(UniversalBaseModel): @@ -15,7 +13,9 @@ class Animal_Dog(UniversalBaseModel): likes_to_woof: bool = pydantic.Field(alias="likesToWoof") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: @@ -30,7 +30,9 @@ class Animal_Cat(UniversalBaseModel): likes_to_meow: bool = pydantic.Field(alias="likesToMeow") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/five-second-timeout/src/seed/types/union/types/cat.py b/seed/python-sdk/exhaustive/five-second-timeout/src/seed/types/union/types/cat.py index 61fc5527b1f..c59b78523c9 100644 --- a/seed/python-sdk/exhaustive/five-second-timeout/src/seed/types/union/types/cat.py +++ b/seed/python-sdk/exhaustive/five-second-timeout/src/seed/types/union/types/cat.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ....core.pydantic_utilities import UniversalBaseModel import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class Cat(UniversalBaseModel): @@ -12,7 +11,9 @@ class Cat(UniversalBaseModel): likes_to_meow: bool = pydantic.Field(alias="likesToMeow") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/five-second-timeout/src/seed/types/union/types/dog.py b/seed/python-sdk/exhaustive/five-second-timeout/src/seed/types/union/types/dog.py index c1ff5339dfe..e250c72edef 100644 --- a/seed/python-sdk/exhaustive/five-second-timeout/src/seed/types/union/types/dog.py +++ b/seed/python-sdk/exhaustive/five-second-timeout/src/seed/types/union/types/dog.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ....core.pydantic_utilities import UniversalBaseModel import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class Dog(UniversalBaseModel): @@ -12,7 +11,9 @@ class Dog(UniversalBaseModel): likes_to_woof: bool = pydantic.Field(alias="likesToWoof") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/five-second-timeout/src/seed/version.py b/seed/python-sdk/exhaustive/five-second-timeout/src/seed/version.py index 63ba170685a..ac44536abdb 100644 --- a/seed/python-sdk/exhaustive/five-second-timeout/src/seed/version.py +++ b/seed/python-sdk/exhaustive/five-second-timeout/src/seed/version.py @@ -1,4 +1,3 @@ - from importlib import metadata __version__ = metadata.version("fern_exhaustive") diff --git a/seed/python-sdk/exhaustive/five-second-timeout/tests/conftest.py b/seed/python-sdk/exhaustive/five-second-timeout/tests/conftest.py index b5b50383b94..86cb2b41af8 100644 --- a/seed/python-sdk/exhaustive/five-second-timeout/tests/conftest.py +++ b/seed/python-sdk/exhaustive/five-second-timeout/tests/conftest.py @@ -1,16 +1,22 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive import os - import pytest -from seed import AsyncSeedExhaustive, SeedExhaustive +from seed import AsyncSeedExhaustive @pytest.fixture def client() -> SeedExhaustive: - return SeedExhaustive(token=os.getenv("ENV_TOKEN", "token"), base_url=os.getenv("TESTS_BASE_URL", "base_url")) + return SeedExhaustive( + token=os.getenv("ENV_TOKEN", "token"), + base_url=os.getenv("TESTS_BASE_URL", "base_url"), + ) @pytest.fixture def async_client() -> AsyncSeedExhaustive: - return AsyncSeedExhaustive(token=os.getenv("ENV_TOKEN", "token"), base_url=os.getenv("TESTS_BASE_URL", "base_url")) + return AsyncSeedExhaustive( + token=os.getenv("ENV_TOKEN", "token"), + base_url=os.getenv("TESTS_BASE_URL", "base_url"), + ) diff --git a/seed/python-sdk/exhaustive/five-second-timeout/tests/custom/test_client.py b/seed/python-sdk/exhaustive/five-second-timeout/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/python-sdk/exhaustive/five-second-timeout/tests/custom/test_client.py +++ b/seed/python-sdk/exhaustive/five-second-timeout/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/python-sdk/exhaustive/five-second-timeout/tests/endpoints/test_container.py b/seed/python-sdk/exhaustive/five-second-timeout/tests/endpoints/test_container.py index 17d9d75240d..240f16f2a8c 100644 --- a/seed/python-sdk/exhaustive/five-second-timeout/tests/endpoints/test_container.py +++ b/seed/python-sdk/exhaustive/five-second-timeout/tests/endpoints/test_container.py @@ -1,91 +1,137 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing - -from seed import AsyncSeedExhaustive, SeedExhaustive -from seed.types.object import ObjectWithRequiredField - from ..utilities import validate_response +from seed.types.object import ObjectWithRequiredField -async def test_get_and_return_list_of_primitives(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_list_of_primitives( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = ["string"] expected_types: typing.Tuple[typing.Any, typing.Any] = ("list", {0: None}) - response = client.endpoints.container.get_and_return_list_of_primitives(request=["string"]) + response = client.endpoints.container.get_and_return_list_of_primitives( + request=["string"] + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.container.get_and_return_list_of_primitives(request=["string"]) + async_response = ( + await async_client.endpoints.container.get_and_return_list_of_primitives( + request=["string"] + ) + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_list_of_objects(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_list_of_objects( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = [{"string": "string"}] - expected_types: typing.Tuple[typing.Any, typing.Any] = ("list", {0: {"string": None}}) + expected_types: typing.Tuple[typing.Any, typing.Any] = ( + "list", + {0: {"string": None}}, + ) response = client.endpoints.container.get_and_return_list_of_objects( request=[ObjectWithRequiredField(string="string")] ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.container.get_and_return_list_of_objects( - request=[ObjectWithRequiredField(string="string")] + async_response = ( + await async_client.endpoints.container.get_and_return_list_of_objects( + request=[ObjectWithRequiredField(string="string")] + ) ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_set_of_primitives(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_set_of_primitives( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = ["string"] expected_types: typing.Tuple[typing.Any, typing.Any] = ("set", {0: None}) - response = client.endpoints.container.get_and_return_set_of_primitives(request={"string"}) + response = client.endpoints.container.get_and_return_set_of_primitives( + request={"string"} + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.container.get_and_return_set_of_primitives(request={"string"}) + async_response = ( + await async_client.endpoints.container.get_and_return_set_of_primitives( + request={"string"} + ) + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_set_of_objects(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_set_of_objects( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = [{"string": "string"}] - expected_types: typing.Tuple[typing.Any, typing.Any] = ("set", {0: {"string": None}}) + expected_types: typing.Tuple[typing.Any, typing.Any] = ( + "set", + {0: {"string": None}}, + ) response = client.endpoints.container.get_and_return_set_of_objects( request=[ObjectWithRequiredField(string="string")] ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.container.get_and_return_set_of_objects( - request=[ObjectWithRequiredField(string="string")] + async_response = ( + await async_client.endpoints.container.get_and_return_set_of_objects( + request=[ObjectWithRequiredField(string="string")] + ) ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_map_prim_to_prim(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_map_prim_to_prim( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = {"string": "string"} expected_types: typing.Tuple[typing.Any, typing.Any] = ("dict", {0: (None, None)}) - response = client.endpoints.container.get_and_return_map_prim_to_prim(request={"string": "string"}) + response = client.endpoints.container.get_and_return_map_prim_to_prim( + request={"string": "string"} + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.container.get_and_return_map_prim_to_prim( - request={"string": "string"} + async_response = ( + await async_client.endpoints.container.get_and_return_map_prim_to_prim( + request={"string": "string"} + ) ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_map_of_prim_to_object(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_map_of_prim_to_object( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = {"string": {"string": "string"}} - expected_types: typing.Tuple[typing.Any, typing.Any] = ("dict", {0: (None, {"string": None})}) + expected_types: typing.Tuple[typing.Any, typing.Any] = ( + "dict", + {0: (None, {"string": None})}, + ) response = client.endpoints.container.get_and_return_map_of_prim_to_object( request={"string": ObjectWithRequiredField(string="string")} ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.container.get_and_return_map_of_prim_to_object( - request={"string": ObjectWithRequiredField(string="string")} + async_response = ( + await async_client.endpoints.container.get_and_return_map_of_prim_to_object( + request={"string": ObjectWithRequiredField(string="string")} + ) ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_optional(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_optional( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = {"string": "string"} expected_types: typing.Any = {"string": None} - response = client.endpoints.container.get_and_return_optional(request=ObjectWithRequiredField(string="string")) + response = client.endpoints.container.get_and_return_optional( + request=ObjectWithRequiredField(string="string") + ) validate_response(response, expected_response, expected_types) async_response = await async_client.endpoints.container.get_and_return_optional( diff --git a/seed/python-sdk/exhaustive/five-second-timeout/tests/endpoints/test_enum.py b/seed/python-sdk/exhaustive/five-second-timeout/tests/endpoints/test_enum.py index 890aada5ce4..ca3fca30b5a 100644 --- a/seed/python-sdk/exhaustive/five-second-timeout/tests/endpoints/test_enum.py +++ b/seed/python-sdk/exhaustive/five-second-timeout/tests/endpoints/test_enum.py @@ -1,17 +1,20 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing - -from seed import AsyncSeedExhaustive, SeedExhaustive - from ..utilities import validate_response -async def test_get_and_return_enum(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_enum( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "SUNNY" expected_types: typing.Any = None response = client.endpoints.enum.get_and_return_enum(request="SUNNY") validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.enum.get_and_return_enum(request="SUNNY") + async_response = await async_client.endpoints.enum.get_and_return_enum( + request="SUNNY" + ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/exhaustive/five-second-timeout/tests/endpoints/test_http_methods.py b/seed/python-sdk/exhaustive/five-second-timeout/tests/endpoints/test_http_methods.py index dc01bafcf6f..77131fc6e8b 100644 --- a/seed/python-sdk/exhaustive/five-second-timeout/tests/endpoints/test_http_methods.py +++ b/seed/python-sdk/exhaustive/five-second-timeout/tests/endpoints/test_http_methods.py @@ -1,15 +1,16 @@ # This file was auto-generated by Fern from our API Definition. -import datetime +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing -import uuid - -from seed import AsyncSeedExhaustive, SeedExhaustive - from ..utilities import validate_response +import datetime +import uuid -async def test_test_get(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_test_get( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "string" expected_types: typing.Any = None response = client.endpoints.http_methods.test_get(id="string") @@ -19,7 +20,9 @@ async def test_test_get(client: SeedExhaustive, async_client: AsyncSeedExhaustiv validate_response(async_response, expected_response, expected_types) -async def test_test_post(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_test_post( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = { "string": "string", "integer": 1, @@ -53,11 +56,15 @@ async def test_test_post(client: SeedExhaustive, async_client: AsyncSeedExhausti response = client.endpoints.http_methods.test_post(string="string") validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.http_methods.test_post(string="string") + async_response = await async_client.endpoints.http_methods.test_post( + string="string" + ) validate_response(async_response, expected_response, expected_types) -async def test_test_put(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_test_put( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = { "string": "string", "integer": 1, @@ -91,11 +98,15 @@ async def test_test_put(client: SeedExhaustive, async_client: AsyncSeedExhaustiv response = client.endpoints.http_methods.test_put(id="string", string="string") validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.http_methods.test_put(id="string", string="string") + async_response = await async_client.endpoints.http_methods.test_put( + id="string", string="string" + ) validate_response(async_response, expected_response, expected_types) -async def test_test_patch(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_test_patch( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = { "string": "string", "integer": 1, @@ -163,7 +174,9 @@ async def test_test_patch(client: SeedExhaustive, async_client: AsyncSeedExhaust validate_response(async_response, expected_response, expected_types) -async def test_test_delete(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_test_delete( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = True expected_types: typing.Any = None response = client.endpoints.http_methods.test_delete(id="string") diff --git a/seed/python-sdk/exhaustive/five-second-timeout/tests/endpoints/test_object.py b/seed/python-sdk/exhaustive/five-second-timeout/tests/endpoints/test_object.py index a9098b6e9ef..c48c4332b22 100644 --- a/seed/python-sdk/exhaustive/five-second-timeout/tests/endpoints/test_object.py +++ b/seed/python-sdk/exhaustive/five-second-timeout/tests/endpoints/test_object.py @@ -1,16 +1,18 @@ # This file was auto-generated by Fern from our API Definition. -import datetime +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing +import datetime import uuid - -from seed import AsyncSeedExhaustive, SeedExhaustive -from seed.types.object import NestedObjectWithRequiredField, ObjectWithOptionalField - from ..utilities import validate_response +from seed.types.object import ObjectWithOptionalField +from seed.types.object import NestedObjectWithRequiredField -async def test_get_and_return_with_optional_field(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_with_optional_field( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = { "string": "string", "integer": 1, @@ -58,38 +60,54 @@ async def test_get_and_return_with_optional_field(client: SeedExhaustive, async_ ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.object.get_and_return_with_optional_field( - string="string", - integer=1, - long_=1000000, - double=1.1, - bool_=True, - datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), - date=datetime.date.fromisoformat("2023-01-15"), - uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), - base_64="SGVsbG8gd29ybGQh", - list_=["string"], - set_={"string"}, - map_={1: "string"}, - bigint="123456789123456789", + async_response = ( + await async_client.endpoints.object.get_and_return_with_optional_field( + string="string", + integer=1, + long_=1000000, + double=1.1, + bool_=True, + datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), + date=datetime.date.fromisoformat("2023-01-15"), + uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + base_64="SGVsbG8gd29ybGQh", + list_=["string"], + set_={"string"}, + map_={1: "string"}, + bigint="123456789123456789", + ) ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_with_required_field(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_with_required_field( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = {"string": "string"} expected_types: typing.Any = {"string": None} - response = client.endpoints.object.get_and_return_with_required_field(string="string") + response = client.endpoints.object.get_and_return_with_required_field( + string="string" + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.object.get_and_return_with_required_field(string="string") + async_response = ( + await async_client.endpoints.object.get_and_return_with_required_field( + string="string" + ) + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_with_map_of_map(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_with_map_of_map( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = {"map": {"string": {"string": "string"}}} - expected_types: typing.Any = {"map": ("dict", {0: (None, ("dict", {0: (None, None)}))})} - response = client.endpoints.object.get_and_return_with_map_of_map(map_={"string": {"string": "string"}}) + expected_types: typing.Any = { + "map": ("dict", {0: (None, ("dict", {0: (None, None)}))}) + } + response = client.endpoints.object.get_and_return_with_map_of_map( + map_={"string": {"string": "string"}} + ) validate_response(response, expected_response, expected_types) async_response = await async_client.endpoints.object.get_and_return_with_map_of_map( @@ -157,23 +175,25 @@ async def test_get_and_return_nested_with_optional_field( ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.object.get_and_return_nested_with_optional_field( - string="string", - nested_object=ObjectWithOptionalField( + async_response = ( + await async_client.endpoints.object.get_and_return_nested_with_optional_field( string="string", - integer=1, - long_=1000000, - double=1.1, - bool_=True, - datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), - date=datetime.date.fromisoformat("2023-01-15"), - uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), - base_64="SGVsbG8gd29ybGQh", - list_=["string"], - set_={"string"}, - map_={1: "string"}, - bigint="123456789123456789", - ), + nested_object=ObjectWithOptionalField( + string="string", + integer=1, + long_=1000000, + double=1.1, + bool_=True, + datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), + date=datetime.date.fromisoformat("2023-01-15"), + uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + base_64="SGVsbG8gd29ybGQh", + list_=["string"], + set_={"string"}, + map_={1: "string"}, + bigint="123456789123456789", + ), + ) ) validate_response(async_response, expected_response, expected_types) @@ -238,24 +258,26 @@ async def test_get_and_return_nested_with_required_field( ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.object.get_and_return_nested_with_required_field( - string_="string", - string="string", - nested_object=ObjectWithOptionalField( + async_response = ( + await async_client.endpoints.object.get_and_return_nested_with_required_field( + string_="string", string="string", - integer=1, - long_=1000000, - double=1.1, - bool_=True, - datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), - date=datetime.date.fromisoformat("2023-01-15"), - uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), - base_64="SGVsbG8gd29ybGQh", - list_=["string"], - set_={"string"}, - map_={1: "string"}, - bigint="123456789123456789", - ), + nested_object=ObjectWithOptionalField( + string="string", + integer=1, + long_=1000000, + double=1.1, + bool_=True, + datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), + date=datetime.date.fromisoformat("2023-01-15"), + uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + base_64="SGVsbG8gd29ybGQh", + list_=["string"], + set_={"string"}, + map_={1: "string"}, + bigint="123456789123456789", + ), + ) ) validate_response(async_response, expected_response, expected_types) @@ -299,27 +321,31 @@ async def test_get_and_return_nested_with_required_field_as_list( "bigint": None, }, } - response = client.endpoints.object.get_and_return_nested_with_required_field_as_list( - request=[ - NestedObjectWithRequiredField( - string="string", - nested_object=ObjectWithOptionalField( + response = ( + client.endpoints.object.get_and_return_nested_with_required_field_as_list( + request=[ + NestedObjectWithRequiredField( string="string", - integer=1, - long_=1000000, - double=1.1, - bool_=True, - datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), - date=datetime.date.fromisoformat("2023-01-15"), - uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), - base_64="SGVsbG8gd29ybGQh", - list_=["string"], - set_={"string"}, - map_={1: "string"}, - bigint="123456789123456789", - ), - ) - ] + nested_object=ObjectWithOptionalField( + string="string", + integer=1, + long_=1000000, + double=1.1, + bool_=True, + datetime=datetime.datetime.fromisoformat( + "2024-01-15 09:30:00+00:00" + ), + date=datetime.date.fromisoformat("2023-01-15"), + uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + base_64="SGVsbG8gd29ybGQh", + list_=["string"], + set_={"string"}, + map_={1: "string"}, + bigint="123456789123456789", + ), + ) + ] + ) ) validate_response(response, expected_response, expected_types) @@ -333,7 +359,9 @@ async def test_get_and_return_nested_with_required_field_as_list( long_=1000000, double=1.1, bool_=True, - datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), + datetime=datetime.datetime.fromisoformat( + "2024-01-15 09:30:00+00:00" + ), date=datetime.date.fromisoformat("2023-01-15"), uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), base_64="SGVsbG8gd29ybGQh", diff --git a/seed/python-sdk/exhaustive/five-second-timeout/tests/endpoints/test_params.py b/seed/python-sdk/exhaustive/five-second-timeout/tests/endpoints/test_params.py index 163d7b9161d..d8ffb00c0a0 100644 --- a/seed/python-sdk/exhaustive/five-second-timeout/tests/endpoints/test_params.py +++ b/seed/python-sdk/exhaustive/five-second-timeout/tests/endpoints/test_params.py @@ -1,13 +1,14 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing - -from seed import AsyncSeedExhaustive, SeedExhaustive - from ..utilities import validate_response -async def test_get_with_path(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_with_path( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "string" expected_types: typing.Any = None response = client.endpoints.params.get_with_path(param="string") @@ -17,32 +18,63 @@ async def test_get_with_path(client: SeedExhaustive, async_client: AsyncSeedExha validate_response(async_response, expected_response, expected_types) -async def test_get_with_query(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_with_query( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: # Type ignore to avoid mypy complaining about the function not being meant to return a value assert client.endpoints.params.get_with_query(query="string", number=1) is None # type: ignore[func-returns-value] - assert await async_client.endpoints.params.get_with_query(query="string", number=1) is None # type: ignore[func-returns-value] + assert ( + await async_client.endpoints.params.get_with_query(query="string", number=1) + is None + ) # type: ignore[func-returns-value] -async def test_get_with_allow_multiple_query(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_with_allow_multiple_query( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: # Type ignore to avoid mypy complaining about the function not being meant to return a value - assert client.endpoints.params.get_with_allow_multiple_query(query="string", numer=1) is None # type: ignore[func-returns-value] - - assert await async_client.endpoints.params.get_with_allow_multiple_query(query="string", numer=1) is None # type: ignore[func-returns-value] - - -async def test_get_with_path_and_query(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: + assert ( + client.endpoints.params.get_with_allow_multiple_query(query="string", numer=1) + is None + ) # type: ignore[func-returns-value] + + assert ( + await async_client.endpoints.params.get_with_allow_multiple_query( + query="string", numer=1 + ) + is None + ) # type: ignore[func-returns-value] + + +async def test_get_with_path_and_query( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: # Type ignore to avoid mypy complaining about the function not being meant to return a value - assert client.endpoints.params.get_with_path_and_query(param="string", query="string") is None # type: ignore[func-returns-value] - - assert await async_client.endpoints.params.get_with_path_and_query(param="string", query="string") is None # type: ignore[func-returns-value] - - -async def test_modify_with_path(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: + assert ( + client.endpoints.params.get_with_path_and_query(param="string", query="string") + is None + ) # type: ignore[func-returns-value] + + assert ( + await async_client.endpoints.params.get_with_path_and_query( + param="string", query="string" + ) + is None + ) # type: ignore[func-returns-value] + + +async def test_modify_with_path( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "string" expected_types: typing.Any = None - response = client.endpoints.params.modify_with_path(param="string", request="string") + response = client.endpoints.params.modify_with_path( + param="string", request="string" + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.params.modify_with_path(param="string", request="string") + async_response = await async_client.endpoints.params.modify_with_path( + param="string", request="string" + ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/exhaustive/five-second-timeout/tests/endpoints/test_primitive.py b/seed/python-sdk/exhaustive/five-second-timeout/tests/endpoints/test_primitive.py index ba3bc7e29e5..26cbcf45d2f 100644 --- a/seed/python-sdk/exhaustive/five-second-timeout/tests/endpoints/test_primitive.py +++ b/seed/python-sdk/exhaustive/five-second-timeout/tests/endpoints/test_primitive.py @@ -1,65 +1,86 @@ # This file was auto-generated by Fern from our API Definition. -import datetime +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing -import uuid - -from seed import AsyncSeedExhaustive, SeedExhaustive - from ..utilities import validate_response +import datetime +import uuid -async def test_get_and_return_string(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_string( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "string" expected_types: typing.Any = None response = client.endpoints.primitive.get_and_return_string(request="string") validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.primitive.get_and_return_string(request="string") + async_response = await async_client.endpoints.primitive.get_and_return_string( + request="string" + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_int(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_int( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = 1 expected_types: typing.Any = "integer" response = client.endpoints.primitive.get_and_return_int(request=1) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.primitive.get_and_return_int(request=1) + async_response = await async_client.endpoints.primitive.get_and_return_int( + request=1 + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_long(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_long( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = 1000000 expected_types: typing.Any = None response = client.endpoints.primitive.get_and_return_long(request=1000000) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.primitive.get_and_return_long(request=1000000) + async_response = await async_client.endpoints.primitive.get_and_return_long( + request=1000000 + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_double(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_double( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = 1.1 expected_types: typing.Any = None response = client.endpoints.primitive.get_and_return_double(request=1.1) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.primitive.get_and_return_double(request=1.1) + async_response = await async_client.endpoints.primitive.get_and_return_double( + request=1.1 + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_bool(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_bool( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = True expected_types: typing.Any = None response = client.endpoints.primitive.get_and_return_bool(request=True) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.primitive.get_and_return_bool(request=True) + async_response = await async_client.endpoints.primitive.get_and_return_bool( + request=True + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_datetime(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_datetime( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "2024-01-15T09:30:00Z" expected_types: typing.Any = "datetime" response = client.endpoints.primitive.get_and_return_datetime( @@ -73,10 +94,14 @@ async def test_get_and_return_datetime(client: SeedExhaustive, async_client: Asy validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_date(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_date( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "2023-01-15" expected_types: typing.Any = "date" - response = client.endpoints.primitive.get_and_return_date(request=datetime.date.fromisoformat("2023-01-15")) + response = client.endpoints.primitive.get_and_return_date( + request=datetime.date.fromisoformat("2023-01-15") + ) validate_response(response, expected_response, expected_types) async_response = await async_client.endpoints.primitive.get_and_return_date( @@ -85,10 +110,14 @@ async def test_get_and_return_date(client: SeedExhaustive, async_client: AsyncSe validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_uuid(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_uuid( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32" expected_types: typing.Any = "uuid" - response = client.endpoints.primitive.get_and_return_uuid(request=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32")) + response = client.endpoints.primitive.get_and_return_uuid( + request=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32") + ) validate_response(response, expected_response, expected_types) async_response = await async_client.endpoints.primitive.get_and_return_uuid( @@ -97,11 +126,17 @@ async def test_get_and_return_uuid(client: SeedExhaustive, async_client: AsyncSe validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_base_64(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_base_64( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "SGVsbG8gd29ybGQh" expected_types: typing.Any = None - response = client.endpoints.primitive.get_and_return_base_64(request="SGVsbG8gd29ybGQh") + response = client.endpoints.primitive.get_and_return_base_64( + request="SGVsbG8gd29ybGQh" + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.primitive.get_and_return_base_64(request="SGVsbG8gd29ybGQh") + async_response = await async_client.endpoints.primitive.get_and_return_base_64( + request="SGVsbG8gd29ybGQh" + ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/exhaustive/five-second-timeout/tests/endpoints/test_union.py b/seed/python-sdk/exhaustive/five-second-timeout/tests/endpoints/test_union.py index 14e34c2a6df..ceb84928cd9 100644 --- a/seed/python-sdk/exhaustive/five-second-timeout/tests/endpoints/test_union.py +++ b/seed/python-sdk/exhaustive/five-second-timeout/tests/endpoints/test_union.py @@ -1,17 +1,24 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing - -from seed import AsyncSeedExhaustive, SeedExhaustive from seed.types.union import Animal_Dog - from ..utilities import validate_response -async def test_get_and_return_union(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: - expected_response: typing.Any = {"animal": "dog", "name": "string", "likesToWoof": True} +async def test_get_and_return_union( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: + expected_response: typing.Any = { + "animal": "dog", + "name": "string", + "likesToWoof": True, + } expected_types: typing.Any = "no_validate" - response = client.endpoints.union.get_and_return_union(request=Animal_Dog(name="string", likes_to_woof=True)) + response = client.endpoints.union.get_and_return_union( + request=Animal_Dog(name="string", likes_to_woof=True) + ) validate_response(response, expected_response, expected_types) async_response = await async_client.endpoints.union.get_and_return_union( diff --git a/seed/python-sdk/exhaustive/five-second-timeout/tests/test_inlined_requests.py b/seed/python-sdk/exhaustive/five-second-timeout/tests/test_inlined_requests.py index bb9390d3845..03f46b31cc9 100644 --- a/seed/python-sdk/exhaustive/five-second-timeout/tests/test_inlined_requests.py +++ b/seed/python-sdk/exhaustive/five-second-timeout/tests/test_inlined_requests.py @@ -1,16 +1,17 @@ # This file was auto-generated by Fern from our API Definition. -import datetime +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing -import uuid - -from seed import AsyncSeedExhaustive, SeedExhaustive from seed.types.object import ObjectWithOptionalField - +import datetime +import uuid from .utilities import validate_response -async def test_post_with_object_bodyand_response(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_post_with_object_bodyand_response( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = { "string": "string", "integer": 1, @@ -62,23 +63,25 @@ async def test_post_with_object_bodyand_response(client: SeedExhaustive, async_c ) validate_response(response, expected_response, expected_types) - async_response = await async_client.inlined_requests.post_with_object_bodyand_response( - string="string", - integer=1, - nested_object=ObjectWithOptionalField( + async_response = ( + await async_client.inlined_requests.post_with_object_bodyand_response( string="string", integer=1, - long_=1000000, - double=1.1, - bool_=True, - datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), - date=datetime.date.fromisoformat("2023-01-15"), - uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), - base_64="SGVsbG8gd29ybGQh", - list_=["string"], - set_={"string"}, - map_={1: "string"}, - bigint="123456789123456789", - ), + nested_object=ObjectWithOptionalField( + string="string", + integer=1, + long_=1000000, + double=1.1, + bool_=True, + datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), + date=datetime.date.fromisoformat("2023-01-15"), + uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + base_64="SGVsbG8gd29ybGQh", + list_=["string"], + set_={"string"}, + map_={1: "string"}, + bigint="123456789123456789", + ), + ) ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/exhaustive/five-second-timeout/tests/test_no_auth.py b/seed/python-sdk/exhaustive/five-second-timeout/tests/test_no_auth.py index 3328661bb48..fc475f4b6fb 100644 --- a/seed/python-sdk/exhaustive/five-second-timeout/tests/test_no_auth.py +++ b/seed/python-sdk/exhaustive/five-second-timeout/tests/test_no_auth.py @@ -1,17 +1,20 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing - -from seed import AsyncSeedExhaustive, SeedExhaustive - from .utilities import validate_response -async def test_post_with_no_auth(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_post_with_no_auth( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = True expected_types: typing.Any = None response = client.no_auth.post_with_no_auth(request={"key": "value"}) validate_response(response, expected_response, expected_types) - async_response = await async_client.no_auth.post_with_no_auth(request={"key": "value"}) + async_response = await async_client.no_auth.post_with_no_auth( + request={"key": "value"} + ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/exhaustive/five-second-timeout/tests/test_no_req_body.py b/seed/python-sdk/exhaustive/five-second-timeout/tests/test_no_req_body.py index 73abac9d2d8..07061a0e99e 100644 --- a/seed/python-sdk/exhaustive/five-second-timeout/tests/test_no_req_body.py +++ b/seed/python-sdk/exhaustive/five-second-timeout/tests/test_no_req_body.py @@ -1,13 +1,14 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing - -from seed import AsyncSeedExhaustive, SeedExhaustive - from .utilities import validate_response -async def test_get_with_no_request_body(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_with_no_request_body( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = { "string": "string", "integer": 1, @@ -45,7 +46,9 @@ async def test_get_with_no_request_body(client: SeedExhaustive, async_client: As validate_response(async_response, expected_response, expected_types) -async def test_post_with_no_request_body(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_post_with_no_request_body( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "string" expected_types: typing.Any = None response = client.no_req_body.post_with_no_request_body() diff --git a/seed/python-sdk/exhaustive/five-second-timeout/tests/test_req_with_headers.py b/seed/python-sdk/exhaustive/five-second-timeout/tests/test_req_with_headers.py index bba3b5b5507..75ce9d00c03 100644 --- a/seed/python-sdk/exhaustive/five-second-timeout/tests/test_req_with_headers.py +++ b/seed/python-sdk/exhaustive/five-second-timeout/tests/test_req_with_headers.py @@ -1,10 +1,27 @@ # This file was auto-generated by Fern from our API Definition. -from seed import AsyncSeedExhaustive, SeedExhaustive +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive -async def test_get_with_custom_header(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_with_custom_header( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: # Type ignore to avoid mypy complaining about the function not being meant to return a value - assert client.req_with_headers.get_with_custom_header(x_test_service_header="string", x_test_endpoint_header="string", request="string") is None # type: ignore[func-returns-value] + assert ( + client.req_with_headers.get_with_custom_header( + x_test_service_header="string", + x_test_endpoint_header="string", + request="string", + ) + is None + ) # type: ignore[func-returns-value] - assert await async_client.req_with_headers.get_with_custom_header(x_test_service_header="string", x_test_endpoint_header="string", request="string") is None # type: ignore[func-returns-value] + assert ( + await async_client.req_with_headers.get_with_custom_header( + x_test_service_header="string", + x_test_endpoint_header="string", + request="string", + ) + is None + ) # type: ignore[func-returns-value] diff --git a/seed/python-sdk/exhaustive/five-second-timeout/tests/utilities.py b/seed/python-sdk/exhaustive/five-second-timeout/tests/utilities.py index 13da208eb3a..e8f4472564c 100644 --- a/seed/python-sdk/exhaustive/five-second-timeout/tests/utilities.py +++ b/seed/python-sdk/exhaustive/five-second-timeout/tests/utilities.py @@ -3,11 +3,14 @@ import typing import uuid -import pydantic from dateutil import parser +import pydantic + -def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> typing.Any: +def cast_field( + json_expectation: typing.Any, type_expectation: typing.Any +) -> typing.Any: # Cast these specific types which come through as string and expect our # models to cast to the correct type. if type_expectation == "uuid": @@ -25,7 +28,9 @@ def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> ty return json_expectation -def validate_field(response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any) -> None: +def validate_field( + response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectation == "no_validate": return @@ -44,7 +49,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(entry_expectation, dict): is_container_of_complex_type = True validate_response( - response=response[idx], json_expectation=ex, type_expectations=entry_expectation + response=response[idx], + json_expectation=ex, + type_expectations=entry_expectation, ) else: cast_json_expectation.append(cast_field(ex, entry_expectation)) @@ -56,7 +63,10 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # if any of the values of the set have a type_expectation of a dict, we're assuming it's a pydantic # model and keeping it a list. if container_expectation != "set" or not any( - map(lambda value: isinstance(value, dict), list(contents_expectation.values())) + map( + lambda value: isinstance(value, dict), + list(contents_expectation.values()), + ) ): json_expectation = cast_field(json_expectation, container_expectation) elif isinstance(type_expectation, tuple): @@ -65,9 +75,15 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(contents_expectation, dict): json_expectation = { cast_field( - key, contents_expectation.get(idx)[0] if contents_expectation.get(idx) is not None else None # type: ignore + key, + contents_expectation.get(idx)[0] + if contents_expectation.get(idx) is not None + else None, # type: ignore ): cast_field( - value, contents_expectation.get(idx)[1] if contents_expectation.get(idx) is not None else None # type: ignore + value, + contents_expectation.get(idx)[1] + if contents_expectation.get(idx) is not None + else None, # type: ignore ) for idx, (key, value) in enumerate(json_expectation.items()) } @@ -86,7 +102,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # Arg type_expectations is a deeply nested structure that matches the response, but with the values replaced with the expected types -def validate_response(response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any) -> None: +def validate_response( + response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectations == "no_validate": return @@ -96,11 +114,17 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e and not isinstance(response, dict) and not issubclass(type(response), pydantic.BaseModel) ): - validate_field(response=response, json_expectation=json_expectation, type_expectation=type_expectations) + validate_field( + response=response, + json_expectation=json_expectation, + type_expectation=type_expectations, + ) return if isinstance(response, list): - assert len(response) == len(json_expectation), "Length mismatch, expected: {0}, Actual: {1}".format( + assert len(response) == len( + json_expectation + ), "Length mismatch, expected: {0}, Actual: {1}".format( len(response), len(json_expectation) ) content_expectation = type_expectations @@ -108,7 +132,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e content_expectation = type_expectations[1] for idx, item in enumerate(response): validate_response( - response=item, json_expectation=json_expectation[idx], type_expectations=content_expectation[idx] + response=item, + json_expectation=json_expectation[idx], + type_expectations=content_expectation[idx], ) else: response_json = response @@ -116,7 +142,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e response_json = response.dict(by_alias=True) for key, value in json_expectation.items(): - assert key in response_json, "Field {0} not found within the response object: {1}".format( + assert ( + key in response_json + ), "Field {0} not found within the response object: {1}".format( key, response_json ) @@ -128,11 +156,19 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e # Otherwise, we're just validating a single field that's a pydantic model. if isinstance(value, dict) and not isinstance(type_expectation, tuple): validate_response( - response=response_json[key], json_expectation=value, type_expectations=type_expectation + response=response_json[key], + json_expectation=value, + type_expectations=type_expectation, ) else: - validate_field(response=response_json[key], json_expectation=value, type_expectation=type_expectation) + validate_field( + response=response_json[key], + json_expectation=value, + type_expectation=type_expectation, + ) # Ensure there are no additional fields here either del response_json[key] - assert len(response_json) == 0, "Additional fields found, expected None: {0}".format(response_json) + assert ( + len(response_json) == 0 + ), "Additional fields found, expected None: {0}".format(response_json) diff --git a/seed/python-sdk/exhaustive/five-second-timeout/tests/utils/assets/models/__init__.py b/seed/python-sdk/exhaustive/five-second-timeout/tests/utils/assets/models/__init__.py index 2cf01263529..3a1c852e71e 100644 --- a/seed/python-sdk/exhaustive/five-second-timeout/tests/utils/assets/models/__init__.py +++ b/seed/python-sdk/exhaustive/five-second-timeout/tests/utils/assets/models/__init__.py @@ -5,7 +5,7 @@ from .circle import CircleParams from .object_with_defaults import ObjectWithDefaultsParams from .object_with_optional_field import ObjectWithOptionalFieldParams -from .shape import Shape_CircleParams, Shape_SquareParams, ShapeParams +from .shape import ShapeParams, Shape_CircleParams, Shape_SquareParams from .square import SquareParams from .undiscriminated_shape import UndiscriminatedShapeParams diff --git a/seed/python-sdk/exhaustive/five-second-timeout/tests/utils/assets/models/circle.py b/seed/python-sdk/exhaustive/five-second-timeout/tests/utils/assets/models/circle.py index af7a1bf8a8e..253f12d38b3 100644 --- a/seed/python-sdk/exhaustive/five-second-timeout/tests/utils/assets/models/circle.py +++ b/seed/python-sdk/exhaustive/five-second-timeout/tests/utils/assets/models/circle.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class CircleParams(typing_extensions.TypedDict): - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] diff --git a/seed/python-sdk/exhaustive/five-second-timeout/tests/utils/assets/models/object_with_optional_field.py b/seed/python-sdk/exhaustive/five-second-timeout/tests/utils/assets/models/object_with_optional_field.py index 3ad93d5f305..ebe7dc80547 100644 --- a/seed/python-sdk/exhaustive/five-second-timeout/tests/utils/assets/models/object_with_optional_field.py +++ b/seed/python-sdk/exhaustive/five-second-timeout/tests/utils/assets/models/object_with_optional_field.py @@ -7,8 +7,8 @@ import uuid import typing_extensions -from seed.core.serialization import FieldMetadata +from seed.core.serialization import FieldMetadata from .color import Color from .shape import ShapeParams from .undiscriminated_shape import UndiscriminatedShapeParams @@ -18,16 +18,30 @@ class ObjectWithOptionalFieldParams(typing_extensions.TypedDict): literal: typing.Literal["lit_one"] string: typing_extensions.NotRequired[str] integer: typing_extensions.NotRequired[int] - long_: typing_extensions.NotRequired[typing_extensions.Annotated[int, FieldMetadata(alias="long")]] + long_: typing_extensions.NotRequired[ + typing_extensions.Annotated[int, FieldMetadata(alias="long")] + ] double: typing_extensions.NotRequired[float] - bool_: typing_extensions.NotRequired[typing_extensions.Annotated[bool, FieldMetadata(alias="bool")]] + bool_: typing_extensions.NotRequired[ + typing_extensions.Annotated[bool, FieldMetadata(alias="bool")] + ] datetime: typing_extensions.NotRequired[dt.datetime] date: typing_extensions.NotRequired[dt.date] - uuid_: typing_extensions.NotRequired[typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")]] - base_64: typing_extensions.NotRequired[typing_extensions.Annotated[str, FieldMetadata(alias="base64")]] - list_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")]] - set_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")]] - map_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")]] + uuid_: typing_extensions.NotRequired[ + typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")] + ] + base_64: typing_extensions.NotRequired[ + typing_extensions.Annotated[str, FieldMetadata(alias="base64")] + ] + list_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")] + ] + set_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")] + ] + map_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")] + ] enum: typing_extensions.NotRequired[Color] union: typing_extensions.NotRequired[ShapeParams] second_union: typing_extensions.NotRequired[ShapeParams] diff --git a/seed/python-sdk/exhaustive/five-second-timeout/tests/utils/assets/models/shape.py b/seed/python-sdk/exhaustive/five-second-timeout/tests/utils/assets/models/shape.py index 2c33c877951..816ffc51bdc 100644 --- a/seed/python-sdk/exhaustive/five-second-timeout/tests/utils/assets/models/shape.py +++ b/seed/python-sdk/exhaustive/five-second-timeout/tests/utils/assets/models/shape.py @@ -7,6 +7,7 @@ import typing import typing_extensions + from seed.core.serialization import FieldMetadata @@ -15,13 +16,21 @@ class Base(typing_extensions.TypedDict): class Shape_CircleParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["circle"], FieldMetadata(alias="shapeType")] - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["circle"], FieldMetadata(alias="shapeType") + ] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] class Shape_SquareParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["square"], FieldMetadata(alias="shapeType")] - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["square"], FieldMetadata(alias="shapeType") + ] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] ShapeParams = typing.Union[Shape_CircleParams, Shape_SquareParams] diff --git a/seed/python-sdk/exhaustive/five-second-timeout/tests/utils/assets/models/square.py b/seed/python-sdk/exhaustive/five-second-timeout/tests/utils/assets/models/square.py index b9b7dd319bc..bcf08a723c5 100644 --- a/seed/python-sdk/exhaustive/five-second-timeout/tests/utils/assets/models/square.py +++ b/seed/python-sdk/exhaustive/five-second-timeout/tests/utils/assets/models/square.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class SquareParams(typing_extensions.TypedDict): - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] diff --git a/seed/python-sdk/exhaustive/five-second-timeout/tests/utils/test_http_client.py b/seed/python-sdk/exhaustive/five-second-timeout/tests/utils/test_http_client.py index edd11ca7afb..f5a874a75f3 100644 --- a/seed/python-sdk/exhaustive/five-second-timeout/tests/utils/test_http_client.py +++ b/seed/python-sdk/exhaustive/five-second-timeout/tests/utils/test_http_client.py @@ -9,12 +9,17 @@ def get_request_options() -> RequestOptions: def test_get_json_request_body() -> None: - json_body, data_body = get_request_body(json={"hello": "world"}, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json={"hello": "world"}, data=None, request_options=None, omit=None + ) assert json_body == {"hello": "world"} assert data_body is None json_body_extras, data_body_extras = get_request_body( - json={"goodbye": "world"}, data=None, request_options=get_request_options(), omit=None + json={"goodbye": "world"}, + data=None, + request_options=get_request_options(), + omit=None, ) assert json_body_extras == {"goodbye": "world", "see you": "later"} @@ -22,12 +27,17 @@ def test_get_json_request_body() -> None: def test_get_files_request_body() -> None: - json_body, data_body = get_request_body(json=None, data={"hello": "world"}, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data={"hello": "world"}, request_options=None, omit=None + ) assert data_body == {"hello": "world"} assert json_body is None json_body_extras, data_body_extras = get_request_body( - json=None, data={"goodbye": "world"}, request_options=get_request_options(), omit=None + json=None, + data={"goodbye": "world"}, + request_options=get_request_options(), + omit=None, ) assert data_body_extras == {"goodbye": "world", "see you": "later"} @@ -35,7 +45,9 @@ def test_get_files_request_body() -> None: def test_get_none_request_body() -> None: - json_body, data_body = get_request_body(json=None, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data=None, request_options=None, omit=None + ) assert data_body is None assert json_body is None diff --git a/seed/python-sdk/exhaustive/five-second-timeout/tests/utils/test_query_encoding.py b/seed/python-sdk/exhaustive/five-second-timeout/tests/utils/test_query_encoding.py index 247e1551b46..fbc8f402167 100644 --- a/seed/python-sdk/exhaustive/five-second-timeout/tests/utils/test_query_encoding.py +++ b/seed/python-sdk/exhaustive/five-second-timeout/tests/utils/test_query_encoding.py @@ -4,9 +4,15 @@ def test_query_encoding() -> None: - assert encode_query({"hello world": "hello world"}) == {"hello world": "hello world"} - assert encode_query({"hello_world": {"hello": "world"}}) == {"hello_world[hello]": "world"} - assert encode_query({"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"}) == { + assert encode_query({"hello world": "hello world"}) == { + "hello world": "hello world" + } + assert encode_query({"hello_world": {"hello": "world"}}) == { + "hello_world[hello]": "world" + } + assert encode_query( + {"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"} + ) == { "hello_world[hello][world]": "today", "hello_world[test]": "this", "hi": "there", diff --git a/seed/python-sdk/exhaustive/five-second-timeout/tests/utils/test_serialization.py b/seed/python-sdk/exhaustive/five-second-timeout/tests/utils/test_serialization.py index 58b1ed66e6d..5ca956916dd 100644 --- a/seed/python-sdk/exhaustive/five-second-timeout/tests/utils/test_serialization.py +++ b/seed/python-sdk/exhaustive/five-second-timeout/tests/utils/test_serialization.py @@ -1,10 +1,12 @@ # This file was auto-generated by Fern from our API Definition. -from typing import Any, List +from typing import List, Any -from seed.core.serialization import convert_and_respect_annotation_metadata +from seed.core.serialization import ( + convert_and_respect_annotation_metadata, +) +from .assets.models import ShapeParams, ObjectWithOptionalFieldParams -from .assets.models import ObjectWithOptionalFieldParams, ShapeParams UNION_TEST: ShapeParams = {"radius_measurement": 1.0, "shape_type": "circle", "id": "1"} UNION_TEST_CONVERTED = {"shapeType": "circle", "radiusMeasurement": 1.0, "id": "1"} @@ -18,20 +20,54 @@ def test_convert_and_respect_annotation_metadata() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) - assert converted == {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"} + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) + assert converted == { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + } def test_convert_and_respect_annotation_metadata_in_list() -> None: data: List[ObjectWithOptionalFieldParams] = [ - {"string": "string", "long_": 12345, "bool_": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long_": 67890, "list_": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long_": 12345, + "bool_": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long_": 67890, + "list_": [], + "literal": "lit_one", + "any": "any", + }, ] - converted = convert_and_respect_annotation_metadata(object_=data, annotation=List[ObjectWithOptionalFieldParams]) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=List[ObjectWithOptionalFieldParams] + ) assert converted == [ - {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long": 67890, "list": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long": 67890, + "list": [], + "literal": "lit_one", + "any": "any", + }, ] @@ -43,7 +79,9 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) assert converted == { "string": "string", @@ -55,12 +93,16 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: def test_convert_and_respect_annotation_metadata_in_union() -> None: - converted = convert_and_respect_annotation_metadata(object_=UNION_TEST, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=UNION_TEST, annotation=ShapeParams + ) assert converted == UNION_TEST_CONVERTED def test_convert_and_respect_annotation_metadata_with_empty_object() -> None: data: Any = {} - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ShapeParams + ) assert converted == data diff --git a/seed/python-sdk/exhaustive/follow_redirects_by_default/pyproject.toml b/seed/python-sdk/exhaustive/follow_redirects_by_default/pyproject.toml index c6cd3a2b7b9..fc29a237334 100644 --- a/seed/python-sdk/exhaustive/follow_redirects_by_default/pyproject.toml +++ b/seed/python-sdk/exhaustive/follow_redirects_by_default/pyproject.toml @@ -43,6 +43,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/__init__.py b/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/__init__.py index eb56b0ce275..dc1ef03a650 100644 --- a/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/__init__.py +++ b/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/__init__.py @@ -1,6 +1,14 @@ # This file was auto-generated by Fern from our API Definition. -from . import endpoints, general_errors, inlined_requests, no_auth, no_req_body, req_with_headers, types +from . import ( + endpoints, + general_errors, + inlined_requests, + no_auth, + no_req_body, + req_with_headers, + types, +) from .client import AsyncSeedExhaustive, SeedExhaustive from .general_errors import BadObjectRequestInfo, BadRequestBody from .version import __version__ diff --git a/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/client.py b/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/client.py index b1b9764c7a7..f5ab292af6b 100644 --- a/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/client.py +++ b/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/client.py @@ -1,15 +1,19 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from .endpoints.client import AsyncEndpointsClient, EndpointsClient -from .inlined_requests.client import AsyncInlinedRequestsClient, InlinedRequestsClient -from .no_auth.client import AsyncNoAuthClient, NoAuthClient -from .no_req_body.client import AsyncNoReqBodyClient, NoReqBodyClient -from .req_with_headers.client import AsyncReqWithHeadersClient, ReqWithHeadersClient +from .core.client_wrapper import SyncClientWrapper +from .endpoints.client import EndpointsClient +from .inlined_requests.client import InlinedRequestsClient +from .no_auth.client import NoAuthClient +from .no_req_body.client import NoReqBodyClient +from .req_with_headers.client import ReqWithHeadersClient +from .core.client_wrapper import AsyncClientWrapper +from .endpoints.client import AsyncEndpointsClient +from .inlined_requests.client import AsyncInlinedRequestsClient +from .no_auth.client import AsyncNoAuthClient +from .no_req_body.client import AsyncNoReqBodyClient +from .req_with_headers.client import AsyncReqWithHeadersClient class SeedExhaustive: @@ -48,24 +52,32 @@ def __init__( token: typing.Optional[typing.Union[str, typing.Callable[[], str]]] = None, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.Client] = None + httpx_client: typing.Optional[httpx.Client] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = SyncClientWrapper( base_url=base_url, token=token, httpx_client=httpx_client if httpx_client is not None - else httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.Client( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.Client(timeout=_defaulted_timeout), timeout=_defaulted_timeout, ) self.endpoints = EndpointsClient(client_wrapper=self._client_wrapper) - self.inlined_requests = InlinedRequestsClient(client_wrapper=self._client_wrapper) + self.inlined_requests = InlinedRequestsClient( + client_wrapper=self._client_wrapper + ) self.no_auth = NoAuthClient(client_wrapper=self._client_wrapper) self.no_req_body = NoReqBodyClient(client_wrapper=self._client_wrapper) - self.req_with_headers = ReqWithHeadersClient(client_wrapper=self._client_wrapper) + self.req_with_headers = ReqWithHeadersClient( + client_wrapper=self._client_wrapper + ) class AsyncSeedExhaustive: @@ -104,21 +116,29 @@ def __init__( token: typing.Optional[typing.Union[str, typing.Callable[[], str]]] = None, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.AsyncClient] = None + httpx_client: typing.Optional[httpx.AsyncClient] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = AsyncClientWrapper( base_url=base_url, token=token, httpx_client=httpx_client if httpx_client is not None - else httpx.AsyncClient(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.AsyncClient( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.AsyncClient(timeout=_defaulted_timeout), timeout=_defaulted_timeout, ) self.endpoints = AsyncEndpointsClient(client_wrapper=self._client_wrapper) - self.inlined_requests = AsyncInlinedRequestsClient(client_wrapper=self._client_wrapper) + self.inlined_requests = AsyncInlinedRequestsClient( + client_wrapper=self._client_wrapper + ) self.no_auth = AsyncNoAuthClient(client_wrapper=self._client_wrapper) self.no_req_body = AsyncNoReqBodyClient(client_wrapper=self._client_wrapper) - self.req_with_headers = AsyncReqWithHeadersClient(client_wrapper=self._client_wrapper) + self.req_with_headers = AsyncReqWithHeadersClient( + client_wrapper=self._client_wrapper + ) diff --git a/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/core/api_error.py b/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/core/api_error.py index 2e9fc5431cd..da734b58068 100644 --- a/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/core/api_error.py +++ b/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/core/api_error.py @@ -7,7 +7,9 @@ class ApiError(Exception): status_code: typing.Optional[int] body: typing.Any - def __init__(self, *, status_code: typing.Optional[int] = None, body: typing.Any = None): + def __init__( + self, *, status_code: typing.Optional[int] = None, body: typing.Any = None + ): self.status_code = status_code self.body = body diff --git a/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/core/client_wrapper.py b/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/core/client_wrapper.py index 8d01b584b82..d037184a816 100644 --- a/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/core/client_wrapper.py +++ b/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/core/client_wrapper.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .http_client import AsyncHttpClient, HttpClient +from .http_client import HttpClient +from .http_client import AsyncHttpClient class BaseClientWrapper: diff --git a/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/core/datetime_utils.py b/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/core/datetime_utils.py +++ b/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/core/file.py b/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/core/file.py index cb0d40bbbf3..6e0f92bfcb1 100644 --- a/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/core/file.py +++ b/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/core/file.py @@ -13,12 +13,17 @@ # (filename, file (or bytes), content_type) typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str]], # (filename, file (or bytes), content_type, headers) - typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str], typing.Mapping[str, str]], + typing.Tuple[ + typing.Optional[str], + FileContent, + typing.Optional[str], + typing.Mapping[str, str], + ], ] def convert_file_dict_to_httpx_tuples( - d: typing.Dict[str, typing.Union[File, typing.List[File]]] + d: typing.Dict[str, typing.Union[File, typing.List[File]]], ) -> typing.List[typing.Tuple[str, File]]: """ The format we use is a list of tuples, where the first element is the diff --git a/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/core/http_client.py b/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/core/http_client.py index 9333d8a7f15..091f71bc185 100644 --- a/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/core/http_client.py +++ b/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/core/http_client.py @@ -77,7 +77,9 @@ def _retry_timeout(response: httpx.Response, retries: int) -> float: return retry_after # Apply exponential backoff, capped at MAX_RETRY_DELAY_SECONDS. - retry_delay = min(INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS) + retry_delay = min( + INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS + ) # Add a randomness / jitter to the retry delay to avoid overwhelming the server with retries. timeout = retry_delay * (1 - 0.25 * random()) @@ -90,7 +92,8 @@ def _should_retry(response: httpx.Response) -> bool: def remove_omit_from_dict( - original: typing.Dict[str, typing.Optional[typing.Any]], omit: typing.Optional[typing.Any] + original: typing.Dict[str, typing.Optional[typing.Any]], + omit: typing.Optional[typing.Any], ) -> typing.Dict[str, typing.Any]: if omit is None: return original @@ -108,7 +111,8 @@ def maybe_filter_request_body( ) -> typing.Optional[typing.Any]: if data is None: return ( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else None ) @@ -118,7 +122,8 @@ def maybe_filter_request_body( data_content = { **(jsonable_encoder(remove_omit_from_dict(data, omit))), # type: ignore **( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else {} ), @@ -162,7 +167,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url def request( @@ -174,8 +181,12 @@ def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -184,11 +195,14 @@ def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) response = self.httpx_client.request( method=method, @@ -198,7 +212,11 @@ def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -209,7 +227,10 @@ def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -222,11 +243,15 @@ def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: time.sleep(_retry_timeout(response=response, retries=retries)) @@ -256,8 +281,12 @@ def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -266,11 +295,14 @@ def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) with self.httpx_client.stream( method=method, @@ -280,7 +312,11 @@ def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -291,7 +327,9 @@ def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -304,7 +342,9 @@ def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream @@ -327,7 +367,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url async def request( @@ -339,8 +381,12 @@ async def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -349,11 +395,14 @@ async def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) # Add the input to each of these and do None-safety checks response = await self.httpx_client.request( @@ -364,7 +413,11 @@ async def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -375,7 +428,10 @@ async def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -388,11 +444,15 @@ async def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: await asyncio.sleep(_retry_timeout(response=response, retries=retries)) @@ -421,8 +481,12 @@ async def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -431,11 +495,14 @@ async def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) async with self.httpx_client.stream( method=method, @@ -445,7 +512,11 @@ async def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -456,7 +527,9 @@ async def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -469,7 +542,9 @@ async def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream diff --git a/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/core/jsonable_encoder.py b/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/core/jsonable_encoder.py index d3fd328fd41..12a8b52fc22 100644 --- a/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/core/jsonable_encoder.py +++ b/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/core/jsonable_encoder.py @@ -19,13 +19,19 @@ import pydantic from .datetime_utils import serialize_datetime -from .pydantic_utilities import IS_PYDANTIC_V2, encode_by_type, to_jsonable_with_fallback +from .pydantic_utilities import ( + IS_PYDANTIC_V2, + encode_by_type, + to_jsonable_with_fallback, +) SetIntStr = Set[Union[int, str]] DictIntStrAny = Dict[Union[int, str], Any] -def jsonable_encoder(obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None) -> Any: +def jsonable_encoder( + obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None +) -> Any: custom_encoder = custom_encoder or {} if custom_encoder: if type(obj) in custom_encoder: diff --git a/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/core/pydantic_utilities.py b/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/core/pydantic_utilities.py index 170a563d6eb..c63935c32a2 100644 --- a/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/core/pydantic_utilities.py +++ b/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) # type: ignore # Pydantic v1 diff --git a/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/core/query_encoder.py b/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/core/query_encoder.py index 24076d72ee9..7cb98f52cd7 100644 --- a/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/core/query_encoder.py +++ b/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/core/query_encoder.py @@ -7,7 +7,9 @@ # Flattens dicts to be of the form {"key[subkey][subkey2]": value} where value is not a dict -def traverse_query_dict(dict_flat: Dict[str, Any], key_prefix: Optional[str] = None) -> Dict[str, Any]: +def traverse_query_dict( + dict_flat: Dict[str, Any], key_prefix: Optional[str] = None +) -> Dict[str, Any]: result = {} for k, v in dict_flat.items(): key = f"{key_prefix}[{k}]" if key_prefix is not None else k @@ -30,4 +32,8 @@ def single_query_encoder(query_key: str, query_value: Any) -> Dict[str, Any]: def encode_query(query: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: - return dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) if query is not None else None + return ( + dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) + if query is not None + else None + ) diff --git a/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/core/serialization.py b/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/core/serialization.py +++ b/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/endpoints/__init__.py b/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/endpoints/__init__.py index 92307cab7fe..a9496ece178 100644 --- a/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/endpoints/__init__.py +++ b/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/endpoints/__init__.py @@ -2,4 +2,12 @@ from . import container, enum, http_methods, object, params, primitive, union -__all__ = ["container", "enum", "http_methods", "object", "params", "primitive", "union"] +__all__ = [ + "container", + "enum", + "http_methods", + "object", + "params", + "primitive", + "union", +] diff --git a/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/endpoints/client.py b/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/endpoints/client.py index 18dc397fdf1..69930de54d7 100644 --- a/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/endpoints/client.py +++ b/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/endpoints/client.py @@ -1,13 +1,21 @@ # This file was auto-generated by Fern from our API Definition. -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from .container.client import AsyncContainerClient, ContainerClient -from .enum.client import AsyncEnumClient, EnumClient -from .http_methods.client import AsyncHttpMethodsClient, HttpMethodsClient -from .object.client import AsyncObjectClient, ObjectClient -from .params.client import AsyncParamsClient, ParamsClient -from .primitive.client import AsyncPrimitiveClient, PrimitiveClient -from .union.client import AsyncUnionClient, UnionClient +from ..core.client_wrapper import SyncClientWrapper +from .container.client import ContainerClient +from .enum.client import EnumClient +from .http_methods.client import HttpMethodsClient +from .object.client import ObjectClient +from .params.client import ParamsClient +from .primitive.client import PrimitiveClient +from .union.client import UnionClient +from ..core.client_wrapper import AsyncClientWrapper +from .container.client import AsyncContainerClient +from .enum.client import AsyncEnumClient +from .http_methods.client import AsyncHttpMethodsClient +from .object.client import AsyncObjectClient +from .params.client import AsyncParamsClient +from .primitive.client import AsyncPrimitiveClient +from .union.client import AsyncUnionClient class EndpointsClient: diff --git a/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/endpoints/container/client.py b/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/endpoints/container/client.py index c6cf14f63ac..4af9c12d534 100644 --- a/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/endpoints/container/client.py +++ b/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/endpoints/container/client.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. import typing +from ...core.client_wrapper import SyncClientWrapper +from ...core.request_options import RequestOptions +from ...core.pydantic_utilities import parse_obj_as from json.decoder import JSONDecodeError - from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ...core.pydantic_utilities import parse_obj_as -from ...core.request_options import RequestOptions from ...types.object.types.object_with_required_field import ObjectWithRequiredField +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -18,7 +18,10 @@ def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper def get_and_return_list_of_primitives( - self, *, request: typing.Sequence[str], request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Sequence[str], + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[str]: """ Parameters @@ -45,11 +48,18 @@ def get_and_return_list_of_primitives( ) """ _response = self._client_wrapper.httpx_client.request( - "container/list-of-primitives", method="POST", json=request, request_options=request_options, omit=OMIT + "container/list-of-primitives", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.List[str], parse_obj_as(type_=typing.List[str], object_=_response.json())) # type: ignore + return typing.cast( + typing.List[str], + parse_obj_as(type_=typing.List[str], object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -59,7 +69,7 @@ def get_and_return_list_of_objects( self, *, request: typing.Sequence[ObjectWithRequiredField], - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[ObjectWithRequiredField]: """ Parameters @@ -91,18 +101,31 @@ def get_and_return_list_of_objects( ) """ _response = self._client_wrapper.httpx_client.request( - "container/list-of-objects", method="POST", json=request, request_options=request_options, omit=OMIT + "container/list-of-objects", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.List[ObjectWithRequiredField], parse_obj_as(type_=typing.List[ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.List[ObjectWithRequiredField], + parse_obj_as( + type_=typing.List[ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_and_return_set_of_primitives( - self, *, request: typing.Set[str], request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Set[str], + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Set[str]: """ Parameters @@ -129,11 +152,18 @@ def get_and_return_set_of_primitives( ) """ _response = self._client_wrapper.httpx_client.request( - "container/set-of-primitives", method="POST", json=request, request_options=request_options, omit=OMIT + "container/set-of-primitives", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Set[str], parse_obj_as(type_=typing.Set[str], object_=_response.json())) # type: ignore + return typing.cast( + typing.Set[str], + parse_obj_as(type_=typing.Set[str], object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -143,7 +173,7 @@ def get_and_return_set_of_objects( self, *, request: typing.Sequence[ObjectWithRequiredField], - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[ObjectWithRequiredField]: """ Parameters @@ -175,18 +205,31 @@ def get_and_return_set_of_objects( ) """ _response = self._client_wrapper.httpx_client.request( - "container/set-of-objects", method="POST", json=request, request_options=request_options, omit=OMIT + "container/set-of-objects", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.List[ObjectWithRequiredField], parse_obj_as(type_=typing.List[ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.List[ObjectWithRequiredField], + parse_obj_as( + type_=typing.List[ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_and_return_map_prim_to_prim( - self, *, request: typing.Dict[str, str], request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Dict[str, str], + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Dict[str, str]: """ Parameters @@ -213,11 +256,18 @@ def get_and_return_map_prim_to_prim( ) """ _response = self._client_wrapper.httpx_client.request( - "container/map-prim-to-prim", method="POST", json=request, request_options=request_options, omit=OMIT + "container/map-prim-to-prim", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Dict[str, str], parse_obj_as(type_=typing.Dict[str, str], object_=_response.json())) # type: ignore + return typing.cast( + typing.Dict[str, str], + parse_obj_as(type_=typing.Dict[str, str], object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -227,7 +277,7 @@ def get_and_return_map_of_prim_to_object( self, *, request: typing.Dict[str, ObjectWithRequiredField], - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Dict[str, ObjectWithRequiredField]: """ Parameters @@ -259,11 +309,21 @@ def get_and_return_map_of_prim_to_object( ) """ _response = self._client_wrapper.httpx_client.request( - "container/map-prim-to-object", method="POST", json=request, request_options=request_options, omit=OMIT + "container/map-prim-to-object", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Dict[str, ObjectWithRequiredField], parse_obj_as(type_=typing.Dict[str, ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.Dict[str, ObjectWithRequiredField], + parse_obj_as( + type_=typing.Dict[str, ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -273,7 +333,7 @@ def get_and_return_optional( self, *, request: typing.Optional[ObjectWithRequiredField] = None, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Optional[ObjectWithRequiredField]: """ Parameters @@ -303,11 +363,21 @@ def get_and_return_optional( ) """ _response = self._client_wrapper.httpx_client.request( - "container/opt-objects", method="POST", json=request, request_options=request_options, omit=OMIT + "container/opt-objects", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Optional[ObjectWithRequiredField], parse_obj_as(type_=typing.Optional[ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.Optional[ObjectWithRequiredField], + parse_obj_as( + type_=typing.Optional[ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -319,7 +389,10 @@ def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper async def get_and_return_list_of_primitives( - self, *, request: typing.Sequence[str], request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Sequence[str], + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[str]: """ Parameters @@ -354,11 +427,18 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/list-of-primitives", method="POST", json=request, request_options=request_options, omit=OMIT + "container/list-of-primitives", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.List[str], parse_obj_as(type_=typing.List[str], object_=_response.json())) # type: ignore + return typing.cast( + typing.List[str], + parse_obj_as(type_=typing.List[str], object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -368,7 +448,7 @@ async def get_and_return_list_of_objects( self, *, request: typing.Sequence[ObjectWithRequiredField], - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[ObjectWithRequiredField]: """ Parameters @@ -408,18 +488,31 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/list-of-objects", method="POST", json=request, request_options=request_options, omit=OMIT + "container/list-of-objects", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.List[ObjectWithRequiredField], parse_obj_as(type_=typing.List[ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.List[ObjectWithRequiredField], + parse_obj_as( + type_=typing.List[ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_and_return_set_of_primitives( - self, *, request: typing.Set[str], request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Set[str], + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Set[str]: """ Parameters @@ -454,11 +547,18 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/set-of-primitives", method="POST", json=request, request_options=request_options, omit=OMIT + "container/set-of-primitives", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Set[str], parse_obj_as(type_=typing.Set[str], object_=_response.json())) # type: ignore + return typing.cast( + typing.Set[str], + parse_obj_as(type_=typing.Set[str], object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -468,7 +568,7 @@ async def get_and_return_set_of_objects( self, *, request: typing.Sequence[ObjectWithRequiredField], - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[ObjectWithRequiredField]: """ Parameters @@ -508,18 +608,31 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/set-of-objects", method="POST", json=request, request_options=request_options, omit=OMIT + "container/set-of-objects", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.List[ObjectWithRequiredField], parse_obj_as(type_=typing.List[ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.List[ObjectWithRequiredField], + parse_obj_as( + type_=typing.List[ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_and_return_map_prim_to_prim( - self, *, request: typing.Dict[str, str], request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Dict[str, str], + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Dict[str, str]: """ Parameters @@ -554,11 +667,18 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/map-prim-to-prim", method="POST", json=request, request_options=request_options, omit=OMIT + "container/map-prim-to-prim", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Dict[str, str], parse_obj_as(type_=typing.Dict[str, str], object_=_response.json())) # type: ignore + return typing.cast( + typing.Dict[str, str], + parse_obj_as(type_=typing.Dict[str, str], object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -568,7 +688,7 @@ async def get_and_return_map_of_prim_to_object( self, *, request: typing.Dict[str, ObjectWithRequiredField], - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Dict[str, ObjectWithRequiredField]: """ Parameters @@ -608,11 +728,21 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/map-prim-to-object", method="POST", json=request, request_options=request_options, omit=OMIT + "container/map-prim-to-object", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Dict[str, ObjectWithRequiredField], parse_obj_as(type_=typing.Dict[str, ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.Dict[str, ObjectWithRequiredField], + parse_obj_as( + type_=typing.Dict[str, ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -622,7 +752,7 @@ async def get_and_return_optional( self, *, request: typing.Optional[ObjectWithRequiredField] = None, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Optional[ObjectWithRequiredField]: """ Parameters @@ -660,11 +790,21 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/opt-objects", method="POST", json=request, request_options=request_options, omit=OMIT + "container/opt-objects", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Optional[ObjectWithRequiredField], parse_obj_as(type_=typing.Optional[ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.Optional[ObjectWithRequiredField], + parse_obj_as( + type_=typing.Optional[ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/endpoints/enum/client.py b/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/endpoints/enum/client.py index 44e2690ff6c..3e3208e3bcf 100644 --- a/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/endpoints/enum/client.py +++ b/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/endpoints/enum/client.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. import typing +from ...core.client_wrapper import SyncClientWrapper +from ...types.enum.types.weather_report import WeatherReport +from ...core.request_options import RequestOptions +from ...core.pydantic_utilities import parse_obj_as from json.decoder import JSONDecodeError - from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ...core.pydantic_utilities import parse_obj_as -from ...core.request_options import RequestOptions -from ...types.enum.types.weather_report import WeatherReport +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -18,7 +18,10 @@ def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper def get_and_return_enum( - self, *, request: WeatherReport, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: WeatherReport, + request_options: typing.Optional[RequestOptions] = None, ) -> WeatherReport: """ Parameters @@ -45,11 +48,18 @@ def get_and_return_enum( ) """ _response = self._client_wrapper.httpx_client.request( - "enum", method="POST", json=request, request_options=request_options, omit=OMIT + "enum", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(WeatherReport, parse_obj_as(type_=WeatherReport, object_=_response.json())) # type: ignore + return typing.cast( + WeatherReport, + parse_obj_as(type_=WeatherReport, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -61,7 +71,10 @@ def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper async def get_and_return_enum( - self, *, request: WeatherReport, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: WeatherReport, + request_options: typing.Optional[RequestOptions] = None, ) -> WeatherReport: """ Parameters @@ -96,11 +109,18 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "enum", method="POST", json=request, request_options=request_options, omit=OMIT + "enum", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(WeatherReport, parse_obj_as(type_=WeatherReport, object_=_response.json())) # type: ignore + return typing.cast( + WeatherReport, + parse_obj_as(type_=WeatherReport, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/endpoints/http_methods/client.py b/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/endpoints/http_methods/client.py index a2549280a1b..570a227844f 100644 --- a/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/endpoints/http_methods/client.py +++ b/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/endpoints/http_methods/client.py @@ -1,16 +1,16 @@ # This file was auto-generated by Fern from our API Definition. -import datetime as dt import typing -import uuid -from json.decoder import JSONDecodeError - -from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper +from ...core.client_wrapper import SyncClientWrapper +from ...core.request_options import RequestOptions from ...core.jsonable_encoder import jsonable_encoder from ...core.pydantic_utilities import parse_obj_as -from ...core.request_options import RequestOptions +from json.decoder import JSONDecodeError +from ...core.api_error import ApiError from ...types.object.types.object_with_optional_field import ObjectWithOptionalField +import datetime as dt +import uuid +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -20,7 +20,9 @@ class HttpMethodsClient: def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper - def test_get(self, id: str, *, request_options: typing.Optional[RequestOptions] = None) -> str: + def test_get( + self, id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -46,11 +48,15 @@ def test_get(self, id: str, *, request_options: typing.Optional[RequestOptions] ) """ _response = self._client_wrapper.httpx_client.request( - f"http-methods/{jsonable_encoder(id)}", method="GET", request_options=request_options + f"http-methods/{jsonable_encoder(id)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -84,18 +90,33 @@ def test_post( ) """ _response = self._client_wrapper.httpx_client.request( - "http-methods", method="POST", json={"string": string}, request_options=request_options, omit=OMIT + "http-methods", + method="POST", + json={ + "string": string, + }, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def test_put( - self, id: str, *, string: str, request_options: typing.Optional[RequestOptions] = None + self, + id: str, + *, + string: str, + request_options: typing.Optional[RequestOptions] = None, ) -> ObjectWithOptionalField: """ Parameters @@ -127,13 +148,20 @@ def test_put( _response = self._client_wrapper.httpx_client.request( f"http-methods/{jsonable_encoder(id)}", method="PUT", - json={"string": string}, + json={ + "string": string, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -254,13 +282,20 @@ def test_patch( ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def test_delete(self, id: str, *, request_options: typing.Optional[RequestOptions] = None) -> bool: + def test_delete( + self, id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> bool: """ Parameters ---------- @@ -286,11 +321,15 @@ def test_delete(self, id: str, *, request_options: typing.Optional[RequestOption ) """ _response = self._client_wrapper.httpx_client.request( - f"http-methods/{jsonable_encoder(id)}", method="DELETE", request_options=request_options + f"http-methods/{jsonable_encoder(id)}", + method="DELETE", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -301,7 +340,9 @@ class AsyncHttpMethodsClient: def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper - async def test_get(self, id: str, *, request_options: typing.Optional[RequestOptions] = None) -> str: + async def test_get( + self, id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -335,11 +376,15 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - f"http-methods/{jsonable_encoder(id)}", method="GET", request_options=request_options + f"http-methods/{jsonable_encoder(id)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -381,18 +426,33 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "http-methods", method="POST", json={"string": string}, request_options=request_options, omit=OMIT + "http-methods", + method="POST", + json={ + "string": string, + }, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def test_put( - self, id: str, *, string: str, request_options: typing.Optional[RequestOptions] = None + self, + id: str, + *, + string: str, + request_options: typing.Optional[RequestOptions] = None, ) -> ObjectWithOptionalField: """ Parameters @@ -432,13 +492,20 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( f"http-methods/{jsonable_encoder(id)}", method="PUT", - json={"string": string}, + json={ + "string": string, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -566,13 +633,20 @@ async def main() -> None: ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - async def test_delete(self, id: str, *, request_options: typing.Optional[RequestOptions] = None) -> bool: + async def test_delete( + self, id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> bool: """ Parameters ---------- @@ -606,11 +680,15 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - f"http-methods/{jsonable_encoder(id)}", method="DELETE", request_options=request_options + f"http-methods/{jsonable_encoder(id)}", + method="DELETE", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/endpoints/object/client.py b/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/endpoints/object/client.py index a724f959193..dcb1324b74b 100644 --- a/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/endpoints/object/client.py +++ b/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/endpoints/object/client.py @@ -1,20 +1,24 @@ # This file was auto-generated by Fern from our API Definition. -import datetime as dt import typing +from ...core.client_wrapper import SyncClientWrapper +import datetime as dt import uuid -from json.decoder import JSONDecodeError - -from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ...core.jsonable_encoder import jsonable_encoder -from ...core.pydantic_utilities import parse_obj_as from ...core.request_options import RequestOptions -from ...types.object.types.nested_object_with_optional_field import NestedObjectWithOptionalField -from ...types.object.types.nested_object_with_required_field import NestedObjectWithRequiredField -from ...types.object.types.object_with_map_of_map import ObjectWithMapOfMap from ...types.object.types.object_with_optional_field import ObjectWithOptionalField +from ...core.pydantic_utilities import parse_obj_as +from json.decoder import JSONDecodeError +from ...core.api_error import ApiError from ...types.object.types.object_with_required_field import ObjectWithRequiredField +from ...types.object.types.object_with_map_of_map import ObjectWithMapOfMap +from ...types.object.types.nested_object_with_optional_field import ( + NestedObjectWithOptionalField, +) +from ...types.object.types.nested_object_with_required_field import ( + NestedObjectWithRequiredField, +) +from ...core.jsonable_encoder import jsonable_encoder +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -135,7 +139,12 @@ def get_and_return_with_optional_field( ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -171,20 +180,30 @@ def get_and_return_with_required_field( _response = self._client_wrapper.httpx_client.request( "object/get-and-return-with-required-field", method="POST", - json={"string": string}, + json={ + "string": string, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithRequiredField, parse_obj_as(type_=ObjectWithRequiredField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithRequiredField, + parse_obj_as( + type_=ObjectWithRequiredField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_and_return_with_map_of_map( - self, *, map_: typing.Dict[str, typing.Dict[str, str]], request_options: typing.Optional[RequestOptions] = None + self, + *, + map_: typing.Dict[str, typing.Dict[str, str]], + request_options: typing.Optional[RequestOptions] = None, ) -> ObjectWithMapOfMap: """ Parameters @@ -213,13 +232,18 @@ def get_and_return_with_map_of_map( _response = self._client_wrapper.httpx_client.request( "object/get-and-return-with-map-of-map", method="POST", - json={"map": map_}, + json={ + "map": map_, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithMapOfMap, parse_obj_as(type_=ObjectWithMapOfMap, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithMapOfMap, + parse_obj_as(type_=ObjectWithMapOfMap, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -286,13 +310,21 @@ def get_and_return_nested_with_optional_field( _response = self._client_wrapper.httpx_client.request( "object/get-and-return-nested-with-optional-field", method="POST", - json={"string": string, "NestedObject": nested_object}, + json={ + "string": string, + "NestedObject": nested_object, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(NestedObjectWithOptionalField, parse_obj_as(type_=NestedObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + NestedObjectWithOptionalField, + parse_obj_as( + type_=NestedObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -363,13 +395,21 @@ def get_and_return_nested_with_required_field( _response = self._client_wrapper.httpx_client.request( f"object/get-and-return-nested-with-required-field/{jsonable_encoder(string_)}", method="POST", - json={"string": string, "NestedObject": nested_object}, + json={ + "string": string, + "NestedObject": nested_object, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(NestedObjectWithRequiredField, parse_obj_as(type_=NestedObjectWithRequiredField, object_=_response.json())) # type: ignore + return typing.cast( + NestedObjectWithRequiredField, + parse_obj_as( + type_=NestedObjectWithRequiredField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -446,7 +486,12 @@ def get_and_return_nested_with_required_field_as_list( ) try: if 200 <= _response.status_code < 300: - return typing.cast(NestedObjectWithRequiredField, parse_obj_as(type_=NestedObjectWithRequiredField, object_=_response.json())) # type: ignore + return typing.cast( + NestedObjectWithRequiredField, + parse_obj_as( + type_=NestedObjectWithRequiredField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -575,7 +620,12 @@ async def main() -> None: ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -619,20 +669,30 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( "object/get-and-return-with-required-field", method="POST", - json={"string": string}, + json={ + "string": string, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithRequiredField, parse_obj_as(type_=ObjectWithRequiredField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithRequiredField, + parse_obj_as( + type_=ObjectWithRequiredField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_and_return_with_map_of_map( - self, *, map_: typing.Dict[str, typing.Dict[str, str]], request_options: typing.Optional[RequestOptions] = None + self, + *, + map_: typing.Dict[str, typing.Dict[str, str]], + request_options: typing.Optional[RequestOptions] = None, ) -> ObjectWithMapOfMap: """ Parameters @@ -669,13 +729,18 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( "object/get-and-return-with-map-of-map", method="POST", - json={"map": map_}, + json={ + "map": map_, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithMapOfMap, parse_obj_as(type_=ObjectWithMapOfMap, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithMapOfMap, + parse_obj_as(type_=ObjectWithMapOfMap, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -749,13 +814,21 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( "object/get-and-return-nested-with-optional-field", method="POST", - json={"string": string, "NestedObject": nested_object}, + json={ + "string": string, + "NestedObject": nested_object, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(NestedObjectWithOptionalField, parse_obj_as(type_=NestedObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + NestedObjectWithOptionalField, + parse_obj_as( + type_=NestedObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -833,13 +906,21 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( f"object/get-and-return-nested-with-required-field/{jsonable_encoder(string_)}", method="POST", - json={"string": string, "NestedObject": nested_object}, + json={ + "string": string, + "NestedObject": nested_object, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(NestedObjectWithRequiredField, parse_obj_as(type_=NestedObjectWithRequiredField, object_=_response.json())) # type: ignore + return typing.cast( + NestedObjectWithRequiredField, + parse_obj_as( + type_=NestedObjectWithRequiredField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -923,7 +1004,12 @@ async def main() -> None: ) try: if 200 <= _response.status_code < 300: - return typing.cast(NestedObjectWithRequiredField, parse_obj_as(type_=NestedObjectWithRequiredField, object_=_response.json())) # type: ignore + return typing.cast( + NestedObjectWithRequiredField, + parse_obj_as( + type_=NestedObjectWithRequiredField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/endpoints/params/client.py b/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/endpoints/params/client.py index 5cd7ceef42a..a9187ac94b8 100644 --- a/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/endpoints/params/client.py +++ b/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/endpoints/params/client.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. import typing -from json.decoder import JSONDecodeError - -from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper +from ...core.client_wrapper import SyncClientWrapper +from ...core.request_options import RequestOptions from ...core.jsonable_encoder import jsonable_encoder from ...core.pydantic_utilities import parse_obj_as -from ...core.request_options import RequestOptions +from json.decoder import JSONDecodeError +from ...core.api_error import ApiError +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -17,7 +17,9 @@ class ParamsClient: def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper - def get_with_path(self, param: str, *, request_options: typing.Optional[RequestOptions] = None) -> str: + def get_with_path( + self, param: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ GET with path param @@ -45,18 +47,26 @@ def get_with_path(self, param: str, *, request_options: typing.Optional[RequestO ) """ _response = self._client_wrapper.httpx_client.request( - f"params/path/{jsonable_encoder(param)}", method="GET", request_options=request_options + f"params/path/{jsonable_encoder(param)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_with_query( - self, *, query: str, number: int, request_options: typing.Optional[RequestOptions] = None + self, + *, + query: str, + number: int, + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ GET with query param @@ -88,7 +98,13 @@ def get_with_query( ) """ _response = self._client_wrapper.httpx_client.request( - "params", method="GET", params={"query": query, "number": number}, request_options=request_options + "params", + method="GET", + params={ + "query": query, + "number": number, + }, + request_options=request_options, ) try: if 200 <= _response.status_code < 300: @@ -135,7 +151,13 @@ def get_with_allow_multiple_query( ) """ _response = self._client_wrapper.httpx_client.request( - "params", method="GET", params={"query": query, "numer": numer}, request_options=request_options + "params", + method="GET", + params={ + "query": query, + "numer": numer, + }, + request_options=request_options, ) try: if 200 <= _response.status_code < 300: @@ -146,7 +168,11 @@ def get_with_allow_multiple_query( raise ApiError(status_code=_response.status_code, body=_response_json) def get_with_path_and_query( - self, param: str, *, query: str, request_options: typing.Optional[RequestOptions] = None + self, + param: str, + *, + query: str, + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ GET with path and query params @@ -180,7 +206,9 @@ def get_with_path_and_query( _response = self._client_wrapper.httpx_client.request( f"params/path-query/{jsonable_encoder(param)}", method="GET", - params={"query": query}, + params={ + "query": query, + }, request_options=request_options, ) try: @@ -192,7 +220,11 @@ def get_with_path_and_query( raise ApiError(status_code=_response.status_code, body=_response_json) def modify_with_path( - self, param: str, *, request: str, request_options: typing.Optional[RequestOptions] = None + self, + param: str, + *, + request: str, + request_options: typing.Optional[RequestOptions] = None, ) -> str: """ PUT to update with path param @@ -232,7 +264,9 @@ def modify_with_path( ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -243,7 +277,9 @@ class AsyncParamsClient: def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper - async def get_with_path(self, param: str, *, request_options: typing.Optional[RequestOptions] = None) -> str: + async def get_with_path( + self, param: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ GET with path param @@ -279,18 +315,26 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - f"params/path/{jsonable_encoder(param)}", method="GET", request_options=request_options + f"params/path/{jsonable_encoder(param)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_with_query( - self, *, query: str, number: int, request_options: typing.Optional[RequestOptions] = None + self, + *, + query: str, + number: int, + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ GET with query param @@ -330,7 +374,13 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "params", method="GET", params={"query": query, "number": number}, request_options=request_options + "params", + method="GET", + params={ + "query": query, + "number": number, + }, + request_options=request_options, ) try: if 200 <= _response.status_code < 300: @@ -385,7 +435,13 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "params", method="GET", params={"query": query, "numer": numer}, request_options=request_options + "params", + method="GET", + params={ + "query": query, + "numer": numer, + }, + request_options=request_options, ) try: if 200 <= _response.status_code < 300: @@ -396,7 +452,11 @@ async def main() -> None: raise ApiError(status_code=_response.status_code, body=_response_json) async def get_with_path_and_query( - self, param: str, *, query: str, request_options: typing.Optional[RequestOptions] = None + self, + param: str, + *, + query: str, + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ GET with path and query params @@ -438,7 +498,9 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( f"params/path-query/{jsonable_encoder(param)}", method="GET", - params={"query": query}, + params={ + "query": query, + }, request_options=request_options, ) try: @@ -450,7 +512,11 @@ async def main() -> None: raise ApiError(status_code=_response.status_code, body=_response_json) async def modify_with_path( - self, param: str, *, request: str, request_options: typing.Optional[RequestOptions] = None + self, + param: str, + *, + request: str, + request_options: typing.Optional[RequestOptions] = None, ) -> str: """ PUT to update with path param @@ -498,7 +564,9 @@ async def main() -> None: ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/endpoints/primitive/client.py b/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/endpoints/primitive/client.py index 844b6a782f0..20a66f049b4 100644 --- a/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/endpoints/primitive/client.py +++ b/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/endpoints/primitive/client.py @@ -1,14 +1,14 @@ # This file was auto-generated by Fern from our API Definition. -import datetime as dt import typing -import uuid +from ...core.client_wrapper import SyncClientWrapper +from ...core.request_options import RequestOptions +from ...core.pydantic_utilities import parse_obj_as from json.decoder import JSONDecodeError - from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ...core.pydantic_utilities import parse_obj_as -from ...core.request_options import RequestOptions +import datetime as dt +import uuid +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -18,7 +18,9 @@ class PrimitiveClient: def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper - def get_and_return_string(self, *, request: str, request_options: typing.Optional[RequestOptions] = None) -> str: + def get_and_return_string( + self, *, request: str, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -44,17 +46,25 @@ def get_and_return_string(self, *, request: str, request_options: typing.Optiona ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/string", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/string", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def get_and_return_int(self, *, request: int, request_options: typing.Optional[RequestOptions] = None) -> int: + def get_and_return_int( + self, *, request: int, request_options: typing.Optional[RequestOptions] = None + ) -> int: """ Parameters ---------- @@ -80,17 +90,25 @@ def get_and_return_int(self, *, request: int, request_options: typing.Optional[R ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/integer", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/integer", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(int, parse_obj_as(type_=int, object_=_response.json())) # type: ignore + return typing.cast( + int, parse_obj_as(type_=int, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def get_and_return_long(self, *, request: int, request_options: typing.Optional[RequestOptions] = None) -> int: + def get_and_return_long( + self, *, request: int, request_options: typing.Optional[RequestOptions] = None + ) -> int: """ Parameters ---------- @@ -116,11 +134,17 @@ def get_and_return_long(self, *, request: int, request_options: typing.Optional[ ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/long", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/long", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(int, parse_obj_as(type_=int, object_=_response.json())) # type: ignore + return typing.cast( + int, parse_obj_as(type_=int, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -154,17 +178,25 @@ def get_and_return_double( ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/double", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/double", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(float, parse_obj_as(type_=float, object_=_response.json())) # type: ignore + return typing.cast( + float, parse_obj_as(type_=float, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def get_and_return_bool(self, *, request: bool, request_options: typing.Optional[RequestOptions] = None) -> bool: + def get_and_return_bool( + self, *, request: bool, request_options: typing.Optional[RequestOptions] = None + ) -> bool: """ Parameters ---------- @@ -190,18 +222,27 @@ def get_and_return_bool(self, *, request: bool, request_options: typing.Optional ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/boolean", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/boolean", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_and_return_datetime( - self, *, request: dt.datetime, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: dt.datetime, + request_options: typing.Optional[RequestOptions] = None, ) -> dt.datetime: """ Parameters @@ -232,18 +273,28 @@ def get_and_return_datetime( ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/datetime", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/datetime", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(dt.datetime, parse_obj_as(type_=dt.datetime, object_=_response.json())) # type: ignore + return typing.cast( + dt.datetime, + parse_obj_as(type_=dt.datetime, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_and_return_date( - self, *, request: dt.date, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: dt.date, + request_options: typing.Optional[RequestOptions] = None, ) -> dt.date: """ Parameters @@ -274,18 +325,27 @@ def get_and_return_date( ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/date", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/date", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(dt.date, parse_obj_as(type_=dt.date, object_=_response.json())) # type: ignore + return typing.cast( + dt.date, parse_obj_as(type_=dt.date, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_and_return_uuid( - self, *, request: uuid.UUID, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: uuid.UUID, + request_options: typing.Optional[RequestOptions] = None, ) -> uuid.UUID: """ Parameters @@ -316,17 +376,25 @@ def get_and_return_uuid( ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/uuid", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/uuid", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(uuid.UUID, parse_obj_as(type_=uuid.UUID, object_=_response.json())) # type: ignore + return typing.cast( + uuid.UUID, parse_obj_as(type_=uuid.UUID, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def get_and_return_base_64(self, *, request: str, request_options: typing.Optional[RequestOptions] = None) -> str: + def get_and_return_base_64( + self, *, request: str, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -352,11 +420,17 @@ def get_and_return_base_64(self, *, request: str, request_options: typing.Option ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/base64", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/base64", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -403,17 +477,25 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/string", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/string", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - async def get_and_return_int(self, *, request: int, request_options: typing.Optional[RequestOptions] = None) -> int: + async def get_and_return_int( + self, *, request: int, request_options: typing.Optional[RequestOptions] = None + ) -> int: """ Parameters ---------- @@ -447,11 +529,17 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/integer", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/integer", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(int, parse_obj_as(type_=int, object_=_response.json())) # type: ignore + return typing.cast( + int, parse_obj_as(type_=int, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -493,11 +581,17 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/long", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/long", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(int, parse_obj_as(type_=int, object_=_response.json())) # type: ignore + return typing.cast( + int, parse_obj_as(type_=int, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -539,11 +633,17 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/double", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/double", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(float, parse_obj_as(type_=float, object_=_response.json())) # type: ignore + return typing.cast( + float, parse_obj_as(type_=float, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -585,18 +685,27 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/boolean", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/boolean", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_and_return_datetime( - self, *, request: dt.datetime, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: dt.datetime, + request_options: typing.Optional[RequestOptions] = None, ) -> dt.datetime: """ Parameters @@ -634,18 +743,28 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/datetime", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/datetime", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(dt.datetime, parse_obj_as(type_=dt.datetime, object_=_response.json())) # type: ignore + return typing.cast( + dt.datetime, + parse_obj_as(type_=dt.datetime, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_and_return_date( - self, *, request: dt.date, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: dt.date, + request_options: typing.Optional[RequestOptions] = None, ) -> dt.date: """ Parameters @@ -683,18 +802,27 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/date", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/date", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(dt.date, parse_obj_as(type_=dt.date, object_=_response.json())) # type: ignore + return typing.cast( + dt.date, parse_obj_as(type_=dt.date, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_and_return_uuid( - self, *, request: uuid.UUID, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: uuid.UUID, + request_options: typing.Optional[RequestOptions] = None, ) -> uuid.UUID: """ Parameters @@ -732,11 +860,17 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/uuid", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/uuid", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(uuid.UUID, parse_obj_as(type_=uuid.UUID, object_=_response.json())) # type: ignore + return typing.cast( + uuid.UUID, parse_obj_as(type_=uuid.UUID, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -778,11 +912,17 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/base64", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/base64", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/endpoints/union/client.py b/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/endpoints/union/client.py index 77153587a27..f4c3d9312de 100644 --- a/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/endpoints/union/client.py +++ b/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/endpoints/union/client.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. import typing +from ...core.client_wrapper import SyncClientWrapper +from ...types.union.types.animal import Animal +from ...core.request_options import RequestOptions +from ...core.pydantic_utilities import parse_obj_as from json.decoder import JSONDecodeError - from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ...core.pydantic_utilities import parse_obj_as -from ...core.request_options import RequestOptions -from ...types.union.types.animal import Animal +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -18,7 +18,10 @@ def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper def get_and_return_union( - self, *, request: Animal, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: Animal, + request_options: typing.Optional[RequestOptions] = None, ) -> Animal: """ Parameters @@ -49,11 +52,17 @@ def get_and_return_union( ) """ _response = self._client_wrapper.httpx_client.request( - "union", method="POST", json=request, request_options=request_options, omit=OMIT + "union", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(Animal, parse_obj_as(type_=Animal, object_=_response.json())) # type: ignore + return typing.cast( + Animal, parse_obj_as(type_=Animal, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -65,7 +74,10 @@ def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper async def get_and_return_union( - self, *, request: Animal, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: Animal, + request_options: typing.Optional[RequestOptions] = None, ) -> Animal: """ Parameters @@ -104,11 +116,17 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "union", method="POST", json=request, request_options=request_options, omit=OMIT + "union", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(Animal, parse_obj_as(type_=Animal, object_=_response.json())) # type: ignore + return typing.cast( + Animal, parse_obj_as(type_=Animal, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/general_errors/types/bad_object_request_info.py b/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/general_errors/types/bad_object_request_info.py index 7f03429e922..73c44b89531 100644 --- a/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/general_errors/types/bad_object_request_info.py +++ b/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/general_errors/types/bad_object_request_info.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class BadObjectRequestInfo(UniversalBaseModel): message: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/inlined_requests/client.py b/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/inlined_requests/client.py index f7c46698eb9..39e0c8fe637 100644 --- a/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/inlined_requests/client.py +++ b/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/inlined_requests/client.py @@ -1,15 +1,15 @@ # This file was auto-generated by Fern from our API Definition. import typing -from json.decoder import JSONDecodeError - -from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.pydantic_utilities import parse_obj_as +from ..core.client_wrapper import SyncClientWrapper +from ..types.object.types.object_with_optional_field import ObjectWithOptionalField from ..core.request_options import RequestOptions +from ..core.pydantic_utilities import parse_obj_as from ..general_errors.errors.bad_request_body import BadRequestBody from ..general_errors.types.bad_object_request_info import BadObjectRequestInfo -from ..types.object.types.object_with_optional_field import ObjectWithOptionalField +from json.decoder import JSONDecodeError +from ..core.api_error import ApiError +from ..core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -25,7 +25,7 @@ def post_with_object_bodyand_response( string: str, integer: int, nested_object: ObjectWithOptionalField, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> ObjectWithOptionalField: """ POST with custom object in request body, response is an object @@ -86,16 +86,30 @@ def post_with_object_bodyand_response( _response = self._client_wrapper.httpx_client.request( "req-bodies/object", method="POST", - json={"string": string, "integer": integer, "NestedObject": nested_object}, + json={ + "string": string, + "integer": integer, + "NestedObject": nested_object, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore if _response.status_code == 400: raise BadRequestBody( - typing.cast(BadObjectRequestInfo, parse_obj_as(type_=BadObjectRequestInfo, object_=_response.json())) # type: ignore + typing.cast( + BadObjectRequestInfo, + parse_obj_as( + type_=BadObjectRequestInfo, object_=_response.json() + ), + ) # type: ignore ) _response_json = _response.json() except JSONDecodeError: @@ -113,7 +127,7 @@ async def post_with_object_bodyand_response( string: str, integer: int, nested_object: ObjectWithOptionalField, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> ObjectWithOptionalField: """ POST with custom object in request body, response is an object @@ -181,16 +195,30 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( "req-bodies/object", method="POST", - json={"string": string, "integer": integer, "NestedObject": nested_object}, + json={ + "string": string, + "integer": integer, + "NestedObject": nested_object, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore if _response.status_code == 400: raise BadRequestBody( - typing.cast(BadObjectRequestInfo, parse_obj_as(type_=BadObjectRequestInfo, object_=_response.json())) # type: ignore + typing.cast( + BadObjectRequestInfo, + parse_obj_as( + type_=BadObjectRequestInfo, object_=_response.json() + ), + ) # type: ignore ) _response_json = _response.json() except JSONDecodeError: diff --git a/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/no_auth/client.py b/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/no_auth/client.py index 3d203bcea34..e5590cde0df 100644 --- a/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/no_auth/client.py +++ b/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/no_auth/client.py @@ -1,14 +1,14 @@ # This file was auto-generated by Fern from our API Definition. import typing -from json.decoder import JSONDecodeError - -from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.pydantic_utilities import parse_obj_as +from ..core.client_wrapper import SyncClientWrapper from ..core.request_options import RequestOptions +from ..core.pydantic_utilities import parse_obj_as from ..general_errors.errors.bad_request_body import BadRequestBody from ..general_errors.types.bad_object_request_info import BadObjectRequestInfo +from json.decoder import JSONDecodeError +from ..core.api_error import ApiError +from ..core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -19,7 +19,10 @@ def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper def post_with_no_auth( - self, *, request: typing.Any, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Any, + request_options: typing.Optional[RequestOptions] = None, ) -> bool: """ POST request with no auth @@ -48,14 +51,25 @@ def post_with_no_auth( ) """ _response = self._client_wrapper.httpx_client.request( - "no-auth", method="POST", json=request, request_options=request_options, omit=OMIT + "no-auth", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore if _response.status_code == 400: raise BadRequestBody( - typing.cast(BadObjectRequestInfo, parse_obj_as(type_=BadObjectRequestInfo, object_=_response.json())) # type: ignore + typing.cast( + BadObjectRequestInfo, + parse_obj_as( + type_=BadObjectRequestInfo, object_=_response.json() + ), + ) # type: ignore ) _response_json = _response.json() except JSONDecodeError: @@ -68,7 +82,10 @@ def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper async def post_with_no_auth( - self, *, request: typing.Any, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Any, + request_options: typing.Optional[RequestOptions] = None, ) -> bool: """ POST request with no auth @@ -105,14 +122,25 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "no-auth", method="POST", json=request, request_options=request_options, omit=OMIT + "no-auth", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore if _response.status_code == 400: raise BadRequestBody( - typing.cast(BadObjectRequestInfo, parse_obj_as(type_=BadObjectRequestInfo, object_=_response.json())) # type: ignore + typing.cast( + BadObjectRequestInfo, + parse_obj_as( + type_=BadObjectRequestInfo, object_=_response.json() + ), + ) # type: ignore ) _response_json = _response.json() except JSONDecodeError: diff --git a/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/no_req_body/client.py b/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/no_req_body/client.py index 33fa0c77d27..5afdd703fdc 100644 --- a/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/no_req_body/client.py +++ b/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/no_req_body/client.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. +from ..core.client_wrapper import SyncClientWrapper import typing -from json.decoder import JSONDecodeError - -from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.pydantic_utilities import parse_obj_as from ..core.request_options import RequestOptions from ..types.object.types.object_with_optional_field import ObjectWithOptionalField +from ..core.pydantic_utilities import parse_obj_as +from json.decoder import JSONDecodeError +from ..core.api_error import ApiError +from ..core.client_wrapper import AsyncClientWrapper class NoReqBodyClient: @@ -38,17 +38,26 @@ def get_with_no_request_body( client.no_req_body.get_with_no_request_body() """ _response = self._client_wrapper.httpx_client.request( - "no-req-body", method="GET", request_options=request_options + "no-req-body", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def post_with_no_request_body(self, *, request_options: typing.Optional[RequestOptions] = None) -> str: + def post_with_no_request_body( + self, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -70,11 +79,15 @@ def post_with_no_request_body(self, *, request_options: typing.Optional[RequestO client.no_req_body.post_with_no_request_body() """ _response = self._client_wrapper.httpx_client.request( - "no-req-body", method="POST", request_options=request_options + "no-req-body", + method="POST", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -117,17 +130,26 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "no-req-body", method="GET", request_options=request_options + "no-req-body", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - async def post_with_no_request_body(self, *, request_options: typing.Optional[RequestOptions] = None) -> str: + async def post_with_no_request_body( + self, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -157,11 +179,15 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "no-req-body", method="POST", request_options=request_options + "no-req-body", + method="POST", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/req_with_headers/client.py b/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/req_with_headers/client.py index 655402249e9..984428516e3 100644 --- a/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/req_with_headers/client.py +++ b/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/req_with_headers/client.py @@ -1,11 +1,11 @@ # This file was auto-generated by Fern from our API Definition. import typing +from ..core.client_wrapper import SyncClientWrapper +from ..core.request_options import RequestOptions from json.decoder import JSONDecodeError - from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.request_options import RequestOptions +from ..core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -21,7 +21,7 @@ def get_with_custom_header( x_test_service_header: str, x_test_endpoint_header: str, request: str, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ Parameters @@ -58,8 +58,12 @@ def get_with_custom_header( method="POST", json=request, headers={ - "X-TEST-SERVICE-HEADER": str(x_test_service_header) if x_test_service_header is not None else None, - "X-TEST-ENDPOINT-HEADER": str(x_test_endpoint_header) if x_test_endpoint_header is not None else None, + "X-TEST-SERVICE-HEADER": str(x_test_service_header) + if x_test_service_header is not None + else None, + "X-TEST-ENDPOINT-HEADER": str(x_test_endpoint_header) + if x_test_endpoint_header is not None + else None, }, request_options=request_options, omit=OMIT, @@ -83,7 +87,7 @@ async def get_with_custom_header( x_test_service_header: str, x_test_endpoint_header: str, request: str, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ Parameters @@ -128,8 +132,12 @@ async def main() -> None: method="POST", json=request, headers={ - "X-TEST-SERVICE-HEADER": str(x_test_service_header) if x_test_service_header is not None else None, - "X-TEST-ENDPOINT-HEADER": str(x_test_endpoint_header) if x_test_endpoint_header is not None else None, + "X-TEST-SERVICE-HEADER": str(x_test_service_header) + if x_test_service_header is not None + else None, + "X-TEST-ENDPOINT-HEADER": str(x_test_endpoint_header) + if x_test_endpoint_header is not None + else None, }, request_options=request_options, omit=OMIT, diff --git a/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/types/enum/types/weather_report.py b/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/types/enum/types/weather_report.py index 2d54965dc22..84017ef161d 100644 --- a/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/types/enum/types/weather_report.py +++ b/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/types/enum/types/weather_report.py @@ -2,4 +2,6 @@ import typing -WeatherReport = typing.Union[typing.Literal["SUNNY", "CLOUDY", "RAINING", "SNOWING"], typing.Any] +WeatherReport = typing.Union[ + typing.Literal["SUNNY", "CLOUDY", "RAINING", "SNOWING"], typing.Any +] diff --git a/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/types/object/types/double_optional.py b/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/types/object/types/double_optional.py index ddf165b13bd..ed236347357 100644 --- a/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/types/object/types/double_optional.py +++ b/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/types/object/types/double_optional.py @@ -1,18 +1,21 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .optional_alias import OptionalAlias +import pydantic +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class DoubleOptional(UniversalBaseModel): - optional_alias: typing.Optional[OptionalAlias] = pydantic.Field(alias="optionalAlias", default=None) + optional_alias: typing.Optional[OptionalAlias] = pydantic.Field( + alias="optionalAlias", default=None + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/types/object/types/nested_object_with_optional_field.py b/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/types/object/types/nested_object_with_optional_field.py index 81669c0dd39..20a4d40a714 100644 --- a/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/types/object/types/nested_object_with_optional_field.py +++ b/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/types/object/types/nested_object_with_optional_field.py @@ -1,19 +1,22 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .object_with_optional_field import ObjectWithOptionalField +import pydantic +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class NestedObjectWithOptionalField(UniversalBaseModel): string: typing.Optional[str] = None - nested_object: typing.Optional[ObjectWithOptionalField] = pydantic.Field(alias="NestedObject", default=None) + nested_object: typing.Optional[ObjectWithOptionalField] = pydantic.Field( + alias="NestedObject", default=None + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/types/object/types/nested_object_with_required_field.py b/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/types/object/types/nested_object_with_required_field.py index 1a621942c6c..a6ca8781190 100644 --- a/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/types/object/types/nested_object_with_required_field.py +++ b/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/types/object/types/nested_object_with_required_field.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import UniversalBaseModel from .object_with_optional_field import ObjectWithOptionalField +import pydantic +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class NestedObjectWithRequiredField(UniversalBaseModel): @@ -13,7 +12,9 @@ class NestedObjectWithRequiredField(UniversalBaseModel): nested_object: ObjectWithOptionalField = pydantic.Field(alias="NestedObject") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/types/object/types/object_with_map_of_map.py b/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/types/object/types/object_with_map_of_map.py index 8883cc1d498..313cd25ceb8 100644 --- a/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/types/object/types/object_with_map_of_map.py +++ b/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/types/object/types/object_with_map_of_map.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class ObjectWithMapOfMap(UniversalBaseModel): map_: typing.Dict[str, typing.Dict[str, str]] = pydantic.Field(alias="map") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/types/object/types/object_with_optional_field.py b/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/types/object/types/object_with_optional_field.py index 6aab170be0c..9131f0e91d7 100644 --- a/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/types/object/types/object_with_optional_field.py +++ b/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/types/object/types/object_with_optional_field.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. -import datetime as dt +from ....core.pydantic_utilities import UniversalBaseModel import typing -import uuid - import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +import datetime as dt +import uuid +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class ObjectWithOptionalField(UniversalBaseModel): @@ -23,13 +22,19 @@ class ObjectWithOptionalField(UniversalBaseModel): date: typing.Optional[dt.date] = None uuid_: typing.Optional[uuid.UUID] = pydantic.Field(alias="uuid", default=None) base_64: typing.Optional[str] = pydantic.Field(alias="base64", default=None) - list_: typing.Optional[typing.List[str]] = pydantic.Field(alias="list", default=None) + list_: typing.Optional[typing.List[str]] = pydantic.Field( + alias="list", default=None + ) set_: typing.Optional[typing.Set[str]] = pydantic.Field(alias="set", default=None) - map_: typing.Optional[typing.Dict[int, str]] = pydantic.Field(alias="map", default=None) + map_: typing.Optional[typing.Dict[int, str]] = pydantic.Field( + alias="map", default=None + ) bigint: typing.Optional[str] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/types/object/types/object_with_required_field.py b/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/types/object/types/object_with_required_field.py index 61b98867984..24db26a3cf8 100644 --- a/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/types/object/types/object_with_required_field.py +++ b/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/types/object/types/object_with_required_field.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class ObjectWithRequiredField(UniversalBaseModel): string: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/types/union/types/animal.py b/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/types/union/types/animal.py index 1ae43d1663e..84c71d2009a 100644 --- a/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/types/union/types/animal.py +++ b/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/types/union/types/animal.py @@ -1,12 +1,10 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ....core.pydantic_utilities import UniversalBaseModel import typing - import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class Animal_Dog(UniversalBaseModel): @@ -15,7 +13,9 @@ class Animal_Dog(UniversalBaseModel): likes_to_woof: bool = pydantic.Field(alias="likesToWoof") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: @@ -30,7 +30,9 @@ class Animal_Cat(UniversalBaseModel): likes_to_meow: bool = pydantic.Field(alias="likesToMeow") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/types/union/types/cat.py b/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/types/union/types/cat.py index 61fc5527b1f..c59b78523c9 100644 --- a/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/types/union/types/cat.py +++ b/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/types/union/types/cat.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ....core.pydantic_utilities import UniversalBaseModel import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class Cat(UniversalBaseModel): @@ -12,7 +11,9 @@ class Cat(UniversalBaseModel): likes_to_meow: bool = pydantic.Field(alias="likesToMeow") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/types/union/types/dog.py b/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/types/union/types/dog.py index c1ff5339dfe..e250c72edef 100644 --- a/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/types/union/types/dog.py +++ b/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/types/union/types/dog.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ....core.pydantic_utilities import UniversalBaseModel import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class Dog(UniversalBaseModel): @@ -12,7 +11,9 @@ class Dog(UniversalBaseModel): likes_to_woof: bool = pydantic.Field(alias="likesToWoof") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/version.py b/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/version.py index 63ba170685a..ac44536abdb 100644 --- a/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/version.py +++ b/seed/python-sdk/exhaustive/follow_redirects_by_default/src/seed/version.py @@ -1,4 +1,3 @@ - from importlib import metadata __version__ = metadata.version("fern_exhaustive") diff --git a/seed/python-sdk/exhaustive/follow_redirects_by_default/tests/conftest.py b/seed/python-sdk/exhaustive/follow_redirects_by_default/tests/conftest.py index b5b50383b94..86cb2b41af8 100644 --- a/seed/python-sdk/exhaustive/follow_redirects_by_default/tests/conftest.py +++ b/seed/python-sdk/exhaustive/follow_redirects_by_default/tests/conftest.py @@ -1,16 +1,22 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive import os - import pytest -from seed import AsyncSeedExhaustive, SeedExhaustive +from seed import AsyncSeedExhaustive @pytest.fixture def client() -> SeedExhaustive: - return SeedExhaustive(token=os.getenv("ENV_TOKEN", "token"), base_url=os.getenv("TESTS_BASE_URL", "base_url")) + return SeedExhaustive( + token=os.getenv("ENV_TOKEN", "token"), + base_url=os.getenv("TESTS_BASE_URL", "base_url"), + ) @pytest.fixture def async_client() -> AsyncSeedExhaustive: - return AsyncSeedExhaustive(token=os.getenv("ENV_TOKEN", "token"), base_url=os.getenv("TESTS_BASE_URL", "base_url")) + return AsyncSeedExhaustive( + token=os.getenv("ENV_TOKEN", "token"), + base_url=os.getenv("TESTS_BASE_URL", "base_url"), + ) diff --git a/seed/python-sdk/exhaustive/follow_redirects_by_default/tests/custom/test_client.py b/seed/python-sdk/exhaustive/follow_redirects_by_default/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/python-sdk/exhaustive/follow_redirects_by_default/tests/custom/test_client.py +++ b/seed/python-sdk/exhaustive/follow_redirects_by_default/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/python-sdk/exhaustive/follow_redirects_by_default/tests/endpoints/test_container.py b/seed/python-sdk/exhaustive/follow_redirects_by_default/tests/endpoints/test_container.py index 17d9d75240d..240f16f2a8c 100644 --- a/seed/python-sdk/exhaustive/follow_redirects_by_default/tests/endpoints/test_container.py +++ b/seed/python-sdk/exhaustive/follow_redirects_by_default/tests/endpoints/test_container.py @@ -1,91 +1,137 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing - -from seed import AsyncSeedExhaustive, SeedExhaustive -from seed.types.object import ObjectWithRequiredField - from ..utilities import validate_response +from seed.types.object import ObjectWithRequiredField -async def test_get_and_return_list_of_primitives(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_list_of_primitives( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = ["string"] expected_types: typing.Tuple[typing.Any, typing.Any] = ("list", {0: None}) - response = client.endpoints.container.get_and_return_list_of_primitives(request=["string"]) + response = client.endpoints.container.get_and_return_list_of_primitives( + request=["string"] + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.container.get_and_return_list_of_primitives(request=["string"]) + async_response = ( + await async_client.endpoints.container.get_and_return_list_of_primitives( + request=["string"] + ) + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_list_of_objects(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_list_of_objects( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = [{"string": "string"}] - expected_types: typing.Tuple[typing.Any, typing.Any] = ("list", {0: {"string": None}}) + expected_types: typing.Tuple[typing.Any, typing.Any] = ( + "list", + {0: {"string": None}}, + ) response = client.endpoints.container.get_and_return_list_of_objects( request=[ObjectWithRequiredField(string="string")] ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.container.get_and_return_list_of_objects( - request=[ObjectWithRequiredField(string="string")] + async_response = ( + await async_client.endpoints.container.get_and_return_list_of_objects( + request=[ObjectWithRequiredField(string="string")] + ) ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_set_of_primitives(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_set_of_primitives( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = ["string"] expected_types: typing.Tuple[typing.Any, typing.Any] = ("set", {0: None}) - response = client.endpoints.container.get_and_return_set_of_primitives(request={"string"}) + response = client.endpoints.container.get_and_return_set_of_primitives( + request={"string"} + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.container.get_and_return_set_of_primitives(request={"string"}) + async_response = ( + await async_client.endpoints.container.get_and_return_set_of_primitives( + request={"string"} + ) + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_set_of_objects(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_set_of_objects( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = [{"string": "string"}] - expected_types: typing.Tuple[typing.Any, typing.Any] = ("set", {0: {"string": None}}) + expected_types: typing.Tuple[typing.Any, typing.Any] = ( + "set", + {0: {"string": None}}, + ) response = client.endpoints.container.get_and_return_set_of_objects( request=[ObjectWithRequiredField(string="string")] ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.container.get_and_return_set_of_objects( - request=[ObjectWithRequiredField(string="string")] + async_response = ( + await async_client.endpoints.container.get_and_return_set_of_objects( + request=[ObjectWithRequiredField(string="string")] + ) ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_map_prim_to_prim(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_map_prim_to_prim( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = {"string": "string"} expected_types: typing.Tuple[typing.Any, typing.Any] = ("dict", {0: (None, None)}) - response = client.endpoints.container.get_and_return_map_prim_to_prim(request={"string": "string"}) + response = client.endpoints.container.get_and_return_map_prim_to_prim( + request={"string": "string"} + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.container.get_and_return_map_prim_to_prim( - request={"string": "string"} + async_response = ( + await async_client.endpoints.container.get_and_return_map_prim_to_prim( + request={"string": "string"} + ) ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_map_of_prim_to_object(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_map_of_prim_to_object( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = {"string": {"string": "string"}} - expected_types: typing.Tuple[typing.Any, typing.Any] = ("dict", {0: (None, {"string": None})}) + expected_types: typing.Tuple[typing.Any, typing.Any] = ( + "dict", + {0: (None, {"string": None})}, + ) response = client.endpoints.container.get_and_return_map_of_prim_to_object( request={"string": ObjectWithRequiredField(string="string")} ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.container.get_and_return_map_of_prim_to_object( - request={"string": ObjectWithRequiredField(string="string")} + async_response = ( + await async_client.endpoints.container.get_and_return_map_of_prim_to_object( + request={"string": ObjectWithRequiredField(string="string")} + ) ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_optional(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_optional( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = {"string": "string"} expected_types: typing.Any = {"string": None} - response = client.endpoints.container.get_and_return_optional(request=ObjectWithRequiredField(string="string")) + response = client.endpoints.container.get_and_return_optional( + request=ObjectWithRequiredField(string="string") + ) validate_response(response, expected_response, expected_types) async_response = await async_client.endpoints.container.get_and_return_optional( diff --git a/seed/python-sdk/exhaustive/follow_redirects_by_default/tests/endpoints/test_enum.py b/seed/python-sdk/exhaustive/follow_redirects_by_default/tests/endpoints/test_enum.py index 890aada5ce4..ca3fca30b5a 100644 --- a/seed/python-sdk/exhaustive/follow_redirects_by_default/tests/endpoints/test_enum.py +++ b/seed/python-sdk/exhaustive/follow_redirects_by_default/tests/endpoints/test_enum.py @@ -1,17 +1,20 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing - -from seed import AsyncSeedExhaustive, SeedExhaustive - from ..utilities import validate_response -async def test_get_and_return_enum(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_enum( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "SUNNY" expected_types: typing.Any = None response = client.endpoints.enum.get_and_return_enum(request="SUNNY") validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.enum.get_and_return_enum(request="SUNNY") + async_response = await async_client.endpoints.enum.get_and_return_enum( + request="SUNNY" + ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/exhaustive/follow_redirects_by_default/tests/endpoints/test_http_methods.py b/seed/python-sdk/exhaustive/follow_redirects_by_default/tests/endpoints/test_http_methods.py index dc01bafcf6f..77131fc6e8b 100644 --- a/seed/python-sdk/exhaustive/follow_redirects_by_default/tests/endpoints/test_http_methods.py +++ b/seed/python-sdk/exhaustive/follow_redirects_by_default/tests/endpoints/test_http_methods.py @@ -1,15 +1,16 @@ # This file was auto-generated by Fern from our API Definition. -import datetime +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing -import uuid - -from seed import AsyncSeedExhaustive, SeedExhaustive - from ..utilities import validate_response +import datetime +import uuid -async def test_test_get(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_test_get( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "string" expected_types: typing.Any = None response = client.endpoints.http_methods.test_get(id="string") @@ -19,7 +20,9 @@ async def test_test_get(client: SeedExhaustive, async_client: AsyncSeedExhaustiv validate_response(async_response, expected_response, expected_types) -async def test_test_post(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_test_post( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = { "string": "string", "integer": 1, @@ -53,11 +56,15 @@ async def test_test_post(client: SeedExhaustive, async_client: AsyncSeedExhausti response = client.endpoints.http_methods.test_post(string="string") validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.http_methods.test_post(string="string") + async_response = await async_client.endpoints.http_methods.test_post( + string="string" + ) validate_response(async_response, expected_response, expected_types) -async def test_test_put(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_test_put( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = { "string": "string", "integer": 1, @@ -91,11 +98,15 @@ async def test_test_put(client: SeedExhaustive, async_client: AsyncSeedExhaustiv response = client.endpoints.http_methods.test_put(id="string", string="string") validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.http_methods.test_put(id="string", string="string") + async_response = await async_client.endpoints.http_methods.test_put( + id="string", string="string" + ) validate_response(async_response, expected_response, expected_types) -async def test_test_patch(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_test_patch( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = { "string": "string", "integer": 1, @@ -163,7 +174,9 @@ async def test_test_patch(client: SeedExhaustive, async_client: AsyncSeedExhaust validate_response(async_response, expected_response, expected_types) -async def test_test_delete(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_test_delete( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = True expected_types: typing.Any = None response = client.endpoints.http_methods.test_delete(id="string") diff --git a/seed/python-sdk/exhaustive/follow_redirects_by_default/tests/endpoints/test_object.py b/seed/python-sdk/exhaustive/follow_redirects_by_default/tests/endpoints/test_object.py index a9098b6e9ef..c48c4332b22 100644 --- a/seed/python-sdk/exhaustive/follow_redirects_by_default/tests/endpoints/test_object.py +++ b/seed/python-sdk/exhaustive/follow_redirects_by_default/tests/endpoints/test_object.py @@ -1,16 +1,18 @@ # This file was auto-generated by Fern from our API Definition. -import datetime +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing +import datetime import uuid - -from seed import AsyncSeedExhaustive, SeedExhaustive -from seed.types.object import NestedObjectWithRequiredField, ObjectWithOptionalField - from ..utilities import validate_response +from seed.types.object import ObjectWithOptionalField +from seed.types.object import NestedObjectWithRequiredField -async def test_get_and_return_with_optional_field(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_with_optional_field( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = { "string": "string", "integer": 1, @@ -58,38 +60,54 @@ async def test_get_and_return_with_optional_field(client: SeedExhaustive, async_ ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.object.get_and_return_with_optional_field( - string="string", - integer=1, - long_=1000000, - double=1.1, - bool_=True, - datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), - date=datetime.date.fromisoformat("2023-01-15"), - uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), - base_64="SGVsbG8gd29ybGQh", - list_=["string"], - set_={"string"}, - map_={1: "string"}, - bigint="123456789123456789", + async_response = ( + await async_client.endpoints.object.get_and_return_with_optional_field( + string="string", + integer=1, + long_=1000000, + double=1.1, + bool_=True, + datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), + date=datetime.date.fromisoformat("2023-01-15"), + uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + base_64="SGVsbG8gd29ybGQh", + list_=["string"], + set_={"string"}, + map_={1: "string"}, + bigint="123456789123456789", + ) ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_with_required_field(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_with_required_field( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = {"string": "string"} expected_types: typing.Any = {"string": None} - response = client.endpoints.object.get_and_return_with_required_field(string="string") + response = client.endpoints.object.get_and_return_with_required_field( + string="string" + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.object.get_and_return_with_required_field(string="string") + async_response = ( + await async_client.endpoints.object.get_and_return_with_required_field( + string="string" + ) + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_with_map_of_map(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_with_map_of_map( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = {"map": {"string": {"string": "string"}}} - expected_types: typing.Any = {"map": ("dict", {0: (None, ("dict", {0: (None, None)}))})} - response = client.endpoints.object.get_and_return_with_map_of_map(map_={"string": {"string": "string"}}) + expected_types: typing.Any = { + "map": ("dict", {0: (None, ("dict", {0: (None, None)}))}) + } + response = client.endpoints.object.get_and_return_with_map_of_map( + map_={"string": {"string": "string"}} + ) validate_response(response, expected_response, expected_types) async_response = await async_client.endpoints.object.get_and_return_with_map_of_map( @@ -157,23 +175,25 @@ async def test_get_and_return_nested_with_optional_field( ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.object.get_and_return_nested_with_optional_field( - string="string", - nested_object=ObjectWithOptionalField( + async_response = ( + await async_client.endpoints.object.get_and_return_nested_with_optional_field( string="string", - integer=1, - long_=1000000, - double=1.1, - bool_=True, - datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), - date=datetime.date.fromisoformat("2023-01-15"), - uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), - base_64="SGVsbG8gd29ybGQh", - list_=["string"], - set_={"string"}, - map_={1: "string"}, - bigint="123456789123456789", - ), + nested_object=ObjectWithOptionalField( + string="string", + integer=1, + long_=1000000, + double=1.1, + bool_=True, + datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), + date=datetime.date.fromisoformat("2023-01-15"), + uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + base_64="SGVsbG8gd29ybGQh", + list_=["string"], + set_={"string"}, + map_={1: "string"}, + bigint="123456789123456789", + ), + ) ) validate_response(async_response, expected_response, expected_types) @@ -238,24 +258,26 @@ async def test_get_and_return_nested_with_required_field( ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.object.get_and_return_nested_with_required_field( - string_="string", - string="string", - nested_object=ObjectWithOptionalField( + async_response = ( + await async_client.endpoints.object.get_and_return_nested_with_required_field( + string_="string", string="string", - integer=1, - long_=1000000, - double=1.1, - bool_=True, - datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), - date=datetime.date.fromisoformat("2023-01-15"), - uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), - base_64="SGVsbG8gd29ybGQh", - list_=["string"], - set_={"string"}, - map_={1: "string"}, - bigint="123456789123456789", - ), + nested_object=ObjectWithOptionalField( + string="string", + integer=1, + long_=1000000, + double=1.1, + bool_=True, + datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), + date=datetime.date.fromisoformat("2023-01-15"), + uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + base_64="SGVsbG8gd29ybGQh", + list_=["string"], + set_={"string"}, + map_={1: "string"}, + bigint="123456789123456789", + ), + ) ) validate_response(async_response, expected_response, expected_types) @@ -299,27 +321,31 @@ async def test_get_and_return_nested_with_required_field_as_list( "bigint": None, }, } - response = client.endpoints.object.get_and_return_nested_with_required_field_as_list( - request=[ - NestedObjectWithRequiredField( - string="string", - nested_object=ObjectWithOptionalField( + response = ( + client.endpoints.object.get_and_return_nested_with_required_field_as_list( + request=[ + NestedObjectWithRequiredField( string="string", - integer=1, - long_=1000000, - double=1.1, - bool_=True, - datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), - date=datetime.date.fromisoformat("2023-01-15"), - uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), - base_64="SGVsbG8gd29ybGQh", - list_=["string"], - set_={"string"}, - map_={1: "string"}, - bigint="123456789123456789", - ), - ) - ] + nested_object=ObjectWithOptionalField( + string="string", + integer=1, + long_=1000000, + double=1.1, + bool_=True, + datetime=datetime.datetime.fromisoformat( + "2024-01-15 09:30:00+00:00" + ), + date=datetime.date.fromisoformat("2023-01-15"), + uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + base_64="SGVsbG8gd29ybGQh", + list_=["string"], + set_={"string"}, + map_={1: "string"}, + bigint="123456789123456789", + ), + ) + ] + ) ) validate_response(response, expected_response, expected_types) @@ -333,7 +359,9 @@ async def test_get_and_return_nested_with_required_field_as_list( long_=1000000, double=1.1, bool_=True, - datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), + datetime=datetime.datetime.fromisoformat( + "2024-01-15 09:30:00+00:00" + ), date=datetime.date.fromisoformat("2023-01-15"), uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), base_64="SGVsbG8gd29ybGQh", diff --git a/seed/python-sdk/exhaustive/follow_redirects_by_default/tests/endpoints/test_params.py b/seed/python-sdk/exhaustive/follow_redirects_by_default/tests/endpoints/test_params.py index 163d7b9161d..d8ffb00c0a0 100644 --- a/seed/python-sdk/exhaustive/follow_redirects_by_default/tests/endpoints/test_params.py +++ b/seed/python-sdk/exhaustive/follow_redirects_by_default/tests/endpoints/test_params.py @@ -1,13 +1,14 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing - -from seed import AsyncSeedExhaustive, SeedExhaustive - from ..utilities import validate_response -async def test_get_with_path(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_with_path( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "string" expected_types: typing.Any = None response = client.endpoints.params.get_with_path(param="string") @@ -17,32 +18,63 @@ async def test_get_with_path(client: SeedExhaustive, async_client: AsyncSeedExha validate_response(async_response, expected_response, expected_types) -async def test_get_with_query(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_with_query( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: # Type ignore to avoid mypy complaining about the function not being meant to return a value assert client.endpoints.params.get_with_query(query="string", number=1) is None # type: ignore[func-returns-value] - assert await async_client.endpoints.params.get_with_query(query="string", number=1) is None # type: ignore[func-returns-value] + assert ( + await async_client.endpoints.params.get_with_query(query="string", number=1) + is None + ) # type: ignore[func-returns-value] -async def test_get_with_allow_multiple_query(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_with_allow_multiple_query( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: # Type ignore to avoid mypy complaining about the function not being meant to return a value - assert client.endpoints.params.get_with_allow_multiple_query(query="string", numer=1) is None # type: ignore[func-returns-value] - - assert await async_client.endpoints.params.get_with_allow_multiple_query(query="string", numer=1) is None # type: ignore[func-returns-value] - - -async def test_get_with_path_and_query(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: + assert ( + client.endpoints.params.get_with_allow_multiple_query(query="string", numer=1) + is None + ) # type: ignore[func-returns-value] + + assert ( + await async_client.endpoints.params.get_with_allow_multiple_query( + query="string", numer=1 + ) + is None + ) # type: ignore[func-returns-value] + + +async def test_get_with_path_and_query( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: # Type ignore to avoid mypy complaining about the function not being meant to return a value - assert client.endpoints.params.get_with_path_and_query(param="string", query="string") is None # type: ignore[func-returns-value] - - assert await async_client.endpoints.params.get_with_path_and_query(param="string", query="string") is None # type: ignore[func-returns-value] - - -async def test_modify_with_path(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: + assert ( + client.endpoints.params.get_with_path_and_query(param="string", query="string") + is None + ) # type: ignore[func-returns-value] + + assert ( + await async_client.endpoints.params.get_with_path_and_query( + param="string", query="string" + ) + is None + ) # type: ignore[func-returns-value] + + +async def test_modify_with_path( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "string" expected_types: typing.Any = None - response = client.endpoints.params.modify_with_path(param="string", request="string") + response = client.endpoints.params.modify_with_path( + param="string", request="string" + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.params.modify_with_path(param="string", request="string") + async_response = await async_client.endpoints.params.modify_with_path( + param="string", request="string" + ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/exhaustive/follow_redirects_by_default/tests/endpoints/test_primitive.py b/seed/python-sdk/exhaustive/follow_redirects_by_default/tests/endpoints/test_primitive.py index ba3bc7e29e5..26cbcf45d2f 100644 --- a/seed/python-sdk/exhaustive/follow_redirects_by_default/tests/endpoints/test_primitive.py +++ b/seed/python-sdk/exhaustive/follow_redirects_by_default/tests/endpoints/test_primitive.py @@ -1,65 +1,86 @@ # This file was auto-generated by Fern from our API Definition. -import datetime +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing -import uuid - -from seed import AsyncSeedExhaustive, SeedExhaustive - from ..utilities import validate_response +import datetime +import uuid -async def test_get_and_return_string(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_string( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "string" expected_types: typing.Any = None response = client.endpoints.primitive.get_and_return_string(request="string") validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.primitive.get_and_return_string(request="string") + async_response = await async_client.endpoints.primitive.get_and_return_string( + request="string" + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_int(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_int( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = 1 expected_types: typing.Any = "integer" response = client.endpoints.primitive.get_and_return_int(request=1) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.primitive.get_and_return_int(request=1) + async_response = await async_client.endpoints.primitive.get_and_return_int( + request=1 + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_long(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_long( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = 1000000 expected_types: typing.Any = None response = client.endpoints.primitive.get_and_return_long(request=1000000) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.primitive.get_and_return_long(request=1000000) + async_response = await async_client.endpoints.primitive.get_and_return_long( + request=1000000 + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_double(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_double( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = 1.1 expected_types: typing.Any = None response = client.endpoints.primitive.get_and_return_double(request=1.1) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.primitive.get_and_return_double(request=1.1) + async_response = await async_client.endpoints.primitive.get_and_return_double( + request=1.1 + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_bool(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_bool( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = True expected_types: typing.Any = None response = client.endpoints.primitive.get_and_return_bool(request=True) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.primitive.get_and_return_bool(request=True) + async_response = await async_client.endpoints.primitive.get_and_return_bool( + request=True + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_datetime(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_datetime( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "2024-01-15T09:30:00Z" expected_types: typing.Any = "datetime" response = client.endpoints.primitive.get_and_return_datetime( @@ -73,10 +94,14 @@ async def test_get_and_return_datetime(client: SeedExhaustive, async_client: Asy validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_date(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_date( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "2023-01-15" expected_types: typing.Any = "date" - response = client.endpoints.primitive.get_and_return_date(request=datetime.date.fromisoformat("2023-01-15")) + response = client.endpoints.primitive.get_and_return_date( + request=datetime.date.fromisoformat("2023-01-15") + ) validate_response(response, expected_response, expected_types) async_response = await async_client.endpoints.primitive.get_and_return_date( @@ -85,10 +110,14 @@ async def test_get_and_return_date(client: SeedExhaustive, async_client: AsyncSe validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_uuid(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_uuid( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32" expected_types: typing.Any = "uuid" - response = client.endpoints.primitive.get_and_return_uuid(request=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32")) + response = client.endpoints.primitive.get_and_return_uuid( + request=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32") + ) validate_response(response, expected_response, expected_types) async_response = await async_client.endpoints.primitive.get_and_return_uuid( @@ -97,11 +126,17 @@ async def test_get_and_return_uuid(client: SeedExhaustive, async_client: AsyncSe validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_base_64(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_base_64( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "SGVsbG8gd29ybGQh" expected_types: typing.Any = None - response = client.endpoints.primitive.get_and_return_base_64(request="SGVsbG8gd29ybGQh") + response = client.endpoints.primitive.get_and_return_base_64( + request="SGVsbG8gd29ybGQh" + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.primitive.get_and_return_base_64(request="SGVsbG8gd29ybGQh") + async_response = await async_client.endpoints.primitive.get_and_return_base_64( + request="SGVsbG8gd29ybGQh" + ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/exhaustive/follow_redirects_by_default/tests/endpoints/test_union.py b/seed/python-sdk/exhaustive/follow_redirects_by_default/tests/endpoints/test_union.py index 14e34c2a6df..ceb84928cd9 100644 --- a/seed/python-sdk/exhaustive/follow_redirects_by_default/tests/endpoints/test_union.py +++ b/seed/python-sdk/exhaustive/follow_redirects_by_default/tests/endpoints/test_union.py @@ -1,17 +1,24 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing - -from seed import AsyncSeedExhaustive, SeedExhaustive from seed.types.union import Animal_Dog - from ..utilities import validate_response -async def test_get_and_return_union(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: - expected_response: typing.Any = {"animal": "dog", "name": "string", "likesToWoof": True} +async def test_get_and_return_union( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: + expected_response: typing.Any = { + "animal": "dog", + "name": "string", + "likesToWoof": True, + } expected_types: typing.Any = "no_validate" - response = client.endpoints.union.get_and_return_union(request=Animal_Dog(name="string", likes_to_woof=True)) + response = client.endpoints.union.get_and_return_union( + request=Animal_Dog(name="string", likes_to_woof=True) + ) validate_response(response, expected_response, expected_types) async_response = await async_client.endpoints.union.get_and_return_union( diff --git a/seed/python-sdk/exhaustive/follow_redirects_by_default/tests/test_inlined_requests.py b/seed/python-sdk/exhaustive/follow_redirects_by_default/tests/test_inlined_requests.py index bb9390d3845..03f46b31cc9 100644 --- a/seed/python-sdk/exhaustive/follow_redirects_by_default/tests/test_inlined_requests.py +++ b/seed/python-sdk/exhaustive/follow_redirects_by_default/tests/test_inlined_requests.py @@ -1,16 +1,17 @@ # This file was auto-generated by Fern from our API Definition. -import datetime +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing -import uuid - -from seed import AsyncSeedExhaustive, SeedExhaustive from seed.types.object import ObjectWithOptionalField - +import datetime +import uuid from .utilities import validate_response -async def test_post_with_object_bodyand_response(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_post_with_object_bodyand_response( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = { "string": "string", "integer": 1, @@ -62,23 +63,25 @@ async def test_post_with_object_bodyand_response(client: SeedExhaustive, async_c ) validate_response(response, expected_response, expected_types) - async_response = await async_client.inlined_requests.post_with_object_bodyand_response( - string="string", - integer=1, - nested_object=ObjectWithOptionalField( + async_response = ( + await async_client.inlined_requests.post_with_object_bodyand_response( string="string", integer=1, - long_=1000000, - double=1.1, - bool_=True, - datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), - date=datetime.date.fromisoformat("2023-01-15"), - uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), - base_64="SGVsbG8gd29ybGQh", - list_=["string"], - set_={"string"}, - map_={1: "string"}, - bigint="123456789123456789", - ), + nested_object=ObjectWithOptionalField( + string="string", + integer=1, + long_=1000000, + double=1.1, + bool_=True, + datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), + date=datetime.date.fromisoformat("2023-01-15"), + uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + base_64="SGVsbG8gd29ybGQh", + list_=["string"], + set_={"string"}, + map_={1: "string"}, + bigint="123456789123456789", + ), + ) ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/exhaustive/follow_redirects_by_default/tests/test_no_auth.py b/seed/python-sdk/exhaustive/follow_redirects_by_default/tests/test_no_auth.py index 3328661bb48..fc475f4b6fb 100644 --- a/seed/python-sdk/exhaustive/follow_redirects_by_default/tests/test_no_auth.py +++ b/seed/python-sdk/exhaustive/follow_redirects_by_default/tests/test_no_auth.py @@ -1,17 +1,20 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing - -from seed import AsyncSeedExhaustive, SeedExhaustive - from .utilities import validate_response -async def test_post_with_no_auth(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_post_with_no_auth( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = True expected_types: typing.Any = None response = client.no_auth.post_with_no_auth(request={"key": "value"}) validate_response(response, expected_response, expected_types) - async_response = await async_client.no_auth.post_with_no_auth(request={"key": "value"}) + async_response = await async_client.no_auth.post_with_no_auth( + request={"key": "value"} + ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/exhaustive/follow_redirects_by_default/tests/test_no_req_body.py b/seed/python-sdk/exhaustive/follow_redirects_by_default/tests/test_no_req_body.py index 73abac9d2d8..07061a0e99e 100644 --- a/seed/python-sdk/exhaustive/follow_redirects_by_default/tests/test_no_req_body.py +++ b/seed/python-sdk/exhaustive/follow_redirects_by_default/tests/test_no_req_body.py @@ -1,13 +1,14 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing - -from seed import AsyncSeedExhaustive, SeedExhaustive - from .utilities import validate_response -async def test_get_with_no_request_body(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_with_no_request_body( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = { "string": "string", "integer": 1, @@ -45,7 +46,9 @@ async def test_get_with_no_request_body(client: SeedExhaustive, async_client: As validate_response(async_response, expected_response, expected_types) -async def test_post_with_no_request_body(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_post_with_no_request_body( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "string" expected_types: typing.Any = None response = client.no_req_body.post_with_no_request_body() diff --git a/seed/python-sdk/exhaustive/follow_redirects_by_default/tests/test_req_with_headers.py b/seed/python-sdk/exhaustive/follow_redirects_by_default/tests/test_req_with_headers.py index bba3b5b5507..75ce9d00c03 100644 --- a/seed/python-sdk/exhaustive/follow_redirects_by_default/tests/test_req_with_headers.py +++ b/seed/python-sdk/exhaustive/follow_redirects_by_default/tests/test_req_with_headers.py @@ -1,10 +1,27 @@ # This file was auto-generated by Fern from our API Definition. -from seed import AsyncSeedExhaustive, SeedExhaustive +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive -async def test_get_with_custom_header(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_with_custom_header( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: # Type ignore to avoid mypy complaining about the function not being meant to return a value - assert client.req_with_headers.get_with_custom_header(x_test_service_header="string", x_test_endpoint_header="string", request="string") is None # type: ignore[func-returns-value] + assert ( + client.req_with_headers.get_with_custom_header( + x_test_service_header="string", + x_test_endpoint_header="string", + request="string", + ) + is None + ) # type: ignore[func-returns-value] - assert await async_client.req_with_headers.get_with_custom_header(x_test_service_header="string", x_test_endpoint_header="string", request="string") is None # type: ignore[func-returns-value] + assert ( + await async_client.req_with_headers.get_with_custom_header( + x_test_service_header="string", + x_test_endpoint_header="string", + request="string", + ) + is None + ) # type: ignore[func-returns-value] diff --git a/seed/python-sdk/exhaustive/follow_redirects_by_default/tests/utilities.py b/seed/python-sdk/exhaustive/follow_redirects_by_default/tests/utilities.py index 13da208eb3a..e8f4472564c 100644 --- a/seed/python-sdk/exhaustive/follow_redirects_by_default/tests/utilities.py +++ b/seed/python-sdk/exhaustive/follow_redirects_by_default/tests/utilities.py @@ -3,11 +3,14 @@ import typing import uuid -import pydantic from dateutil import parser +import pydantic + -def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> typing.Any: +def cast_field( + json_expectation: typing.Any, type_expectation: typing.Any +) -> typing.Any: # Cast these specific types which come through as string and expect our # models to cast to the correct type. if type_expectation == "uuid": @@ -25,7 +28,9 @@ def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> ty return json_expectation -def validate_field(response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any) -> None: +def validate_field( + response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectation == "no_validate": return @@ -44,7 +49,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(entry_expectation, dict): is_container_of_complex_type = True validate_response( - response=response[idx], json_expectation=ex, type_expectations=entry_expectation + response=response[idx], + json_expectation=ex, + type_expectations=entry_expectation, ) else: cast_json_expectation.append(cast_field(ex, entry_expectation)) @@ -56,7 +63,10 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # if any of the values of the set have a type_expectation of a dict, we're assuming it's a pydantic # model and keeping it a list. if container_expectation != "set" or not any( - map(lambda value: isinstance(value, dict), list(contents_expectation.values())) + map( + lambda value: isinstance(value, dict), + list(contents_expectation.values()), + ) ): json_expectation = cast_field(json_expectation, container_expectation) elif isinstance(type_expectation, tuple): @@ -65,9 +75,15 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(contents_expectation, dict): json_expectation = { cast_field( - key, contents_expectation.get(idx)[0] if contents_expectation.get(idx) is not None else None # type: ignore + key, + contents_expectation.get(idx)[0] + if contents_expectation.get(idx) is not None + else None, # type: ignore ): cast_field( - value, contents_expectation.get(idx)[1] if contents_expectation.get(idx) is not None else None # type: ignore + value, + contents_expectation.get(idx)[1] + if contents_expectation.get(idx) is not None + else None, # type: ignore ) for idx, (key, value) in enumerate(json_expectation.items()) } @@ -86,7 +102,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # Arg type_expectations is a deeply nested structure that matches the response, but with the values replaced with the expected types -def validate_response(response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any) -> None: +def validate_response( + response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectations == "no_validate": return @@ -96,11 +114,17 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e and not isinstance(response, dict) and not issubclass(type(response), pydantic.BaseModel) ): - validate_field(response=response, json_expectation=json_expectation, type_expectation=type_expectations) + validate_field( + response=response, + json_expectation=json_expectation, + type_expectation=type_expectations, + ) return if isinstance(response, list): - assert len(response) == len(json_expectation), "Length mismatch, expected: {0}, Actual: {1}".format( + assert len(response) == len( + json_expectation + ), "Length mismatch, expected: {0}, Actual: {1}".format( len(response), len(json_expectation) ) content_expectation = type_expectations @@ -108,7 +132,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e content_expectation = type_expectations[1] for idx, item in enumerate(response): validate_response( - response=item, json_expectation=json_expectation[idx], type_expectations=content_expectation[idx] + response=item, + json_expectation=json_expectation[idx], + type_expectations=content_expectation[idx], ) else: response_json = response @@ -116,7 +142,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e response_json = response.dict(by_alias=True) for key, value in json_expectation.items(): - assert key in response_json, "Field {0} not found within the response object: {1}".format( + assert ( + key in response_json + ), "Field {0} not found within the response object: {1}".format( key, response_json ) @@ -128,11 +156,19 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e # Otherwise, we're just validating a single field that's a pydantic model. if isinstance(value, dict) and not isinstance(type_expectation, tuple): validate_response( - response=response_json[key], json_expectation=value, type_expectations=type_expectation + response=response_json[key], + json_expectation=value, + type_expectations=type_expectation, ) else: - validate_field(response=response_json[key], json_expectation=value, type_expectation=type_expectation) + validate_field( + response=response_json[key], + json_expectation=value, + type_expectation=type_expectation, + ) # Ensure there are no additional fields here either del response_json[key] - assert len(response_json) == 0, "Additional fields found, expected None: {0}".format(response_json) + assert ( + len(response_json) == 0 + ), "Additional fields found, expected None: {0}".format(response_json) diff --git a/seed/python-sdk/exhaustive/follow_redirects_by_default/tests/utils/assets/models/__init__.py b/seed/python-sdk/exhaustive/follow_redirects_by_default/tests/utils/assets/models/__init__.py index 2cf01263529..3a1c852e71e 100644 --- a/seed/python-sdk/exhaustive/follow_redirects_by_default/tests/utils/assets/models/__init__.py +++ b/seed/python-sdk/exhaustive/follow_redirects_by_default/tests/utils/assets/models/__init__.py @@ -5,7 +5,7 @@ from .circle import CircleParams from .object_with_defaults import ObjectWithDefaultsParams from .object_with_optional_field import ObjectWithOptionalFieldParams -from .shape import Shape_CircleParams, Shape_SquareParams, ShapeParams +from .shape import ShapeParams, Shape_CircleParams, Shape_SquareParams from .square import SquareParams from .undiscriminated_shape import UndiscriminatedShapeParams diff --git a/seed/python-sdk/exhaustive/follow_redirects_by_default/tests/utils/assets/models/circle.py b/seed/python-sdk/exhaustive/follow_redirects_by_default/tests/utils/assets/models/circle.py index af7a1bf8a8e..253f12d38b3 100644 --- a/seed/python-sdk/exhaustive/follow_redirects_by_default/tests/utils/assets/models/circle.py +++ b/seed/python-sdk/exhaustive/follow_redirects_by_default/tests/utils/assets/models/circle.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class CircleParams(typing_extensions.TypedDict): - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] diff --git a/seed/python-sdk/exhaustive/follow_redirects_by_default/tests/utils/assets/models/object_with_optional_field.py b/seed/python-sdk/exhaustive/follow_redirects_by_default/tests/utils/assets/models/object_with_optional_field.py index 3ad93d5f305..ebe7dc80547 100644 --- a/seed/python-sdk/exhaustive/follow_redirects_by_default/tests/utils/assets/models/object_with_optional_field.py +++ b/seed/python-sdk/exhaustive/follow_redirects_by_default/tests/utils/assets/models/object_with_optional_field.py @@ -7,8 +7,8 @@ import uuid import typing_extensions -from seed.core.serialization import FieldMetadata +from seed.core.serialization import FieldMetadata from .color import Color from .shape import ShapeParams from .undiscriminated_shape import UndiscriminatedShapeParams @@ -18,16 +18,30 @@ class ObjectWithOptionalFieldParams(typing_extensions.TypedDict): literal: typing.Literal["lit_one"] string: typing_extensions.NotRequired[str] integer: typing_extensions.NotRequired[int] - long_: typing_extensions.NotRequired[typing_extensions.Annotated[int, FieldMetadata(alias="long")]] + long_: typing_extensions.NotRequired[ + typing_extensions.Annotated[int, FieldMetadata(alias="long")] + ] double: typing_extensions.NotRequired[float] - bool_: typing_extensions.NotRequired[typing_extensions.Annotated[bool, FieldMetadata(alias="bool")]] + bool_: typing_extensions.NotRequired[ + typing_extensions.Annotated[bool, FieldMetadata(alias="bool")] + ] datetime: typing_extensions.NotRequired[dt.datetime] date: typing_extensions.NotRequired[dt.date] - uuid_: typing_extensions.NotRequired[typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")]] - base_64: typing_extensions.NotRequired[typing_extensions.Annotated[str, FieldMetadata(alias="base64")]] - list_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")]] - set_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")]] - map_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")]] + uuid_: typing_extensions.NotRequired[ + typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")] + ] + base_64: typing_extensions.NotRequired[ + typing_extensions.Annotated[str, FieldMetadata(alias="base64")] + ] + list_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")] + ] + set_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")] + ] + map_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")] + ] enum: typing_extensions.NotRequired[Color] union: typing_extensions.NotRequired[ShapeParams] second_union: typing_extensions.NotRequired[ShapeParams] diff --git a/seed/python-sdk/exhaustive/follow_redirects_by_default/tests/utils/assets/models/shape.py b/seed/python-sdk/exhaustive/follow_redirects_by_default/tests/utils/assets/models/shape.py index 2c33c877951..816ffc51bdc 100644 --- a/seed/python-sdk/exhaustive/follow_redirects_by_default/tests/utils/assets/models/shape.py +++ b/seed/python-sdk/exhaustive/follow_redirects_by_default/tests/utils/assets/models/shape.py @@ -7,6 +7,7 @@ import typing import typing_extensions + from seed.core.serialization import FieldMetadata @@ -15,13 +16,21 @@ class Base(typing_extensions.TypedDict): class Shape_CircleParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["circle"], FieldMetadata(alias="shapeType")] - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["circle"], FieldMetadata(alias="shapeType") + ] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] class Shape_SquareParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["square"], FieldMetadata(alias="shapeType")] - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["square"], FieldMetadata(alias="shapeType") + ] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] ShapeParams = typing.Union[Shape_CircleParams, Shape_SquareParams] diff --git a/seed/python-sdk/exhaustive/follow_redirects_by_default/tests/utils/assets/models/square.py b/seed/python-sdk/exhaustive/follow_redirects_by_default/tests/utils/assets/models/square.py index b9b7dd319bc..bcf08a723c5 100644 --- a/seed/python-sdk/exhaustive/follow_redirects_by_default/tests/utils/assets/models/square.py +++ b/seed/python-sdk/exhaustive/follow_redirects_by_default/tests/utils/assets/models/square.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class SquareParams(typing_extensions.TypedDict): - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] diff --git a/seed/python-sdk/exhaustive/follow_redirects_by_default/tests/utils/test_http_client.py b/seed/python-sdk/exhaustive/follow_redirects_by_default/tests/utils/test_http_client.py index edd11ca7afb..f5a874a75f3 100644 --- a/seed/python-sdk/exhaustive/follow_redirects_by_default/tests/utils/test_http_client.py +++ b/seed/python-sdk/exhaustive/follow_redirects_by_default/tests/utils/test_http_client.py @@ -9,12 +9,17 @@ def get_request_options() -> RequestOptions: def test_get_json_request_body() -> None: - json_body, data_body = get_request_body(json={"hello": "world"}, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json={"hello": "world"}, data=None, request_options=None, omit=None + ) assert json_body == {"hello": "world"} assert data_body is None json_body_extras, data_body_extras = get_request_body( - json={"goodbye": "world"}, data=None, request_options=get_request_options(), omit=None + json={"goodbye": "world"}, + data=None, + request_options=get_request_options(), + omit=None, ) assert json_body_extras == {"goodbye": "world", "see you": "later"} @@ -22,12 +27,17 @@ def test_get_json_request_body() -> None: def test_get_files_request_body() -> None: - json_body, data_body = get_request_body(json=None, data={"hello": "world"}, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data={"hello": "world"}, request_options=None, omit=None + ) assert data_body == {"hello": "world"} assert json_body is None json_body_extras, data_body_extras = get_request_body( - json=None, data={"goodbye": "world"}, request_options=get_request_options(), omit=None + json=None, + data={"goodbye": "world"}, + request_options=get_request_options(), + omit=None, ) assert data_body_extras == {"goodbye": "world", "see you": "later"} @@ -35,7 +45,9 @@ def test_get_files_request_body() -> None: def test_get_none_request_body() -> None: - json_body, data_body = get_request_body(json=None, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data=None, request_options=None, omit=None + ) assert data_body is None assert json_body is None diff --git a/seed/python-sdk/exhaustive/follow_redirects_by_default/tests/utils/test_query_encoding.py b/seed/python-sdk/exhaustive/follow_redirects_by_default/tests/utils/test_query_encoding.py index 247e1551b46..fbc8f402167 100644 --- a/seed/python-sdk/exhaustive/follow_redirects_by_default/tests/utils/test_query_encoding.py +++ b/seed/python-sdk/exhaustive/follow_redirects_by_default/tests/utils/test_query_encoding.py @@ -4,9 +4,15 @@ def test_query_encoding() -> None: - assert encode_query({"hello world": "hello world"}) == {"hello world": "hello world"} - assert encode_query({"hello_world": {"hello": "world"}}) == {"hello_world[hello]": "world"} - assert encode_query({"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"}) == { + assert encode_query({"hello world": "hello world"}) == { + "hello world": "hello world" + } + assert encode_query({"hello_world": {"hello": "world"}}) == { + "hello_world[hello]": "world" + } + assert encode_query( + {"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"} + ) == { "hello_world[hello][world]": "today", "hello_world[test]": "this", "hi": "there", diff --git a/seed/python-sdk/exhaustive/follow_redirects_by_default/tests/utils/test_serialization.py b/seed/python-sdk/exhaustive/follow_redirects_by_default/tests/utils/test_serialization.py index 58b1ed66e6d..5ca956916dd 100644 --- a/seed/python-sdk/exhaustive/follow_redirects_by_default/tests/utils/test_serialization.py +++ b/seed/python-sdk/exhaustive/follow_redirects_by_default/tests/utils/test_serialization.py @@ -1,10 +1,12 @@ # This file was auto-generated by Fern from our API Definition. -from typing import Any, List +from typing import List, Any -from seed.core.serialization import convert_and_respect_annotation_metadata +from seed.core.serialization import ( + convert_and_respect_annotation_metadata, +) +from .assets.models import ShapeParams, ObjectWithOptionalFieldParams -from .assets.models import ObjectWithOptionalFieldParams, ShapeParams UNION_TEST: ShapeParams = {"radius_measurement": 1.0, "shape_type": "circle", "id": "1"} UNION_TEST_CONVERTED = {"shapeType": "circle", "radiusMeasurement": 1.0, "id": "1"} @@ -18,20 +20,54 @@ def test_convert_and_respect_annotation_metadata() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) - assert converted == {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"} + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) + assert converted == { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + } def test_convert_and_respect_annotation_metadata_in_list() -> None: data: List[ObjectWithOptionalFieldParams] = [ - {"string": "string", "long_": 12345, "bool_": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long_": 67890, "list_": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long_": 12345, + "bool_": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long_": 67890, + "list_": [], + "literal": "lit_one", + "any": "any", + }, ] - converted = convert_and_respect_annotation_metadata(object_=data, annotation=List[ObjectWithOptionalFieldParams]) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=List[ObjectWithOptionalFieldParams] + ) assert converted == [ - {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long": 67890, "list": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long": 67890, + "list": [], + "literal": "lit_one", + "any": "any", + }, ] @@ -43,7 +79,9 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) assert converted == { "string": "string", @@ -55,12 +93,16 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: def test_convert_and_respect_annotation_metadata_in_union() -> None: - converted = convert_and_respect_annotation_metadata(object_=UNION_TEST, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=UNION_TEST, annotation=ShapeParams + ) assert converted == UNION_TEST_CONVERTED def test_convert_and_respect_annotation_metadata_with_empty_object() -> None: data: Any = {} - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ShapeParams + ) assert converted == data diff --git a/seed/python-sdk/exhaustive/improved_imports/pyproject.toml b/seed/python-sdk/exhaustive/improved_imports/pyproject.toml index c6cd3a2b7b9..fc29a237334 100644 --- a/seed/python-sdk/exhaustive/improved_imports/pyproject.toml +++ b/seed/python-sdk/exhaustive/improved_imports/pyproject.toml @@ -43,6 +43,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/python-sdk/exhaustive/improved_imports/src/seed/__init__.py b/seed/python-sdk/exhaustive/improved_imports/src/seed/__init__.py index eb56b0ce275..dc1ef03a650 100644 --- a/seed/python-sdk/exhaustive/improved_imports/src/seed/__init__.py +++ b/seed/python-sdk/exhaustive/improved_imports/src/seed/__init__.py @@ -1,6 +1,14 @@ # This file was auto-generated by Fern from our API Definition. -from . import endpoints, general_errors, inlined_requests, no_auth, no_req_body, req_with_headers, types +from . import ( + endpoints, + general_errors, + inlined_requests, + no_auth, + no_req_body, + req_with_headers, + types, +) from .client import AsyncSeedExhaustive, SeedExhaustive from .general_errors import BadObjectRequestInfo, BadRequestBody from .version import __version__ diff --git a/seed/python-sdk/exhaustive/improved_imports/src/seed/client.py b/seed/python-sdk/exhaustive/improved_imports/src/seed/client.py index b1b9764c7a7..f5ab292af6b 100644 --- a/seed/python-sdk/exhaustive/improved_imports/src/seed/client.py +++ b/seed/python-sdk/exhaustive/improved_imports/src/seed/client.py @@ -1,15 +1,19 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from .endpoints.client import AsyncEndpointsClient, EndpointsClient -from .inlined_requests.client import AsyncInlinedRequestsClient, InlinedRequestsClient -from .no_auth.client import AsyncNoAuthClient, NoAuthClient -from .no_req_body.client import AsyncNoReqBodyClient, NoReqBodyClient -from .req_with_headers.client import AsyncReqWithHeadersClient, ReqWithHeadersClient +from .core.client_wrapper import SyncClientWrapper +from .endpoints.client import EndpointsClient +from .inlined_requests.client import InlinedRequestsClient +from .no_auth.client import NoAuthClient +from .no_req_body.client import NoReqBodyClient +from .req_with_headers.client import ReqWithHeadersClient +from .core.client_wrapper import AsyncClientWrapper +from .endpoints.client import AsyncEndpointsClient +from .inlined_requests.client import AsyncInlinedRequestsClient +from .no_auth.client import AsyncNoAuthClient +from .no_req_body.client import AsyncNoReqBodyClient +from .req_with_headers.client import AsyncReqWithHeadersClient class SeedExhaustive: @@ -48,24 +52,32 @@ def __init__( token: typing.Optional[typing.Union[str, typing.Callable[[], str]]] = None, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.Client] = None + httpx_client: typing.Optional[httpx.Client] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = SyncClientWrapper( base_url=base_url, token=token, httpx_client=httpx_client if httpx_client is not None - else httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.Client( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.Client(timeout=_defaulted_timeout), timeout=_defaulted_timeout, ) self.endpoints = EndpointsClient(client_wrapper=self._client_wrapper) - self.inlined_requests = InlinedRequestsClient(client_wrapper=self._client_wrapper) + self.inlined_requests = InlinedRequestsClient( + client_wrapper=self._client_wrapper + ) self.no_auth = NoAuthClient(client_wrapper=self._client_wrapper) self.no_req_body = NoReqBodyClient(client_wrapper=self._client_wrapper) - self.req_with_headers = ReqWithHeadersClient(client_wrapper=self._client_wrapper) + self.req_with_headers = ReqWithHeadersClient( + client_wrapper=self._client_wrapper + ) class AsyncSeedExhaustive: @@ -104,21 +116,29 @@ def __init__( token: typing.Optional[typing.Union[str, typing.Callable[[], str]]] = None, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.AsyncClient] = None + httpx_client: typing.Optional[httpx.AsyncClient] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = AsyncClientWrapper( base_url=base_url, token=token, httpx_client=httpx_client if httpx_client is not None - else httpx.AsyncClient(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.AsyncClient( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.AsyncClient(timeout=_defaulted_timeout), timeout=_defaulted_timeout, ) self.endpoints = AsyncEndpointsClient(client_wrapper=self._client_wrapper) - self.inlined_requests = AsyncInlinedRequestsClient(client_wrapper=self._client_wrapper) + self.inlined_requests = AsyncInlinedRequestsClient( + client_wrapper=self._client_wrapper + ) self.no_auth = AsyncNoAuthClient(client_wrapper=self._client_wrapper) self.no_req_body = AsyncNoReqBodyClient(client_wrapper=self._client_wrapper) - self.req_with_headers = AsyncReqWithHeadersClient(client_wrapper=self._client_wrapper) + self.req_with_headers = AsyncReqWithHeadersClient( + client_wrapper=self._client_wrapper + ) diff --git a/seed/python-sdk/exhaustive/improved_imports/src/seed/core/api_error.py b/seed/python-sdk/exhaustive/improved_imports/src/seed/core/api_error.py index 2e9fc5431cd..da734b58068 100644 --- a/seed/python-sdk/exhaustive/improved_imports/src/seed/core/api_error.py +++ b/seed/python-sdk/exhaustive/improved_imports/src/seed/core/api_error.py @@ -7,7 +7,9 @@ class ApiError(Exception): status_code: typing.Optional[int] body: typing.Any - def __init__(self, *, status_code: typing.Optional[int] = None, body: typing.Any = None): + def __init__( + self, *, status_code: typing.Optional[int] = None, body: typing.Any = None + ): self.status_code = status_code self.body = body diff --git a/seed/python-sdk/exhaustive/improved_imports/src/seed/core/client_wrapper.py b/seed/python-sdk/exhaustive/improved_imports/src/seed/core/client_wrapper.py index 8d01b584b82..d037184a816 100644 --- a/seed/python-sdk/exhaustive/improved_imports/src/seed/core/client_wrapper.py +++ b/seed/python-sdk/exhaustive/improved_imports/src/seed/core/client_wrapper.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .http_client import AsyncHttpClient, HttpClient +from .http_client import HttpClient +from .http_client import AsyncHttpClient class BaseClientWrapper: diff --git a/seed/python-sdk/exhaustive/improved_imports/src/seed/core/datetime_utils.py b/seed/python-sdk/exhaustive/improved_imports/src/seed/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/python-sdk/exhaustive/improved_imports/src/seed/core/datetime_utils.py +++ b/seed/python-sdk/exhaustive/improved_imports/src/seed/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/python-sdk/exhaustive/improved_imports/src/seed/core/file.py b/seed/python-sdk/exhaustive/improved_imports/src/seed/core/file.py index cb0d40bbbf3..6e0f92bfcb1 100644 --- a/seed/python-sdk/exhaustive/improved_imports/src/seed/core/file.py +++ b/seed/python-sdk/exhaustive/improved_imports/src/seed/core/file.py @@ -13,12 +13,17 @@ # (filename, file (or bytes), content_type) typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str]], # (filename, file (or bytes), content_type, headers) - typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str], typing.Mapping[str, str]], + typing.Tuple[ + typing.Optional[str], + FileContent, + typing.Optional[str], + typing.Mapping[str, str], + ], ] def convert_file_dict_to_httpx_tuples( - d: typing.Dict[str, typing.Union[File, typing.List[File]]] + d: typing.Dict[str, typing.Union[File, typing.List[File]]], ) -> typing.List[typing.Tuple[str, File]]: """ The format we use is a list of tuples, where the first element is the diff --git a/seed/python-sdk/exhaustive/improved_imports/src/seed/core/http_client.py b/seed/python-sdk/exhaustive/improved_imports/src/seed/core/http_client.py index 9333d8a7f15..091f71bc185 100644 --- a/seed/python-sdk/exhaustive/improved_imports/src/seed/core/http_client.py +++ b/seed/python-sdk/exhaustive/improved_imports/src/seed/core/http_client.py @@ -77,7 +77,9 @@ def _retry_timeout(response: httpx.Response, retries: int) -> float: return retry_after # Apply exponential backoff, capped at MAX_RETRY_DELAY_SECONDS. - retry_delay = min(INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS) + retry_delay = min( + INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS + ) # Add a randomness / jitter to the retry delay to avoid overwhelming the server with retries. timeout = retry_delay * (1 - 0.25 * random()) @@ -90,7 +92,8 @@ def _should_retry(response: httpx.Response) -> bool: def remove_omit_from_dict( - original: typing.Dict[str, typing.Optional[typing.Any]], omit: typing.Optional[typing.Any] + original: typing.Dict[str, typing.Optional[typing.Any]], + omit: typing.Optional[typing.Any], ) -> typing.Dict[str, typing.Any]: if omit is None: return original @@ -108,7 +111,8 @@ def maybe_filter_request_body( ) -> typing.Optional[typing.Any]: if data is None: return ( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else None ) @@ -118,7 +122,8 @@ def maybe_filter_request_body( data_content = { **(jsonable_encoder(remove_omit_from_dict(data, omit))), # type: ignore **( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else {} ), @@ -162,7 +167,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url def request( @@ -174,8 +181,12 @@ def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -184,11 +195,14 @@ def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) response = self.httpx_client.request( method=method, @@ -198,7 +212,11 @@ def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -209,7 +227,10 @@ def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -222,11 +243,15 @@ def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: time.sleep(_retry_timeout(response=response, retries=retries)) @@ -256,8 +281,12 @@ def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -266,11 +295,14 @@ def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) with self.httpx_client.stream( method=method, @@ -280,7 +312,11 @@ def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -291,7 +327,9 @@ def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -304,7 +342,9 @@ def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream @@ -327,7 +367,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url async def request( @@ -339,8 +381,12 @@ async def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -349,11 +395,14 @@ async def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) # Add the input to each of these and do None-safety checks response = await self.httpx_client.request( @@ -364,7 +413,11 @@ async def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -375,7 +428,10 @@ async def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -388,11 +444,15 @@ async def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: await asyncio.sleep(_retry_timeout(response=response, retries=retries)) @@ -421,8 +481,12 @@ async def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -431,11 +495,14 @@ async def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) async with self.httpx_client.stream( method=method, @@ -445,7 +512,11 @@ async def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -456,7 +527,9 @@ async def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -469,7 +542,9 @@ async def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream diff --git a/seed/python-sdk/exhaustive/improved_imports/src/seed/core/jsonable_encoder.py b/seed/python-sdk/exhaustive/improved_imports/src/seed/core/jsonable_encoder.py index d3fd328fd41..12a8b52fc22 100644 --- a/seed/python-sdk/exhaustive/improved_imports/src/seed/core/jsonable_encoder.py +++ b/seed/python-sdk/exhaustive/improved_imports/src/seed/core/jsonable_encoder.py @@ -19,13 +19,19 @@ import pydantic from .datetime_utils import serialize_datetime -from .pydantic_utilities import IS_PYDANTIC_V2, encode_by_type, to_jsonable_with_fallback +from .pydantic_utilities import ( + IS_PYDANTIC_V2, + encode_by_type, + to_jsonable_with_fallback, +) SetIntStr = Set[Union[int, str]] DictIntStrAny = Dict[Union[int, str], Any] -def jsonable_encoder(obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None) -> Any: +def jsonable_encoder( + obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None +) -> Any: custom_encoder = custom_encoder or {} if custom_encoder: if type(obj) in custom_encoder: diff --git a/seed/python-sdk/exhaustive/improved_imports/src/seed/core/pydantic_utilities.py b/seed/python-sdk/exhaustive/improved_imports/src/seed/core/pydantic_utilities.py index 170a563d6eb..c63935c32a2 100644 --- a/seed/python-sdk/exhaustive/improved_imports/src/seed/core/pydantic_utilities.py +++ b/seed/python-sdk/exhaustive/improved_imports/src/seed/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) # type: ignore # Pydantic v1 diff --git a/seed/python-sdk/exhaustive/improved_imports/src/seed/core/query_encoder.py b/seed/python-sdk/exhaustive/improved_imports/src/seed/core/query_encoder.py index 24076d72ee9..7cb98f52cd7 100644 --- a/seed/python-sdk/exhaustive/improved_imports/src/seed/core/query_encoder.py +++ b/seed/python-sdk/exhaustive/improved_imports/src/seed/core/query_encoder.py @@ -7,7 +7,9 @@ # Flattens dicts to be of the form {"key[subkey][subkey2]": value} where value is not a dict -def traverse_query_dict(dict_flat: Dict[str, Any], key_prefix: Optional[str] = None) -> Dict[str, Any]: +def traverse_query_dict( + dict_flat: Dict[str, Any], key_prefix: Optional[str] = None +) -> Dict[str, Any]: result = {} for k, v in dict_flat.items(): key = f"{key_prefix}[{k}]" if key_prefix is not None else k @@ -30,4 +32,8 @@ def single_query_encoder(query_key: str, query_value: Any) -> Dict[str, Any]: def encode_query(query: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: - return dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) if query is not None else None + return ( + dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) + if query is not None + else None + ) diff --git a/seed/python-sdk/exhaustive/improved_imports/src/seed/core/serialization.py b/seed/python-sdk/exhaustive/improved_imports/src/seed/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/python-sdk/exhaustive/improved_imports/src/seed/core/serialization.py +++ b/seed/python-sdk/exhaustive/improved_imports/src/seed/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/python-sdk/exhaustive/improved_imports/src/seed/endpoints/__init__.py b/seed/python-sdk/exhaustive/improved_imports/src/seed/endpoints/__init__.py index 92307cab7fe..a9496ece178 100644 --- a/seed/python-sdk/exhaustive/improved_imports/src/seed/endpoints/__init__.py +++ b/seed/python-sdk/exhaustive/improved_imports/src/seed/endpoints/__init__.py @@ -2,4 +2,12 @@ from . import container, enum, http_methods, object, params, primitive, union -__all__ = ["container", "enum", "http_methods", "object", "params", "primitive", "union"] +__all__ = [ + "container", + "enum", + "http_methods", + "object", + "params", + "primitive", + "union", +] diff --git a/seed/python-sdk/exhaustive/improved_imports/src/seed/endpoints/client.py b/seed/python-sdk/exhaustive/improved_imports/src/seed/endpoints/client.py index 18dc397fdf1..69930de54d7 100644 --- a/seed/python-sdk/exhaustive/improved_imports/src/seed/endpoints/client.py +++ b/seed/python-sdk/exhaustive/improved_imports/src/seed/endpoints/client.py @@ -1,13 +1,21 @@ # This file was auto-generated by Fern from our API Definition. -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from .container.client import AsyncContainerClient, ContainerClient -from .enum.client import AsyncEnumClient, EnumClient -from .http_methods.client import AsyncHttpMethodsClient, HttpMethodsClient -from .object.client import AsyncObjectClient, ObjectClient -from .params.client import AsyncParamsClient, ParamsClient -from .primitive.client import AsyncPrimitiveClient, PrimitiveClient -from .union.client import AsyncUnionClient, UnionClient +from ..core.client_wrapper import SyncClientWrapper +from .container.client import ContainerClient +from .enum.client import EnumClient +from .http_methods.client import HttpMethodsClient +from .object.client import ObjectClient +from .params.client import ParamsClient +from .primitive.client import PrimitiveClient +from .union.client import UnionClient +from ..core.client_wrapper import AsyncClientWrapper +from .container.client import AsyncContainerClient +from .enum.client import AsyncEnumClient +from .http_methods.client import AsyncHttpMethodsClient +from .object.client import AsyncObjectClient +from .params.client import AsyncParamsClient +from .primitive.client import AsyncPrimitiveClient +from .union.client import AsyncUnionClient class EndpointsClient: diff --git a/seed/python-sdk/exhaustive/improved_imports/src/seed/endpoints/container/client.py b/seed/python-sdk/exhaustive/improved_imports/src/seed/endpoints/container/client.py index c6cf14f63ac..4af9c12d534 100644 --- a/seed/python-sdk/exhaustive/improved_imports/src/seed/endpoints/container/client.py +++ b/seed/python-sdk/exhaustive/improved_imports/src/seed/endpoints/container/client.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. import typing +from ...core.client_wrapper import SyncClientWrapper +from ...core.request_options import RequestOptions +from ...core.pydantic_utilities import parse_obj_as from json.decoder import JSONDecodeError - from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ...core.pydantic_utilities import parse_obj_as -from ...core.request_options import RequestOptions from ...types.object.types.object_with_required_field import ObjectWithRequiredField +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -18,7 +18,10 @@ def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper def get_and_return_list_of_primitives( - self, *, request: typing.Sequence[str], request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Sequence[str], + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[str]: """ Parameters @@ -45,11 +48,18 @@ def get_and_return_list_of_primitives( ) """ _response = self._client_wrapper.httpx_client.request( - "container/list-of-primitives", method="POST", json=request, request_options=request_options, omit=OMIT + "container/list-of-primitives", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.List[str], parse_obj_as(type_=typing.List[str], object_=_response.json())) # type: ignore + return typing.cast( + typing.List[str], + parse_obj_as(type_=typing.List[str], object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -59,7 +69,7 @@ def get_and_return_list_of_objects( self, *, request: typing.Sequence[ObjectWithRequiredField], - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[ObjectWithRequiredField]: """ Parameters @@ -91,18 +101,31 @@ def get_and_return_list_of_objects( ) """ _response = self._client_wrapper.httpx_client.request( - "container/list-of-objects", method="POST", json=request, request_options=request_options, omit=OMIT + "container/list-of-objects", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.List[ObjectWithRequiredField], parse_obj_as(type_=typing.List[ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.List[ObjectWithRequiredField], + parse_obj_as( + type_=typing.List[ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_and_return_set_of_primitives( - self, *, request: typing.Set[str], request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Set[str], + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Set[str]: """ Parameters @@ -129,11 +152,18 @@ def get_and_return_set_of_primitives( ) """ _response = self._client_wrapper.httpx_client.request( - "container/set-of-primitives", method="POST", json=request, request_options=request_options, omit=OMIT + "container/set-of-primitives", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Set[str], parse_obj_as(type_=typing.Set[str], object_=_response.json())) # type: ignore + return typing.cast( + typing.Set[str], + parse_obj_as(type_=typing.Set[str], object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -143,7 +173,7 @@ def get_and_return_set_of_objects( self, *, request: typing.Sequence[ObjectWithRequiredField], - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[ObjectWithRequiredField]: """ Parameters @@ -175,18 +205,31 @@ def get_and_return_set_of_objects( ) """ _response = self._client_wrapper.httpx_client.request( - "container/set-of-objects", method="POST", json=request, request_options=request_options, omit=OMIT + "container/set-of-objects", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.List[ObjectWithRequiredField], parse_obj_as(type_=typing.List[ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.List[ObjectWithRequiredField], + parse_obj_as( + type_=typing.List[ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_and_return_map_prim_to_prim( - self, *, request: typing.Dict[str, str], request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Dict[str, str], + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Dict[str, str]: """ Parameters @@ -213,11 +256,18 @@ def get_and_return_map_prim_to_prim( ) """ _response = self._client_wrapper.httpx_client.request( - "container/map-prim-to-prim", method="POST", json=request, request_options=request_options, omit=OMIT + "container/map-prim-to-prim", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Dict[str, str], parse_obj_as(type_=typing.Dict[str, str], object_=_response.json())) # type: ignore + return typing.cast( + typing.Dict[str, str], + parse_obj_as(type_=typing.Dict[str, str], object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -227,7 +277,7 @@ def get_and_return_map_of_prim_to_object( self, *, request: typing.Dict[str, ObjectWithRequiredField], - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Dict[str, ObjectWithRequiredField]: """ Parameters @@ -259,11 +309,21 @@ def get_and_return_map_of_prim_to_object( ) """ _response = self._client_wrapper.httpx_client.request( - "container/map-prim-to-object", method="POST", json=request, request_options=request_options, omit=OMIT + "container/map-prim-to-object", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Dict[str, ObjectWithRequiredField], parse_obj_as(type_=typing.Dict[str, ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.Dict[str, ObjectWithRequiredField], + parse_obj_as( + type_=typing.Dict[str, ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -273,7 +333,7 @@ def get_and_return_optional( self, *, request: typing.Optional[ObjectWithRequiredField] = None, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Optional[ObjectWithRequiredField]: """ Parameters @@ -303,11 +363,21 @@ def get_and_return_optional( ) """ _response = self._client_wrapper.httpx_client.request( - "container/opt-objects", method="POST", json=request, request_options=request_options, omit=OMIT + "container/opt-objects", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Optional[ObjectWithRequiredField], parse_obj_as(type_=typing.Optional[ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.Optional[ObjectWithRequiredField], + parse_obj_as( + type_=typing.Optional[ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -319,7 +389,10 @@ def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper async def get_and_return_list_of_primitives( - self, *, request: typing.Sequence[str], request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Sequence[str], + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[str]: """ Parameters @@ -354,11 +427,18 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/list-of-primitives", method="POST", json=request, request_options=request_options, omit=OMIT + "container/list-of-primitives", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.List[str], parse_obj_as(type_=typing.List[str], object_=_response.json())) # type: ignore + return typing.cast( + typing.List[str], + parse_obj_as(type_=typing.List[str], object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -368,7 +448,7 @@ async def get_and_return_list_of_objects( self, *, request: typing.Sequence[ObjectWithRequiredField], - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[ObjectWithRequiredField]: """ Parameters @@ -408,18 +488,31 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/list-of-objects", method="POST", json=request, request_options=request_options, omit=OMIT + "container/list-of-objects", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.List[ObjectWithRequiredField], parse_obj_as(type_=typing.List[ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.List[ObjectWithRequiredField], + parse_obj_as( + type_=typing.List[ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_and_return_set_of_primitives( - self, *, request: typing.Set[str], request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Set[str], + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Set[str]: """ Parameters @@ -454,11 +547,18 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/set-of-primitives", method="POST", json=request, request_options=request_options, omit=OMIT + "container/set-of-primitives", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Set[str], parse_obj_as(type_=typing.Set[str], object_=_response.json())) # type: ignore + return typing.cast( + typing.Set[str], + parse_obj_as(type_=typing.Set[str], object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -468,7 +568,7 @@ async def get_and_return_set_of_objects( self, *, request: typing.Sequence[ObjectWithRequiredField], - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[ObjectWithRequiredField]: """ Parameters @@ -508,18 +608,31 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/set-of-objects", method="POST", json=request, request_options=request_options, omit=OMIT + "container/set-of-objects", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.List[ObjectWithRequiredField], parse_obj_as(type_=typing.List[ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.List[ObjectWithRequiredField], + parse_obj_as( + type_=typing.List[ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_and_return_map_prim_to_prim( - self, *, request: typing.Dict[str, str], request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Dict[str, str], + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Dict[str, str]: """ Parameters @@ -554,11 +667,18 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/map-prim-to-prim", method="POST", json=request, request_options=request_options, omit=OMIT + "container/map-prim-to-prim", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Dict[str, str], parse_obj_as(type_=typing.Dict[str, str], object_=_response.json())) # type: ignore + return typing.cast( + typing.Dict[str, str], + parse_obj_as(type_=typing.Dict[str, str], object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -568,7 +688,7 @@ async def get_and_return_map_of_prim_to_object( self, *, request: typing.Dict[str, ObjectWithRequiredField], - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Dict[str, ObjectWithRequiredField]: """ Parameters @@ -608,11 +728,21 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/map-prim-to-object", method="POST", json=request, request_options=request_options, omit=OMIT + "container/map-prim-to-object", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Dict[str, ObjectWithRequiredField], parse_obj_as(type_=typing.Dict[str, ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.Dict[str, ObjectWithRequiredField], + parse_obj_as( + type_=typing.Dict[str, ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -622,7 +752,7 @@ async def get_and_return_optional( self, *, request: typing.Optional[ObjectWithRequiredField] = None, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Optional[ObjectWithRequiredField]: """ Parameters @@ -660,11 +790,21 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/opt-objects", method="POST", json=request, request_options=request_options, omit=OMIT + "container/opt-objects", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Optional[ObjectWithRequiredField], parse_obj_as(type_=typing.Optional[ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.Optional[ObjectWithRequiredField], + parse_obj_as( + type_=typing.Optional[ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/improved_imports/src/seed/endpoints/enum/client.py b/seed/python-sdk/exhaustive/improved_imports/src/seed/endpoints/enum/client.py index 44e2690ff6c..3e3208e3bcf 100644 --- a/seed/python-sdk/exhaustive/improved_imports/src/seed/endpoints/enum/client.py +++ b/seed/python-sdk/exhaustive/improved_imports/src/seed/endpoints/enum/client.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. import typing +from ...core.client_wrapper import SyncClientWrapper +from ...types.enum.types.weather_report import WeatherReport +from ...core.request_options import RequestOptions +from ...core.pydantic_utilities import parse_obj_as from json.decoder import JSONDecodeError - from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ...core.pydantic_utilities import parse_obj_as -from ...core.request_options import RequestOptions -from ...types.enum.types.weather_report import WeatherReport +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -18,7 +18,10 @@ def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper def get_and_return_enum( - self, *, request: WeatherReport, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: WeatherReport, + request_options: typing.Optional[RequestOptions] = None, ) -> WeatherReport: """ Parameters @@ -45,11 +48,18 @@ def get_and_return_enum( ) """ _response = self._client_wrapper.httpx_client.request( - "enum", method="POST", json=request, request_options=request_options, omit=OMIT + "enum", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(WeatherReport, parse_obj_as(type_=WeatherReport, object_=_response.json())) # type: ignore + return typing.cast( + WeatherReport, + parse_obj_as(type_=WeatherReport, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -61,7 +71,10 @@ def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper async def get_and_return_enum( - self, *, request: WeatherReport, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: WeatherReport, + request_options: typing.Optional[RequestOptions] = None, ) -> WeatherReport: """ Parameters @@ -96,11 +109,18 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "enum", method="POST", json=request, request_options=request_options, omit=OMIT + "enum", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(WeatherReport, parse_obj_as(type_=WeatherReport, object_=_response.json())) # type: ignore + return typing.cast( + WeatherReport, + parse_obj_as(type_=WeatherReport, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/improved_imports/src/seed/endpoints/http_methods/client.py b/seed/python-sdk/exhaustive/improved_imports/src/seed/endpoints/http_methods/client.py index a2549280a1b..570a227844f 100644 --- a/seed/python-sdk/exhaustive/improved_imports/src/seed/endpoints/http_methods/client.py +++ b/seed/python-sdk/exhaustive/improved_imports/src/seed/endpoints/http_methods/client.py @@ -1,16 +1,16 @@ # This file was auto-generated by Fern from our API Definition. -import datetime as dt import typing -import uuid -from json.decoder import JSONDecodeError - -from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper +from ...core.client_wrapper import SyncClientWrapper +from ...core.request_options import RequestOptions from ...core.jsonable_encoder import jsonable_encoder from ...core.pydantic_utilities import parse_obj_as -from ...core.request_options import RequestOptions +from json.decoder import JSONDecodeError +from ...core.api_error import ApiError from ...types.object.types.object_with_optional_field import ObjectWithOptionalField +import datetime as dt +import uuid +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -20,7 +20,9 @@ class HttpMethodsClient: def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper - def test_get(self, id: str, *, request_options: typing.Optional[RequestOptions] = None) -> str: + def test_get( + self, id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -46,11 +48,15 @@ def test_get(self, id: str, *, request_options: typing.Optional[RequestOptions] ) """ _response = self._client_wrapper.httpx_client.request( - f"http-methods/{jsonable_encoder(id)}", method="GET", request_options=request_options + f"http-methods/{jsonable_encoder(id)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -84,18 +90,33 @@ def test_post( ) """ _response = self._client_wrapper.httpx_client.request( - "http-methods", method="POST", json={"string": string}, request_options=request_options, omit=OMIT + "http-methods", + method="POST", + json={ + "string": string, + }, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def test_put( - self, id: str, *, string: str, request_options: typing.Optional[RequestOptions] = None + self, + id: str, + *, + string: str, + request_options: typing.Optional[RequestOptions] = None, ) -> ObjectWithOptionalField: """ Parameters @@ -127,13 +148,20 @@ def test_put( _response = self._client_wrapper.httpx_client.request( f"http-methods/{jsonable_encoder(id)}", method="PUT", - json={"string": string}, + json={ + "string": string, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -254,13 +282,20 @@ def test_patch( ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def test_delete(self, id: str, *, request_options: typing.Optional[RequestOptions] = None) -> bool: + def test_delete( + self, id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> bool: """ Parameters ---------- @@ -286,11 +321,15 @@ def test_delete(self, id: str, *, request_options: typing.Optional[RequestOption ) """ _response = self._client_wrapper.httpx_client.request( - f"http-methods/{jsonable_encoder(id)}", method="DELETE", request_options=request_options + f"http-methods/{jsonable_encoder(id)}", + method="DELETE", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -301,7 +340,9 @@ class AsyncHttpMethodsClient: def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper - async def test_get(self, id: str, *, request_options: typing.Optional[RequestOptions] = None) -> str: + async def test_get( + self, id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -335,11 +376,15 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - f"http-methods/{jsonable_encoder(id)}", method="GET", request_options=request_options + f"http-methods/{jsonable_encoder(id)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -381,18 +426,33 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "http-methods", method="POST", json={"string": string}, request_options=request_options, omit=OMIT + "http-methods", + method="POST", + json={ + "string": string, + }, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def test_put( - self, id: str, *, string: str, request_options: typing.Optional[RequestOptions] = None + self, + id: str, + *, + string: str, + request_options: typing.Optional[RequestOptions] = None, ) -> ObjectWithOptionalField: """ Parameters @@ -432,13 +492,20 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( f"http-methods/{jsonable_encoder(id)}", method="PUT", - json={"string": string}, + json={ + "string": string, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -566,13 +633,20 @@ async def main() -> None: ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - async def test_delete(self, id: str, *, request_options: typing.Optional[RequestOptions] = None) -> bool: + async def test_delete( + self, id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> bool: """ Parameters ---------- @@ -606,11 +680,15 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - f"http-methods/{jsonable_encoder(id)}", method="DELETE", request_options=request_options + f"http-methods/{jsonable_encoder(id)}", + method="DELETE", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/improved_imports/src/seed/endpoints/object/client.py b/seed/python-sdk/exhaustive/improved_imports/src/seed/endpoints/object/client.py index a724f959193..dcb1324b74b 100644 --- a/seed/python-sdk/exhaustive/improved_imports/src/seed/endpoints/object/client.py +++ b/seed/python-sdk/exhaustive/improved_imports/src/seed/endpoints/object/client.py @@ -1,20 +1,24 @@ # This file was auto-generated by Fern from our API Definition. -import datetime as dt import typing +from ...core.client_wrapper import SyncClientWrapper +import datetime as dt import uuid -from json.decoder import JSONDecodeError - -from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ...core.jsonable_encoder import jsonable_encoder -from ...core.pydantic_utilities import parse_obj_as from ...core.request_options import RequestOptions -from ...types.object.types.nested_object_with_optional_field import NestedObjectWithOptionalField -from ...types.object.types.nested_object_with_required_field import NestedObjectWithRequiredField -from ...types.object.types.object_with_map_of_map import ObjectWithMapOfMap from ...types.object.types.object_with_optional_field import ObjectWithOptionalField +from ...core.pydantic_utilities import parse_obj_as +from json.decoder import JSONDecodeError +from ...core.api_error import ApiError from ...types.object.types.object_with_required_field import ObjectWithRequiredField +from ...types.object.types.object_with_map_of_map import ObjectWithMapOfMap +from ...types.object.types.nested_object_with_optional_field import ( + NestedObjectWithOptionalField, +) +from ...types.object.types.nested_object_with_required_field import ( + NestedObjectWithRequiredField, +) +from ...core.jsonable_encoder import jsonable_encoder +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -135,7 +139,12 @@ def get_and_return_with_optional_field( ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -171,20 +180,30 @@ def get_and_return_with_required_field( _response = self._client_wrapper.httpx_client.request( "object/get-and-return-with-required-field", method="POST", - json={"string": string}, + json={ + "string": string, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithRequiredField, parse_obj_as(type_=ObjectWithRequiredField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithRequiredField, + parse_obj_as( + type_=ObjectWithRequiredField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_and_return_with_map_of_map( - self, *, map_: typing.Dict[str, typing.Dict[str, str]], request_options: typing.Optional[RequestOptions] = None + self, + *, + map_: typing.Dict[str, typing.Dict[str, str]], + request_options: typing.Optional[RequestOptions] = None, ) -> ObjectWithMapOfMap: """ Parameters @@ -213,13 +232,18 @@ def get_and_return_with_map_of_map( _response = self._client_wrapper.httpx_client.request( "object/get-and-return-with-map-of-map", method="POST", - json={"map": map_}, + json={ + "map": map_, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithMapOfMap, parse_obj_as(type_=ObjectWithMapOfMap, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithMapOfMap, + parse_obj_as(type_=ObjectWithMapOfMap, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -286,13 +310,21 @@ def get_and_return_nested_with_optional_field( _response = self._client_wrapper.httpx_client.request( "object/get-and-return-nested-with-optional-field", method="POST", - json={"string": string, "NestedObject": nested_object}, + json={ + "string": string, + "NestedObject": nested_object, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(NestedObjectWithOptionalField, parse_obj_as(type_=NestedObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + NestedObjectWithOptionalField, + parse_obj_as( + type_=NestedObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -363,13 +395,21 @@ def get_and_return_nested_with_required_field( _response = self._client_wrapper.httpx_client.request( f"object/get-and-return-nested-with-required-field/{jsonable_encoder(string_)}", method="POST", - json={"string": string, "NestedObject": nested_object}, + json={ + "string": string, + "NestedObject": nested_object, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(NestedObjectWithRequiredField, parse_obj_as(type_=NestedObjectWithRequiredField, object_=_response.json())) # type: ignore + return typing.cast( + NestedObjectWithRequiredField, + parse_obj_as( + type_=NestedObjectWithRequiredField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -446,7 +486,12 @@ def get_and_return_nested_with_required_field_as_list( ) try: if 200 <= _response.status_code < 300: - return typing.cast(NestedObjectWithRequiredField, parse_obj_as(type_=NestedObjectWithRequiredField, object_=_response.json())) # type: ignore + return typing.cast( + NestedObjectWithRequiredField, + parse_obj_as( + type_=NestedObjectWithRequiredField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -575,7 +620,12 @@ async def main() -> None: ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -619,20 +669,30 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( "object/get-and-return-with-required-field", method="POST", - json={"string": string}, + json={ + "string": string, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithRequiredField, parse_obj_as(type_=ObjectWithRequiredField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithRequiredField, + parse_obj_as( + type_=ObjectWithRequiredField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_and_return_with_map_of_map( - self, *, map_: typing.Dict[str, typing.Dict[str, str]], request_options: typing.Optional[RequestOptions] = None + self, + *, + map_: typing.Dict[str, typing.Dict[str, str]], + request_options: typing.Optional[RequestOptions] = None, ) -> ObjectWithMapOfMap: """ Parameters @@ -669,13 +729,18 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( "object/get-and-return-with-map-of-map", method="POST", - json={"map": map_}, + json={ + "map": map_, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithMapOfMap, parse_obj_as(type_=ObjectWithMapOfMap, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithMapOfMap, + parse_obj_as(type_=ObjectWithMapOfMap, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -749,13 +814,21 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( "object/get-and-return-nested-with-optional-field", method="POST", - json={"string": string, "NestedObject": nested_object}, + json={ + "string": string, + "NestedObject": nested_object, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(NestedObjectWithOptionalField, parse_obj_as(type_=NestedObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + NestedObjectWithOptionalField, + parse_obj_as( + type_=NestedObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -833,13 +906,21 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( f"object/get-and-return-nested-with-required-field/{jsonable_encoder(string_)}", method="POST", - json={"string": string, "NestedObject": nested_object}, + json={ + "string": string, + "NestedObject": nested_object, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(NestedObjectWithRequiredField, parse_obj_as(type_=NestedObjectWithRequiredField, object_=_response.json())) # type: ignore + return typing.cast( + NestedObjectWithRequiredField, + parse_obj_as( + type_=NestedObjectWithRequiredField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -923,7 +1004,12 @@ async def main() -> None: ) try: if 200 <= _response.status_code < 300: - return typing.cast(NestedObjectWithRequiredField, parse_obj_as(type_=NestedObjectWithRequiredField, object_=_response.json())) # type: ignore + return typing.cast( + NestedObjectWithRequiredField, + parse_obj_as( + type_=NestedObjectWithRequiredField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/improved_imports/src/seed/endpoints/params/client.py b/seed/python-sdk/exhaustive/improved_imports/src/seed/endpoints/params/client.py index 5cd7ceef42a..a9187ac94b8 100644 --- a/seed/python-sdk/exhaustive/improved_imports/src/seed/endpoints/params/client.py +++ b/seed/python-sdk/exhaustive/improved_imports/src/seed/endpoints/params/client.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. import typing -from json.decoder import JSONDecodeError - -from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper +from ...core.client_wrapper import SyncClientWrapper +from ...core.request_options import RequestOptions from ...core.jsonable_encoder import jsonable_encoder from ...core.pydantic_utilities import parse_obj_as -from ...core.request_options import RequestOptions +from json.decoder import JSONDecodeError +from ...core.api_error import ApiError +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -17,7 +17,9 @@ class ParamsClient: def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper - def get_with_path(self, param: str, *, request_options: typing.Optional[RequestOptions] = None) -> str: + def get_with_path( + self, param: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ GET with path param @@ -45,18 +47,26 @@ def get_with_path(self, param: str, *, request_options: typing.Optional[RequestO ) """ _response = self._client_wrapper.httpx_client.request( - f"params/path/{jsonable_encoder(param)}", method="GET", request_options=request_options + f"params/path/{jsonable_encoder(param)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_with_query( - self, *, query: str, number: int, request_options: typing.Optional[RequestOptions] = None + self, + *, + query: str, + number: int, + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ GET with query param @@ -88,7 +98,13 @@ def get_with_query( ) """ _response = self._client_wrapper.httpx_client.request( - "params", method="GET", params={"query": query, "number": number}, request_options=request_options + "params", + method="GET", + params={ + "query": query, + "number": number, + }, + request_options=request_options, ) try: if 200 <= _response.status_code < 300: @@ -135,7 +151,13 @@ def get_with_allow_multiple_query( ) """ _response = self._client_wrapper.httpx_client.request( - "params", method="GET", params={"query": query, "numer": numer}, request_options=request_options + "params", + method="GET", + params={ + "query": query, + "numer": numer, + }, + request_options=request_options, ) try: if 200 <= _response.status_code < 300: @@ -146,7 +168,11 @@ def get_with_allow_multiple_query( raise ApiError(status_code=_response.status_code, body=_response_json) def get_with_path_and_query( - self, param: str, *, query: str, request_options: typing.Optional[RequestOptions] = None + self, + param: str, + *, + query: str, + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ GET with path and query params @@ -180,7 +206,9 @@ def get_with_path_and_query( _response = self._client_wrapper.httpx_client.request( f"params/path-query/{jsonable_encoder(param)}", method="GET", - params={"query": query}, + params={ + "query": query, + }, request_options=request_options, ) try: @@ -192,7 +220,11 @@ def get_with_path_and_query( raise ApiError(status_code=_response.status_code, body=_response_json) def modify_with_path( - self, param: str, *, request: str, request_options: typing.Optional[RequestOptions] = None + self, + param: str, + *, + request: str, + request_options: typing.Optional[RequestOptions] = None, ) -> str: """ PUT to update with path param @@ -232,7 +264,9 @@ def modify_with_path( ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -243,7 +277,9 @@ class AsyncParamsClient: def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper - async def get_with_path(self, param: str, *, request_options: typing.Optional[RequestOptions] = None) -> str: + async def get_with_path( + self, param: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ GET with path param @@ -279,18 +315,26 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - f"params/path/{jsonable_encoder(param)}", method="GET", request_options=request_options + f"params/path/{jsonable_encoder(param)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_with_query( - self, *, query: str, number: int, request_options: typing.Optional[RequestOptions] = None + self, + *, + query: str, + number: int, + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ GET with query param @@ -330,7 +374,13 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "params", method="GET", params={"query": query, "number": number}, request_options=request_options + "params", + method="GET", + params={ + "query": query, + "number": number, + }, + request_options=request_options, ) try: if 200 <= _response.status_code < 300: @@ -385,7 +435,13 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "params", method="GET", params={"query": query, "numer": numer}, request_options=request_options + "params", + method="GET", + params={ + "query": query, + "numer": numer, + }, + request_options=request_options, ) try: if 200 <= _response.status_code < 300: @@ -396,7 +452,11 @@ async def main() -> None: raise ApiError(status_code=_response.status_code, body=_response_json) async def get_with_path_and_query( - self, param: str, *, query: str, request_options: typing.Optional[RequestOptions] = None + self, + param: str, + *, + query: str, + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ GET with path and query params @@ -438,7 +498,9 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( f"params/path-query/{jsonable_encoder(param)}", method="GET", - params={"query": query}, + params={ + "query": query, + }, request_options=request_options, ) try: @@ -450,7 +512,11 @@ async def main() -> None: raise ApiError(status_code=_response.status_code, body=_response_json) async def modify_with_path( - self, param: str, *, request: str, request_options: typing.Optional[RequestOptions] = None + self, + param: str, + *, + request: str, + request_options: typing.Optional[RequestOptions] = None, ) -> str: """ PUT to update with path param @@ -498,7 +564,9 @@ async def main() -> None: ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/improved_imports/src/seed/endpoints/primitive/client.py b/seed/python-sdk/exhaustive/improved_imports/src/seed/endpoints/primitive/client.py index 844b6a782f0..20a66f049b4 100644 --- a/seed/python-sdk/exhaustive/improved_imports/src/seed/endpoints/primitive/client.py +++ b/seed/python-sdk/exhaustive/improved_imports/src/seed/endpoints/primitive/client.py @@ -1,14 +1,14 @@ # This file was auto-generated by Fern from our API Definition. -import datetime as dt import typing -import uuid +from ...core.client_wrapper import SyncClientWrapper +from ...core.request_options import RequestOptions +from ...core.pydantic_utilities import parse_obj_as from json.decoder import JSONDecodeError - from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ...core.pydantic_utilities import parse_obj_as -from ...core.request_options import RequestOptions +import datetime as dt +import uuid +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -18,7 +18,9 @@ class PrimitiveClient: def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper - def get_and_return_string(self, *, request: str, request_options: typing.Optional[RequestOptions] = None) -> str: + def get_and_return_string( + self, *, request: str, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -44,17 +46,25 @@ def get_and_return_string(self, *, request: str, request_options: typing.Optiona ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/string", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/string", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def get_and_return_int(self, *, request: int, request_options: typing.Optional[RequestOptions] = None) -> int: + def get_and_return_int( + self, *, request: int, request_options: typing.Optional[RequestOptions] = None + ) -> int: """ Parameters ---------- @@ -80,17 +90,25 @@ def get_and_return_int(self, *, request: int, request_options: typing.Optional[R ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/integer", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/integer", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(int, parse_obj_as(type_=int, object_=_response.json())) # type: ignore + return typing.cast( + int, parse_obj_as(type_=int, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def get_and_return_long(self, *, request: int, request_options: typing.Optional[RequestOptions] = None) -> int: + def get_and_return_long( + self, *, request: int, request_options: typing.Optional[RequestOptions] = None + ) -> int: """ Parameters ---------- @@ -116,11 +134,17 @@ def get_and_return_long(self, *, request: int, request_options: typing.Optional[ ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/long", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/long", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(int, parse_obj_as(type_=int, object_=_response.json())) # type: ignore + return typing.cast( + int, parse_obj_as(type_=int, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -154,17 +178,25 @@ def get_and_return_double( ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/double", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/double", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(float, parse_obj_as(type_=float, object_=_response.json())) # type: ignore + return typing.cast( + float, parse_obj_as(type_=float, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def get_and_return_bool(self, *, request: bool, request_options: typing.Optional[RequestOptions] = None) -> bool: + def get_and_return_bool( + self, *, request: bool, request_options: typing.Optional[RequestOptions] = None + ) -> bool: """ Parameters ---------- @@ -190,18 +222,27 @@ def get_and_return_bool(self, *, request: bool, request_options: typing.Optional ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/boolean", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/boolean", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_and_return_datetime( - self, *, request: dt.datetime, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: dt.datetime, + request_options: typing.Optional[RequestOptions] = None, ) -> dt.datetime: """ Parameters @@ -232,18 +273,28 @@ def get_and_return_datetime( ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/datetime", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/datetime", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(dt.datetime, parse_obj_as(type_=dt.datetime, object_=_response.json())) # type: ignore + return typing.cast( + dt.datetime, + parse_obj_as(type_=dt.datetime, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_and_return_date( - self, *, request: dt.date, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: dt.date, + request_options: typing.Optional[RequestOptions] = None, ) -> dt.date: """ Parameters @@ -274,18 +325,27 @@ def get_and_return_date( ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/date", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/date", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(dt.date, parse_obj_as(type_=dt.date, object_=_response.json())) # type: ignore + return typing.cast( + dt.date, parse_obj_as(type_=dt.date, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_and_return_uuid( - self, *, request: uuid.UUID, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: uuid.UUID, + request_options: typing.Optional[RequestOptions] = None, ) -> uuid.UUID: """ Parameters @@ -316,17 +376,25 @@ def get_and_return_uuid( ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/uuid", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/uuid", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(uuid.UUID, parse_obj_as(type_=uuid.UUID, object_=_response.json())) # type: ignore + return typing.cast( + uuid.UUID, parse_obj_as(type_=uuid.UUID, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def get_and_return_base_64(self, *, request: str, request_options: typing.Optional[RequestOptions] = None) -> str: + def get_and_return_base_64( + self, *, request: str, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -352,11 +420,17 @@ def get_and_return_base_64(self, *, request: str, request_options: typing.Option ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/base64", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/base64", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -403,17 +477,25 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/string", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/string", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - async def get_and_return_int(self, *, request: int, request_options: typing.Optional[RequestOptions] = None) -> int: + async def get_and_return_int( + self, *, request: int, request_options: typing.Optional[RequestOptions] = None + ) -> int: """ Parameters ---------- @@ -447,11 +529,17 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/integer", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/integer", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(int, parse_obj_as(type_=int, object_=_response.json())) # type: ignore + return typing.cast( + int, parse_obj_as(type_=int, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -493,11 +581,17 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/long", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/long", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(int, parse_obj_as(type_=int, object_=_response.json())) # type: ignore + return typing.cast( + int, parse_obj_as(type_=int, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -539,11 +633,17 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/double", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/double", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(float, parse_obj_as(type_=float, object_=_response.json())) # type: ignore + return typing.cast( + float, parse_obj_as(type_=float, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -585,18 +685,27 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/boolean", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/boolean", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_and_return_datetime( - self, *, request: dt.datetime, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: dt.datetime, + request_options: typing.Optional[RequestOptions] = None, ) -> dt.datetime: """ Parameters @@ -634,18 +743,28 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/datetime", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/datetime", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(dt.datetime, parse_obj_as(type_=dt.datetime, object_=_response.json())) # type: ignore + return typing.cast( + dt.datetime, + parse_obj_as(type_=dt.datetime, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_and_return_date( - self, *, request: dt.date, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: dt.date, + request_options: typing.Optional[RequestOptions] = None, ) -> dt.date: """ Parameters @@ -683,18 +802,27 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/date", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/date", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(dt.date, parse_obj_as(type_=dt.date, object_=_response.json())) # type: ignore + return typing.cast( + dt.date, parse_obj_as(type_=dt.date, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_and_return_uuid( - self, *, request: uuid.UUID, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: uuid.UUID, + request_options: typing.Optional[RequestOptions] = None, ) -> uuid.UUID: """ Parameters @@ -732,11 +860,17 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/uuid", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/uuid", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(uuid.UUID, parse_obj_as(type_=uuid.UUID, object_=_response.json())) # type: ignore + return typing.cast( + uuid.UUID, parse_obj_as(type_=uuid.UUID, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -778,11 +912,17 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/base64", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/base64", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/improved_imports/src/seed/endpoints/union/client.py b/seed/python-sdk/exhaustive/improved_imports/src/seed/endpoints/union/client.py index 77153587a27..f4c3d9312de 100644 --- a/seed/python-sdk/exhaustive/improved_imports/src/seed/endpoints/union/client.py +++ b/seed/python-sdk/exhaustive/improved_imports/src/seed/endpoints/union/client.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. import typing +from ...core.client_wrapper import SyncClientWrapper +from ...types.union.types.animal import Animal +from ...core.request_options import RequestOptions +from ...core.pydantic_utilities import parse_obj_as from json.decoder import JSONDecodeError - from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ...core.pydantic_utilities import parse_obj_as -from ...core.request_options import RequestOptions -from ...types.union.types.animal import Animal +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -18,7 +18,10 @@ def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper def get_and_return_union( - self, *, request: Animal, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: Animal, + request_options: typing.Optional[RequestOptions] = None, ) -> Animal: """ Parameters @@ -49,11 +52,17 @@ def get_and_return_union( ) """ _response = self._client_wrapper.httpx_client.request( - "union", method="POST", json=request, request_options=request_options, omit=OMIT + "union", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(Animal, parse_obj_as(type_=Animal, object_=_response.json())) # type: ignore + return typing.cast( + Animal, parse_obj_as(type_=Animal, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -65,7 +74,10 @@ def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper async def get_and_return_union( - self, *, request: Animal, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: Animal, + request_options: typing.Optional[RequestOptions] = None, ) -> Animal: """ Parameters @@ -104,11 +116,17 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "union", method="POST", json=request, request_options=request_options, omit=OMIT + "union", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(Animal, parse_obj_as(type_=Animal, object_=_response.json())) # type: ignore + return typing.cast( + Animal, parse_obj_as(type_=Animal, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/improved_imports/src/seed/general_errors/types/bad_object_request_info.py b/seed/python-sdk/exhaustive/improved_imports/src/seed/general_errors/types/bad_object_request_info.py index 7f03429e922..73c44b89531 100644 --- a/seed/python-sdk/exhaustive/improved_imports/src/seed/general_errors/types/bad_object_request_info.py +++ b/seed/python-sdk/exhaustive/improved_imports/src/seed/general_errors/types/bad_object_request_info.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class BadObjectRequestInfo(UniversalBaseModel): message: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/improved_imports/src/seed/inlined_requests/client.py b/seed/python-sdk/exhaustive/improved_imports/src/seed/inlined_requests/client.py index f7c46698eb9..39e0c8fe637 100644 --- a/seed/python-sdk/exhaustive/improved_imports/src/seed/inlined_requests/client.py +++ b/seed/python-sdk/exhaustive/improved_imports/src/seed/inlined_requests/client.py @@ -1,15 +1,15 @@ # This file was auto-generated by Fern from our API Definition. import typing -from json.decoder import JSONDecodeError - -from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.pydantic_utilities import parse_obj_as +from ..core.client_wrapper import SyncClientWrapper +from ..types.object.types.object_with_optional_field import ObjectWithOptionalField from ..core.request_options import RequestOptions +from ..core.pydantic_utilities import parse_obj_as from ..general_errors.errors.bad_request_body import BadRequestBody from ..general_errors.types.bad_object_request_info import BadObjectRequestInfo -from ..types.object.types.object_with_optional_field import ObjectWithOptionalField +from json.decoder import JSONDecodeError +from ..core.api_error import ApiError +from ..core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -25,7 +25,7 @@ def post_with_object_bodyand_response( string: str, integer: int, nested_object: ObjectWithOptionalField, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> ObjectWithOptionalField: """ POST with custom object in request body, response is an object @@ -86,16 +86,30 @@ def post_with_object_bodyand_response( _response = self._client_wrapper.httpx_client.request( "req-bodies/object", method="POST", - json={"string": string, "integer": integer, "NestedObject": nested_object}, + json={ + "string": string, + "integer": integer, + "NestedObject": nested_object, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore if _response.status_code == 400: raise BadRequestBody( - typing.cast(BadObjectRequestInfo, parse_obj_as(type_=BadObjectRequestInfo, object_=_response.json())) # type: ignore + typing.cast( + BadObjectRequestInfo, + parse_obj_as( + type_=BadObjectRequestInfo, object_=_response.json() + ), + ) # type: ignore ) _response_json = _response.json() except JSONDecodeError: @@ -113,7 +127,7 @@ async def post_with_object_bodyand_response( string: str, integer: int, nested_object: ObjectWithOptionalField, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> ObjectWithOptionalField: """ POST with custom object in request body, response is an object @@ -181,16 +195,30 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( "req-bodies/object", method="POST", - json={"string": string, "integer": integer, "NestedObject": nested_object}, + json={ + "string": string, + "integer": integer, + "NestedObject": nested_object, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore if _response.status_code == 400: raise BadRequestBody( - typing.cast(BadObjectRequestInfo, parse_obj_as(type_=BadObjectRequestInfo, object_=_response.json())) # type: ignore + typing.cast( + BadObjectRequestInfo, + parse_obj_as( + type_=BadObjectRequestInfo, object_=_response.json() + ), + ) # type: ignore ) _response_json = _response.json() except JSONDecodeError: diff --git a/seed/python-sdk/exhaustive/improved_imports/src/seed/no_auth/client.py b/seed/python-sdk/exhaustive/improved_imports/src/seed/no_auth/client.py index 3d203bcea34..e5590cde0df 100644 --- a/seed/python-sdk/exhaustive/improved_imports/src/seed/no_auth/client.py +++ b/seed/python-sdk/exhaustive/improved_imports/src/seed/no_auth/client.py @@ -1,14 +1,14 @@ # This file was auto-generated by Fern from our API Definition. import typing -from json.decoder import JSONDecodeError - -from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.pydantic_utilities import parse_obj_as +from ..core.client_wrapper import SyncClientWrapper from ..core.request_options import RequestOptions +from ..core.pydantic_utilities import parse_obj_as from ..general_errors.errors.bad_request_body import BadRequestBody from ..general_errors.types.bad_object_request_info import BadObjectRequestInfo +from json.decoder import JSONDecodeError +from ..core.api_error import ApiError +from ..core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -19,7 +19,10 @@ def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper def post_with_no_auth( - self, *, request: typing.Any, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Any, + request_options: typing.Optional[RequestOptions] = None, ) -> bool: """ POST request with no auth @@ -48,14 +51,25 @@ def post_with_no_auth( ) """ _response = self._client_wrapper.httpx_client.request( - "no-auth", method="POST", json=request, request_options=request_options, omit=OMIT + "no-auth", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore if _response.status_code == 400: raise BadRequestBody( - typing.cast(BadObjectRequestInfo, parse_obj_as(type_=BadObjectRequestInfo, object_=_response.json())) # type: ignore + typing.cast( + BadObjectRequestInfo, + parse_obj_as( + type_=BadObjectRequestInfo, object_=_response.json() + ), + ) # type: ignore ) _response_json = _response.json() except JSONDecodeError: @@ -68,7 +82,10 @@ def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper async def post_with_no_auth( - self, *, request: typing.Any, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Any, + request_options: typing.Optional[RequestOptions] = None, ) -> bool: """ POST request with no auth @@ -105,14 +122,25 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "no-auth", method="POST", json=request, request_options=request_options, omit=OMIT + "no-auth", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore if _response.status_code == 400: raise BadRequestBody( - typing.cast(BadObjectRequestInfo, parse_obj_as(type_=BadObjectRequestInfo, object_=_response.json())) # type: ignore + typing.cast( + BadObjectRequestInfo, + parse_obj_as( + type_=BadObjectRequestInfo, object_=_response.json() + ), + ) # type: ignore ) _response_json = _response.json() except JSONDecodeError: diff --git a/seed/python-sdk/exhaustive/improved_imports/src/seed/no_req_body/client.py b/seed/python-sdk/exhaustive/improved_imports/src/seed/no_req_body/client.py index 33fa0c77d27..5afdd703fdc 100644 --- a/seed/python-sdk/exhaustive/improved_imports/src/seed/no_req_body/client.py +++ b/seed/python-sdk/exhaustive/improved_imports/src/seed/no_req_body/client.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. +from ..core.client_wrapper import SyncClientWrapper import typing -from json.decoder import JSONDecodeError - -from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.pydantic_utilities import parse_obj_as from ..core.request_options import RequestOptions from ..types.object.types.object_with_optional_field import ObjectWithOptionalField +from ..core.pydantic_utilities import parse_obj_as +from json.decoder import JSONDecodeError +from ..core.api_error import ApiError +from ..core.client_wrapper import AsyncClientWrapper class NoReqBodyClient: @@ -38,17 +38,26 @@ def get_with_no_request_body( client.no_req_body.get_with_no_request_body() """ _response = self._client_wrapper.httpx_client.request( - "no-req-body", method="GET", request_options=request_options + "no-req-body", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def post_with_no_request_body(self, *, request_options: typing.Optional[RequestOptions] = None) -> str: + def post_with_no_request_body( + self, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -70,11 +79,15 @@ def post_with_no_request_body(self, *, request_options: typing.Optional[RequestO client.no_req_body.post_with_no_request_body() """ _response = self._client_wrapper.httpx_client.request( - "no-req-body", method="POST", request_options=request_options + "no-req-body", + method="POST", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -117,17 +130,26 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "no-req-body", method="GET", request_options=request_options + "no-req-body", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - async def post_with_no_request_body(self, *, request_options: typing.Optional[RequestOptions] = None) -> str: + async def post_with_no_request_body( + self, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -157,11 +179,15 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "no-req-body", method="POST", request_options=request_options + "no-req-body", + method="POST", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/improved_imports/src/seed/req_with_headers/client.py b/seed/python-sdk/exhaustive/improved_imports/src/seed/req_with_headers/client.py index 655402249e9..984428516e3 100644 --- a/seed/python-sdk/exhaustive/improved_imports/src/seed/req_with_headers/client.py +++ b/seed/python-sdk/exhaustive/improved_imports/src/seed/req_with_headers/client.py @@ -1,11 +1,11 @@ # This file was auto-generated by Fern from our API Definition. import typing +from ..core.client_wrapper import SyncClientWrapper +from ..core.request_options import RequestOptions from json.decoder import JSONDecodeError - from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.request_options import RequestOptions +from ..core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -21,7 +21,7 @@ def get_with_custom_header( x_test_service_header: str, x_test_endpoint_header: str, request: str, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ Parameters @@ -58,8 +58,12 @@ def get_with_custom_header( method="POST", json=request, headers={ - "X-TEST-SERVICE-HEADER": str(x_test_service_header) if x_test_service_header is not None else None, - "X-TEST-ENDPOINT-HEADER": str(x_test_endpoint_header) if x_test_endpoint_header is not None else None, + "X-TEST-SERVICE-HEADER": str(x_test_service_header) + if x_test_service_header is not None + else None, + "X-TEST-ENDPOINT-HEADER": str(x_test_endpoint_header) + if x_test_endpoint_header is not None + else None, }, request_options=request_options, omit=OMIT, @@ -83,7 +87,7 @@ async def get_with_custom_header( x_test_service_header: str, x_test_endpoint_header: str, request: str, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ Parameters @@ -128,8 +132,12 @@ async def main() -> None: method="POST", json=request, headers={ - "X-TEST-SERVICE-HEADER": str(x_test_service_header) if x_test_service_header is not None else None, - "X-TEST-ENDPOINT-HEADER": str(x_test_endpoint_header) if x_test_endpoint_header is not None else None, + "X-TEST-SERVICE-HEADER": str(x_test_service_header) + if x_test_service_header is not None + else None, + "X-TEST-ENDPOINT-HEADER": str(x_test_endpoint_header) + if x_test_endpoint_header is not None + else None, }, request_options=request_options, omit=OMIT, diff --git a/seed/python-sdk/exhaustive/improved_imports/src/seed/types/enum/types/weather_report.py b/seed/python-sdk/exhaustive/improved_imports/src/seed/types/enum/types/weather_report.py index 2d54965dc22..84017ef161d 100644 --- a/seed/python-sdk/exhaustive/improved_imports/src/seed/types/enum/types/weather_report.py +++ b/seed/python-sdk/exhaustive/improved_imports/src/seed/types/enum/types/weather_report.py @@ -2,4 +2,6 @@ import typing -WeatherReport = typing.Union[typing.Literal["SUNNY", "CLOUDY", "RAINING", "SNOWING"], typing.Any] +WeatherReport = typing.Union[ + typing.Literal["SUNNY", "CLOUDY", "RAINING", "SNOWING"], typing.Any +] diff --git a/seed/python-sdk/exhaustive/improved_imports/src/seed/types/object/types/double_optional.py b/seed/python-sdk/exhaustive/improved_imports/src/seed/types/object/types/double_optional.py index ddf165b13bd..ed236347357 100644 --- a/seed/python-sdk/exhaustive/improved_imports/src/seed/types/object/types/double_optional.py +++ b/seed/python-sdk/exhaustive/improved_imports/src/seed/types/object/types/double_optional.py @@ -1,18 +1,21 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .optional_alias import OptionalAlias +import pydantic +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class DoubleOptional(UniversalBaseModel): - optional_alias: typing.Optional[OptionalAlias] = pydantic.Field(alias="optionalAlias", default=None) + optional_alias: typing.Optional[OptionalAlias] = pydantic.Field( + alias="optionalAlias", default=None + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/improved_imports/src/seed/types/object/types/nested_object_with_optional_field.py b/seed/python-sdk/exhaustive/improved_imports/src/seed/types/object/types/nested_object_with_optional_field.py index 81669c0dd39..20a4d40a714 100644 --- a/seed/python-sdk/exhaustive/improved_imports/src/seed/types/object/types/nested_object_with_optional_field.py +++ b/seed/python-sdk/exhaustive/improved_imports/src/seed/types/object/types/nested_object_with_optional_field.py @@ -1,19 +1,22 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .object_with_optional_field import ObjectWithOptionalField +import pydantic +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class NestedObjectWithOptionalField(UniversalBaseModel): string: typing.Optional[str] = None - nested_object: typing.Optional[ObjectWithOptionalField] = pydantic.Field(alias="NestedObject", default=None) + nested_object: typing.Optional[ObjectWithOptionalField] = pydantic.Field( + alias="NestedObject", default=None + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/improved_imports/src/seed/types/object/types/nested_object_with_required_field.py b/seed/python-sdk/exhaustive/improved_imports/src/seed/types/object/types/nested_object_with_required_field.py index 1a621942c6c..a6ca8781190 100644 --- a/seed/python-sdk/exhaustive/improved_imports/src/seed/types/object/types/nested_object_with_required_field.py +++ b/seed/python-sdk/exhaustive/improved_imports/src/seed/types/object/types/nested_object_with_required_field.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import UniversalBaseModel from .object_with_optional_field import ObjectWithOptionalField +import pydantic +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class NestedObjectWithRequiredField(UniversalBaseModel): @@ -13,7 +12,9 @@ class NestedObjectWithRequiredField(UniversalBaseModel): nested_object: ObjectWithOptionalField = pydantic.Field(alias="NestedObject") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/improved_imports/src/seed/types/object/types/object_with_map_of_map.py b/seed/python-sdk/exhaustive/improved_imports/src/seed/types/object/types/object_with_map_of_map.py index 8883cc1d498..313cd25ceb8 100644 --- a/seed/python-sdk/exhaustive/improved_imports/src/seed/types/object/types/object_with_map_of_map.py +++ b/seed/python-sdk/exhaustive/improved_imports/src/seed/types/object/types/object_with_map_of_map.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class ObjectWithMapOfMap(UniversalBaseModel): map_: typing.Dict[str, typing.Dict[str, str]] = pydantic.Field(alias="map") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/improved_imports/src/seed/types/object/types/object_with_optional_field.py b/seed/python-sdk/exhaustive/improved_imports/src/seed/types/object/types/object_with_optional_field.py index 6aab170be0c..9131f0e91d7 100644 --- a/seed/python-sdk/exhaustive/improved_imports/src/seed/types/object/types/object_with_optional_field.py +++ b/seed/python-sdk/exhaustive/improved_imports/src/seed/types/object/types/object_with_optional_field.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. -import datetime as dt +from ....core.pydantic_utilities import UniversalBaseModel import typing -import uuid - import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +import datetime as dt +import uuid +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class ObjectWithOptionalField(UniversalBaseModel): @@ -23,13 +22,19 @@ class ObjectWithOptionalField(UniversalBaseModel): date: typing.Optional[dt.date] = None uuid_: typing.Optional[uuid.UUID] = pydantic.Field(alias="uuid", default=None) base_64: typing.Optional[str] = pydantic.Field(alias="base64", default=None) - list_: typing.Optional[typing.List[str]] = pydantic.Field(alias="list", default=None) + list_: typing.Optional[typing.List[str]] = pydantic.Field( + alias="list", default=None + ) set_: typing.Optional[typing.Set[str]] = pydantic.Field(alias="set", default=None) - map_: typing.Optional[typing.Dict[int, str]] = pydantic.Field(alias="map", default=None) + map_: typing.Optional[typing.Dict[int, str]] = pydantic.Field( + alias="map", default=None + ) bigint: typing.Optional[str] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/improved_imports/src/seed/types/object/types/object_with_required_field.py b/seed/python-sdk/exhaustive/improved_imports/src/seed/types/object/types/object_with_required_field.py index 61b98867984..24db26a3cf8 100644 --- a/seed/python-sdk/exhaustive/improved_imports/src/seed/types/object/types/object_with_required_field.py +++ b/seed/python-sdk/exhaustive/improved_imports/src/seed/types/object/types/object_with_required_field.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class ObjectWithRequiredField(UniversalBaseModel): string: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/improved_imports/src/seed/types/union/types/animal.py b/seed/python-sdk/exhaustive/improved_imports/src/seed/types/union/types/animal.py index 1ae43d1663e..84c71d2009a 100644 --- a/seed/python-sdk/exhaustive/improved_imports/src/seed/types/union/types/animal.py +++ b/seed/python-sdk/exhaustive/improved_imports/src/seed/types/union/types/animal.py @@ -1,12 +1,10 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ....core.pydantic_utilities import UniversalBaseModel import typing - import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class Animal_Dog(UniversalBaseModel): @@ -15,7 +13,9 @@ class Animal_Dog(UniversalBaseModel): likes_to_woof: bool = pydantic.Field(alias="likesToWoof") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: @@ -30,7 +30,9 @@ class Animal_Cat(UniversalBaseModel): likes_to_meow: bool = pydantic.Field(alias="likesToMeow") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/improved_imports/src/seed/types/union/types/cat.py b/seed/python-sdk/exhaustive/improved_imports/src/seed/types/union/types/cat.py index 61fc5527b1f..c59b78523c9 100644 --- a/seed/python-sdk/exhaustive/improved_imports/src/seed/types/union/types/cat.py +++ b/seed/python-sdk/exhaustive/improved_imports/src/seed/types/union/types/cat.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ....core.pydantic_utilities import UniversalBaseModel import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class Cat(UniversalBaseModel): @@ -12,7 +11,9 @@ class Cat(UniversalBaseModel): likes_to_meow: bool = pydantic.Field(alias="likesToMeow") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/improved_imports/src/seed/types/union/types/dog.py b/seed/python-sdk/exhaustive/improved_imports/src/seed/types/union/types/dog.py index c1ff5339dfe..e250c72edef 100644 --- a/seed/python-sdk/exhaustive/improved_imports/src/seed/types/union/types/dog.py +++ b/seed/python-sdk/exhaustive/improved_imports/src/seed/types/union/types/dog.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ....core.pydantic_utilities import UniversalBaseModel import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class Dog(UniversalBaseModel): @@ -12,7 +11,9 @@ class Dog(UniversalBaseModel): likes_to_woof: bool = pydantic.Field(alias="likesToWoof") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/improved_imports/src/seed/version.py b/seed/python-sdk/exhaustive/improved_imports/src/seed/version.py index 63ba170685a..ac44536abdb 100644 --- a/seed/python-sdk/exhaustive/improved_imports/src/seed/version.py +++ b/seed/python-sdk/exhaustive/improved_imports/src/seed/version.py @@ -1,4 +1,3 @@ - from importlib import metadata __version__ = metadata.version("fern_exhaustive") diff --git a/seed/python-sdk/exhaustive/improved_imports/tests/conftest.py b/seed/python-sdk/exhaustive/improved_imports/tests/conftest.py index b5b50383b94..86cb2b41af8 100644 --- a/seed/python-sdk/exhaustive/improved_imports/tests/conftest.py +++ b/seed/python-sdk/exhaustive/improved_imports/tests/conftest.py @@ -1,16 +1,22 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive import os - import pytest -from seed import AsyncSeedExhaustive, SeedExhaustive +from seed import AsyncSeedExhaustive @pytest.fixture def client() -> SeedExhaustive: - return SeedExhaustive(token=os.getenv("ENV_TOKEN", "token"), base_url=os.getenv("TESTS_BASE_URL", "base_url")) + return SeedExhaustive( + token=os.getenv("ENV_TOKEN", "token"), + base_url=os.getenv("TESTS_BASE_URL", "base_url"), + ) @pytest.fixture def async_client() -> AsyncSeedExhaustive: - return AsyncSeedExhaustive(token=os.getenv("ENV_TOKEN", "token"), base_url=os.getenv("TESTS_BASE_URL", "base_url")) + return AsyncSeedExhaustive( + token=os.getenv("ENV_TOKEN", "token"), + base_url=os.getenv("TESTS_BASE_URL", "base_url"), + ) diff --git a/seed/python-sdk/exhaustive/improved_imports/tests/custom/test_client.py b/seed/python-sdk/exhaustive/improved_imports/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/python-sdk/exhaustive/improved_imports/tests/custom/test_client.py +++ b/seed/python-sdk/exhaustive/improved_imports/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/python-sdk/exhaustive/improved_imports/tests/endpoints/test_container.py b/seed/python-sdk/exhaustive/improved_imports/tests/endpoints/test_container.py index 17d9d75240d..240f16f2a8c 100644 --- a/seed/python-sdk/exhaustive/improved_imports/tests/endpoints/test_container.py +++ b/seed/python-sdk/exhaustive/improved_imports/tests/endpoints/test_container.py @@ -1,91 +1,137 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing - -from seed import AsyncSeedExhaustive, SeedExhaustive -from seed.types.object import ObjectWithRequiredField - from ..utilities import validate_response +from seed.types.object import ObjectWithRequiredField -async def test_get_and_return_list_of_primitives(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_list_of_primitives( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = ["string"] expected_types: typing.Tuple[typing.Any, typing.Any] = ("list", {0: None}) - response = client.endpoints.container.get_and_return_list_of_primitives(request=["string"]) + response = client.endpoints.container.get_and_return_list_of_primitives( + request=["string"] + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.container.get_and_return_list_of_primitives(request=["string"]) + async_response = ( + await async_client.endpoints.container.get_and_return_list_of_primitives( + request=["string"] + ) + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_list_of_objects(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_list_of_objects( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = [{"string": "string"}] - expected_types: typing.Tuple[typing.Any, typing.Any] = ("list", {0: {"string": None}}) + expected_types: typing.Tuple[typing.Any, typing.Any] = ( + "list", + {0: {"string": None}}, + ) response = client.endpoints.container.get_and_return_list_of_objects( request=[ObjectWithRequiredField(string="string")] ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.container.get_and_return_list_of_objects( - request=[ObjectWithRequiredField(string="string")] + async_response = ( + await async_client.endpoints.container.get_and_return_list_of_objects( + request=[ObjectWithRequiredField(string="string")] + ) ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_set_of_primitives(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_set_of_primitives( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = ["string"] expected_types: typing.Tuple[typing.Any, typing.Any] = ("set", {0: None}) - response = client.endpoints.container.get_and_return_set_of_primitives(request={"string"}) + response = client.endpoints.container.get_and_return_set_of_primitives( + request={"string"} + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.container.get_and_return_set_of_primitives(request={"string"}) + async_response = ( + await async_client.endpoints.container.get_and_return_set_of_primitives( + request={"string"} + ) + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_set_of_objects(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_set_of_objects( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = [{"string": "string"}] - expected_types: typing.Tuple[typing.Any, typing.Any] = ("set", {0: {"string": None}}) + expected_types: typing.Tuple[typing.Any, typing.Any] = ( + "set", + {0: {"string": None}}, + ) response = client.endpoints.container.get_and_return_set_of_objects( request=[ObjectWithRequiredField(string="string")] ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.container.get_and_return_set_of_objects( - request=[ObjectWithRequiredField(string="string")] + async_response = ( + await async_client.endpoints.container.get_and_return_set_of_objects( + request=[ObjectWithRequiredField(string="string")] + ) ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_map_prim_to_prim(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_map_prim_to_prim( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = {"string": "string"} expected_types: typing.Tuple[typing.Any, typing.Any] = ("dict", {0: (None, None)}) - response = client.endpoints.container.get_and_return_map_prim_to_prim(request={"string": "string"}) + response = client.endpoints.container.get_and_return_map_prim_to_prim( + request={"string": "string"} + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.container.get_and_return_map_prim_to_prim( - request={"string": "string"} + async_response = ( + await async_client.endpoints.container.get_and_return_map_prim_to_prim( + request={"string": "string"} + ) ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_map_of_prim_to_object(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_map_of_prim_to_object( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = {"string": {"string": "string"}} - expected_types: typing.Tuple[typing.Any, typing.Any] = ("dict", {0: (None, {"string": None})}) + expected_types: typing.Tuple[typing.Any, typing.Any] = ( + "dict", + {0: (None, {"string": None})}, + ) response = client.endpoints.container.get_and_return_map_of_prim_to_object( request={"string": ObjectWithRequiredField(string="string")} ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.container.get_and_return_map_of_prim_to_object( - request={"string": ObjectWithRequiredField(string="string")} + async_response = ( + await async_client.endpoints.container.get_and_return_map_of_prim_to_object( + request={"string": ObjectWithRequiredField(string="string")} + ) ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_optional(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_optional( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = {"string": "string"} expected_types: typing.Any = {"string": None} - response = client.endpoints.container.get_and_return_optional(request=ObjectWithRequiredField(string="string")) + response = client.endpoints.container.get_and_return_optional( + request=ObjectWithRequiredField(string="string") + ) validate_response(response, expected_response, expected_types) async_response = await async_client.endpoints.container.get_and_return_optional( diff --git a/seed/python-sdk/exhaustive/improved_imports/tests/endpoints/test_enum.py b/seed/python-sdk/exhaustive/improved_imports/tests/endpoints/test_enum.py index 890aada5ce4..ca3fca30b5a 100644 --- a/seed/python-sdk/exhaustive/improved_imports/tests/endpoints/test_enum.py +++ b/seed/python-sdk/exhaustive/improved_imports/tests/endpoints/test_enum.py @@ -1,17 +1,20 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing - -from seed import AsyncSeedExhaustive, SeedExhaustive - from ..utilities import validate_response -async def test_get_and_return_enum(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_enum( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "SUNNY" expected_types: typing.Any = None response = client.endpoints.enum.get_and_return_enum(request="SUNNY") validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.enum.get_and_return_enum(request="SUNNY") + async_response = await async_client.endpoints.enum.get_and_return_enum( + request="SUNNY" + ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/exhaustive/improved_imports/tests/endpoints/test_http_methods.py b/seed/python-sdk/exhaustive/improved_imports/tests/endpoints/test_http_methods.py index dc01bafcf6f..77131fc6e8b 100644 --- a/seed/python-sdk/exhaustive/improved_imports/tests/endpoints/test_http_methods.py +++ b/seed/python-sdk/exhaustive/improved_imports/tests/endpoints/test_http_methods.py @@ -1,15 +1,16 @@ # This file was auto-generated by Fern from our API Definition. -import datetime +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing -import uuid - -from seed import AsyncSeedExhaustive, SeedExhaustive - from ..utilities import validate_response +import datetime +import uuid -async def test_test_get(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_test_get( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "string" expected_types: typing.Any = None response = client.endpoints.http_methods.test_get(id="string") @@ -19,7 +20,9 @@ async def test_test_get(client: SeedExhaustive, async_client: AsyncSeedExhaustiv validate_response(async_response, expected_response, expected_types) -async def test_test_post(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_test_post( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = { "string": "string", "integer": 1, @@ -53,11 +56,15 @@ async def test_test_post(client: SeedExhaustive, async_client: AsyncSeedExhausti response = client.endpoints.http_methods.test_post(string="string") validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.http_methods.test_post(string="string") + async_response = await async_client.endpoints.http_methods.test_post( + string="string" + ) validate_response(async_response, expected_response, expected_types) -async def test_test_put(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_test_put( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = { "string": "string", "integer": 1, @@ -91,11 +98,15 @@ async def test_test_put(client: SeedExhaustive, async_client: AsyncSeedExhaustiv response = client.endpoints.http_methods.test_put(id="string", string="string") validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.http_methods.test_put(id="string", string="string") + async_response = await async_client.endpoints.http_methods.test_put( + id="string", string="string" + ) validate_response(async_response, expected_response, expected_types) -async def test_test_patch(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_test_patch( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = { "string": "string", "integer": 1, @@ -163,7 +174,9 @@ async def test_test_patch(client: SeedExhaustive, async_client: AsyncSeedExhaust validate_response(async_response, expected_response, expected_types) -async def test_test_delete(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_test_delete( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = True expected_types: typing.Any = None response = client.endpoints.http_methods.test_delete(id="string") diff --git a/seed/python-sdk/exhaustive/improved_imports/tests/endpoints/test_object.py b/seed/python-sdk/exhaustive/improved_imports/tests/endpoints/test_object.py index a9098b6e9ef..c48c4332b22 100644 --- a/seed/python-sdk/exhaustive/improved_imports/tests/endpoints/test_object.py +++ b/seed/python-sdk/exhaustive/improved_imports/tests/endpoints/test_object.py @@ -1,16 +1,18 @@ # This file was auto-generated by Fern from our API Definition. -import datetime +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing +import datetime import uuid - -from seed import AsyncSeedExhaustive, SeedExhaustive -from seed.types.object import NestedObjectWithRequiredField, ObjectWithOptionalField - from ..utilities import validate_response +from seed.types.object import ObjectWithOptionalField +from seed.types.object import NestedObjectWithRequiredField -async def test_get_and_return_with_optional_field(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_with_optional_field( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = { "string": "string", "integer": 1, @@ -58,38 +60,54 @@ async def test_get_and_return_with_optional_field(client: SeedExhaustive, async_ ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.object.get_and_return_with_optional_field( - string="string", - integer=1, - long_=1000000, - double=1.1, - bool_=True, - datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), - date=datetime.date.fromisoformat("2023-01-15"), - uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), - base_64="SGVsbG8gd29ybGQh", - list_=["string"], - set_={"string"}, - map_={1: "string"}, - bigint="123456789123456789", + async_response = ( + await async_client.endpoints.object.get_and_return_with_optional_field( + string="string", + integer=1, + long_=1000000, + double=1.1, + bool_=True, + datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), + date=datetime.date.fromisoformat("2023-01-15"), + uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + base_64="SGVsbG8gd29ybGQh", + list_=["string"], + set_={"string"}, + map_={1: "string"}, + bigint="123456789123456789", + ) ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_with_required_field(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_with_required_field( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = {"string": "string"} expected_types: typing.Any = {"string": None} - response = client.endpoints.object.get_and_return_with_required_field(string="string") + response = client.endpoints.object.get_and_return_with_required_field( + string="string" + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.object.get_and_return_with_required_field(string="string") + async_response = ( + await async_client.endpoints.object.get_and_return_with_required_field( + string="string" + ) + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_with_map_of_map(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_with_map_of_map( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = {"map": {"string": {"string": "string"}}} - expected_types: typing.Any = {"map": ("dict", {0: (None, ("dict", {0: (None, None)}))})} - response = client.endpoints.object.get_and_return_with_map_of_map(map_={"string": {"string": "string"}}) + expected_types: typing.Any = { + "map": ("dict", {0: (None, ("dict", {0: (None, None)}))}) + } + response = client.endpoints.object.get_and_return_with_map_of_map( + map_={"string": {"string": "string"}} + ) validate_response(response, expected_response, expected_types) async_response = await async_client.endpoints.object.get_and_return_with_map_of_map( @@ -157,23 +175,25 @@ async def test_get_and_return_nested_with_optional_field( ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.object.get_and_return_nested_with_optional_field( - string="string", - nested_object=ObjectWithOptionalField( + async_response = ( + await async_client.endpoints.object.get_and_return_nested_with_optional_field( string="string", - integer=1, - long_=1000000, - double=1.1, - bool_=True, - datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), - date=datetime.date.fromisoformat("2023-01-15"), - uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), - base_64="SGVsbG8gd29ybGQh", - list_=["string"], - set_={"string"}, - map_={1: "string"}, - bigint="123456789123456789", - ), + nested_object=ObjectWithOptionalField( + string="string", + integer=1, + long_=1000000, + double=1.1, + bool_=True, + datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), + date=datetime.date.fromisoformat("2023-01-15"), + uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + base_64="SGVsbG8gd29ybGQh", + list_=["string"], + set_={"string"}, + map_={1: "string"}, + bigint="123456789123456789", + ), + ) ) validate_response(async_response, expected_response, expected_types) @@ -238,24 +258,26 @@ async def test_get_and_return_nested_with_required_field( ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.object.get_and_return_nested_with_required_field( - string_="string", - string="string", - nested_object=ObjectWithOptionalField( + async_response = ( + await async_client.endpoints.object.get_and_return_nested_with_required_field( + string_="string", string="string", - integer=1, - long_=1000000, - double=1.1, - bool_=True, - datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), - date=datetime.date.fromisoformat("2023-01-15"), - uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), - base_64="SGVsbG8gd29ybGQh", - list_=["string"], - set_={"string"}, - map_={1: "string"}, - bigint="123456789123456789", - ), + nested_object=ObjectWithOptionalField( + string="string", + integer=1, + long_=1000000, + double=1.1, + bool_=True, + datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), + date=datetime.date.fromisoformat("2023-01-15"), + uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + base_64="SGVsbG8gd29ybGQh", + list_=["string"], + set_={"string"}, + map_={1: "string"}, + bigint="123456789123456789", + ), + ) ) validate_response(async_response, expected_response, expected_types) @@ -299,27 +321,31 @@ async def test_get_and_return_nested_with_required_field_as_list( "bigint": None, }, } - response = client.endpoints.object.get_and_return_nested_with_required_field_as_list( - request=[ - NestedObjectWithRequiredField( - string="string", - nested_object=ObjectWithOptionalField( + response = ( + client.endpoints.object.get_and_return_nested_with_required_field_as_list( + request=[ + NestedObjectWithRequiredField( string="string", - integer=1, - long_=1000000, - double=1.1, - bool_=True, - datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), - date=datetime.date.fromisoformat("2023-01-15"), - uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), - base_64="SGVsbG8gd29ybGQh", - list_=["string"], - set_={"string"}, - map_={1: "string"}, - bigint="123456789123456789", - ), - ) - ] + nested_object=ObjectWithOptionalField( + string="string", + integer=1, + long_=1000000, + double=1.1, + bool_=True, + datetime=datetime.datetime.fromisoformat( + "2024-01-15 09:30:00+00:00" + ), + date=datetime.date.fromisoformat("2023-01-15"), + uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + base_64="SGVsbG8gd29ybGQh", + list_=["string"], + set_={"string"}, + map_={1: "string"}, + bigint="123456789123456789", + ), + ) + ] + ) ) validate_response(response, expected_response, expected_types) @@ -333,7 +359,9 @@ async def test_get_and_return_nested_with_required_field_as_list( long_=1000000, double=1.1, bool_=True, - datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), + datetime=datetime.datetime.fromisoformat( + "2024-01-15 09:30:00+00:00" + ), date=datetime.date.fromisoformat("2023-01-15"), uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), base_64="SGVsbG8gd29ybGQh", diff --git a/seed/python-sdk/exhaustive/improved_imports/tests/endpoints/test_params.py b/seed/python-sdk/exhaustive/improved_imports/tests/endpoints/test_params.py index 163d7b9161d..d8ffb00c0a0 100644 --- a/seed/python-sdk/exhaustive/improved_imports/tests/endpoints/test_params.py +++ b/seed/python-sdk/exhaustive/improved_imports/tests/endpoints/test_params.py @@ -1,13 +1,14 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing - -from seed import AsyncSeedExhaustive, SeedExhaustive - from ..utilities import validate_response -async def test_get_with_path(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_with_path( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "string" expected_types: typing.Any = None response = client.endpoints.params.get_with_path(param="string") @@ -17,32 +18,63 @@ async def test_get_with_path(client: SeedExhaustive, async_client: AsyncSeedExha validate_response(async_response, expected_response, expected_types) -async def test_get_with_query(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_with_query( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: # Type ignore to avoid mypy complaining about the function not being meant to return a value assert client.endpoints.params.get_with_query(query="string", number=1) is None # type: ignore[func-returns-value] - assert await async_client.endpoints.params.get_with_query(query="string", number=1) is None # type: ignore[func-returns-value] + assert ( + await async_client.endpoints.params.get_with_query(query="string", number=1) + is None + ) # type: ignore[func-returns-value] -async def test_get_with_allow_multiple_query(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_with_allow_multiple_query( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: # Type ignore to avoid mypy complaining about the function not being meant to return a value - assert client.endpoints.params.get_with_allow_multiple_query(query="string", numer=1) is None # type: ignore[func-returns-value] - - assert await async_client.endpoints.params.get_with_allow_multiple_query(query="string", numer=1) is None # type: ignore[func-returns-value] - - -async def test_get_with_path_and_query(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: + assert ( + client.endpoints.params.get_with_allow_multiple_query(query="string", numer=1) + is None + ) # type: ignore[func-returns-value] + + assert ( + await async_client.endpoints.params.get_with_allow_multiple_query( + query="string", numer=1 + ) + is None + ) # type: ignore[func-returns-value] + + +async def test_get_with_path_and_query( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: # Type ignore to avoid mypy complaining about the function not being meant to return a value - assert client.endpoints.params.get_with_path_and_query(param="string", query="string") is None # type: ignore[func-returns-value] - - assert await async_client.endpoints.params.get_with_path_and_query(param="string", query="string") is None # type: ignore[func-returns-value] - - -async def test_modify_with_path(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: + assert ( + client.endpoints.params.get_with_path_and_query(param="string", query="string") + is None + ) # type: ignore[func-returns-value] + + assert ( + await async_client.endpoints.params.get_with_path_and_query( + param="string", query="string" + ) + is None + ) # type: ignore[func-returns-value] + + +async def test_modify_with_path( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "string" expected_types: typing.Any = None - response = client.endpoints.params.modify_with_path(param="string", request="string") + response = client.endpoints.params.modify_with_path( + param="string", request="string" + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.params.modify_with_path(param="string", request="string") + async_response = await async_client.endpoints.params.modify_with_path( + param="string", request="string" + ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/exhaustive/improved_imports/tests/endpoints/test_primitive.py b/seed/python-sdk/exhaustive/improved_imports/tests/endpoints/test_primitive.py index ba3bc7e29e5..26cbcf45d2f 100644 --- a/seed/python-sdk/exhaustive/improved_imports/tests/endpoints/test_primitive.py +++ b/seed/python-sdk/exhaustive/improved_imports/tests/endpoints/test_primitive.py @@ -1,65 +1,86 @@ # This file was auto-generated by Fern from our API Definition. -import datetime +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing -import uuid - -from seed import AsyncSeedExhaustive, SeedExhaustive - from ..utilities import validate_response +import datetime +import uuid -async def test_get_and_return_string(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_string( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "string" expected_types: typing.Any = None response = client.endpoints.primitive.get_and_return_string(request="string") validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.primitive.get_and_return_string(request="string") + async_response = await async_client.endpoints.primitive.get_and_return_string( + request="string" + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_int(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_int( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = 1 expected_types: typing.Any = "integer" response = client.endpoints.primitive.get_and_return_int(request=1) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.primitive.get_and_return_int(request=1) + async_response = await async_client.endpoints.primitive.get_and_return_int( + request=1 + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_long(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_long( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = 1000000 expected_types: typing.Any = None response = client.endpoints.primitive.get_and_return_long(request=1000000) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.primitive.get_and_return_long(request=1000000) + async_response = await async_client.endpoints.primitive.get_and_return_long( + request=1000000 + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_double(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_double( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = 1.1 expected_types: typing.Any = None response = client.endpoints.primitive.get_and_return_double(request=1.1) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.primitive.get_and_return_double(request=1.1) + async_response = await async_client.endpoints.primitive.get_and_return_double( + request=1.1 + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_bool(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_bool( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = True expected_types: typing.Any = None response = client.endpoints.primitive.get_and_return_bool(request=True) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.primitive.get_and_return_bool(request=True) + async_response = await async_client.endpoints.primitive.get_and_return_bool( + request=True + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_datetime(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_datetime( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "2024-01-15T09:30:00Z" expected_types: typing.Any = "datetime" response = client.endpoints.primitive.get_and_return_datetime( @@ -73,10 +94,14 @@ async def test_get_and_return_datetime(client: SeedExhaustive, async_client: Asy validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_date(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_date( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "2023-01-15" expected_types: typing.Any = "date" - response = client.endpoints.primitive.get_and_return_date(request=datetime.date.fromisoformat("2023-01-15")) + response = client.endpoints.primitive.get_and_return_date( + request=datetime.date.fromisoformat("2023-01-15") + ) validate_response(response, expected_response, expected_types) async_response = await async_client.endpoints.primitive.get_and_return_date( @@ -85,10 +110,14 @@ async def test_get_and_return_date(client: SeedExhaustive, async_client: AsyncSe validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_uuid(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_uuid( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32" expected_types: typing.Any = "uuid" - response = client.endpoints.primitive.get_and_return_uuid(request=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32")) + response = client.endpoints.primitive.get_and_return_uuid( + request=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32") + ) validate_response(response, expected_response, expected_types) async_response = await async_client.endpoints.primitive.get_and_return_uuid( @@ -97,11 +126,17 @@ async def test_get_and_return_uuid(client: SeedExhaustive, async_client: AsyncSe validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_base_64(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_base_64( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "SGVsbG8gd29ybGQh" expected_types: typing.Any = None - response = client.endpoints.primitive.get_and_return_base_64(request="SGVsbG8gd29ybGQh") + response = client.endpoints.primitive.get_and_return_base_64( + request="SGVsbG8gd29ybGQh" + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.primitive.get_and_return_base_64(request="SGVsbG8gd29ybGQh") + async_response = await async_client.endpoints.primitive.get_and_return_base_64( + request="SGVsbG8gd29ybGQh" + ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/exhaustive/improved_imports/tests/endpoints/test_union.py b/seed/python-sdk/exhaustive/improved_imports/tests/endpoints/test_union.py index 14e34c2a6df..ceb84928cd9 100644 --- a/seed/python-sdk/exhaustive/improved_imports/tests/endpoints/test_union.py +++ b/seed/python-sdk/exhaustive/improved_imports/tests/endpoints/test_union.py @@ -1,17 +1,24 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing - -from seed import AsyncSeedExhaustive, SeedExhaustive from seed.types.union import Animal_Dog - from ..utilities import validate_response -async def test_get_and_return_union(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: - expected_response: typing.Any = {"animal": "dog", "name": "string", "likesToWoof": True} +async def test_get_and_return_union( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: + expected_response: typing.Any = { + "animal": "dog", + "name": "string", + "likesToWoof": True, + } expected_types: typing.Any = "no_validate" - response = client.endpoints.union.get_and_return_union(request=Animal_Dog(name="string", likes_to_woof=True)) + response = client.endpoints.union.get_and_return_union( + request=Animal_Dog(name="string", likes_to_woof=True) + ) validate_response(response, expected_response, expected_types) async_response = await async_client.endpoints.union.get_and_return_union( diff --git a/seed/python-sdk/exhaustive/improved_imports/tests/test_inlined_requests.py b/seed/python-sdk/exhaustive/improved_imports/tests/test_inlined_requests.py index bb9390d3845..03f46b31cc9 100644 --- a/seed/python-sdk/exhaustive/improved_imports/tests/test_inlined_requests.py +++ b/seed/python-sdk/exhaustive/improved_imports/tests/test_inlined_requests.py @@ -1,16 +1,17 @@ # This file was auto-generated by Fern from our API Definition. -import datetime +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing -import uuid - -from seed import AsyncSeedExhaustive, SeedExhaustive from seed.types.object import ObjectWithOptionalField - +import datetime +import uuid from .utilities import validate_response -async def test_post_with_object_bodyand_response(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_post_with_object_bodyand_response( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = { "string": "string", "integer": 1, @@ -62,23 +63,25 @@ async def test_post_with_object_bodyand_response(client: SeedExhaustive, async_c ) validate_response(response, expected_response, expected_types) - async_response = await async_client.inlined_requests.post_with_object_bodyand_response( - string="string", - integer=1, - nested_object=ObjectWithOptionalField( + async_response = ( + await async_client.inlined_requests.post_with_object_bodyand_response( string="string", integer=1, - long_=1000000, - double=1.1, - bool_=True, - datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), - date=datetime.date.fromisoformat("2023-01-15"), - uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), - base_64="SGVsbG8gd29ybGQh", - list_=["string"], - set_={"string"}, - map_={1: "string"}, - bigint="123456789123456789", - ), + nested_object=ObjectWithOptionalField( + string="string", + integer=1, + long_=1000000, + double=1.1, + bool_=True, + datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), + date=datetime.date.fromisoformat("2023-01-15"), + uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + base_64="SGVsbG8gd29ybGQh", + list_=["string"], + set_={"string"}, + map_={1: "string"}, + bigint="123456789123456789", + ), + ) ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/exhaustive/improved_imports/tests/test_no_auth.py b/seed/python-sdk/exhaustive/improved_imports/tests/test_no_auth.py index 3328661bb48..fc475f4b6fb 100644 --- a/seed/python-sdk/exhaustive/improved_imports/tests/test_no_auth.py +++ b/seed/python-sdk/exhaustive/improved_imports/tests/test_no_auth.py @@ -1,17 +1,20 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing - -from seed import AsyncSeedExhaustive, SeedExhaustive - from .utilities import validate_response -async def test_post_with_no_auth(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_post_with_no_auth( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = True expected_types: typing.Any = None response = client.no_auth.post_with_no_auth(request={"key": "value"}) validate_response(response, expected_response, expected_types) - async_response = await async_client.no_auth.post_with_no_auth(request={"key": "value"}) + async_response = await async_client.no_auth.post_with_no_auth( + request={"key": "value"} + ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/exhaustive/improved_imports/tests/test_no_req_body.py b/seed/python-sdk/exhaustive/improved_imports/tests/test_no_req_body.py index 73abac9d2d8..07061a0e99e 100644 --- a/seed/python-sdk/exhaustive/improved_imports/tests/test_no_req_body.py +++ b/seed/python-sdk/exhaustive/improved_imports/tests/test_no_req_body.py @@ -1,13 +1,14 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing - -from seed import AsyncSeedExhaustive, SeedExhaustive - from .utilities import validate_response -async def test_get_with_no_request_body(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_with_no_request_body( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = { "string": "string", "integer": 1, @@ -45,7 +46,9 @@ async def test_get_with_no_request_body(client: SeedExhaustive, async_client: As validate_response(async_response, expected_response, expected_types) -async def test_post_with_no_request_body(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_post_with_no_request_body( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "string" expected_types: typing.Any = None response = client.no_req_body.post_with_no_request_body() diff --git a/seed/python-sdk/exhaustive/improved_imports/tests/test_req_with_headers.py b/seed/python-sdk/exhaustive/improved_imports/tests/test_req_with_headers.py index bba3b5b5507..75ce9d00c03 100644 --- a/seed/python-sdk/exhaustive/improved_imports/tests/test_req_with_headers.py +++ b/seed/python-sdk/exhaustive/improved_imports/tests/test_req_with_headers.py @@ -1,10 +1,27 @@ # This file was auto-generated by Fern from our API Definition. -from seed import AsyncSeedExhaustive, SeedExhaustive +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive -async def test_get_with_custom_header(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_with_custom_header( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: # Type ignore to avoid mypy complaining about the function not being meant to return a value - assert client.req_with_headers.get_with_custom_header(x_test_service_header="string", x_test_endpoint_header="string", request="string") is None # type: ignore[func-returns-value] + assert ( + client.req_with_headers.get_with_custom_header( + x_test_service_header="string", + x_test_endpoint_header="string", + request="string", + ) + is None + ) # type: ignore[func-returns-value] - assert await async_client.req_with_headers.get_with_custom_header(x_test_service_header="string", x_test_endpoint_header="string", request="string") is None # type: ignore[func-returns-value] + assert ( + await async_client.req_with_headers.get_with_custom_header( + x_test_service_header="string", + x_test_endpoint_header="string", + request="string", + ) + is None + ) # type: ignore[func-returns-value] diff --git a/seed/python-sdk/exhaustive/improved_imports/tests/utilities.py b/seed/python-sdk/exhaustive/improved_imports/tests/utilities.py index 13da208eb3a..e8f4472564c 100644 --- a/seed/python-sdk/exhaustive/improved_imports/tests/utilities.py +++ b/seed/python-sdk/exhaustive/improved_imports/tests/utilities.py @@ -3,11 +3,14 @@ import typing import uuid -import pydantic from dateutil import parser +import pydantic + -def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> typing.Any: +def cast_field( + json_expectation: typing.Any, type_expectation: typing.Any +) -> typing.Any: # Cast these specific types which come through as string and expect our # models to cast to the correct type. if type_expectation == "uuid": @@ -25,7 +28,9 @@ def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> ty return json_expectation -def validate_field(response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any) -> None: +def validate_field( + response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectation == "no_validate": return @@ -44,7 +49,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(entry_expectation, dict): is_container_of_complex_type = True validate_response( - response=response[idx], json_expectation=ex, type_expectations=entry_expectation + response=response[idx], + json_expectation=ex, + type_expectations=entry_expectation, ) else: cast_json_expectation.append(cast_field(ex, entry_expectation)) @@ -56,7 +63,10 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # if any of the values of the set have a type_expectation of a dict, we're assuming it's a pydantic # model and keeping it a list. if container_expectation != "set" or not any( - map(lambda value: isinstance(value, dict), list(contents_expectation.values())) + map( + lambda value: isinstance(value, dict), + list(contents_expectation.values()), + ) ): json_expectation = cast_field(json_expectation, container_expectation) elif isinstance(type_expectation, tuple): @@ -65,9 +75,15 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(contents_expectation, dict): json_expectation = { cast_field( - key, contents_expectation.get(idx)[0] if contents_expectation.get(idx) is not None else None # type: ignore + key, + contents_expectation.get(idx)[0] + if contents_expectation.get(idx) is not None + else None, # type: ignore ): cast_field( - value, contents_expectation.get(idx)[1] if contents_expectation.get(idx) is not None else None # type: ignore + value, + contents_expectation.get(idx)[1] + if contents_expectation.get(idx) is not None + else None, # type: ignore ) for idx, (key, value) in enumerate(json_expectation.items()) } @@ -86,7 +102,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # Arg type_expectations is a deeply nested structure that matches the response, but with the values replaced with the expected types -def validate_response(response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any) -> None: +def validate_response( + response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectations == "no_validate": return @@ -96,11 +114,17 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e and not isinstance(response, dict) and not issubclass(type(response), pydantic.BaseModel) ): - validate_field(response=response, json_expectation=json_expectation, type_expectation=type_expectations) + validate_field( + response=response, + json_expectation=json_expectation, + type_expectation=type_expectations, + ) return if isinstance(response, list): - assert len(response) == len(json_expectation), "Length mismatch, expected: {0}, Actual: {1}".format( + assert len(response) == len( + json_expectation + ), "Length mismatch, expected: {0}, Actual: {1}".format( len(response), len(json_expectation) ) content_expectation = type_expectations @@ -108,7 +132,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e content_expectation = type_expectations[1] for idx, item in enumerate(response): validate_response( - response=item, json_expectation=json_expectation[idx], type_expectations=content_expectation[idx] + response=item, + json_expectation=json_expectation[idx], + type_expectations=content_expectation[idx], ) else: response_json = response @@ -116,7 +142,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e response_json = response.dict(by_alias=True) for key, value in json_expectation.items(): - assert key in response_json, "Field {0} not found within the response object: {1}".format( + assert ( + key in response_json + ), "Field {0} not found within the response object: {1}".format( key, response_json ) @@ -128,11 +156,19 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e # Otherwise, we're just validating a single field that's a pydantic model. if isinstance(value, dict) and not isinstance(type_expectation, tuple): validate_response( - response=response_json[key], json_expectation=value, type_expectations=type_expectation + response=response_json[key], + json_expectation=value, + type_expectations=type_expectation, ) else: - validate_field(response=response_json[key], json_expectation=value, type_expectation=type_expectation) + validate_field( + response=response_json[key], + json_expectation=value, + type_expectation=type_expectation, + ) # Ensure there are no additional fields here either del response_json[key] - assert len(response_json) == 0, "Additional fields found, expected None: {0}".format(response_json) + assert ( + len(response_json) == 0 + ), "Additional fields found, expected None: {0}".format(response_json) diff --git a/seed/python-sdk/exhaustive/improved_imports/tests/utils/assets/models/__init__.py b/seed/python-sdk/exhaustive/improved_imports/tests/utils/assets/models/__init__.py index 2cf01263529..3a1c852e71e 100644 --- a/seed/python-sdk/exhaustive/improved_imports/tests/utils/assets/models/__init__.py +++ b/seed/python-sdk/exhaustive/improved_imports/tests/utils/assets/models/__init__.py @@ -5,7 +5,7 @@ from .circle import CircleParams from .object_with_defaults import ObjectWithDefaultsParams from .object_with_optional_field import ObjectWithOptionalFieldParams -from .shape import Shape_CircleParams, Shape_SquareParams, ShapeParams +from .shape import ShapeParams, Shape_CircleParams, Shape_SquareParams from .square import SquareParams from .undiscriminated_shape import UndiscriminatedShapeParams diff --git a/seed/python-sdk/exhaustive/improved_imports/tests/utils/assets/models/circle.py b/seed/python-sdk/exhaustive/improved_imports/tests/utils/assets/models/circle.py index af7a1bf8a8e..253f12d38b3 100644 --- a/seed/python-sdk/exhaustive/improved_imports/tests/utils/assets/models/circle.py +++ b/seed/python-sdk/exhaustive/improved_imports/tests/utils/assets/models/circle.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class CircleParams(typing_extensions.TypedDict): - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] diff --git a/seed/python-sdk/exhaustive/improved_imports/tests/utils/assets/models/object_with_optional_field.py b/seed/python-sdk/exhaustive/improved_imports/tests/utils/assets/models/object_with_optional_field.py index 3ad93d5f305..ebe7dc80547 100644 --- a/seed/python-sdk/exhaustive/improved_imports/tests/utils/assets/models/object_with_optional_field.py +++ b/seed/python-sdk/exhaustive/improved_imports/tests/utils/assets/models/object_with_optional_field.py @@ -7,8 +7,8 @@ import uuid import typing_extensions -from seed.core.serialization import FieldMetadata +from seed.core.serialization import FieldMetadata from .color import Color from .shape import ShapeParams from .undiscriminated_shape import UndiscriminatedShapeParams @@ -18,16 +18,30 @@ class ObjectWithOptionalFieldParams(typing_extensions.TypedDict): literal: typing.Literal["lit_one"] string: typing_extensions.NotRequired[str] integer: typing_extensions.NotRequired[int] - long_: typing_extensions.NotRequired[typing_extensions.Annotated[int, FieldMetadata(alias="long")]] + long_: typing_extensions.NotRequired[ + typing_extensions.Annotated[int, FieldMetadata(alias="long")] + ] double: typing_extensions.NotRequired[float] - bool_: typing_extensions.NotRequired[typing_extensions.Annotated[bool, FieldMetadata(alias="bool")]] + bool_: typing_extensions.NotRequired[ + typing_extensions.Annotated[bool, FieldMetadata(alias="bool")] + ] datetime: typing_extensions.NotRequired[dt.datetime] date: typing_extensions.NotRequired[dt.date] - uuid_: typing_extensions.NotRequired[typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")]] - base_64: typing_extensions.NotRequired[typing_extensions.Annotated[str, FieldMetadata(alias="base64")]] - list_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")]] - set_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")]] - map_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")]] + uuid_: typing_extensions.NotRequired[ + typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")] + ] + base_64: typing_extensions.NotRequired[ + typing_extensions.Annotated[str, FieldMetadata(alias="base64")] + ] + list_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")] + ] + set_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")] + ] + map_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")] + ] enum: typing_extensions.NotRequired[Color] union: typing_extensions.NotRequired[ShapeParams] second_union: typing_extensions.NotRequired[ShapeParams] diff --git a/seed/python-sdk/exhaustive/improved_imports/tests/utils/assets/models/shape.py b/seed/python-sdk/exhaustive/improved_imports/tests/utils/assets/models/shape.py index 2c33c877951..816ffc51bdc 100644 --- a/seed/python-sdk/exhaustive/improved_imports/tests/utils/assets/models/shape.py +++ b/seed/python-sdk/exhaustive/improved_imports/tests/utils/assets/models/shape.py @@ -7,6 +7,7 @@ import typing import typing_extensions + from seed.core.serialization import FieldMetadata @@ -15,13 +16,21 @@ class Base(typing_extensions.TypedDict): class Shape_CircleParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["circle"], FieldMetadata(alias="shapeType")] - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["circle"], FieldMetadata(alias="shapeType") + ] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] class Shape_SquareParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["square"], FieldMetadata(alias="shapeType")] - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["square"], FieldMetadata(alias="shapeType") + ] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] ShapeParams = typing.Union[Shape_CircleParams, Shape_SquareParams] diff --git a/seed/python-sdk/exhaustive/improved_imports/tests/utils/assets/models/square.py b/seed/python-sdk/exhaustive/improved_imports/tests/utils/assets/models/square.py index b9b7dd319bc..bcf08a723c5 100644 --- a/seed/python-sdk/exhaustive/improved_imports/tests/utils/assets/models/square.py +++ b/seed/python-sdk/exhaustive/improved_imports/tests/utils/assets/models/square.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class SquareParams(typing_extensions.TypedDict): - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] diff --git a/seed/python-sdk/exhaustive/improved_imports/tests/utils/test_http_client.py b/seed/python-sdk/exhaustive/improved_imports/tests/utils/test_http_client.py index edd11ca7afb..f5a874a75f3 100644 --- a/seed/python-sdk/exhaustive/improved_imports/tests/utils/test_http_client.py +++ b/seed/python-sdk/exhaustive/improved_imports/tests/utils/test_http_client.py @@ -9,12 +9,17 @@ def get_request_options() -> RequestOptions: def test_get_json_request_body() -> None: - json_body, data_body = get_request_body(json={"hello": "world"}, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json={"hello": "world"}, data=None, request_options=None, omit=None + ) assert json_body == {"hello": "world"} assert data_body is None json_body_extras, data_body_extras = get_request_body( - json={"goodbye": "world"}, data=None, request_options=get_request_options(), omit=None + json={"goodbye": "world"}, + data=None, + request_options=get_request_options(), + omit=None, ) assert json_body_extras == {"goodbye": "world", "see you": "later"} @@ -22,12 +27,17 @@ def test_get_json_request_body() -> None: def test_get_files_request_body() -> None: - json_body, data_body = get_request_body(json=None, data={"hello": "world"}, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data={"hello": "world"}, request_options=None, omit=None + ) assert data_body == {"hello": "world"} assert json_body is None json_body_extras, data_body_extras = get_request_body( - json=None, data={"goodbye": "world"}, request_options=get_request_options(), omit=None + json=None, + data={"goodbye": "world"}, + request_options=get_request_options(), + omit=None, ) assert data_body_extras == {"goodbye": "world", "see you": "later"} @@ -35,7 +45,9 @@ def test_get_files_request_body() -> None: def test_get_none_request_body() -> None: - json_body, data_body = get_request_body(json=None, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data=None, request_options=None, omit=None + ) assert data_body is None assert json_body is None diff --git a/seed/python-sdk/exhaustive/improved_imports/tests/utils/test_query_encoding.py b/seed/python-sdk/exhaustive/improved_imports/tests/utils/test_query_encoding.py index 247e1551b46..fbc8f402167 100644 --- a/seed/python-sdk/exhaustive/improved_imports/tests/utils/test_query_encoding.py +++ b/seed/python-sdk/exhaustive/improved_imports/tests/utils/test_query_encoding.py @@ -4,9 +4,15 @@ def test_query_encoding() -> None: - assert encode_query({"hello world": "hello world"}) == {"hello world": "hello world"} - assert encode_query({"hello_world": {"hello": "world"}}) == {"hello_world[hello]": "world"} - assert encode_query({"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"}) == { + assert encode_query({"hello world": "hello world"}) == { + "hello world": "hello world" + } + assert encode_query({"hello_world": {"hello": "world"}}) == { + "hello_world[hello]": "world" + } + assert encode_query( + {"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"} + ) == { "hello_world[hello][world]": "today", "hello_world[test]": "this", "hi": "there", diff --git a/seed/python-sdk/exhaustive/improved_imports/tests/utils/test_serialization.py b/seed/python-sdk/exhaustive/improved_imports/tests/utils/test_serialization.py index 58b1ed66e6d..5ca956916dd 100644 --- a/seed/python-sdk/exhaustive/improved_imports/tests/utils/test_serialization.py +++ b/seed/python-sdk/exhaustive/improved_imports/tests/utils/test_serialization.py @@ -1,10 +1,12 @@ # This file was auto-generated by Fern from our API Definition. -from typing import Any, List +from typing import List, Any -from seed.core.serialization import convert_and_respect_annotation_metadata +from seed.core.serialization import ( + convert_and_respect_annotation_metadata, +) +from .assets.models import ShapeParams, ObjectWithOptionalFieldParams -from .assets.models import ObjectWithOptionalFieldParams, ShapeParams UNION_TEST: ShapeParams = {"radius_measurement": 1.0, "shape_type": "circle", "id": "1"} UNION_TEST_CONVERTED = {"shapeType": "circle", "radiusMeasurement": 1.0, "id": "1"} @@ -18,20 +20,54 @@ def test_convert_and_respect_annotation_metadata() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) - assert converted == {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"} + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) + assert converted == { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + } def test_convert_and_respect_annotation_metadata_in_list() -> None: data: List[ObjectWithOptionalFieldParams] = [ - {"string": "string", "long_": 12345, "bool_": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long_": 67890, "list_": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long_": 12345, + "bool_": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long_": 67890, + "list_": [], + "literal": "lit_one", + "any": "any", + }, ] - converted = convert_and_respect_annotation_metadata(object_=data, annotation=List[ObjectWithOptionalFieldParams]) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=List[ObjectWithOptionalFieldParams] + ) assert converted == [ - {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long": 67890, "list": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long": 67890, + "list": [], + "literal": "lit_one", + "any": "any", + }, ] @@ -43,7 +79,9 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) assert converted == { "string": "string", @@ -55,12 +93,16 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: def test_convert_and_respect_annotation_metadata_in_union() -> None: - converted = convert_and_respect_annotation_metadata(object_=UNION_TEST, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=UNION_TEST, annotation=ShapeParams + ) assert converted == UNION_TEST_CONVERTED def test_convert_and_respect_annotation_metadata_with_empty_object() -> None: data: Any = {} - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ShapeParams + ) assert converted == data diff --git a/seed/python-sdk/exhaustive/infinite-timeout/pyproject.toml b/seed/python-sdk/exhaustive/infinite-timeout/pyproject.toml index c6cd3a2b7b9..fc29a237334 100644 --- a/seed/python-sdk/exhaustive/infinite-timeout/pyproject.toml +++ b/seed/python-sdk/exhaustive/infinite-timeout/pyproject.toml @@ -43,6 +43,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/python-sdk/exhaustive/infinite-timeout/src/seed/__init__.py b/seed/python-sdk/exhaustive/infinite-timeout/src/seed/__init__.py index eb56b0ce275..dc1ef03a650 100644 --- a/seed/python-sdk/exhaustive/infinite-timeout/src/seed/__init__.py +++ b/seed/python-sdk/exhaustive/infinite-timeout/src/seed/__init__.py @@ -1,6 +1,14 @@ # This file was auto-generated by Fern from our API Definition. -from . import endpoints, general_errors, inlined_requests, no_auth, no_req_body, req_with_headers, types +from . import ( + endpoints, + general_errors, + inlined_requests, + no_auth, + no_req_body, + req_with_headers, + types, +) from .client import AsyncSeedExhaustive, SeedExhaustive from .general_errors import BadObjectRequestInfo, BadRequestBody from .version import __version__ diff --git a/seed/python-sdk/exhaustive/infinite-timeout/src/seed/client.py b/seed/python-sdk/exhaustive/infinite-timeout/src/seed/client.py index 5ff557bb2b1..8d5606f6c4f 100644 --- a/seed/python-sdk/exhaustive/infinite-timeout/src/seed/client.py +++ b/seed/python-sdk/exhaustive/infinite-timeout/src/seed/client.py @@ -1,15 +1,19 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from .endpoints.client import AsyncEndpointsClient, EndpointsClient -from .inlined_requests.client import AsyncInlinedRequestsClient, InlinedRequestsClient -from .no_auth.client import AsyncNoAuthClient, NoAuthClient -from .no_req_body.client import AsyncNoReqBodyClient, NoReqBodyClient -from .req_with_headers.client import AsyncReqWithHeadersClient, ReqWithHeadersClient +from .core.client_wrapper import SyncClientWrapper +from .endpoints.client import EndpointsClient +from .inlined_requests.client import InlinedRequestsClient +from .no_auth.client import NoAuthClient +from .no_req_body.client import NoReqBodyClient +from .req_with_headers.client import ReqWithHeadersClient +from .core.client_wrapper import AsyncClientWrapper +from .endpoints.client import AsyncEndpointsClient +from .inlined_requests.client import AsyncInlinedRequestsClient +from .no_auth.client import AsyncNoAuthClient +from .no_req_body.client import AsyncNoReqBodyClient +from .req_with_headers.client import AsyncReqWithHeadersClient class SeedExhaustive: @@ -48,24 +52,32 @@ def __init__( token: typing.Optional[typing.Union[str, typing.Callable[[], str]]] = None, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.Client] = None + httpx_client: typing.Optional[httpx.Client] = None, ): - _defaulted_timeout = timeout if timeout is not None else None if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else None if httpx_client is None else None + ) self._client_wrapper = SyncClientWrapper( base_url=base_url, token=token, httpx_client=httpx_client if httpx_client is not None - else httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.Client( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.Client(timeout=_defaulted_timeout), timeout=_defaulted_timeout, ) self.endpoints = EndpointsClient(client_wrapper=self._client_wrapper) - self.inlined_requests = InlinedRequestsClient(client_wrapper=self._client_wrapper) + self.inlined_requests = InlinedRequestsClient( + client_wrapper=self._client_wrapper + ) self.no_auth = NoAuthClient(client_wrapper=self._client_wrapper) self.no_req_body = NoReqBodyClient(client_wrapper=self._client_wrapper) - self.req_with_headers = ReqWithHeadersClient(client_wrapper=self._client_wrapper) + self.req_with_headers = ReqWithHeadersClient( + client_wrapper=self._client_wrapper + ) class AsyncSeedExhaustive: @@ -104,21 +116,29 @@ def __init__( token: typing.Optional[typing.Union[str, typing.Callable[[], str]]] = None, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.AsyncClient] = None + httpx_client: typing.Optional[httpx.AsyncClient] = None, ): - _defaulted_timeout = timeout if timeout is not None else None if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else None if httpx_client is None else None + ) self._client_wrapper = AsyncClientWrapper( base_url=base_url, token=token, httpx_client=httpx_client if httpx_client is not None - else httpx.AsyncClient(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.AsyncClient( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.AsyncClient(timeout=_defaulted_timeout), timeout=_defaulted_timeout, ) self.endpoints = AsyncEndpointsClient(client_wrapper=self._client_wrapper) - self.inlined_requests = AsyncInlinedRequestsClient(client_wrapper=self._client_wrapper) + self.inlined_requests = AsyncInlinedRequestsClient( + client_wrapper=self._client_wrapper + ) self.no_auth = AsyncNoAuthClient(client_wrapper=self._client_wrapper) self.no_req_body = AsyncNoReqBodyClient(client_wrapper=self._client_wrapper) - self.req_with_headers = AsyncReqWithHeadersClient(client_wrapper=self._client_wrapper) + self.req_with_headers = AsyncReqWithHeadersClient( + client_wrapper=self._client_wrapper + ) diff --git a/seed/python-sdk/exhaustive/infinite-timeout/src/seed/core/api_error.py b/seed/python-sdk/exhaustive/infinite-timeout/src/seed/core/api_error.py index 2e9fc5431cd..da734b58068 100644 --- a/seed/python-sdk/exhaustive/infinite-timeout/src/seed/core/api_error.py +++ b/seed/python-sdk/exhaustive/infinite-timeout/src/seed/core/api_error.py @@ -7,7 +7,9 @@ class ApiError(Exception): status_code: typing.Optional[int] body: typing.Any - def __init__(self, *, status_code: typing.Optional[int] = None, body: typing.Any = None): + def __init__( + self, *, status_code: typing.Optional[int] = None, body: typing.Any = None + ): self.status_code = status_code self.body = body diff --git a/seed/python-sdk/exhaustive/infinite-timeout/src/seed/core/client_wrapper.py b/seed/python-sdk/exhaustive/infinite-timeout/src/seed/core/client_wrapper.py index 8d01b584b82..d037184a816 100644 --- a/seed/python-sdk/exhaustive/infinite-timeout/src/seed/core/client_wrapper.py +++ b/seed/python-sdk/exhaustive/infinite-timeout/src/seed/core/client_wrapper.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .http_client import AsyncHttpClient, HttpClient +from .http_client import HttpClient +from .http_client import AsyncHttpClient class BaseClientWrapper: diff --git a/seed/python-sdk/exhaustive/infinite-timeout/src/seed/core/datetime_utils.py b/seed/python-sdk/exhaustive/infinite-timeout/src/seed/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/python-sdk/exhaustive/infinite-timeout/src/seed/core/datetime_utils.py +++ b/seed/python-sdk/exhaustive/infinite-timeout/src/seed/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/python-sdk/exhaustive/infinite-timeout/src/seed/core/file.py b/seed/python-sdk/exhaustive/infinite-timeout/src/seed/core/file.py index cb0d40bbbf3..6e0f92bfcb1 100644 --- a/seed/python-sdk/exhaustive/infinite-timeout/src/seed/core/file.py +++ b/seed/python-sdk/exhaustive/infinite-timeout/src/seed/core/file.py @@ -13,12 +13,17 @@ # (filename, file (or bytes), content_type) typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str]], # (filename, file (or bytes), content_type, headers) - typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str], typing.Mapping[str, str]], + typing.Tuple[ + typing.Optional[str], + FileContent, + typing.Optional[str], + typing.Mapping[str, str], + ], ] def convert_file_dict_to_httpx_tuples( - d: typing.Dict[str, typing.Union[File, typing.List[File]]] + d: typing.Dict[str, typing.Union[File, typing.List[File]]], ) -> typing.List[typing.Tuple[str, File]]: """ The format we use is a list of tuples, where the first element is the diff --git a/seed/python-sdk/exhaustive/infinite-timeout/src/seed/core/http_client.py b/seed/python-sdk/exhaustive/infinite-timeout/src/seed/core/http_client.py index 9333d8a7f15..091f71bc185 100644 --- a/seed/python-sdk/exhaustive/infinite-timeout/src/seed/core/http_client.py +++ b/seed/python-sdk/exhaustive/infinite-timeout/src/seed/core/http_client.py @@ -77,7 +77,9 @@ def _retry_timeout(response: httpx.Response, retries: int) -> float: return retry_after # Apply exponential backoff, capped at MAX_RETRY_DELAY_SECONDS. - retry_delay = min(INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS) + retry_delay = min( + INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS + ) # Add a randomness / jitter to the retry delay to avoid overwhelming the server with retries. timeout = retry_delay * (1 - 0.25 * random()) @@ -90,7 +92,8 @@ def _should_retry(response: httpx.Response) -> bool: def remove_omit_from_dict( - original: typing.Dict[str, typing.Optional[typing.Any]], omit: typing.Optional[typing.Any] + original: typing.Dict[str, typing.Optional[typing.Any]], + omit: typing.Optional[typing.Any], ) -> typing.Dict[str, typing.Any]: if omit is None: return original @@ -108,7 +111,8 @@ def maybe_filter_request_body( ) -> typing.Optional[typing.Any]: if data is None: return ( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else None ) @@ -118,7 +122,8 @@ def maybe_filter_request_body( data_content = { **(jsonable_encoder(remove_omit_from_dict(data, omit))), # type: ignore **( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else {} ), @@ -162,7 +167,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url def request( @@ -174,8 +181,12 @@ def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -184,11 +195,14 @@ def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) response = self.httpx_client.request( method=method, @@ -198,7 +212,11 @@ def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -209,7 +227,10 @@ def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -222,11 +243,15 @@ def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: time.sleep(_retry_timeout(response=response, retries=retries)) @@ -256,8 +281,12 @@ def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -266,11 +295,14 @@ def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) with self.httpx_client.stream( method=method, @@ -280,7 +312,11 @@ def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -291,7 +327,9 @@ def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -304,7 +342,9 @@ def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream @@ -327,7 +367,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url async def request( @@ -339,8 +381,12 @@ async def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -349,11 +395,14 @@ async def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) # Add the input to each of these and do None-safety checks response = await self.httpx_client.request( @@ -364,7 +413,11 @@ async def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -375,7 +428,10 @@ async def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -388,11 +444,15 @@ async def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: await asyncio.sleep(_retry_timeout(response=response, retries=retries)) @@ -421,8 +481,12 @@ async def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -431,11 +495,14 @@ async def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) async with self.httpx_client.stream( method=method, @@ -445,7 +512,11 @@ async def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -456,7 +527,9 @@ async def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -469,7 +542,9 @@ async def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream diff --git a/seed/python-sdk/exhaustive/infinite-timeout/src/seed/core/jsonable_encoder.py b/seed/python-sdk/exhaustive/infinite-timeout/src/seed/core/jsonable_encoder.py index d3fd328fd41..12a8b52fc22 100644 --- a/seed/python-sdk/exhaustive/infinite-timeout/src/seed/core/jsonable_encoder.py +++ b/seed/python-sdk/exhaustive/infinite-timeout/src/seed/core/jsonable_encoder.py @@ -19,13 +19,19 @@ import pydantic from .datetime_utils import serialize_datetime -from .pydantic_utilities import IS_PYDANTIC_V2, encode_by_type, to_jsonable_with_fallback +from .pydantic_utilities import ( + IS_PYDANTIC_V2, + encode_by_type, + to_jsonable_with_fallback, +) SetIntStr = Set[Union[int, str]] DictIntStrAny = Dict[Union[int, str], Any] -def jsonable_encoder(obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None) -> Any: +def jsonable_encoder( + obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None +) -> Any: custom_encoder = custom_encoder or {} if custom_encoder: if type(obj) in custom_encoder: diff --git a/seed/python-sdk/exhaustive/infinite-timeout/src/seed/core/pydantic_utilities.py b/seed/python-sdk/exhaustive/infinite-timeout/src/seed/core/pydantic_utilities.py index 170a563d6eb..c63935c32a2 100644 --- a/seed/python-sdk/exhaustive/infinite-timeout/src/seed/core/pydantic_utilities.py +++ b/seed/python-sdk/exhaustive/infinite-timeout/src/seed/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) # type: ignore # Pydantic v1 diff --git a/seed/python-sdk/exhaustive/infinite-timeout/src/seed/core/query_encoder.py b/seed/python-sdk/exhaustive/infinite-timeout/src/seed/core/query_encoder.py index 24076d72ee9..7cb98f52cd7 100644 --- a/seed/python-sdk/exhaustive/infinite-timeout/src/seed/core/query_encoder.py +++ b/seed/python-sdk/exhaustive/infinite-timeout/src/seed/core/query_encoder.py @@ -7,7 +7,9 @@ # Flattens dicts to be of the form {"key[subkey][subkey2]": value} where value is not a dict -def traverse_query_dict(dict_flat: Dict[str, Any], key_prefix: Optional[str] = None) -> Dict[str, Any]: +def traverse_query_dict( + dict_flat: Dict[str, Any], key_prefix: Optional[str] = None +) -> Dict[str, Any]: result = {} for k, v in dict_flat.items(): key = f"{key_prefix}[{k}]" if key_prefix is not None else k @@ -30,4 +32,8 @@ def single_query_encoder(query_key: str, query_value: Any) -> Dict[str, Any]: def encode_query(query: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: - return dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) if query is not None else None + return ( + dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) + if query is not None + else None + ) diff --git a/seed/python-sdk/exhaustive/infinite-timeout/src/seed/core/serialization.py b/seed/python-sdk/exhaustive/infinite-timeout/src/seed/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/python-sdk/exhaustive/infinite-timeout/src/seed/core/serialization.py +++ b/seed/python-sdk/exhaustive/infinite-timeout/src/seed/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/python-sdk/exhaustive/infinite-timeout/src/seed/endpoints/__init__.py b/seed/python-sdk/exhaustive/infinite-timeout/src/seed/endpoints/__init__.py index 92307cab7fe..a9496ece178 100644 --- a/seed/python-sdk/exhaustive/infinite-timeout/src/seed/endpoints/__init__.py +++ b/seed/python-sdk/exhaustive/infinite-timeout/src/seed/endpoints/__init__.py @@ -2,4 +2,12 @@ from . import container, enum, http_methods, object, params, primitive, union -__all__ = ["container", "enum", "http_methods", "object", "params", "primitive", "union"] +__all__ = [ + "container", + "enum", + "http_methods", + "object", + "params", + "primitive", + "union", +] diff --git a/seed/python-sdk/exhaustive/infinite-timeout/src/seed/endpoints/client.py b/seed/python-sdk/exhaustive/infinite-timeout/src/seed/endpoints/client.py index 18dc397fdf1..69930de54d7 100644 --- a/seed/python-sdk/exhaustive/infinite-timeout/src/seed/endpoints/client.py +++ b/seed/python-sdk/exhaustive/infinite-timeout/src/seed/endpoints/client.py @@ -1,13 +1,21 @@ # This file was auto-generated by Fern from our API Definition. -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from .container.client import AsyncContainerClient, ContainerClient -from .enum.client import AsyncEnumClient, EnumClient -from .http_methods.client import AsyncHttpMethodsClient, HttpMethodsClient -from .object.client import AsyncObjectClient, ObjectClient -from .params.client import AsyncParamsClient, ParamsClient -from .primitive.client import AsyncPrimitiveClient, PrimitiveClient -from .union.client import AsyncUnionClient, UnionClient +from ..core.client_wrapper import SyncClientWrapper +from .container.client import ContainerClient +from .enum.client import EnumClient +from .http_methods.client import HttpMethodsClient +from .object.client import ObjectClient +from .params.client import ParamsClient +from .primitive.client import PrimitiveClient +from .union.client import UnionClient +from ..core.client_wrapper import AsyncClientWrapper +from .container.client import AsyncContainerClient +from .enum.client import AsyncEnumClient +from .http_methods.client import AsyncHttpMethodsClient +from .object.client import AsyncObjectClient +from .params.client import AsyncParamsClient +from .primitive.client import AsyncPrimitiveClient +from .union.client import AsyncUnionClient class EndpointsClient: diff --git a/seed/python-sdk/exhaustive/infinite-timeout/src/seed/endpoints/container/client.py b/seed/python-sdk/exhaustive/infinite-timeout/src/seed/endpoints/container/client.py index c6cf14f63ac..4af9c12d534 100644 --- a/seed/python-sdk/exhaustive/infinite-timeout/src/seed/endpoints/container/client.py +++ b/seed/python-sdk/exhaustive/infinite-timeout/src/seed/endpoints/container/client.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. import typing +from ...core.client_wrapper import SyncClientWrapper +from ...core.request_options import RequestOptions +from ...core.pydantic_utilities import parse_obj_as from json.decoder import JSONDecodeError - from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ...core.pydantic_utilities import parse_obj_as -from ...core.request_options import RequestOptions from ...types.object.types.object_with_required_field import ObjectWithRequiredField +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -18,7 +18,10 @@ def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper def get_and_return_list_of_primitives( - self, *, request: typing.Sequence[str], request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Sequence[str], + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[str]: """ Parameters @@ -45,11 +48,18 @@ def get_and_return_list_of_primitives( ) """ _response = self._client_wrapper.httpx_client.request( - "container/list-of-primitives", method="POST", json=request, request_options=request_options, omit=OMIT + "container/list-of-primitives", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.List[str], parse_obj_as(type_=typing.List[str], object_=_response.json())) # type: ignore + return typing.cast( + typing.List[str], + parse_obj_as(type_=typing.List[str], object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -59,7 +69,7 @@ def get_and_return_list_of_objects( self, *, request: typing.Sequence[ObjectWithRequiredField], - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[ObjectWithRequiredField]: """ Parameters @@ -91,18 +101,31 @@ def get_and_return_list_of_objects( ) """ _response = self._client_wrapper.httpx_client.request( - "container/list-of-objects", method="POST", json=request, request_options=request_options, omit=OMIT + "container/list-of-objects", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.List[ObjectWithRequiredField], parse_obj_as(type_=typing.List[ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.List[ObjectWithRequiredField], + parse_obj_as( + type_=typing.List[ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_and_return_set_of_primitives( - self, *, request: typing.Set[str], request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Set[str], + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Set[str]: """ Parameters @@ -129,11 +152,18 @@ def get_and_return_set_of_primitives( ) """ _response = self._client_wrapper.httpx_client.request( - "container/set-of-primitives", method="POST", json=request, request_options=request_options, omit=OMIT + "container/set-of-primitives", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Set[str], parse_obj_as(type_=typing.Set[str], object_=_response.json())) # type: ignore + return typing.cast( + typing.Set[str], + parse_obj_as(type_=typing.Set[str], object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -143,7 +173,7 @@ def get_and_return_set_of_objects( self, *, request: typing.Sequence[ObjectWithRequiredField], - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[ObjectWithRequiredField]: """ Parameters @@ -175,18 +205,31 @@ def get_and_return_set_of_objects( ) """ _response = self._client_wrapper.httpx_client.request( - "container/set-of-objects", method="POST", json=request, request_options=request_options, omit=OMIT + "container/set-of-objects", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.List[ObjectWithRequiredField], parse_obj_as(type_=typing.List[ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.List[ObjectWithRequiredField], + parse_obj_as( + type_=typing.List[ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_and_return_map_prim_to_prim( - self, *, request: typing.Dict[str, str], request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Dict[str, str], + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Dict[str, str]: """ Parameters @@ -213,11 +256,18 @@ def get_and_return_map_prim_to_prim( ) """ _response = self._client_wrapper.httpx_client.request( - "container/map-prim-to-prim", method="POST", json=request, request_options=request_options, omit=OMIT + "container/map-prim-to-prim", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Dict[str, str], parse_obj_as(type_=typing.Dict[str, str], object_=_response.json())) # type: ignore + return typing.cast( + typing.Dict[str, str], + parse_obj_as(type_=typing.Dict[str, str], object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -227,7 +277,7 @@ def get_and_return_map_of_prim_to_object( self, *, request: typing.Dict[str, ObjectWithRequiredField], - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Dict[str, ObjectWithRequiredField]: """ Parameters @@ -259,11 +309,21 @@ def get_and_return_map_of_prim_to_object( ) """ _response = self._client_wrapper.httpx_client.request( - "container/map-prim-to-object", method="POST", json=request, request_options=request_options, omit=OMIT + "container/map-prim-to-object", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Dict[str, ObjectWithRequiredField], parse_obj_as(type_=typing.Dict[str, ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.Dict[str, ObjectWithRequiredField], + parse_obj_as( + type_=typing.Dict[str, ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -273,7 +333,7 @@ def get_and_return_optional( self, *, request: typing.Optional[ObjectWithRequiredField] = None, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Optional[ObjectWithRequiredField]: """ Parameters @@ -303,11 +363,21 @@ def get_and_return_optional( ) """ _response = self._client_wrapper.httpx_client.request( - "container/opt-objects", method="POST", json=request, request_options=request_options, omit=OMIT + "container/opt-objects", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Optional[ObjectWithRequiredField], parse_obj_as(type_=typing.Optional[ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.Optional[ObjectWithRequiredField], + parse_obj_as( + type_=typing.Optional[ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -319,7 +389,10 @@ def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper async def get_and_return_list_of_primitives( - self, *, request: typing.Sequence[str], request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Sequence[str], + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[str]: """ Parameters @@ -354,11 +427,18 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/list-of-primitives", method="POST", json=request, request_options=request_options, omit=OMIT + "container/list-of-primitives", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.List[str], parse_obj_as(type_=typing.List[str], object_=_response.json())) # type: ignore + return typing.cast( + typing.List[str], + parse_obj_as(type_=typing.List[str], object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -368,7 +448,7 @@ async def get_and_return_list_of_objects( self, *, request: typing.Sequence[ObjectWithRequiredField], - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[ObjectWithRequiredField]: """ Parameters @@ -408,18 +488,31 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/list-of-objects", method="POST", json=request, request_options=request_options, omit=OMIT + "container/list-of-objects", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.List[ObjectWithRequiredField], parse_obj_as(type_=typing.List[ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.List[ObjectWithRequiredField], + parse_obj_as( + type_=typing.List[ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_and_return_set_of_primitives( - self, *, request: typing.Set[str], request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Set[str], + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Set[str]: """ Parameters @@ -454,11 +547,18 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/set-of-primitives", method="POST", json=request, request_options=request_options, omit=OMIT + "container/set-of-primitives", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Set[str], parse_obj_as(type_=typing.Set[str], object_=_response.json())) # type: ignore + return typing.cast( + typing.Set[str], + parse_obj_as(type_=typing.Set[str], object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -468,7 +568,7 @@ async def get_and_return_set_of_objects( self, *, request: typing.Sequence[ObjectWithRequiredField], - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[ObjectWithRequiredField]: """ Parameters @@ -508,18 +608,31 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/set-of-objects", method="POST", json=request, request_options=request_options, omit=OMIT + "container/set-of-objects", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.List[ObjectWithRequiredField], parse_obj_as(type_=typing.List[ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.List[ObjectWithRequiredField], + parse_obj_as( + type_=typing.List[ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_and_return_map_prim_to_prim( - self, *, request: typing.Dict[str, str], request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Dict[str, str], + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Dict[str, str]: """ Parameters @@ -554,11 +667,18 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/map-prim-to-prim", method="POST", json=request, request_options=request_options, omit=OMIT + "container/map-prim-to-prim", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Dict[str, str], parse_obj_as(type_=typing.Dict[str, str], object_=_response.json())) # type: ignore + return typing.cast( + typing.Dict[str, str], + parse_obj_as(type_=typing.Dict[str, str], object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -568,7 +688,7 @@ async def get_and_return_map_of_prim_to_object( self, *, request: typing.Dict[str, ObjectWithRequiredField], - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Dict[str, ObjectWithRequiredField]: """ Parameters @@ -608,11 +728,21 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/map-prim-to-object", method="POST", json=request, request_options=request_options, omit=OMIT + "container/map-prim-to-object", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Dict[str, ObjectWithRequiredField], parse_obj_as(type_=typing.Dict[str, ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.Dict[str, ObjectWithRequiredField], + parse_obj_as( + type_=typing.Dict[str, ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -622,7 +752,7 @@ async def get_and_return_optional( self, *, request: typing.Optional[ObjectWithRequiredField] = None, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Optional[ObjectWithRequiredField]: """ Parameters @@ -660,11 +790,21 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/opt-objects", method="POST", json=request, request_options=request_options, omit=OMIT + "container/opt-objects", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Optional[ObjectWithRequiredField], parse_obj_as(type_=typing.Optional[ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.Optional[ObjectWithRequiredField], + parse_obj_as( + type_=typing.Optional[ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/infinite-timeout/src/seed/endpoints/enum/client.py b/seed/python-sdk/exhaustive/infinite-timeout/src/seed/endpoints/enum/client.py index 44e2690ff6c..3e3208e3bcf 100644 --- a/seed/python-sdk/exhaustive/infinite-timeout/src/seed/endpoints/enum/client.py +++ b/seed/python-sdk/exhaustive/infinite-timeout/src/seed/endpoints/enum/client.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. import typing +from ...core.client_wrapper import SyncClientWrapper +from ...types.enum.types.weather_report import WeatherReport +from ...core.request_options import RequestOptions +from ...core.pydantic_utilities import parse_obj_as from json.decoder import JSONDecodeError - from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ...core.pydantic_utilities import parse_obj_as -from ...core.request_options import RequestOptions -from ...types.enum.types.weather_report import WeatherReport +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -18,7 +18,10 @@ def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper def get_and_return_enum( - self, *, request: WeatherReport, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: WeatherReport, + request_options: typing.Optional[RequestOptions] = None, ) -> WeatherReport: """ Parameters @@ -45,11 +48,18 @@ def get_and_return_enum( ) """ _response = self._client_wrapper.httpx_client.request( - "enum", method="POST", json=request, request_options=request_options, omit=OMIT + "enum", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(WeatherReport, parse_obj_as(type_=WeatherReport, object_=_response.json())) # type: ignore + return typing.cast( + WeatherReport, + parse_obj_as(type_=WeatherReport, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -61,7 +71,10 @@ def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper async def get_and_return_enum( - self, *, request: WeatherReport, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: WeatherReport, + request_options: typing.Optional[RequestOptions] = None, ) -> WeatherReport: """ Parameters @@ -96,11 +109,18 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "enum", method="POST", json=request, request_options=request_options, omit=OMIT + "enum", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(WeatherReport, parse_obj_as(type_=WeatherReport, object_=_response.json())) # type: ignore + return typing.cast( + WeatherReport, + parse_obj_as(type_=WeatherReport, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/infinite-timeout/src/seed/endpoints/http_methods/client.py b/seed/python-sdk/exhaustive/infinite-timeout/src/seed/endpoints/http_methods/client.py index a2549280a1b..570a227844f 100644 --- a/seed/python-sdk/exhaustive/infinite-timeout/src/seed/endpoints/http_methods/client.py +++ b/seed/python-sdk/exhaustive/infinite-timeout/src/seed/endpoints/http_methods/client.py @@ -1,16 +1,16 @@ # This file was auto-generated by Fern from our API Definition. -import datetime as dt import typing -import uuid -from json.decoder import JSONDecodeError - -from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper +from ...core.client_wrapper import SyncClientWrapper +from ...core.request_options import RequestOptions from ...core.jsonable_encoder import jsonable_encoder from ...core.pydantic_utilities import parse_obj_as -from ...core.request_options import RequestOptions +from json.decoder import JSONDecodeError +from ...core.api_error import ApiError from ...types.object.types.object_with_optional_field import ObjectWithOptionalField +import datetime as dt +import uuid +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -20,7 +20,9 @@ class HttpMethodsClient: def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper - def test_get(self, id: str, *, request_options: typing.Optional[RequestOptions] = None) -> str: + def test_get( + self, id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -46,11 +48,15 @@ def test_get(self, id: str, *, request_options: typing.Optional[RequestOptions] ) """ _response = self._client_wrapper.httpx_client.request( - f"http-methods/{jsonable_encoder(id)}", method="GET", request_options=request_options + f"http-methods/{jsonable_encoder(id)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -84,18 +90,33 @@ def test_post( ) """ _response = self._client_wrapper.httpx_client.request( - "http-methods", method="POST", json={"string": string}, request_options=request_options, omit=OMIT + "http-methods", + method="POST", + json={ + "string": string, + }, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def test_put( - self, id: str, *, string: str, request_options: typing.Optional[RequestOptions] = None + self, + id: str, + *, + string: str, + request_options: typing.Optional[RequestOptions] = None, ) -> ObjectWithOptionalField: """ Parameters @@ -127,13 +148,20 @@ def test_put( _response = self._client_wrapper.httpx_client.request( f"http-methods/{jsonable_encoder(id)}", method="PUT", - json={"string": string}, + json={ + "string": string, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -254,13 +282,20 @@ def test_patch( ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def test_delete(self, id: str, *, request_options: typing.Optional[RequestOptions] = None) -> bool: + def test_delete( + self, id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> bool: """ Parameters ---------- @@ -286,11 +321,15 @@ def test_delete(self, id: str, *, request_options: typing.Optional[RequestOption ) """ _response = self._client_wrapper.httpx_client.request( - f"http-methods/{jsonable_encoder(id)}", method="DELETE", request_options=request_options + f"http-methods/{jsonable_encoder(id)}", + method="DELETE", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -301,7 +340,9 @@ class AsyncHttpMethodsClient: def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper - async def test_get(self, id: str, *, request_options: typing.Optional[RequestOptions] = None) -> str: + async def test_get( + self, id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -335,11 +376,15 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - f"http-methods/{jsonable_encoder(id)}", method="GET", request_options=request_options + f"http-methods/{jsonable_encoder(id)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -381,18 +426,33 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "http-methods", method="POST", json={"string": string}, request_options=request_options, omit=OMIT + "http-methods", + method="POST", + json={ + "string": string, + }, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def test_put( - self, id: str, *, string: str, request_options: typing.Optional[RequestOptions] = None + self, + id: str, + *, + string: str, + request_options: typing.Optional[RequestOptions] = None, ) -> ObjectWithOptionalField: """ Parameters @@ -432,13 +492,20 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( f"http-methods/{jsonable_encoder(id)}", method="PUT", - json={"string": string}, + json={ + "string": string, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -566,13 +633,20 @@ async def main() -> None: ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - async def test_delete(self, id: str, *, request_options: typing.Optional[RequestOptions] = None) -> bool: + async def test_delete( + self, id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> bool: """ Parameters ---------- @@ -606,11 +680,15 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - f"http-methods/{jsonable_encoder(id)}", method="DELETE", request_options=request_options + f"http-methods/{jsonable_encoder(id)}", + method="DELETE", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/infinite-timeout/src/seed/endpoints/object/client.py b/seed/python-sdk/exhaustive/infinite-timeout/src/seed/endpoints/object/client.py index a724f959193..dcb1324b74b 100644 --- a/seed/python-sdk/exhaustive/infinite-timeout/src/seed/endpoints/object/client.py +++ b/seed/python-sdk/exhaustive/infinite-timeout/src/seed/endpoints/object/client.py @@ -1,20 +1,24 @@ # This file was auto-generated by Fern from our API Definition. -import datetime as dt import typing +from ...core.client_wrapper import SyncClientWrapper +import datetime as dt import uuid -from json.decoder import JSONDecodeError - -from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ...core.jsonable_encoder import jsonable_encoder -from ...core.pydantic_utilities import parse_obj_as from ...core.request_options import RequestOptions -from ...types.object.types.nested_object_with_optional_field import NestedObjectWithOptionalField -from ...types.object.types.nested_object_with_required_field import NestedObjectWithRequiredField -from ...types.object.types.object_with_map_of_map import ObjectWithMapOfMap from ...types.object.types.object_with_optional_field import ObjectWithOptionalField +from ...core.pydantic_utilities import parse_obj_as +from json.decoder import JSONDecodeError +from ...core.api_error import ApiError from ...types.object.types.object_with_required_field import ObjectWithRequiredField +from ...types.object.types.object_with_map_of_map import ObjectWithMapOfMap +from ...types.object.types.nested_object_with_optional_field import ( + NestedObjectWithOptionalField, +) +from ...types.object.types.nested_object_with_required_field import ( + NestedObjectWithRequiredField, +) +from ...core.jsonable_encoder import jsonable_encoder +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -135,7 +139,12 @@ def get_and_return_with_optional_field( ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -171,20 +180,30 @@ def get_and_return_with_required_field( _response = self._client_wrapper.httpx_client.request( "object/get-and-return-with-required-field", method="POST", - json={"string": string}, + json={ + "string": string, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithRequiredField, parse_obj_as(type_=ObjectWithRequiredField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithRequiredField, + parse_obj_as( + type_=ObjectWithRequiredField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_and_return_with_map_of_map( - self, *, map_: typing.Dict[str, typing.Dict[str, str]], request_options: typing.Optional[RequestOptions] = None + self, + *, + map_: typing.Dict[str, typing.Dict[str, str]], + request_options: typing.Optional[RequestOptions] = None, ) -> ObjectWithMapOfMap: """ Parameters @@ -213,13 +232,18 @@ def get_and_return_with_map_of_map( _response = self._client_wrapper.httpx_client.request( "object/get-and-return-with-map-of-map", method="POST", - json={"map": map_}, + json={ + "map": map_, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithMapOfMap, parse_obj_as(type_=ObjectWithMapOfMap, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithMapOfMap, + parse_obj_as(type_=ObjectWithMapOfMap, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -286,13 +310,21 @@ def get_and_return_nested_with_optional_field( _response = self._client_wrapper.httpx_client.request( "object/get-and-return-nested-with-optional-field", method="POST", - json={"string": string, "NestedObject": nested_object}, + json={ + "string": string, + "NestedObject": nested_object, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(NestedObjectWithOptionalField, parse_obj_as(type_=NestedObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + NestedObjectWithOptionalField, + parse_obj_as( + type_=NestedObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -363,13 +395,21 @@ def get_and_return_nested_with_required_field( _response = self._client_wrapper.httpx_client.request( f"object/get-and-return-nested-with-required-field/{jsonable_encoder(string_)}", method="POST", - json={"string": string, "NestedObject": nested_object}, + json={ + "string": string, + "NestedObject": nested_object, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(NestedObjectWithRequiredField, parse_obj_as(type_=NestedObjectWithRequiredField, object_=_response.json())) # type: ignore + return typing.cast( + NestedObjectWithRequiredField, + parse_obj_as( + type_=NestedObjectWithRequiredField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -446,7 +486,12 @@ def get_and_return_nested_with_required_field_as_list( ) try: if 200 <= _response.status_code < 300: - return typing.cast(NestedObjectWithRequiredField, parse_obj_as(type_=NestedObjectWithRequiredField, object_=_response.json())) # type: ignore + return typing.cast( + NestedObjectWithRequiredField, + parse_obj_as( + type_=NestedObjectWithRequiredField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -575,7 +620,12 @@ async def main() -> None: ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -619,20 +669,30 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( "object/get-and-return-with-required-field", method="POST", - json={"string": string}, + json={ + "string": string, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithRequiredField, parse_obj_as(type_=ObjectWithRequiredField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithRequiredField, + parse_obj_as( + type_=ObjectWithRequiredField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_and_return_with_map_of_map( - self, *, map_: typing.Dict[str, typing.Dict[str, str]], request_options: typing.Optional[RequestOptions] = None + self, + *, + map_: typing.Dict[str, typing.Dict[str, str]], + request_options: typing.Optional[RequestOptions] = None, ) -> ObjectWithMapOfMap: """ Parameters @@ -669,13 +729,18 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( "object/get-and-return-with-map-of-map", method="POST", - json={"map": map_}, + json={ + "map": map_, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithMapOfMap, parse_obj_as(type_=ObjectWithMapOfMap, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithMapOfMap, + parse_obj_as(type_=ObjectWithMapOfMap, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -749,13 +814,21 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( "object/get-and-return-nested-with-optional-field", method="POST", - json={"string": string, "NestedObject": nested_object}, + json={ + "string": string, + "NestedObject": nested_object, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(NestedObjectWithOptionalField, parse_obj_as(type_=NestedObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + NestedObjectWithOptionalField, + parse_obj_as( + type_=NestedObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -833,13 +906,21 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( f"object/get-and-return-nested-with-required-field/{jsonable_encoder(string_)}", method="POST", - json={"string": string, "NestedObject": nested_object}, + json={ + "string": string, + "NestedObject": nested_object, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(NestedObjectWithRequiredField, parse_obj_as(type_=NestedObjectWithRequiredField, object_=_response.json())) # type: ignore + return typing.cast( + NestedObjectWithRequiredField, + parse_obj_as( + type_=NestedObjectWithRequiredField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -923,7 +1004,12 @@ async def main() -> None: ) try: if 200 <= _response.status_code < 300: - return typing.cast(NestedObjectWithRequiredField, parse_obj_as(type_=NestedObjectWithRequiredField, object_=_response.json())) # type: ignore + return typing.cast( + NestedObjectWithRequiredField, + parse_obj_as( + type_=NestedObjectWithRequiredField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/infinite-timeout/src/seed/endpoints/params/client.py b/seed/python-sdk/exhaustive/infinite-timeout/src/seed/endpoints/params/client.py index 5cd7ceef42a..a9187ac94b8 100644 --- a/seed/python-sdk/exhaustive/infinite-timeout/src/seed/endpoints/params/client.py +++ b/seed/python-sdk/exhaustive/infinite-timeout/src/seed/endpoints/params/client.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. import typing -from json.decoder import JSONDecodeError - -from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper +from ...core.client_wrapper import SyncClientWrapper +from ...core.request_options import RequestOptions from ...core.jsonable_encoder import jsonable_encoder from ...core.pydantic_utilities import parse_obj_as -from ...core.request_options import RequestOptions +from json.decoder import JSONDecodeError +from ...core.api_error import ApiError +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -17,7 +17,9 @@ class ParamsClient: def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper - def get_with_path(self, param: str, *, request_options: typing.Optional[RequestOptions] = None) -> str: + def get_with_path( + self, param: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ GET with path param @@ -45,18 +47,26 @@ def get_with_path(self, param: str, *, request_options: typing.Optional[RequestO ) """ _response = self._client_wrapper.httpx_client.request( - f"params/path/{jsonable_encoder(param)}", method="GET", request_options=request_options + f"params/path/{jsonable_encoder(param)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_with_query( - self, *, query: str, number: int, request_options: typing.Optional[RequestOptions] = None + self, + *, + query: str, + number: int, + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ GET with query param @@ -88,7 +98,13 @@ def get_with_query( ) """ _response = self._client_wrapper.httpx_client.request( - "params", method="GET", params={"query": query, "number": number}, request_options=request_options + "params", + method="GET", + params={ + "query": query, + "number": number, + }, + request_options=request_options, ) try: if 200 <= _response.status_code < 300: @@ -135,7 +151,13 @@ def get_with_allow_multiple_query( ) """ _response = self._client_wrapper.httpx_client.request( - "params", method="GET", params={"query": query, "numer": numer}, request_options=request_options + "params", + method="GET", + params={ + "query": query, + "numer": numer, + }, + request_options=request_options, ) try: if 200 <= _response.status_code < 300: @@ -146,7 +168,11 @@ def get_with_allow_multiple_query( raise ApiError(status_code=_response.status_code, body=_response_json) def get_with_path_and_query( - self, param: str, *, query: str, request_options: typing.Optional[RequestOptions] = None + self, + param: str, + *, + query: str, + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ GET with path and query params @@ -180,7 +206,9 @@ def get_with_path_and_query( _response = self._client_wrapper.httpx_client.request( f"params/path-query/{jsonable_encoder(param)}", method="GET", - params={"query": query}, + params={ + "query": query, + }, request_options=request_options, ) try: @@ -192,7 +220,11 @@ def get_with_path_and_query( raise ApiError(status_code=_response.status_code, body=_response_json) def modify_with_path( - self, param: str, *, request: str, request_options: typing.Optional[RequestOptions] = None + self, + param: str, + *, + request: str, + request_options: typing.Optional[RequestOptions] = None, ) -> str: """ PUT to update with path param @@ -232,7 +264,9 @@ def modify_with_path( ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -243,7 +277,9 @@ class AsyncParamsClient: def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper - async def get_with_path(self, param: str, *, request_options: typing.Optional[RequestOptions] = None) -> str: + async def get_with_path( + self, param: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ GET with path param @@ -279,18 +315,26 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - f"params/path/{jsonable_encoder(param)}", method="GET", request_options=request_options + f"params/path/{jsonable_encoder(param)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_with_query( - self, *, query: str, number: int, request_options: typing.Optional[RequestOptions] = None + self, + *, + query: str, + number: int, + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ GET with query param @@ -330,7 +374,13 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "params", method="GET", params={"query": query, "number": number}, request_options=request_options + "params", + method="GET", + params={ + "query": query, + "number": number, + }, + request_options=request_options, ) try: if 200 <= _response.status_code < 300: @@ -385,7 +435,13 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "params", method="GET", params={"query": query, "numer": numer}, request_options=request_options + "params", + method="GET", + params={ + "query": query, + "numer": numer, + }, + request_options=request_options, ) try: if 200 <= _response.status_code < 300: @@ -396,7 +452,11 @@ async def main() -> None: raise ApiError(status_code=_response.status_code, body=_response_json) async def get_with_path_and_query( - self, param: str, *, query: str, request_options: typing.Optional[RequestOptions] = None + self, + param: str, + *, + query: str, + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ GET with path and query params @@ -438,7 +498,9 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( f"params/path-query/{jsonable_encoder(param)}", method="GET", - params={"query": query}, + params={ + "query": query, + }, request_options=request_options, ) try: @@ -450,7 +512,11 @@ async def main() -> None: raise ApiError(status_code=_response.status_code, body=_response_json) async def modify_with_path( - self, param: str, *, request: str, request_options: typing.Optional[RequestOptions] = None + self, + param: str, + *, + request: str, + request_options: typing.Optional[RequestOptions] = None, ) -> str: """ PUT to update with path param @@ -498,7 +564,9 @@ async def main() -> None: ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/infinite-timeout/src/seed/endpoints/primitive/client.py b/seed/python-sdk/exhaustive/infinite-timeout/src/seed/endpoints/primitive/client.py index 844b6a782f0..20a66f049b4 100644 --- a/seed/python-sdk/exhaustive/infinite-timeout/src/seed/endpoints/primitive/client.py +++ b/seed/python-sdk/exhaustive/infinite-timeout/src/seed/endpoints/primitive/client.py @@ -1,14 +1,14 @@ # This file was auto-generated by Fern from our API Definition. -import datetime as dt import typing -import uuid +from ...core.client_wrapper import SyncClientWrapper +from ...core.request_options import RequestOptions +from ...core.pydantic_utilities import parse_obj_as from json.decoder import JSONDecodeError - from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ...core.pydantic_utilities import parse_obj_as -from ...core.request_options import RequestOptions +import datetime as dt +import uuid +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -18,7 +18,9 @@ class PrimitiveClient: def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper - def get_and_return_string(self, *, request: str, request_options: typing.Optional[RequestOptions] = None) -> str: + def get_and_return_string( + self, *, request: str, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -44,17 +46,25 @@ def get_and_return_string(self, *, request: str, request_options: typing.Optiona ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/string", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/string", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def get_and_return_int(self, *, request: int, request_options: typing.Optional[RequestOptions] = None) -> int: + def get_and_return_int( + self, *, request: int, request_options: typing.Optional[RequestOptions] = None + ) -> int: """ Parameters ---------- @@ -80,17 +90,25 @@ def get_and_return_int(self, *, request: int, request_options: typing.Optional[R ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/integer", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/integer", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(int, parse_obj_as(type_=int, object_=_response.json())) # type: ignore + return typing.cast( + int, parse_obj_as(type_=int, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def get_and_return_long(self, *, request: int, request_options: typing.Optional[RequestOptions] = None) -> int: + def get_and_return_long( + self, *, request: int, request_options: typing.Optional[RequestOptions] = None + ) -> int: """ Parameters ---------- @@ -116,11 +134,17 @@ def get_and_return_long(self, *, request: int, request_options: typing.Optional[ ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/long", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/long", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(int, parse_obj_as(type_=int, object_=_response.json())) # type: ignore + return typing.cast( + int, parse_obj_as(type_=int, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -154,17 +178,25 @@ def get_and_return_double( ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/double", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/double", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(float, parse_obj_as(type_=float, object_=_response.json())) # type: ignore + return typing.cast( + float, parse_obj_as(type_=float, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def get_and_return_bool(self, *, request: bool, request_options: typing.Optional[RequestOptions] = None) -> bool: + def get_and_return_bool( + self, *, request: bool, request_options: typing.Optional[RequestOptions] = None + ) -> bool: """ Parameters ---------- @@ -190,18 +222,27 @@ def get_and_return_bool(self, *, request: bool, request_options: typing.Optional ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/boolean", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/boolean", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_and_return_datetime( - self, *, request: dt.datetime, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: dt.datetime, + request_options: typing.Optional[RequestOptions] = None, ) -> dt.datetime: """ Parameters @@ -232,18 +273,28 @@ def get_and_return_datetime( ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/datetime", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/datetime", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(dt.datetime, parse_obj_as(type_=dt.datetime, object_=_response.json())) # type: ignore + return typing.cast( + dt.datetime, + parse_obj_as(type_=dt.datetime, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_and_return_date( - self, *, request: dt.date, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: dt.date, + request_options: typing.Optional[RequestOptions] = None, ) -> dt.date: """ Parameters @@ -274,18 +325,27 @@ def get_and_return_date( ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/date", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/date", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(dt.date, parse_obj_as(type_=dt.date, object_=_response.json())) # type: ignore + return typing.cast( + dt.date, parse_obj_as(type_=dt.date, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_and_return_uuid( - self, *, request: uuid.UUID, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: uuid.UUID, + request_options: typing.Optional[RequestOptions] = None, ) -> uuid.UUID: """ Parameters @@ -316,17 +376,25 @@ def get_and_return_uuid( ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/uuid", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/uuid", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(uuid.UUID, parse_obj_as(type_=uuid.UUID, object_=_response.json())) # type: ignore + return typing.cast( + uuid.UUID, parse_obj_as(type_=uuid.UUID, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def get_and_return_base_64(self, *, request: str, request_options: typing.Optional[RequestOptions] = None) -> str: + def get_and_return_base_64( + self, *, request: str, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -352,11 +420,17 @@ def get_and_return_base_64(self, *, request: str, request_options: typing.Option ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/base64", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/base64", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -403,17 +477,25 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/string", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/string", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - async def get_and_return_int(self, *, request: int, request_options: typing.Optional[RequestOptions] = None) -> int: + async def get_and_return_int( + self, *, request: int, request_options: typing.Optional[RequestOptions] = None + ) -> int: """ Parameters ---------- @@ -447,11 +529,17 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/integer", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/integer", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(int, parse_obj_as(type_=int, object_=_response.json())) # type: ignore + return typing.cast( + int, parse_obj_as(type_=int, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -493,11 +581,17 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/long", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/long", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(int, parse_obj_as(type_=int, object_=_response.json())) # type: ignore + return typing.cast( + int, parse_obj_as(type_=int, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -539,11 +633,17 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/double", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/double", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(float, parse_obj_as(type_=float, object_=_response.json())) # type: ignore + return typing.cast( + float, parse_obj_as(type_=float, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -585,18 +685,27 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/boolean", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/boolean", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_and_return_datetime( - self, *, request: dt.datetime, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: dt.datetime, + request_options: typing.Optional[RequestOptions] = None, ) -> dt.datetime: """ Parameters @@ -634,18 +743,28 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/datetime", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/datetime", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(dt.datetime, parse_obj_as(type_=dt.datetime, object_=_response.json())) # type: ignore + return typing.cast( + dt.datetime, + parse_obj_as(type_=dt.datetime, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_and_return_date( - self, *, request: dt.date, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: dt.date, + request_options: typing.Optional[RequestOptions] = None, ) -> dt.date: """ Parameters @@ -683,18 +802,27 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/date", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/date", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(dt.date, parse_obj_as(type_=dt.date, object_=_response.json())) # type: ignore + return typing.cast( + dt.date, parse_obj_as(type_=dt.date, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_and_return_uuid( - self, *, request: uuid.UUID, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: uuid.UUID, + request_options: typing.Optional[RequestOptions] = None, ) -> uuid.UUID: """ Parameters @@ -732,11 +860,17 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/uuid", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/uuid", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(uuid.UUID, parse_obj_as(type_=uuid.UUID, object_=_response.json())) # type: ignore + return typing.cast( + uuid.UUID, parse_obj_as(type_=uuid.UUID, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -778,11 +912,17 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/base64", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/base64", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/infinite-timeout/src/seed/endpoints/union/client.py b/seed/python-sdk/exhaustive/infinite-timeout/src/seed/endpoints/union/client.py index 77153587a27..f4c3d9312de 100644 --- a/seed/python-sdk/exhaustive/infinite-timeout/src/seed/endpoints/union/client.py +++ b/seed/python-sdk/exhaustive/infinite-timeout/src/seed/endpoints/union/client.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. import typing +from ...core.client_wrapper import SyncClientWrapper +from ...types.union.types.animal import Animal +from ...core.request_options import RequestOptions +from ...core.pydantic_utilities import parse_obj_as from json.decoder import JSONDecodeError - from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ...core.pydantic_utilities import parse_obj_as -from ...core.request_options import RequestOptions -from ...types.union.types.animal import Animal +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -18,7 +18,10 @@ def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper def get_and_return_union( - self, *, request: Animal, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: Animal, + request_options: typing.Optional[RequestOptions] = None, ) -> Animal: """ Parameters @@ -49,11 +52,17 @@ def get_and_return_union( ) """ _response = self._client_wrapper.httpx_client.request( - "union", method="POST", json=request, request_options=request_options, omit=OMIT + "union", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(Animal, parse_obj_as(type_=Animal, object_=_response.json())) # type: ignore + return typing.cast( + Animal, parse_obj_as(type_=Animal, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -65,7 +74,10 @@ def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper async def get_and_return_union( - self, *, request: Animal, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: Animal, + request_options: typing.Optional[RequestOptions] = None, ) -> Animal: """ Parameters @@ -104,11 +116,17 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "union", method="POST", json=request, request_options=request_options, omit=OMIT + "union", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(Animal, parse_obj_as(type_=Animal, object_=_response.json())) # type: ignore + return typing.cast( + Animal, parse_obj_as(type_=Animal, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/infinite-timeout/src/seed/general_errors/types/bad_object_request_info.py b/seed/python-sdk/exhaustive/infinite-timeout/src/seed/general_errors/types/bad_object_request_info.py index 7f03429e922..73c44b89531 100644 --- a/seed/python-sdk/exhaustive/infinite-timeout/src/seed/general_errors/types/bad_object_request_info.py +++ b/seed/python-sdk/exhaustive/infinite-timeout/src/seed/general_errors/types/bad_object_request_info.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class BadObjectRequestInfo(UniversalBaseModel): message: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/infinite-timeout/src/seed/inlined_requests/client.py b/seed/python-sdk/exhaustive/infinite-timeout/src/seed/inlined_requests/client.py index f7c46698eb9..39e0c8fe637 100644 --- a/seed/python-sdk/exhaustive/infinite-timeout/src/seed/inlined_requests/client.py +++ b/seed/python-sdk/exhaustive/infinite-timeout/src/seed/inlined_requests/client.py @@ -1,15 +1,15 @@ # This file was auto-generated by Fern from our API Definition. import typing -from json.decoder import JSONDecodeError - -from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.pydantic_utilities import parse_obj_as +from ..core.client_wrapper import SyncClientWrapper +from ..types.object.types.object_with_optional_field import ObjectWithOptionalField from ..core.request_options import RequestOptions +from ..core.pydantic_utilities import parse_obj_as from ..general_errors.errors.bad_request_body import BadRequestBody from ..general_errors.types.bad_object_request_info import BadObjectRequestInfo -from ..types.object.types.object_with_optional_field import ObjectWithOptionalField +from json.decoder import JSONDecodeError +from ..core.api_error import ApiError +from ..core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -25,7 +25,7 @@ def post_with_object_bodyand_response( string: str, integer: int, nested_object: ObjectWithOptionalField, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> ObjectWithOptionalField: """ POST with custom object in request body, response is an object @@ -86,16 +86,30 @@ def post_with_object_bodyand_response( _response = self._client_wrapper.httpx_client.request( "req-bodies/object", method="POST", - json={"string": string, "integer": integer, "NestedObject": nested_object}, + json={ + "string": string, + "integer": integer, + "NestedObject": nested_object, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore if _response.status_code == 400: raise BadRequestBody( - typing.cast(BadObjectRequestInfo, parse_obj_as(type_=BadObjectRequestInfo, object_=_response.json())) # type: ignore + typing.cast( + BadObjectRequestInfo, + parse_obj_as( + type_=BadObjectRequestInfo, object_=_response.json() + ), + ) # type: ignore ) _response_json = _response.json() except JSONDecodeError: @@ -113,7 +127,7 @@ async def post_with_object_bodyand_response( string: str, integer: int, nested_object: ObjectWithOptionalField, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> ObjectWithOptionalField: """ POST with custom object in request body, response is an object @@ -181,16 +195,30 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( "req-bodies/object", method="POST", - json={"string": string, "integer": integer, "NestedObject": nested_object}, + json={ + "string": string, + "integer": integer, + "NestedObject": nested_object, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore if _response.status_code == 400: raise BadRequestBody( - typing.cast(BadObjectRequestInfo, parse_obj_as(type_=BadObjectRequestInfo, object_=_response.json())) # type: ignore + typing.cast( + BadObjectRequestInfo, + parse_obj_as( + type_=BadObjectRequestInfo, object_=_response.json() + ), + ) # type: ignore ) _response_json = _response.json() except JSONDecodeError: diff --git a/seed/python-sdk/exhaustive/infinite-timeout/src/seed/no_auth/client.py b/seed/python-sdk/exhaustive/infinite-timeout/src/seed/no_auth/client.py index 3d203bcea34..e5590cde0df 100644 --- a/seed/python-sdk/exhaustive/infinite-timeout/src/seed/no_auth/client.py +++ b/seed/python-sdk/exhaustive/infinite-timeout/src/seed/no_auth/client.py @@ -1,14 +1,14 @@ # This file was auto-generated by Fern from our API Definition. import typing -from json.decoder import JSONDecodeError - -from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.pydantic_utilities import parse_obj_as +from ..core.client_wrapper import SyncClientWrapper from ..core.request_options import RequestOptions +from ..core.pydantic_utilities import parse_obj_as from ..general_errors.errors.bad_request_body import BadRequestBody from ..general_errors.types.bad_object_request_info import BadObjectRequestInfo +from json.decoder import JSONDecodeError +from ..core.api_error import ApiError +from ..core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -19,7 +19,10 @@ def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper def post_with_no_auth( - self, *, request: typing.Any, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Any, + request_options: typing.Optional[RequestOptions] = None, ) -> bool: """ POST request with no auth @@ -48,14 +51,25 @@ def post_with_no_auth( ) """ _response = self._client_wrapper.httpx_client.request( - "no-auth", method="POST", json=request, request_options=request_options, omit=OMIT + "no-auth", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore if _response.status_code == 400: raise BadRequestBody( - typing.cast(BadObjectRequestInfo, parse_obj_as(type_=BadObjectRequestInfo, object_=_response.json())) # type: ignore + typing.cast( + BadObjectRequestInfo, + parse_obj_as( + type_=BadObjectRequestInfo, object_=_response.json() + ), + ) # type: ignore ) _response_json = _response.json() except JSONDecodeError: @@ -68,7 +82,10 @@ def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper async def post_with_no_auth( - self, *, request: typing.Any, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Any, + request_options: typing.Optional[RequestOptions] = None, ) -> bool: """ POST request with no auth @@ -105,14 +122,25 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "no-auth", method="POST", json=request, request_options=request_options, omit=OMIT + "no-auth", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore if _response.status_code == 400: raise BadRequestBody( - typing.cast(BadObjectRequestInfo, parse_obj_as(type_=BadObjectRequestInfo, object_=_response.json())) # type: ignore + typing.cast( + BadObjectRequestInfo, + parse_obj_as( + type_=BadObjectRequestInfo, object_=_response.json() + ), + ) # type: ignore ) _response_json = _response.json() except JSONDecodeError: diff --git a/seed/python-sdk/exhaustive/infinite-timeout/src/seed/no_req_body/client.py b/seed/python-sdk/exhaustive/infinite-timeout/src/seed/no_req_body/client.py index 33fa0c77d27..5afdd703fdc 100644 --- a/seed/python-sdk/exhaustive/infinite-timeout/src/seed/no_req_body/client.py +++ b/seed/python-sdk/exhaustive/infinite-timeout/src/seed/no_req_body/client.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. +from ..core.client_wrapper import SyncClientWrapper import typing -from json.decoder import JSONDecodeError - -from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.pydantic_utilities import parse_obj_as from ..core.request_options import RequestOptions from ..types.object.types.object_with_optional_field import ObjectWithOptionalField +from ..core.pydantic_utilities import parse_obj_as +from json.decoder import JSONDecodeError +from ..core.api_error import ApiError +from ..core.client_wrapper import AsyncClientWrapper class NoReqBodyClient: @@ -38,17 +38,26 @@ def get_with_no_request_body( client.no_req_body.get_with_no_request_body() """ _response = self._client_wrapper.httpx_client.request( - "no-req-body", method="GET", request_options=request_options + "no-req-body", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def post_with_no_request_body(self, *, request_options: typing.Optional[RequestOptions] = None) -> str: + def post_with_no_request_body( + self, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -70,11 +79,15 @@ def post_with_no_request_body(self, *, request_options: typing.Optional[RequestO client.no_req_body.post_with_no_request_body() """ _response = self._client_wrapper.httpx_client.request( - "no-req-body", method="POST", request_options=request_options + "no-req-body", + method="POST", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -117,17 +130,26 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "no-req-body", method="GET", request_options=request_options + "no-req-body", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - async def post_with_no_request_body(self, *, request_options: typing.Optional[RequestOptions] = None) -> str: + async def post_with_no_request_body( + self, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -157,11 +179,15 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "no-req-body", method="POST", request_options=request_options + "no-req-body", + method="POST", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/infinite-timeout/src/seed/req_with_headers/client.py b/seed/python-sdk/exhaustive/infinite-timeout/src/seed/req_with_headers/client.py index 655402249e9..984428516e3 100644 --- a/seed/python-sdk/exhaustive/infinite-timeout/src/seed/req_with_headers/client.py +++ b/seed/python-sdk/exhaustive/infinite-timeout/src/seed/req_with_headers/client.py @@ -1,11 +1,11 @@ # This file was auto-generated by Fern from our API Definition. import typing +from ..core.client_wrapper import SyncClientWrapper +from ..core.request_options import RequestOptions from json.decoder import JSONDecodeError - from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.request_options import RequestOptions +from ..core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -21,7 +21,7 @@ def get_with_custom_header( x_test_service_header: str, x_test_endpoint_header: str, request: str, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ Parameters @@ -58,8 +58,12 @@ def get_with_custom_header( method="POST", json=request, headers={ - "X-TEST-SERVICE-HEADER": str(x_test_service_header) if x_test_service_header is not None else None, - "X-TEST-ENDPOINT-HEADER": str(x_test_endpoint_header) if x_test_endpoint_header is not None else None, + "X-TEST-SERVICE-HEADER": str(x_test_service_header) + if x_test_service_header is not None + else None, + "X-TEST-ENDPOINT-HEADER": str(x_test_endpoint_header) + if x_test_endpoint_header is not None + else None, }, request_options=request_options, omit=OMIT, @@ -83,7 +87,7 @@ async def get_with_custom_header( x_test_service_header: str, x_test_endpoint_header: str, request: str, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ Parameters @@ -128,8 +132,12 @@ async def main() -> None: method="POST", json=request, headers={ - "X-TEST-SERVICE-HEADER": str(x_test_service_header) if x_test_service_header is not None else None, - "X-TEST-ENDPOINT-HEADER": str(x_test_endpoint_header) if x_test_endpoint_header is not None else None, + "X-TEST-SERVICE-HEADER": str(x_test_service_header) + if x_test_service_header is not None + else None, + "X-TEST-ENDPOINT-HEADER": str(x_test_endpoint_header) + if x_test_endpoint_header is not None + else None, }, request_options=request_options, omit=OMIT, diff --git a/seed/python-sdk/exhaustive/infinite-timeout/src/seed/types/enum/types/weather_report.py b/seed/python-sdk/exhaustive/infinite-timeout/src/seed/types/enum/types/weather_report.py index 2d54965dc22..84017ef161d 100644 --- a/seed/python-sdk/exhaustive/infinite-timeout/src/seed/types/enum/types/weather_report.py +++ b/seed/python-sdk/exhaustive/infinite-timeout/src/seed/types/enum/types/weather_report.py @@ -2,4 +2,6 @@ import typing -WeatherReport = typing.Union[typing.Literal["SUNNY", "CLOUDY", "RAINING", "SNOWING"], typing.Any] +WeatherReport = typing.Union[ + typing.Literal["SUNNY", "CLOUDY", "RAINING", "SNOWING"], typing.Any +] diff --git a/seed/python-sdk/exhaustive/infinite-timeout/src/seed/types/object/types/double_optional.py b/seed/python-sdk/exhaustive/infinite-timeout/src/seed/types/object/types/double_optional.py index ddf165b13bd..ed236347357 100644 --- a/seed/python-sdk/exhaustive/infinite-timeout/src/seed/types/object/types/double_optional.py +++ b/seed/python-sdk/exhaustive/infinite-timeout/src/seed/types/object/types/double_optional.py @@ -1,18 +1,21 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .optional_alias import OptionalAlias +import pydantic +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class DoubleOptional(UniversalBaseModel): - optional_alias: typing.Optional[OptionalAlias] = pydantic.Field(alias="optionalAlias", default=None) + optional_alias: typing.Optional[OptionalAlias] = pydantic.Field( + alias="optionalAlias", default=None + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/infinite-timeout/src/seed/types/object/types/nested_object_with_optional_field.py b/seed/python-sdk/exhaustive/infinite-timeout/src/seed/types/object/types/nested_object_with_optional_field.py index 81669c0dd39..20a4d40a714 100644 --- a/seed/python-sdk/exhaustive/infinite-timeout/src/seed/types/object/types/nested_object_with_optional_field.py +++ b/seed/python-sdk/exhaustive/infinite-timeout/src/seed/types/object/types/nested_object_with_optional_field.py @@ -1,19 +1,22 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .object_with_optional_field import ObjectWithOptionalField +import pydantic +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class NestedObjectWithOptionalField(UniversalBaseModel): string: typing.Optional[str] = None - nested_object: typing.Optional[ObjectWithOptionalField] = pydantic.Field(alias="NestedObject", default=None) + nested_object: typing.Optional[ObjectWithOptionalField] = pydantic.Field( + alias="NestedObject", default=None + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/infinite-timeout/src/seed/types/object/types/nested_object_with_required_field.py b/seed/python-sdk/exhaustive/infinite-timeout/src/seed/types/object/types/nested_object_with_required_field.py index 1a621942c6c..a6ca8781190 100644 --- a/seed/python-sdk/exhaustive/infinite-timeout/src/seed/types/object/types/nested_object_with_required_field.py +++ b/seed/python-sdk/exhaustive/infinite-timeout/src/seed/types/object/types/nested_object_with_required_field.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import UniversalBaseModel from .object_with_optional_field import ObjectWithOptionalField +import pydantic +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class NestedObjectWithRequiredField(UniversalBaseModel): @@ -13,7 +12,9 @@ class NestedObjectWithRequiredField(UniversalBaseModel): nested_object: ObjectWithOptionalField = pydantic.Field(alias="NestedObject") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/infinite-timeout/src/seed/types/object/types/object_with_map_of_map.py b/seed/python-sdk/exhaustive/infinite-timeout/src/seed/types/object/types/object_with_map_of_map.py index 8883cc1d498..313cd25ceb8 100644 --- a/seed/python-sdk/exhaustive/infinite-timeout/src/seed/types/object/types/object_with_map_of_map.py +++ b/seed/python-sdk/exhaustive/infinite-timeout/src/seed/types/object/types/object_with_map_of_map.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class ObjectWithMapOfMap(UniversalBaseModel): map_: typing.Dict[str, typing.Dict[str, str]] = pydantic.Field(alias="map") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/infinite-timeout/src/seed/types/object/types/object_with_optional_field.py b/seed/python-sdk/exhaustive/infinite-timeout/src/seed/types/object/types/object_with_optional_field.py index 6aab170be0c..9131f0e91d7 100644 --- a/seed/python-sdk/exhaustive/infinite-timeout/src/seed/types/object/types/object_with_optional_field.py +++ b/seed/python-sdk/exhaustive/infinite-timeout/src/seed/types/object/types/object_with_optional_field.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. -import datetime as dt +from ....core.pydantic_utilities import UniversalBaseModel import typing -import uuid - import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +import datetime as dt +import uuid +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class ObjectWithOptionalField(UniversalBaseModel): @@ -23,13 +22,19 @@ class ObjectWithOptionalField(UniversalBaseModel): date: typing.Optional[dt.date] = None uuid_: typing.Optional[uuid.UUID] = pydantic.Field(alias="uuid", default=None) base_64: typing.Optional[str] = pydantic.Field(alias="base64", default=None) - list_: typing.Optional[typing.List[str]] = pydantic.Field(alias="list", default=None) + list_: typing.Optional[typing.List[str]] = pydantic.Field( + alias="list", default=None + ) set_: typing.Optional[typing.Set[str]] = pydantic.Field(alias="set", default=None) - map_: typing.Optional[typing.Dict[int, str]] = pydantic.Field(alias="map", default=None) + map_: typing.Optional[typing.Dict[int, str]] = pydantic.Field( + alias="map", default=None + ) bigint: typing.Optional[str] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/infinite-timeout/src/seed/types/object/types/object_with_required_field.py b/seed/python-sdk/exhaustive/infinite-timeout/src/seed/types/object/types/object_with_required_field.py index 61b98867984..24db26a3cf8 100644 --- a/seed/python-sdk/exhaustive/infinite-timeout/src/seed/types/object/types/object_with_required_field.py +++ b/seed/python-sdk/exhaustive/infinite-timeout/src/seed/types/object/types/object_with_required_field.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class ObjectWithRequiredField(UniversalBaseModel): string: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/infinite-timeout/src/seed/types/union/types/animal.py b/seed/python-sdk/exhaustive/infinite-timeout/src/seed/types/union/types/animal.py index 1ae43d1663e..84c71d2009a 100644 --- a/seed/python-sdk/exhaustive/infinite-timeout/src/seed/types/union/types/animal.py +++ b/seed/python-sdk/exhaustive/infinite-timeout/src/seed/types/union/types/animal.py @@ -1,12 +1,10 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ....core.pydantic_utilities import UniversalBaseModel import typing - import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class Animal_Dog(UniversalBaseModel): @@ -15,7 +13,9 @@ class Animal_Dog(UniversalBaseModel): likes_to_woof: bool = pydantic.Field(alias="likesToWoof") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: @@ -30,7 +30,9 @@ class Animal_Cat(UniversalBaseModel): likes_to_meow: bool = pydantic.Field(alias="likesToMeow") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/infinite-timeout/src/seed/types/union/types/cat.py b/seed/python-sdk/exhaustive/infinite-timeout/src/seed/types/union/types/cat.py index 61fc5527b1f..c59b78523c9 100644 --- a/seed/python-sdk/exhaustive/infinite-timeout/src/seed/types/union/types/cat.py +++ b/seed/python-sdk/exhaustive/infinite-timeout/src/seed/types/union/types/cat.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ....core.pydantic_utilities import UniversalBaseModel import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class Cat(UniversalBaseModel): @@ -12,7 +11,9 @@ class Cat(UniversalBaseModel): likes_to_meow: bool = pydantic.Field(alias="likesToMeow") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/infinite-timeout/src/seed/types/union/types/dog.py b/seed/python-sdk/exhaustive/infinite-timeout/src/seed/types/union/types/dog.py index c1ff5339dfe..e250c72edef 100644 --- a/seed/python-sdk/exhaustive/infinite-timeout/src/seed/types/union/types/dog.py +++ b/seed/python-sdk/exhaustive/infinite-timeout/src/seed/types/union/types/dog.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ....core.pydantic_utilities import UniversalBaseModel import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class Dog(UniversalBaseModel): @@ -12,7 +11,9 @@ class Dog(UniversalBaseModel): likes_to_woof: bool = pydantic.Field(alias="likesToWoof") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/infinite-timeout/src/seed/version.py b/seed/python-sdk/exhaustive/infinite-timeout/src/seed/version.py index 63ba170685a..ac44536abdb 100644 --- a/seed/python-sdk/exhaustive/infinite-timeout/src/seed/version.py +++ b/seed/python-sdk/exhaustive/infinite-timeout/src/seed/version.py @@ -1,4 +1,3 @@ - from importlib import metadata __version__ = metadata.version("fern_exhaustive") diff --git a/seed/python-sdk/exhaustive/infinite-timeout/tests/conftest.py b/seed/python-sdk/exhaustive/infinite-timeout/tests/conftest.py index b5b50383b94..86cb2b41af8 100644 --- a/seed/python-sdk/exhaustive/infinite-timeout/tests/conftest.py +++ b/seed/python-sdk/exhaustive/infinite-timeout/tests/conftest.py @@ -1,16 +1,22 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive import os - import pytest -from seed import AsyncSeedExhaustive, SeedExhaustive +from seed import AsyncSeedExhaustive @pytest.fixture def client() -> SeedExhaustive: - return SeedExhaustive(token=os.getenv("ENV_TOKEN", "token"), base_url=os.getenv("TESTS_BASE_URL", "base_url")) + return SeedExhaustive( + token=os.getenv("ENV_TOKEN", "token"), + base_url=os.getenv("TESTS_BASE_URL", "base_url"), + ) @pytest.fixture def async_client() -> AsyncSeedExhaustive: - return AsyncSeedExhaustive(token=os.getenv("ENV_TOKEN", "token"), base_url=os.getenv("TESTS_BASE_URL", "base_url")) + return AsyncSeedExhaustive( + token=os.getenv("ENV_TOKEN", "token"), + base_url=os.getenv("TESTS_BASE_URL", "base_url"), + ) diff --git a/seed/python-sdk/exhaustive/infinite-timeout/tests/custom/test_client.py b/seed/python-sdk/exhaustive/infinite-timeout/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/python-sdk/exhaustive/infinite-timeout/tests/custom/test_client.py +++ b/seed/python-sdk/exhaustive/infinite-timeout/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/python-sdk/exhaustive/infinite-timeout/tests/endpoints/test_container.py b/seed/python-sdk/exhaustive/infinite-timeout/tests/endpoints/test_container.py index 17d9d75240d..240f16f2a8c 100644 --- a/seed/python-sdk/exhaustive/infinite-timeout/tests/endpoints/test_container.py +++ b/seed/python-sdk/exhaustive/infinite-timeout/tests/endpoints/test_container.py @@ -1,91 +1,137 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing - -from seed import AsyncSeedExhaustive, SeedExhaustive -from seed.types.object import ObjectWithRequiredField - from ..utilities import validate_response +from seed.types.object import ObjectWithRequiredField -async def test_get_and_return_list_of_primitives(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_list_of_primitives( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = ["string"] expected_types: typing.Tuple[typing.Any, typing.Any] = ("list", {0: None}) - response = client.endpoints.container.get_and_return_list_of_primitives(request=["string"]) + response = client.endpoints.container.get_and_return_list_of_primitives( + request=["string"] + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.container.get_and_return_list_of_primitives(request=["string"]) + async_response = ( + await async_client.endpoints.container.get_and_return_list_of_primitives( + request=["string"] + ) + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_list_of_objects(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_list_of_objects( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = [{"string": "string"}] - expected_types: typing.Tuple[typing.Any, typing.Any] = ("list", {0: {"string": None}}) + expected_types: typing.Tuple[typing.Any, typing.Any] = ( + "list", + {0: {"string": None}}, + ) response = client.endpoints.container.get_and_return_list_of_objects( request=[ObjectWithRequiredField(string="string")] ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.container.get_and_return_list_of_objects( - request=[ObjectWithRequiredField(string="string")] + async_response = ( + await async_client.endpoints.container.get_and_return_list_of_objects( + request=[ObjectWithRequiredField(string="string")] + ) ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_set_of_primitives(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_set_of_primitives( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = ["string"] expected_types: typing.Tuple[typing.Any, typing.Any] = ("set", {0: None}) - response = client.endpoints.container.get_and_return_set_of_primitives(request={"string"}) + response = client.endpoints.container.get_and_return_set_of_primitives( + request={"string"} + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.container.get_and_return_set_of_primitives(request={"string"}) + async_response = ( + await async_client.endpoints.container.get_and_return_set_of_primitives( + request={"string"} + ) + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_set_of_objects(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_set_of_objects( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = [{"string": "string"}] - expected_types: typing.Tuple[typing.Any, typing.Any] = ("set", {0: {"string": None}}) + expected_types: typing.Tuple[typing.Any, typing.Any] = ( + "set", + {0: {"string": None}}, + ) response = client.endpoints.container.get_and_return_set_of_objects( request=[ObjectWithRequiredField(string="string")] ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.container.get_and_return_set_of_objects( - request=[ObjectWithRequiredField(string="string")] + async_response = ( + await async_client.endpoints.container.get_and_return_set_of_objects( + request=[ObjectWithRequiredField(string="string")] + ) ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_map_prim_to_prim(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_map_prim_to_prim( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = {"string": "string"} expected_types: typing.Tuple[typing.Any, typing.Any] = ("dict", {0: (None, None)}) - response = client.endpoints.container.get_and_return_map_prim_to_prim(request={"string": "string"}) + response = client.endpoints.container.get_and_return_map_prim_to_prim( + request={"string": "string"} + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.container.get_and_return_map_prim_to_prim( - request={"string": "string"} + async_response = ( + await async_client.endpoints.container.get_and_return_map_prim_to_prim( + request={"string": "string"} + ) ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_map_of_prim_to_object(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_map_of_prim_to_object( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = {"string": {"string": "string"}} - expected_types: typing.Tuple[typing.Any, typing.Any] = ("dict", {0: (None, {"string": None})}) + expected_types: typing.Tuple[typing.Any, typing.Any] = ( + "dict", + {0: (None, {"string": None})}, + ) response = client.endpoints.container.get_and_return_map_of_prim_to_object( request={"string": ObjectWithRequiredField(string="string")} ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.container.get_and_return_map_of_prim_to_object( - request={"string": ObjectWithRequiredField(string="string")} + async_response = ( + await async_client.endpoints.container.get_and_return_map_of_prim_to_object( + request={"string": ObjectWithRequiredField(string="string")} + ) ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_optional(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_optional( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = {"string": "string"} expected_types: typing.Any = {"string": None} - response = client.endpoints.container.get_and_return_optional(request=ObjectWithRequiredField(string="string")) + response = client.endpoints.container.get_and_return_optional( + request=ObjectWithRequiredField(string="string") + ) validate_response(response, expected_response, expected_types) async_response = await async_client.endpoints.container.get_and_return_optional( diff --git a/seed/python-sdk/exhaustive/infinite-timeout/tests/endpoints/test_enum.py b/seed/python-sdk/exhaustive/infinite-timeout/tests/endpoints/test_enum.py index 890aada5ce4..ca3fca30b5a 100644 --- a/seed/python-sdk/exhaustive/infinite-timeout/tests/endpoints/test_enum.py +++ b/seed/python-sdk/exhaustive/infinite-timeout/tests/endpoints/test_enum.py @@ -1,17 +1,20 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing - -from seed import AsyncSeedExhaustive, SeedExhaustive - from ..utilities import validate_response -async def test_get_and_return_enum(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_enum( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "SUNNY" expected_types: typing.Any = None response = client.endpoints.enum.get_and_return_enum(request="SUNNY") validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.enum.get_and_return_enum(request="SUNNY") + async_response = await async_client.endpoints.enum.get_and_return_enum( + request="SUNNY" + ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/exhaustive/infinite-timeout/tests/endpoints/test_http_methods.py b/seed/python-sdk/exhaustive/infinite-timeout/tests/endpoints/test_http_methods.py index dc01bafcf6f..77131fc6e8b 100644 --- a/seed/python-sdk/exhaustive/infinite-timeout/tests/endpoints/test_http_methods.py +++ b/seed/python-sdk/exhaustive/infinite-timeout/tests/endpoints/test_http_methods.py @@ -1,15 +1,16 @@ # This file was auto-generated by Fern from our API Definition. -import datetime +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing -import uuid - -from seed import AsyncSeedExhaustive, SeedExhaustive - from ..utilities import validate_response +import datetime +import uuid -async def test_test_get(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_test_get( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "string" expected_types: typing.Any = None response = client.endpoints.http_methods.test_get(id="string") @@ -19,7 +20,9 @@ async def test_test_get(client: SeedExhaustive, async_client: AsyncSeedExhaustiv validate_response(async_response, expected_response, expected_types) -async def test_test_post(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_test_post( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = { "string": "string", "integer": 1, @@ -53,11 +56,15 @@ async def test_test_post(client: SeedExhaustive, async_client: AsyncSeedExhausti response = client.endpoints.http_methods.test_post(string="string") validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.http_methods.test_post(string="string") + async_response = await async_client.endpoints.http_methods.test_post( + string="string" + ) validate_response(async_response, expected_response, expected_types) -async def test_test_put(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_test_put( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = { "string": "string", "integer": 1, @@ -91,11 +98,15 @@ async def test_test_put(client: SeedExhaustive, async_client: AsyncSeedExhaustiv response = client.endpoints.http_methods.test_put(id="string", string="string") validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.http_methods.test_put(id="string", string="string") + async_response = await async_client.endpoints.http_methods.test_put( + id="string", string="string" + ) validate_response(async_response, expected_response, expected_types) -async def test_test_patch(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_test_patch( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = { "string": "string", "integer": 1, @@ -163,7 +174,9 @@ async def test_test_patch(client: SeedExhaustive, async_client: AsyncSeedExhaust validate_response(async_response, expected_response, expected_types) -async def test_test_delete(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_test_delete( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = True expected_types: typing.Any = None response = client.endpoints.http_methods.test_delete(id="string") diff --git a/seed/python-sdk/exhaustive/infinite-timeout/tests/endpoints/test_object.py b/seed/python-sdk/exhaustive/infinite-timeout/tests/endpoints/test_object.py index a9098b6e9ef..c48c4332b22 100644 --- a/seed/python-sdk/exhaustive/infinite-timeout/tests/endpoints/test_object.py +++ b/seed/python-sdk/exhaustive/infinite-timeout/tests/endpoints/test_object.py @@ -1,16 +1,18 @@ # This file was auto-generated by Fern from our API Definition. -import datetime +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing +import datetime import uuid - -from seed import AsyncSeedExhaustive, SeedExhaustive -from seed.types.object import NestedObjectWithRequiredField, ObjectWithOptionalField - from ..utilities import validate_response +from seed.types.object import ObjectWithOptionalField +from seed.types.object import NestedObjectWithRequiredField -async def test_get_and_return_with_optional_field(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_with_optional_field( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = { "string": "string", "integer": 1, @@ -58,38 +60,54 @@ async def test_get_and_return_with_optional_field(client: SeedExhaustive, async_ ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.object.get_and_return_with_optional_field( - string="string", - integer=1, - long_=1000000, - double=1.1, - bool_=True, - datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), - date=datetime.date.fromisoformat("2023-01-15"), - uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), - base_64="SGVsbG8gd29ybGQh", - list_=["string"], - set_={"string"}, - map_={1: "string"}, - bigint="123456789123456789", + async_response = ( + await async_client.endpoints.object.get_and_return_with_optional_field( + string="string", + integer=1, + long_=1000000, + double=1.1, + bool_=True, + datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), + date=datetime.date.fromisoformat("2023-01-15"), + uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + base_64="SGVsbG8gd29ybGQh", + list_=["string"], + set_={"string"}, + map_={1: "string"}, + bigint="123456789123456789", + ) ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_with_required_field(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_with_required_field( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = {"string": "string"} expected_types: typing.Any = {"string": None} - response = client.endpoints.object.get_and_return_with_required_field(string="string") + response = client.endpoints.object.get_and_return_with_required_field( + string="string" + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.object.get_and_return_with_required_field(string="string") + async_response = ( + await async_client.endpoints.object.get_and_return_with_required_field( + string="string" + ) + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_with_map_of_map(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_with_map_of_map( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = {"map": {"string": {"string": "string"}}} - expected_types: typing.Any = {"map": ("dict", {0: (None, ("dict", {0: (None, None)}))})} - response = client.endpoints.object.get_and_return_with_map_of_map(map_={"string": {"string": "string"}}) + expected_types: typing.Any = { + "map": ("dict", {0: (None, ("dict", {0: (None, None)}))}) + } + response = client.endpoints.object.get_and_return_with_map_of_map( + map_={"string": {"string": "string"}} + ) validate_response(response, expected_response, expected_types) async_response = await async_client.endpoints.object.get_and_return_with_map_of_map( @@ -157,23 +175,25 @@ async def test_get_and_return_nested_with_optional_field( ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.object.get_and_return_nested_with_optional_field( - string="string", - nested_object=ObjectWithOptionalField( + async_response = ( + await async_client.endpoints.object.get_and_return_nested_with_optional_field( string="string", - integer=1, - long_=1000000, - double=1.1, - bool_=True, - datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), - date=datetime.date.fromisoformat("2023-01-15"), - uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), - base_64="SGVsbG8gd29ybGQh", - list_=["string"], - set_={"string"}, - map_={1: "string"}, - bigint="123456789123456789", - ), + nested_object=ObjectWithOptionalField( + string="string", + integer=1, + long_=1000000, + double=1.1, + bool_=True, + datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), + date=datetime.date.fromisoformat("2023-01-15"), + uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + base_64="SGVsbG8gd29ybGQh", + list_=["string"], + set_={"string"}, + map_={1: "string"}, + bigint="123456789123456789", + ), + ) ) validate_response(async_response, expected_response, expected_types) @@ -238,24 +258,26 @@ async def test_get_and_return_nested_with_required_field( ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.object.get_and_return_nested_with_required_field( - string_="string", - string="string", - nested_object=ObjectWithOptionalField( + async_response = ( + await async_client.endpoints.object.get_and_return_nested_with_required_field( + string_="string", string="string", - integer=1, - long_=1000000, - double=1.1, - bool_=True, - datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), - date=datetime.date.fromisoformat("2023-01-15"), - uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), - base_64="SGVsbG8gd29ybGQh", - list_=["string"], - set_={"string"}, - map_={1: "string"}, - bigint="123456789123456789", - ), + nested_object=ObjectWithOptionalField( + string="string", + integer=1, + long_=1000000, + double=1.1, + bool_=True, + datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), + date=datetime.date.fromisoformat("2023-01-15"), + uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + base_64="SGVsbG8gd29ybGQh", + list_=["string"], + set_={"string"}, + map_={1: "string"}, + bigint="123456789123456789", + ), + ) ) validate_response(async_response, expected_response, expected_types) @@ -299,27 +321,31 @@ async def test_get_and_return_nested_with_required_field_as_list( "bigint": None, }, } - response = client.endpoints.object.get_and_return_nested_with_required_field_as_list( - request=[ - NestedObjectWithRequiredField( - string="string", - nested_object=ObjectWithOptionalField( + response = ( + client.endpoints.object.get_and_return_nested_with_required_field_as_list( + request=[ + NestedObjectWithRequiredField( string="string", - integer=1, - long_=1000000, - double=1.1, - bool_=True, - datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), - date=datetime.date.fromisoformat("2023-01-15"), - uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), - base_64="SGVsbG8gd29ybGQh", - list_=["string"], - set_={"string"}, - map_={1: "string"}, - bigint="123456789123456789", - ), - ) - ] + nested_object=ObjectWithOptionalField( + string="string", + integer=1, + long_=1000000, + double=1.1, + bool_=True, + datetime=datetime.datetime.fromisoformat( + "2024-01-15 09:30:00+00:00" + ), + date=datetime.date.fromisoformat("2023-01-15"), + uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + base_64="SGVsbG8gd29ybGQh", + list_=["string"], + set_={"string"}, + map_={1: "string"}, + bigint="123456789123456789", + ), + ) + ] + ) ) validate_response(response, expected_response, expected_types) @@ -333,7 +359,9 @@ async def test_get_and_return_nested_with_required_field_as_list( long_=1000000, double=1.1, bool_=True, - datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), + datetime=datetime.datetime.fromisoformat( + "2024-01-15 09:30:00+00:00" + ), date=datetime.date.fromisoformat("2023-01-15"), uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), base_64="SGVsbG8gd29ybGQh", diff --git a/seed/python-sdk/exhaustive/infinite-timeout/tests/endpoints/test_params.py b/seed/python-sdk/exhaustive/infinite-timeout/tests/endpoints/test_params.py index 163d7b9161d..d8ffb00c0a0 100644 --- a/seed/python-sdk/exhaustive/infinite-timeout/tests/endpoints/test_params.py +++ b/seed/python-sdk/exhaustive/infinite-timeout/tests/endpoints/test_params.py @@ -1,13 +1,14 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing - -from seed import AsyncSeedExhaustive, SeedExhaustive - from ..utilities import validate_response -async def test_get_with_path(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_with_path( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "string" expected_types: typing.Any = None response = client.endpoints.params.get_with_path(param="string") @@ -17,32 +18,63 @@ async def test_get_with_path(client: SeedExhaustive, async_client: AsyncSeedExha validate_response(async_response, expected_response, expected_types) -async def test_get_with_query(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_with_query( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: # Type ignore to avoid mypy complaining about the function not being meant to return a value assert client.endpoints.params.get_with_query(query="string", number=1) is None # type: ignore[func-returns-value] - assert await async_client.endpoints.params.get_with_query(query="string", number=1) is None # type: ignore[func-returns-value] + assert ( + await async_client.endpoints.params.get_with_query(query="string", number=1) + is None + ) # type: ignore[func-returns-value] -async def test_get_with_allow_multiple_query(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_with_allow_multiple_query( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: # Type ignore to avoid mypy complaining about the function not being meant to return a value - assert client.endpoints.params.get_with_allow_multiple_query(query="string", numer=1) is None # type: ignore[func-returns-value] - - assert await async_client.endpoints.params.get_with_allow_multiple_query(query="string", numer=1) is None # type: ignore[func-returns-value] - - -async def test_get_with_path_and_query(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: + assert ( + client.endpoints.params.get_with_allow_multiple_query(query="string", numer=1) + is None + ) # type: ignore[func-returns-value] + + assert ( + await async_client.endpoints.params.get_with_allow_multiple_query( + query="string", numer=1 + ) + is None + ) # type: ignore[func-returns-value] + + +async def test_get_with_path_and_query( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: # Type ignore to avoid mypy complaining about the function not being meant to return a value - assert client.endpoints.params.get_with_path_and_query(param="string", query="string") is None # type: ignore[func-returns-value] - - assert await async_client.endpoints.params.get_with_path_and_query(param="string", query="string") is None # type: ignore[func-returns-value] - - -async def test_modify_with_path(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: + assert ( + client.endpoints.params.get_with_path_and_query(param="string", query="string") + is None + ) # type: ignore[func-returns-value] + + assert ( + await async_client.endpoints.params.get_with_path_and_query( + param="string", query="string" + ) + is None + ) # type: ignore[func-returns-value] + + +async def test_modify_with_path( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "string" expected_types: typing.Any = None - response = client.endpoints.params.modify_with_path(param="string", request="string") + response = client.endpoints.params.modify_with_path( + param="string", request="string" + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.params.modify_with_path(param="string", request="string") + async_response = await async_client.endpoints.params.modify_with_path( + param="string", request="string" + ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/exhaustive/infinite-timeout/tests/endpoints/test_primitive.py b/seed/python-sdk/exhaustive/infinite-timeout/tests/endpoints/test_primitive.py index ba3bc7e29e5..26cbcf45d2f 100644 --- a/seed/python-sdk/exhaustive/infinite-timeout/tests/endpoints/test_primitive.py +++ b/seed/python-sdk/exhaustive/infinite-timeout/tests/endpoints/test_primitive.py @@ -1,65 +1,86 @@ # This file was auto-generated by Fern from our API Definition. -import datetime +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing -import uuid - -from seed import AsyncSeedExhaustive, SeedExhaustive - from ..utilities import validate_response +import datetime +import uuid -async def test_get_and_return_string(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_string( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "string" expected_types: typing.Any = None response = client.endpoints.primitive.get_and_return_string(request="string") validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.primitive.get_and_return_string(request="string") + async_response = await async_client.endpoints.primitive.get_and_return_string( + request="string" + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_int(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_int( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = 1 expected_types: typing.Any = "integer" response = client.endpoints.primitive.get_and_return_int(request=1) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.primitive.get_and_return_int(request=1) + async_response = await async_client.endpoints.primitive.get_and_return_int( + request=1 + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_long(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_long( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = 1000000 expected_types: typing.Any = None response = client.endpoints.primitive.get_and_return_long(request=1000000) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.primitive.get_and_return_long(request=1000000) + async_response = await async_client.endpoints.primitive.get_and_return_long( + request=1000000 + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_double(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_double( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = 1.1 expected_types: typing.Any = None response = client.endpoints.primitive.get_and_return_double(request=1.1) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.primitive.get_and_return_double(request=1.1) + async_response = await async_client.endpoints.primitive.get_and_return_double( + request=1.1 + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_bool(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_bool( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = True expected_types: typing.Any = None response = client.endpoints.primitive.get_and_return_bool(request=True) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.primitive.get_and_return_bool(request=True) + async_response = await async_client.endpoints.primitive.get_and_return_bool( + request=True + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_datetime(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_datetime( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "2024-01-15T09:30:00Z" expected_types: typing.Any = "datetime" response = client.endpoints.primitive.get_and_return_datetime( @@ -73,10 +94,14 @@ async def test_get_and_return_datetime(client: SeedExhaustive, async_client: Asy validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_date(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_date( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "2023-01-15" expected_types: typing.Any = "date" - response = client.endpoints.primitive.get_and_return_date(request=datetime.date.fromisoformat("2023-01-15")) + response = client.endpoints.primitive.get_and_return_date( + request=datetime.date.fromisoformat("2023-01-15") + ) validate_response(response, expected_response, expected_types) async_response = await async_client.endpoints.primitive.get_and_return_date( @@ -85,10 +110,14 @@ async def test_get_and_return_date(client: SeedExhaustive, async_client: AsyncSe validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_uuid(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_uuid( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32" expected_types: typing.Any = "uuid" - response = client.endpoints.primitive.get_and_return_uuid(request=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32")) + response = client.endpoints.primitive.get_and_return_uuid( + request=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32") + ) validate_response(response, expected_response, expected_types) async_response = await async_client.endpoints.primitive.get_and_return_uuid( @@ -97,11 +126,17 @@ async def test_get_and_return_uuid(client: SeedExhaustive, async_client: AsyncSe validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_base_64(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_base_64( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "SGVsbG8gd29ybGQh" expected_types: typing.Any = None - response = client.endpoints.primitive.get_and_return_base_64(request="SGVsbG8gd29ybGQh") + response = client.endpoints.primitive.get_and_return_base_64( + request="SGVsbG8gd29ybGQh" + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.primitive.get_and_return_base_64(request="SGVsbG8gd29ybGQh") + async_response = await async_client.endpoints.primitive.get_and_return_base_64( + request="SGVsbG8gd29ybGQh" + ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/exhaustive/infinite-timeout/tests/endpoints/test_union.py b/seed/python-sdk/exhaustive/infinite-timeout/tests/endpoints/test_union.py index 14e34c2a6df..ceb84928cd9 100644 --- a/seed/python-sdk/exhaustive/infinite-timeout/tests/endpoints/test_union.py +++ b/seed/python-sdk/exhaustive/infinite-timeout/tests/endpoints/test_union.py @@ -1,17 +1,24 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing - -from seed import AsyncSeedExhaustive, SeedExhaustive from seed.types.union import Animal_Dog - from ..utilities import validate_response -async def test_get_and_return_union(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: - expected_response: typing.Any = {"animal": "dog", "name": "string", "likesToWoof": True} +async def test_get_and_return_union( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: + expected_response: typing.Any = { + "animal": "dog", + "name": "string", + "likesToWoof": True, + } expected_types: typing.Any = "no_validate" - response = client.endpoints.union.get_and_return_union(request=Animal_Dog(name="string", likes_to_woof=True)) + response = client.endpoints.union.get_and_return_union( + request=Animal_Dog(name="string", likes_to_woof=True) + ) validate_response(response, expected_response, expected_types) async_response = await async_client.endpoints.union.get_and_return_union( diff --git a/seed/python-sdk/exhaustive/infinite-timeout/tests/test_inlined_requests.py b/seed/python-sdk/exhaustive/infinite-timeout/tests/test_inlined_requests.py index bb9390d3845..03f46b31cc9 100644 --- a/seed/python-sdk/exhaustive/infinite-timeout/tests/test_inlined_requests.py +++ b/seed/python-sdk/exhaustive/infinite-timeout/tests/test_inlined_requests.py @@ -1,16 +1,17 @@ # This file was auto-generated by Fern from our API Definition. -import datetime +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing -import uuid - -from seed import AsyncSeedExhaustive, SeedExhaustive from seed.types.object import ObjectWithOptionalField - +import datetime +import uuid from .utilities import validate_response -async def test_post_with_object_bodyand_response(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_post_with_object_bodyand_response( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = { "string": "string", "integer": 1, @@ -62,23 +63,25 @@ async def test_post_with_object_bodyand_response(client: SeedExhaustive, async_c ) validate_response(response, expected_response, expected_types) - async_response = await async_client.inlined_requests.post_with_object_bodyand_response( - string="string", - integer=1, - nested_object=ObjectWithOptionalField( + async_response = ( + await async_client.inlined_requests.post_with_object_bodyand_response( string="string", integer=1, - long_=1000000, - double=1.1, - bool_=True, - datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), - date=datetime.date.fromisoformat("2023-01-15"), - uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), - base_64="SGVsbG8gd29ybGQh", - list_=["string"], - set_={"string"}, - map_={1: "string"}, - bigint="123456789123456789", - ), + nested_object=ObjectWithOptionalField( + string="string", + integer=1, + long_=1000000, + double=1.1, + bool_=True, + datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), + date=datetime.date.fromisoformat("2023-01-15"), + uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + base_64="SGVsbG8gd29ybGQh", + list_=["string"], + set_={"string"}, + map_={1: "string"}, + bigint="123456789123456789", + ), + ) ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/exhaustive/infinite-timeout/tests/test_no_auth.py b/seed/python-sdk/exhaustive/infinite-timeout/tests/test_no_auth.py index 3328661bb48..fc475f4b6fb 100644 --- a/seed/python-sdk/exhaustive/infinite-timeout/tests/test_no_auth.py +++ b/seed/python-sdk/exhaustive/infinite-timeout/tests/test_no_auth.py @@ -1,17 +1,20 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing - -from seed import AsyncSeedExhaustive, SeedExhaustive - from .utilities import validate_response -async def test_post_with_no_auth(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_post_with_no_auth( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = True expected_types: typing.Any = None response = client.no_auth.post_with_no_auth(request={"key": "value"}) validate_response(response, expected_response, expected_types) - async_response = await async_client.no_auth.post_with_no_auth(request={"key": "value"}) + async_response = await async_client.no_auth.post_with_no_auth( + request={"key": "value"} + ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/exhaustive/infinite-timeout/tests/test_no_req_body.py b/seed/python-sdk/exhaustive/infinite-timeout/tests/test_no_req_body.py index 73abac9d2d8..07061a0e99e 100644 --- a/seed/python-sdk/exhaustive/infinite-timeout/tests/test_no_req_body.py +++ b/seed/python-sdk/exhaustive/infinite-timeout/tests/test_no_req_body.py @@ -1,13 +1,14 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing - -from seed import AsyncSeedExhaustive, SeedExhaustive - from .utilities import validate_response -async def test_get_with_no_request_body(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_with_no_request_body( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = { "string": "string", "integer": 1, @@ -45,7 +46,9 @@ async def test_get_with_no_request_body(client: SeedExhaustive, async_client: As validate_response(async_response, expected_response, expected_types) -async def test_post_with_no_request_body(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_post_with_no_request_body( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "string" expected_types: typing.Any = None response = client.no_req_body.post_with_no_request_body() diff --git a/seed/python-sdk/exhaustive/infinite-timeout/tests/test_req_with_headers.py b/seed/python-sdk/exhaustive/infinite-timeout/tests/test_req_with_headers.py index bba3b5b5507..75ce9d00c03 100644 --- a/seed/python-sdk/exhaustive/infinite-timeout/tests/test_req_with_headers.py +++ b/seed/python-sdk/exhaustive/infinite-timeout/tests/test_req_with_headers.py @@ -1,10 +1,27 @@ # This file was auto-generated by Fern from our API Definition. -from seed import AsyncSeedExhaustive, SeedExhaustive +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive -async def test_get_with_custom_header(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_with_custom_header( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: # Type ignore to avoid mypy complaining about the function not being meant to return a value - assert client.req_with_headers.get_with_custom_header(x_test_service_header="string", x_test_endpoint_header="string", request="string") is None # type: ignore[func-returns-value] + assert ( + client.req_with_headers.get_with_custom_header( + x_test_service_header="string", + x_test_endpoint_header="string", + request="string", + ) + is None + ) # type: ignore[func-returns-value] - assert await async_client.req_with_headers.get_with_custom_header(x_test_service_header="string", x_test_endpoint_header="string", request="string") is None # type: ignore[func-returns-value] + assert ( + await async_client.req_with_headers.get_with_custom_header( + x_test_service_header="string", + x_test_endpoint_header="string", + request="string", + ) + is None + ) # type: ignore[func-returns-value] diff --git a/seed/python-sdk/exhaustive/infinite-timeout/tests/utilities.py b/seed/python-sdk/exhaustive/infinite-timeout/tests/utilities.py index 13da208eb3a..e8f4472564c 100644 --- a/seed/python-sdk/exhaustive/infinite-timeout/tests/utilities.py +++ b/seed/python-sdk/exhaustive/infinite-timeout/tests/utilities.py @@ -3,11 +3,14 @@ import typing import uuid -import pydantic from dateutil import parser +import pydantic + -def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> typing.Any: +def cast_field( + json_expectation: typing.Any, type_expectation: typing.Any +) -> typing.Any: # Cast these specific types which come through as string and expect our # models to cast to the correct type. if type_expectation == "uuid": @@ -25,7 +28,9 @@ def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> ty return json_expectation -def validate_field(response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any) -> None: +def validate_field( + response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectation == "no_validate": return @@ -44,7 +49,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(entry_expectation, dict): is_container_of_complex_type = True validate_response( - response=response[idx], json_expectation=ex, type_expectations=entry_expectation + response=response[idx], + json_expectation=ex, + type_expectations=entry_expectation, ) else: cast_json_expectation.append(cast_field(ex, entry_expectation)) @@ -56,7 +63,10 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # if any of the values of the set have a type_expectation of a dict, we're assuming it's a pydantic # model and keeping it a list. if container_expectation != "set" or not any( - map(lambda value: isinstance(value, dict), list(contents_expectation.values())) + map( + lambda value: isinstance(value, dict), + list(contents_expectation.values()), + ) ): json_expectation = cast_field(json_expectation, container_expectation) elif isinstance(type_expectation, tuple): @@ -65,9 +75,15 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(contents_expectation, dict): json_expectation = { cast_field( - key, contents_expectation.get(idx)[0] if contents_expectation.get(idx) is not None else None # type: ignore + key, + contents_expectation.get(idx)[0] + if contents_expectation.get(idx) is not None + else None, # type: ignore ): cast_field( - value, contents_expectation.get(idx)[1] if contents_expectation.get(idx) is not None else None # type: ignore + value, + contents_expectation.get(idx)[1] + if contents_expectation.get(idx) is not None + else None, # type: ignore ) for idx, (key, value) in enumerate(json_expectation.items()) } @@ -86,7 +102,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # Arg type_expectations is a deeply nested structure that matches the response, but with the values replaced with the expected types -def validate_response(response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any) -> None: +def validate_response( + response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectations == "no_validate": return @@ -96,11 +114,17 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e and not isinstance(response, dict) and not issubclass(type(response), pydantic.BaseModel) ): - validate_field(response=response, json_expectation=json_expectation, type_expectation=type_expectations) + validate_field( + response=response, + json_expectation=json_expectation, + type_expectation=type_expectations, + ) return if isinstance(response, list): - assert len(response) == len(json_expectation), "Length mismatch, expected: {0}, Actual: {1}".format( + assert len(response) == len( + json_expectation + ), "Length mismatch, expected: {0}, Actual: {1}".format( len(response), len(json_expectation) ) content_expectation = type_expectations @@ -108,7 +132,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e content_expectation = type_expectations[1] for idx, item in enumerate(response): validate_response( - response=item, json_expectation=json_expectation[idx], type_expectations=content_expectation[idx] + response=item, + json_expectation=json_expectation[idx], + type_expectations=content_expectation[idx], ) else: response_json = response @@ -116,7 +142,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e response_json = response.dict(by_alias=True) for key, value in json_expectation.items(): - assert key in response_json, "Field {0} not found within the response object: {1}".format( + assert ( + key in response_json + ), "Field {0} not found within the response object: {1}".format( key, response_json ) @@ -128,11 +156,19 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e # Otherwise, we're just validating a single field that's a pydantic model. if isinstance(value, dict) and not isinstance(type_expectation, tuple): validate_response( - response=response_json[key], json_expectation=value, type_expectations=type_expectation + response=response_json[key], + json_expectation=value, + type_expectations=type_expectation, ) else: - validate_field(response=response_json[key], json_expectation=value, type_expectation=type_expectation) + validate_field( + response=response_json[key], + json_expectation=value, + type_expectation=type_expectation, + ) # Ensure there are no additional fields here either del response_json[key] - assert len(response_json) == 0, "Additional fields found, expected None: {0}".format(response_json) + assert ( + len(response_json) == 0 + ), "Additional fields found, expected None: {0}".format(response_json) diff --git a/seed/python-sdk/exhaustive/infinite-timeout/tests/utils/assets/models/__init__.py b/seed/python-sdk/exhaustive/infinite-timeout/tests/utils/assets/models/__init__.py index 2cf01263529..3a1c852e71e 100644 --- a/seed/python-sdk/exhaustive/infinite-timeout/tests/utils/assets/models/__init__.py +++ b/seed/python-sdk/exhaustive/infinite-timeout/tests/utils/assets/models/__init__.py @@ -5,7 +5,7 @@ from .circle import CircleParams from .object_with_defaults import ObjectWithDefaultsParams from .object_with_optional_field import ObjectWithOptionalFieldParams -from .shape import Shape_CircleParams, Shape_SquareParams, ShapeParams +from .shape import ShapeParams, Shape_CircleParams, Shape_SquareParams from .square import SquareParams from .undiscriminated_shape import UndiscriminatedShapeParams diff --git a/seed/python-sdk/exhaustive/infinite-timeout/tests/utils/assets/models/circle.py b/seed/python-sdk/exhaustive/infinite-timeout/tests/utils/assets/models/circle.py index af7a1bf8a8e..253f12d38b3 100644 --- a/seed/python-sdk/exhaustive/infinite-timeout/tests/utils/assets/models/circle.py +++ b/seed/python-sdk/exhaustive/infinite-timeout/tests/utils/assets/models/circle.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class CircleParams(typing_extensions.TypedDict): - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] diff --git a/seed/python-sdk/exhaustive/infinite-timeout/tests/utils/assets/models/object_with_optional_field.py b/seed/python-sdk/exhaustive/infinite-timeout/tests/utils/assets/models/object_with_optional_field.py index 3ad93d5f305..ebe7dc80547 100644 --- a/seed/python-sdk/exhaustive/infinite-timeout/tests/utils/assets/models/object_with_optional_field.py +++ b/seed/python-sdk/exhaustive/infinite-timeout/tests/utils/assets/models/object_with_optional_field.py @@ -7,8 +7,8 @@ import uuid import typing_extensions -from seed.core.serialization import FieldMetadata +from seed.core.serialization import FieldMetadata from .color import Color from .shape import ShapeParams from .undiscriminated_shape import UndiscriminatedShapeParams @@ -18,16 +18,30 @@ class ObjectWithOptionalFieldParams(typing_extensions.TypedDict): literal: typing.Literal["lit_one"] string: typing_extensions.NotRequired[str] integer: typing_extensions.NotRequired[int] - long_: typing_extensions.NotRequired[typing_extensions.Annotated[int, FieldMetadata(alias="long")]] + long_: typing_extensions.NotRequired[ + typing_extensions.Annotated[int, FieldMetadata(alias="long")] + ] double: typing_extensions.NotRequired[float] - bool_: typing_extensions.NotRequired[typing_extensions.Annotated[bool, FieldMetadata(alias="bool")]] + bool_: typing_extensions.NotRequired[ + typing_extensions.Annotated[bool, FieldMetadata(alias="bool")] + ] datetime: typing_extensions.NotRequired[dt.datetime] date: typing_extensions.NotRequired[dt.date] - uuid_: typing_extensions.NotRequired[typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")]] - base_64: typing_extensions.NotRequired[typing_extensions.Annotated[str, FieldMetadata(alias="base64")]] - list_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")]] - set_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")]] - map_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")]] + uuid_: typing_extensions.NotRequired[ + typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")] + ] + base_64: typing_extensions.NotRequired[ + typing_extensions.Annotated[str, FieldMetadata(alias="base64")] + ] + list_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")] + ] + set_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")] + ] + map_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")] + ] enum: typing_extensions.NotRequired[Color] union: typing_extensions.NotRequired[ShapeParams] second_union: typing_extensions.NotRequired[ShapeParams] diff --git a/seed/python-sdk/exhaustive/infinite-timeout/tests/utils/assets/models/shape.py b/seed/python-sdk/exhaustive/infinite-timeout/tests/utils/assets/models/shape.py index 2c33c877951..816ffc51bdc 100644 --- a/seed/python-sdk/exhaustive/infinite-timeout/tests/utils/assets/models/shape.py +++ b/seed/python-sdk/exhaustive/infinite-timeout/tests/utils/assets/models/shape.py @@ -7,6 +7,7 @@ import typing import typing_extensions + from seed.core.serialization import FieldMetadata @@ -15,13 +16,21 @@ class Base(typing_extensions.TypedDict): class Shape_CircleParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["circle"], FieldMetadata(alias="shapeType")] - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["circle"], FieldMetadata(alias="shapeType") + ] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] class Shape_SquareParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["square"], FieldMetadata(alias="shapeType")] - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["square"], FieldMetadata(alias="shapeType") + ] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] ShapeParams = typing.Union[Shape_CircleParams, Shape_SquareParams] diff --git a/seed/python-sdk/exhaustive/infinite-timeout/tests/utils/assets/models/square.py b/seed/python-sdk/exhaustive/infinite-timeout/tests/utils/assets/models/square.py index b9b7dd319bc..bcf08a723c5 100644 --- a/seed/python-sdk/exhaustive/infinite-timeout/tests/utils/assets/models/square.py +++ b/seed/python-sdk/exhaustive/infinite-timeout/tests/utils/assets/models/square.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class SquareParams(typing_extensions.TypedDict): - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] diff --git a/seed/python-sdk/exhaustive/infinite-timeout/tests/utils/test_http_client.py b/seed/python-sdk/exhaustive/infinite-timeout/tests/utils/test_http_client.py index edd11ca7afb..f5a874a75f3 100644 --- a/seed/python-sdk/exhaustive/infinite-timeout/tests/utils/test_http_client.py +++ b/seed/python-sdk/exhaustive/infinite-timeout/tests/utils/test_http_client.py @@ -9,12 +9,17 @@ def get_request_options() -> RequestOptions: def test_get_json_request_body() -> None: - json_body, data_body = get_request_body(json={"hello": "world"}, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json={"hello": "world"}, data=None, request_options=None, omit=None + ) assert json_body == {"hello": "world"} assert data_body is None json_body_extras, data_body_extras = get_request_body( - json={"goodbye": "world"}, data=None, request_options=get_request_options(), omit=None + json={"goodbye": "world"}, + data=None, + request_options=get_request_options(), + omit=None, ) assert json_body_extras == {"goodbye": "world", "see you": "later"} @@ -22,12 +27,17 @@ def test_get_json_request_body() -> None: def test_get_files_request_body() -> None: - json_body, data_body = get_request_body(json=None, data={"hello": "world"}, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data={"hello": "world"}, request_options=None, omit=None + ) assert data_body == {"hello": "world"} assert json_body is None json_body_extras, data_body_extras = get_request_body( - json=None, data={"goodbye": "world"}, request_options=get_request_options(), omit=None + json=None, + data={"goodbye": "world"}, + request_options=get_request_options(), + omit=None, ) assert data_body_extras == {"goodbye": "world", "see you": "later"} @@ -35,7 +45,9 @@ def test_get_files_request_body() -> None: def test_get_none_request_body() -> None: - json_body, data_body = get_request_body(json=None, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data=None, request_options=None, omit=None + ) assert data_body is None assert json_body is None diff --git a/seed/python-sdk/exhaustive/infinite-timeout/tests/utils/test_query_encoding.py b/seed/python-sdk/exhaustive/infinite-timeout/tests/utils/test_query_encoding.py index 247e1551b46..fbc8f402167 100644 --- a/seed/python-sdk/exhaustive/infinite-timeout/tests/utils/test_query_encoding.py +++ b/seed/python-sdk/exhaustive/infinite-timeout/tests/utils/test_query_encoding.py @@ -4,9 +4,15 @@ def test_query_encoding() -> None: - assert encode_query({"hello world": "hello world"}) == {"hello world": "hello world"} - assert encode_query({"hello_world": {"hello": "world"}}) == {"hello_world[hello]": "world"} - assert encode_query({"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"}) == { + assert encode_query({"hello world": "hello world"}) == { + "hello world": "hello world" + } + assert encode_query({"hello_world": {"hello": "world"}}) == { + "hello_world[hello]": "world" + } + assert encode_query( + {"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"} + ) == { "hello_world[hello][world]": "today", "hello_world[test]": "this", "hi": "there", diff --git a/seed/python-sdk/exhaustive/infinite-timeout/tests/utils/test_serialization.py b/seed/python-sdk/exhaustive/infinite-timeout/tests/utils/test_serialization.py index 58b1ed66e6d..5ca956916dd 100644 --- a/seed/python-sdk/exhaustive/infinite-timeout/tests/utils/test_serialization.py +++ b/seed/python-sdk/exhaustive/infinite-timeout/tests/utils/test_serialization.py @@ -1,10 +1,12 @@ # This file was auto-generated by Fern from our API Definition. -from typing import Any, List +from typing import List, Any -from seed.core.serialization import convert_and_respect_annotation_metadata +from seed.core.serialization import ( + convert_and_respect_annotation_metadata, +) +from .assets.models import ShapeParams, ObjectWithOptionalFieldParams -from .assets.models import ObjectWithOptionalFieldParams, ShapeParams UNION_TEST: ShapeParams = {"radius_measurement": 1.0, "shape_type": "circle", "id": "1"} UNION_TEST_CONVERTED = {"shapeType": "circle", "radiusMeasurement": 1.0, "id": "1"} @@ -18,20 +20,54 @@ def test_convert_and_respect_annotation_metadata() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) - assert converted == {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"} + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) + assert converted == { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + } def test_convert_and_respect_annotation_metadata_in_list() -> None: data: List[ObjectWithOptionalFieldParams] = [ - {"string": "string", "long_": 12345, "bool_": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long_": 67890, "list_": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long_": 12345, + "bool_": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long_": 67890, + "list_": [], + "literal": "lit_one", + "any": "any", + }, ] - converted = convert_and_respect_annotation_metadata(object_=data, annotation=List[ObjectWithOptionalFieldParams]) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=List[ObjectWithOptionalFieldParams] + ) assert converted == [ - {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long": 67890, "list": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long": 67890, + "list": [], + "literal": "lit_one", + "any": "any", + }, ] @@ -43,7 +79,9 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) assert converted == { "string": "string", @@ -55,12 +93,16 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: def test_convert_and_respect_annotation_metadata_in_union() -> None: - converted = convert_and_respect_annotation_metadata(object_=UNION_TEST, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=UNION_TEST, annotation=ShapeParams + ) assert converted == UNION_TEST_CONVERTED def test_convert_and_respect_annotation_metadata_with_empty_object() -> None: data: Any = {} - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ShapeParams + ) assert converted == data diff --git a/seed/python-sdk/exhaustive/inline_request_params/pyproject.toml b/seed/python-sdk/exhaustive/inline_request_params/pyproject.toml index c6cd3a2b7b9..fc29a237334 100644 --- a/seed/python-sdk/exhaustive/inline_request_params/pyproject.toml +++ b/seed/python-sdk/exhaustive/inline_request_params/pyproject.toml @@ -43,6 +43,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/python-sdk/exhaustive/inline_request_params/src/seed/__init__.py b/seed/python-sdk/exhaustive/inline_request_params/src/seed/__init__.py index eb56b0ce275..dc1ef03a650 100644 --- a/seed/python-sdk/exhaustive/inline_request_params/src/seed/__init__.py +++ b/seed/python-sdk/exhaustive/inline_request_params/src/seed/__init__.py @@ -1,6 +1,14 @@ # This file was auto-generated by Fern from our API Definition. -from . import endpoints, general_errors, inlined_requests, no_auth, no_req_body, req_with_headers, types +from . import ( + endpoints, + general_errors, + inlined_requests, + no_auth, + no_req_body, + req_with_headers, + types, +) from .client import AsyncSeedExhaustive, SeedExhaustive from .general_errors import BadObjectRequestInfo, BadRequestBody from .version import __version__ diff --git a/seed/python-sdk/exhaustive/inline_request_params/src/seed/client.py b/seed/python-sdk/exhaustive/inline_request_params/src/seed/client.py index b1b9764c7a7..f5ab292af6b 100644 --- a/seed/python-sdk/exhaustive/inline_request_params/src/seed/client.py +++ b/seed/python-sdk/exhaustive/inline_request_params/src/seed/client.py @@ -1,15 +1,19 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from .endpoints.client import AsyncEndpointsClient, EndpointsClient -from .inlined_requests.client import AsyncInlinedRequestsClient, InlinedRequestsClient -from .no_auth.client import AsyncNoAuthClient, NoAuthClient -from .no_req_body.client import AsyncNoReqBodyClient, NoReqBodyClient -from .req_with_headers.client import AsyncReqWithHeadersClient, ReqWithHeadersClient +from .core.client_wrapper import SyncClientWrapper +from .endpoints.client import EndpointsClient +from .inlined_requests.client import InlinedRequestsClient +from .no_auth.client import NoAuthClient +from .no_req_body.client import NoReqBodyClient +from .req_with_headers.client import ReqWithHeadersClient +from .core.client_wrapper import AsyncClientWrapper +from .endpoints.client import AsyncEndpointsClient +from .inlined_requests.client import AsyncInlinedRequestsClient +from .no_auth.client import AsyncNoAuthClient +from .no_req_body.client import AsyncNoReqBodyClient +from .req_with_headers.client import AsyncReqWithHeadersClient class SeedExhaustive: @@ -48,24 +52,32 @@ def __init__( token: typing.Optional[typing.Union[str, typing.Callable[[], str]]] = None, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.Client] = None + httpx_client: typing.Optional[httpx.Client] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = SyncClientWrapper( base_url=base_url, token=token, httpx_client=httpx_client if httpx_client is not None - else httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.Client( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.Client(timeout=_defaulted_timeout), timeout=_defaulted_timeout, ) self.endpoints = EndpointsClient(client_wrapper=self._client_wrapper) - self.inlined_requests = InlinedRequestsClient(client_wrapper=self._client_wrapper) + self.inlined_requests = InlinedRequestsClient( + client_wrapper=self._client_wrapper + ) self.no_auth = NoAuthClient(client_wrapper=self._client_wrapper) self.no_req_body = NoReqBodyClient(client_wrapper=self._client_wrapper) - self.req_with_headers = ReqWithHeadersClient(client_wrapper=self._client_wrapper) + self.req_with_headers = ReqWithHeadersClient( + client_wrapper=self._client_wrapper + ) class AsyncSeedExhaustive: @@ -104,21 +116,29 @@ def __init__( token: typing.Optional[typing.Union[str, typing.Callable[[], str]]] = None, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.AsyncClient] = None + httpx_client: typing.Optional[httpx.AsyncClient] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = AsyncClientWrapper( base_url=base_url, token=token, httpx_client=httpx_client if httpx_client is not None - else httpx.AsyncClient(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.AsyncClient( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.AsyncClient(timeout=_defaulted_timeout), timeout=_defaulted_timeout, ) self.endpoints = AsyncEndpointsClient(client_wrapper=self._client_wrapper) - self.inlined_requests = AsyncInlinedRequestsClient(client_wrapper=self._client_wrapper) + self.inlined_requests = AsyncInlinedRequestsClient( + client_wrapper=self._client_wrapper + ) self.no_auth = AsyncNoAuthClient(client_wrapper=self._client_wrapper) self.no_req_body = AsyncNoReqBodyClient(client_wrapper=self._client_wrapper) - self.req_with_headers = AsyncReqWithHeadersClient(client_wrapper=self._client_wrapper) + self.req_with_headers = AsyncReqWithHeadersClient( + client_wrapper=self._client_wrapper + ) diff --git a/seed/python-sdk/exhaustive/inline_request_params/src/seed/core/api_error.py b/seed/python-sdk/exhaustive/inline_request_params/src/seed/core/api_error.py index 2e9fc5431cd..da734b58068 100644 --- a/seed/python-sdk/exhaustive/inline_request_params/src/seed/core/api_error.py +++ b/seed/python-sdk/exhaustive/inline_request_params/src/seed/core/api_error.py @@ -7,7 +7,9 @@ class ApiError(Exception): status_code: typing.Optional[int] body: typing.Any - def __init__(self, *, status_code: typing.Optional[int] = None, body: typing.Any = None): + def __init__( + self, *, status_code: typing.Optional[int] = None, body: typing.Any = None + ): self.status_code = status_code self.body = body diff --git a/seed/python-sdk/exhaustive/inline_request_params/src/seed/core/client_wrapper.py b/seed/python-sdk/exhaustive/inline_request_params/src/seed/core/client_wrapper.py index 8d01b584b82..d037184a816 100644 --- a/seed/python-sdk/exhaustive/inline_request_params/src/seed/core/client_wrapper.py +++ b/seed/python-sdk/exhaustive/inline_request_params/src/seed/core/client_wrapper.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .http_client import AsyncHttpClient, HttpClient +from .http_client import HttpClient +from .http_client import AsyncHttpClient class BaseClientWrapper: diff --git a/seed/python-sdk/exhaustive/inline_request_params/src/seed/core/datetime_utils.py b/seed/python-sdk/exhaustive/inline_request_params/src/seed/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/python-sdk/exhaustive/inline_request_params/src/seed/core/datetime_utils.py +++ b/seed/python-sdk/exhaustive/inline_request_params/src/seed/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/python-sdk/exhaustive/inline_request_params/src/seed/core/file.py b/seed/python-sdk/exhaustive/inline_request_params/src/seed/core/file.py index cb0d40bbbf3..6e0f92bfcb1 100644 --- a/seed/python-sdk/exhaustive/inline_request_params/src/seed/core/file.py +++ b/seed/python-sdk/exhaustive/inline_request_params/src/seed/core/file.py @@ -13,12 +13,17 @@ # (filename, file (or bytes), content_type) typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str]], # (filename, file (or bytes), content_type, headers) - typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str], typing.Mapping[str, str]], + typing.Tuple[ + typing.Optional[str], + FileContent, + typing.Optional[str], + typing.Mapping[str, str], + ], ] def convert_file_dict_to_httpx_tuples( - d: typing.Dict[str, typing.Union[File, typing.List[File]]] + d: typing.Dict[str, typing.Union[File, typing.List[File]]], ) -> typing.List[typing.Tuple[str, File]]: """ The format we use is a list of tuples, where the first element is the diff --git a/seed/python-sdk/exhaustive/inline_request_params/src/seed/core/http_client.py b/seed/python-sdk/exhaustive/inline_request_params/src/seed/core/http_client.py index 9333d8a7f15..091f71bc185 100644 --- a/seed/python-sdk/exhaustive/inline_request_params/src/seed/core/http_client.py +++ b/seed/python-sdk/exhaustive/inline_request_params/src/seed/core/http_client.py @@ -77,7 +77,9 @@ def _retry_timeout(response: httpx.Response, retries: int) -> float: return retry_after # Apply exponential backoff, capped at MAX_RETRY_DELAY_SECONDS. - retry_delay = min(INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS) + retry_delay = min( + INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS + ) # Add a randomness / jitter to the retry delay to avoid overwhelming the server with retries. timeout = retry_delay * (1 - 0.25 * random()) @@ -90,7 +92,8 @@ def _should_retry(response: httpx.Response) -> bool: def remove_omit_from_dict( - original: typing.Dict[str, typing.Optional[typing.Any]], omit: typing.Optional[typing.Any] + original: typing.Dict[str, typing.Optional[typing.Any]], + omit: typing.Optional[typing.Any], ) -> typing.Dict[str, typing.Any]: if omit is None: return original @@ -108,7 +111,8 @@ def maybe_filter_request_body( ) -> typing.Optional[typing.Any]: if data is None: return ( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else None ) @@ -118,7 +122,8 @@ def maybe_filter_request_body( data_content = { **(jsonable_encoder(remove_omit_from_dict(data, omit))), # type: ignore **( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else {} ), @@ -162,7 +167,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url def request( @@ -174,8 +181,12 @@ def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -184,11 +195,14 @@ def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) response = self.httpx_client.request( method=method, @@ -198,7 +212,11 @@ def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -209,7 +227,10 @@ def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -222,11 +243,15 @@ def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: time.sleep(_retry_timeout(response=response, retries=retries)) @@ -256,8 +281,12 @@ def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -266,11 +295,14 @@ def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) with self.httpx_client.stream( method=method, @@ -280,7 +312,11 @@ def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -291,7 +327,9 @@ def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -304,7 +342,9 @@ def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream @@ -327,7 +367,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url async def request( @@ -339,8 +381,12 @@ async def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -349,11 +395,14 @@ async def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) # Add the input to each of these and do None-safety checks response = await self.httpx_client.request( @@ -364,7 +413,11 @@ async def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -375,7 +428,10 @@ async def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -388,11 +444,15 @@ async def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: await asyncio.sleep(_retry_timeout(response=response, retries=retries)) @@ -421,8 +481,12 @@ async def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -431,11 +495,14 @@ async def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) async with self.httpx_client.stream( method=method, @@ -445,7 +512,11 @@ async def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -456,7 +527,9 @@ async def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -469,7 +542,9 @@ async def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream diff --git a/seed/python-sdk/exhaustive/inline_request_params/src/seed/core/jsonable_encoder.py b/seed/python-sdk/exhaustive/inline_request_params/src/seed/core/jsonable_encoder.py index d3fd328fd41..12a8b52fc22 100644 --- a/seed/python-sdk/exhaustive/inline_request_params/src/seed/core/jsonable_encoder.py +++ b/seed/python-sdk/exhaustive/inline_request_params/src/seed/core/jsonable_encoder.py @@ -19,13 +19,19 @@ import pydantic from .datetime_utils import serialize_datetime -from .pydantic_utilities import IS_PYDANTIC_V2, encode_by_type, to_jsonable_with_fallback +from .pydantic_utilities import ( + IS_PYDANTIC_V2, + encode_by_type, + to_jsonable_with_fallback, +) SetIntStr = Set[Union[int, str]] DictIntStrAny = Dict[Union[int, str], Any] -def jsonable_encoder(obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None) -> Any: +def jsonable_encoder( + obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None +) -> Any: custom_encoder = custom_encoder or {} if custom_encoder: if type(obj) in custom_encoder: diff --git a/seed/python-sdk/exhaustive/inline_request_params/src/seed/core/pydantic_utilities.py b/seed/python-sdk/exhaustive/inline_request_params/src/seed/core/pydantic_utilities.py index 170a563d6eb..c63935c32a2 100644 --- a/seed/python-sdk/exhaustive/inline_request_params/src/seed/core/pydantic_utilities.py +++ b/seed/python-sdk/exhaustive/inline_request_params/src/seed/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) # type: ignore # Pydantic v1 diff --git a/seed/python-sdk/exhaustive/inline_request_params/src/seed/core/query_encoder.py b/seed/python-sdk/exhaustive/inline_request_params/src/seed/core/query_encoder.py index 24076d72ee9..7cb98f52cd7 100644 --- a/seed/python-sdk/exhaustive/inline_request_params/src/seed/core/query_encoder.py +++ b/seed/python-sdk/exhaustive/inline_request_params/src/seed/core/query_encoder.py @@ -7,7 +7,9 @@ # Flattens dicts to be of the form {"key[subkey][subkey2]": value} where value is not a dict -def traverse_query_dict(dict_flat: Dict[str, Any], key_prefix: Optional[str] = None) -> Dict[str, Any]: +def traverse_query_dict( + dict_flat: Dict[str, Any], key_prefix: Optional[str] = None +) -> Dict[str, Any]: result = {} for k, v in dict_flat.items(): key = f"{key_prefix}[{k}]" if key_prefix is not None else k @@ -30,4 +32,8 @@ def single_query_encoder(query_key: str, query_value: Any) -> Dict[str, Any]: def encode_query(query: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: - return dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) if query is not None else None + return ( + dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) + if query is not None + else None + ) diff --git a/seed/python-sdk/exhaustive/inline_request_params/src/seed/core/serialization.py b/seed/python-sdk/exhaustive/inline_request_params/src/seed/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/python-sdk/exhaustive/inline_request_params/src/seed/core/serialization.py +++ b/seed/python-sdk/exhaustive/inline_request_params/src/seed/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/python-sdk/exhaustive/inline_request_params/src/seed/endpoints/__init__.py b/seed/python-sdk/exhaustive/inline_request_params/src/seed/endpoints/__init__.py index 92307cab7fe..a9496ece178 100644 --- a/seed/python-sdk/exhaustive/inline_request_params/src/seed/endpoints/__init__.py +++ b/seed/python-sdk/exhaustive/inline_request_params/src/seed/endpoints/__init__.py @@ -2,4 +2,12 @@ from . import container, enum, http_methods, object, params, primitive, union -__all__ = ["container", "enum", "http_methods", "object", "params", "primitive", "union"] +__all__ = [ + "container", + "enum", + "http_methods", + "object", + "params", + "primitive", + "union", +] diff --git a/seed/python-sdk/exhaustive/inline_request_params/src/seed/endpoints/client.py b/seed/python-sdk/exhaustive/inline_request_params/src/seed/endpoints/client.py index 18dc397fdf1..69930de54d7 100644 --- a/seed/python-sdk/exhaustive/inline_request_params/src/seed/endpoints/client.py +++ b/seed/python-sdk/exhaustive/inline_request_params/src/seed/endpoints/client.py @@ -1,13 +1,21 @@ # This file was auto-generated by Fern from our API Definition. -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from .container.client import AsyncContainerClient, ContainerClient -from .enum.client import AsyncEnumClient, EnumClient -from .http_methods.client import AsyncHttpMethodsClient, HttpMethodsClient -from .object.client import AsyncObjectClient, ObjectClient -from .params.client import AsyncParamsClient, ParamsClient -from .primitive.client import AsyncPrimitiveClient, PrimitiveClient -from .union.client import AsyncUnionClient, UnionClient +from ..core.client_wrapper import SyncClientWrapper +from .container.client import ContainerClient +from .enum.client import EnumClient +from .http_methods.client import HttpMethodsClient +from .object.client import ObjectClient +from .params.client import ParamsClient +from .primitive.client import PrimitiveClient +from .union.client import UnionClient +from ..core.client_wrapper import AsyncClientWrapper +from .container.client import AsyncContainerClient +from .enum.client import AsyncEnumClient +from .http_methods.client import AsyncHttpMethodsClient +from .object.client import AsyncObjectClient +from .params.client import AsyncParamsClient +from .primitive.client import AsyncPrimitiveClient +from .union.client import AsyncUnionClient class EndpointsClient: diff --git a/seed/python-sdk/exhaustive/inline_request_params/src/seed/endpoints/container/client.py b/seed/python-sdk/exhaustive/inline_request_params/src/seed/endpoints/container/client.py index c6cf14f63ac..4af9c12d534 100644 --- a/seed/python-sdk/exhaustive/inline_request_params/src/seed/endpoints/container/client.py +++ b/seed/python-sdk/exhaustive/inline_request_params/src/seed/endpoints/container/client.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. import typing +from ...core.client_wrapper import SyncClientWrapper +from ...core.request_options import RequestOptions +from ...core.pydantic_utilities import parse_obj_as from json.decoder import JSONDecodeError - from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ...core.pydantic_utilities import parse_obj_as -from ...core.request_options import RequestOptions from ...types.object.types.object_with_required_field import ObjectWithRequiredField +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -18,7 +18,10 @@ def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper def get_and_return_list_of_primitives( - self, *, request: typing.Sequence[str], request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Sequence[str], + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[str]: """ Parameters @@ -45,11 +48,18 @@ def get_and_return_list_of_primitives( ) """ _response = self._client_wrapper.httpx_client.request( - "container/list-of-primitives", method="POST", json=request, request_options=request_options, omit=OMIT + "container/list-of-primitives", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.List[str], parse_obj_as(type_=typing.List[str], object_=_response.json())) # type: ignore + return typing.cast( + typing.List[str], + parse_obj_as(type_=typing.List[str], object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -59,7 +69,7 @@ def get_and_return_list_of_objects( self, *, request: typing.Sequence[ObjectWithRequiredField], - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[ObjectWithRequiredField]: """ Parameters @@ -91,18 +101,31 @@ def get_and_return_list_of_objects( ) """ _response = self._client_wrapper.httpx_client.request( - "container/list-of-objects", method="POST", json=request, request_options=request_options, omit=OMIT + "container/list-of-objects", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.List[ObjectWithRequiredField], parse_obj_as(type_=typing.List[ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.List[ObjectWithRequiredField], + parse_obj_as( + type_=typing.List[ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_and_return_set_of_primitives( - self, *, request: typing.Set[str], request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Set[str], + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Set[str]: """ Parameters @@ -129,11 +152,18 @@ def get_and_return_set_of_primitives( ) """ _response = self._client_wrapper.httpx_client.request( - "container/set-of-primitives", method="POST", json=request, request_options=request_options, omit=OMIT + "container/set-of-primitives", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Set[str], parse_obj_as(type_=typing.Set[str], object_=_response.json())) # type: ignore + return typing.cast( + typing.Set[str], + parse_obj_as(type_=typing.Set[str], object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -143,7 +173,7 @@ def get_and_return_set_of_objects( self, *, request: typing.Sequence[ObjectWithRequiredField], - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[ObjectWithRequiredField]: """ Parameters @@ -175,18 +205,31 @@ def get_and_return_set_of_objects( ) """ _response = self._client_wrapper.httpx_client.request( - "container/set-of-objects", method="POST", json=request, request_options=request_options, omit=OMIT + "container/set-of-objects", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.List[ObjectWithRequiredField], parse_obj_as(type_=typing.List[ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.List[ObjectWithRequiredField], + parse_obj_as( + type_=typing.List[ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_and_return_map_prim_to_prim( - self, *, request: typing.Dict[str, str], request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Dict[str, str], + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Dict[str, str]: """ Parameters @@ -213,11 +256,18 @@ def get_and_return_map_prim_to_prim( ) """ _response = self._client_wrapper.httpx_client.request( - "container/map-prim-to-prim", method="POST", json=request, request_options=request_options, omit=OMIT + "container/map-prim-to-prim", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Dict[str, str], parse_obj_as(type_=typing.Dict[str, str], object_=_response.json())) # type: ignore + return typing.cast( + typing.Dict[str, str], + parse_obj_as(type_=typing.Dict[str, str], object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -227,7 +277,7 @@ def get_and_return_map_of_prim_to_object( self, *, request: typing.Dict[str, ObjectWithRequiredField], - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Dict[str, ObjectWithRequiredField]: """ Parameters @@ -259,11 +309,21 @@ def get_and_return_map_of_prim_to_object( ) """ _response = self._client_wrapper.httpx_client.request( - "container/map-prim-to-object", method="POST", json=request, request_options=request_options, omit=OMIT + "container/map-prim-to-object", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Dict[str, ObjectWithRequiredField], parse_obj_as(type_=typing.Dict[str, ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.Dict[str, ObjectWithRequiredField], + parse_obj_as( + type_=typing.Dict[str, ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -273,7 +333,7 @@ def get_and_return_optional( self, *, request: typing.Optional[ObjectWithRequiredField] = None, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Optional[ObjectWithRequiredField]: """ Parameters @@ -303,11 +363,21 @@ def get_and_return_optional( ) """ _response = self._client_wrapper.httpx_client.request( - "container/opt-objects", method="POST", json=request, request_options=request_options, omit=OMIT + "container/opt-objects", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Optional[ObjectWithRequiredField], parse_obj_as(type_=typing.Optional[ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.Optional[ObjectWithRequiredField], + parse_obj_as( + type_=typing.Optional[ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -319,7 +389,10 @@ def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper async def get_and_return_list_of_primitives( - self, *, request: typing.Sequence[str], request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Sequence[str], + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[str]: """ Parameters @@ -354,11 +427,18 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/list-of-primitives", method="POST", json=request, request_options=request_options, omit=OMIT + "container/list-of-primitives", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.List[str], parse_obj_as(type_=typing.List[str], object_=_response.json())) # type: ignore + return typing.cast( + typing.List[str], + parse_obj_as(type_=typing.List[str], object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -368,7 +448,7 @@ async def get_and_return_list_of_objects( self, *, request: typing.Sequence[ObjectWithRequiredField], - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[ObjectWithRequiredField]: """ Parameters @@ -408,18 +488,31 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/list-of-objects", method="POST", json=request, request_options=request_options, omit=OMIT + "container/list-of-objects", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.List[ObjectWithRequiredField], parse_obj_as(type_=typing.List[ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.List[ObjectWithRequiredField], + parse_obj_as( + type_=typing.List[ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_and_return_set_of_primitives( - self, *, request: typing.Set[str], request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Set[str], + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Set[str]: """ Parameters @@ -454,11 +547,18 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/set-of-primitives", method="POST", json=request, request_options=request_options, omit=OMIT + "container/set-of-primitives", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Set[str], parse_obj_as(type_=typing.Set[str], object_=_response.json())) # type: ignore + return typing.cast( + typing.Set[str], + parse_obj_as(type_=typing.Set[str], object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -468,7 +568,7 @@ async def get_and_return_set_of_objects( self, *, request: typing.Sequence[ObjectWithRequiredField], - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[ObjectWithRequiredField]: """ Parameters @@ -508,18 +608,31 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/set-of-objects", method="POST", json=request, request_options=request_options, omit=OMIT + "container/set-of-objects", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.List[ObjectWithRequiredField], parse_obj_as(type_=typing.List[ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.List[ObjectWithRequiredField], + parse_obj_as( + type_=typing.List[ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_and_return_map_prim_to_prim( - self, *, request: typing.Dict[str, str], request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Dict[str, str], + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Dict[str, str]: """ Parameters @@ -554,11 +667,18 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/map-prim-to-prim", method="POST", json=request, request_options=request_options, omit=OMIT + "container/map-prim-to-prim", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Dict[str, str], parse_obj_as(type_=typing.Dict[str, str], object_=_response.json())) # type: ignore + return typing.cast( + typing.Dict[str, str], + parse_obj_as(type_=typing.Dict[str, str], object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -568,7 +688,7 @@ async def get_and_return_map_of_prim_to_object( self, *, request: typing.Dict[str, ObjectWithRequiredField], - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Dict[str, ObjectWithRequiredField]: """ Parameters @@ -608,11 +728,21 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/map-prim-to-object", method="POST", json=request, request_options=request_options, omit=OMIT + "container/map-prim-to-object", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Dict[str, ObjectWithRequiredField], parse_obj_as(type_=typing.Dict[str, ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.Dict[str, ObjectWithRequiredField], + parse_obj_as( + type_=typing.Dict[str, ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -622,7 +752,7 @@ async def get_and_return_optional( self, *, request: typing.Optional[ObjectWithRequiredField] = None, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Optional[ObjectWithRequiredField]: """ Parameters @@ -660,11 +790,21 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/opt-objects", method="POST", json=request, request_options=request_options, omit=OMIT + "container/opt-objects", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Optional[ObjectWithRequiredField], parse_obj_as(type_=typing.Optional[ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.Optional[ObjectWithRequiredField], + parse_obj_as( + type_=typing.Optional[ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/inline_request_params/src/seed/endpoints/enum/client.py b/seed/python-sdk/exhaustive/inline_request_params/src/seed/endpoints/enum/client.py index 44e2690ff6c..3e3208e3bcf 100644 --- a/seed/python-sdk/exhaustive/inline_request_params/src/seed/endpoints/enum/client.py +++ b/seed/python-sdk/exhaustive/inline_request_params/src/seed/endpoints/enum/client.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. import typing +from ...core.client_wrapper import SyncClientWrapper +from ...types.enum.types.weather_report import WeatherReport +from ...core.request_options import RequestOptions +from ...core.pydantic_utilities import parse_obj_as from json.decoder import JSONDecodeError - from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ...core.pydantic_utilities import parse_obj_as -from ...core.request_options import RequestOptions -from ...types.enum.types.weather_report import WeatherReport +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -18,7 +18,10 @@ def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper def get_and_return_enum( - self, *, request: WeatherReport, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: WeatherReport, + request_options: typing.Optional[RequestOptions] = None, ) -> WeatherReport: """ Parameters @@ -45,11 +48,18 @@ def get_and_return_enum( ) """ _response = self._client_wrapper.httpx_client.request( - "enum", method="POST", json=request, request_options=request_options, omit=OMIT + "enum", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(WeatherReport, parse_obj_as(type_=WeatherReport, object_=_response.json())) # type: ignore + return typing.cast( + WeatherReport, + parse_obj_as(type_=WeatherReport, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -61,7 +71,10 @@ def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper async def get_and_return_enum( - self, *, request: WeatherReport, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: WeatherReport, + request_options: typing.Optional[RequestOptions] = None, ) -> WeatherReport: """ Parameters @@ -96,11 +109,18 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "enum", method="POST", json=request, request_options=request_options, omit=OMIT + "enum", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(WeatherReport, parse_obj_as(type_=WeatherReport, object_=_response.json())) # type: ignore + return typing.cast( + WeatherReport, + parse_obj_as(type_=WeatherReport, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/inline_request_params/src/seed/endpoints/http_methods/client.py b/seed/python-sdk/exhaustive/inline_request_params/src/seed/endpoints/http_methods/client.py index a2549280a1b..570a227844f 100644 --- a/seed/python-sdk/exhaustive/inline_request_params/src/seed/endpoints/http_methods/client.py +++ b/seed/python-sdk/exhaustive/inline_request_params/src/seed/endpoints/http_methods/client.py @@ -1,16 +1,16 @@ # This file was auto-generated by Fern from our API Definition. -import datetime as dt import typing -import uuid -from json.decoder import JSONDecodeError - -from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper +from ...core.client_wrapper import SyncClientWrapper +from ...core.request_options import RequestOptions from ...core.jsonable_encoder import jsonable_encoder from ...core.pydantic_utilities import parse_obj_as -from ...core.request_options import RequestOptions +from json.decoder import JSONDecodeError +from ...core.api_error import ApiError from ...types.object.types.object_with_optional_field import ObjectWithOptionalField +import datetime as dt +import uuid +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -20,7 +20,9 @@ class HttpMethodsClient: def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper - def test_get(self, id: str, *, request_options: typing.Optional[RequestOptions] = None) -> str: + def test_get( + self, id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -46,11 +48,15 @@ def test_get(self, id: str, *, request_options: typing.Optional[RequestOptions] ) """ _response = self._client_wrapper.httpx_client.request( - f"http-methods/{jsonable_encoder(id)}", method="GET", request_options=request_options + f"http-methods/{jsonable_encoder(id)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -84,18 +90,33 @@ def test_post( ) """ _response = self._client_wrapper.httpx_client.request( - "http-methods", method="POST", json={"string": string}, request_options=request_options, omit=OMIT + "http-methods", + method="POST", + json={ + "string": string, + }, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def test_put( - self, id: str, *, string: str, request_options: typing.Optional[RequestOptions] = None + self, + id: str, + *, + string: str, + request_options: typing.Optional[RequestOptions] = None, ) -> ObjectWithOptionalField: """ Parameters @@ -127,13 +148,20 @@ def test_put( _response = self._client_wrapper.httpx_client.request( f"http-methods/{jsonable_encoder(id)}", method="PUT", - json={"string": string}, + json={ + "string": string, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -254,13 +282,20 @@ def test_patch( ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def test_delete(self, id: str, *, request_options: typing.Optional[RequestOptions] = None) -> bool: + def test_delete( + self, id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> bool: """ Parameters ---------- @@ -286,11 +321,15 @@ def test_delete(self, id: str, *, request_options: typing.Optional[RequestOption ) """ _response = self._client_wrapper.httpx_client.request( - f"http-methods/{jsonable_encoder(id)}", method="DELETE", request_options=request_options + f"http-methods/{jsonable_encoder(id)}", + method="DELETE", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -301,7 +340,9 @@ class AsyncHttpMethodsClient: def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper - async def test_get(self, id: str, *, request_options: typing.Optional[RequestOptions] = None) -> str: + async def test_get( + self, id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -335,11 +376,15 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - f"http-methods/{jsonable_encoder(id)}", method="GET", request_options=request_options + f"http-methods/{jsonable_encoder(id)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -381,18 +426,33 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "http-methods", method="POST", json={"string": string}, request_options=request_options, omit=OMIT + "http-methods", + method="POST", + json={ + "string": string, + }, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def test_put( - self, id: str, *, string: str, request_options: typing.Optional[RequestOptions] = None + self, + id: str, + *, + string: str, + request_options: typing.Optional[RequestOptions] = None, ) -> ObjectWithOptionalField: """ Parameters @@ -432,13 +492,20 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( f"http-methods/{jsonable_encoder(id)}", method="PUT", - json={"string": string}, + json={ + "string": string, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -566,13 +633,20 @@ async def main() -> None: ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - async def test_delete(self, id: str, *, request_options: typing.Optional[RequestOptions] = None) -> bool: + async def test_delete( + self, id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> bool: """ Parameters ---------- @@ -606,11 +680,15 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - f"http-methods/{jsonable_encoder(id)}", method="DELETE", request_options=request_options + f"http-methods/{jsonable_encoder(id)}", + method="DELETE", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/inline_request_params/src/seed/endpoints/object/client.py b/seed/python-sdk/exhaustive/inline_request_params/src/seed/endpoints/object/client.py index a724f959193..dcb1324b74b 100644 --- a/seed/python-sdk/exhaustive/inline_request_params/src/seed/endpoints/object/client.py +++ b/seed/python-sdk/exhaustive/inline_request_params/src/seed/endpoints/object/client.py @@ -1,20 +1,24 @@ # This file was auto-generated by Fern from our API Definition. -import datetime as dt import typing +from ...core.client_wrapper import SyncClientWrapper +import datetime as dt import uuid -from json.decoder import JSONDecodeError - -from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ...core.jsonable_encoder import jsonable_encoder -from ...core.pydantic_utilities import parse_obj_as from ...core.request_options import RequestOptions -from ...types.object.types.nested_object_with_optional_field import NestedObjectWithOptionalField -from ...types.object.types.nested_object_with_required_field import NestedObjectWithRequiredField -from ...types.object.types.object_with_map_of_map import ObjectWithMapOfMap from ...types.object.types.object_with_optional_field import ObjectWithOptionalField +from ...core.pydantic_utilities import parse_obj_as +from json.decoder import JSONDecodeError +from ...core.api_error import ApiError from ...types.object.types.object_with_required_field import ObjectWithRequiredField +from ...types.object.types.object_with_map_of_map import ObjectWithMapOfMap +from ...types.object.types.nested_object_with_optional_field import ( + NestedObjectWithOptionalField, +) +from ...types.object.types.nested_object_with_required_field import ( + NestedObjectWithRequiredField, +) +from ...core.jsonable_encoder import jsonable_encoder +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -135,7 +139,12 @@ def get_and_return_with_optional_field( ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -171,20 +180,30 @@ def get_and_return_with_required_field( _response = self._client_wrapper.httpx_client.request( "object/get-and-return-with-required-field", method="POST", - json={"string": string}, + json={ + "string": string, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithRequiredField, parse_obj_as(type_=ObjectWithRequiredField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithRequiredField, + parse_obj_as( + type_=ObjectWithRequiredField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_and_return_with_map_of_map( - self, *, map_: typing.Dict[str, typing.Dict[str, str]], request_options: typing.Optional[RequestOptions] = None + self, + *, + map_: typing.Dict[str, typing.Dict[str, str]], + request_options: typing.Optional[RequestOptions] = None, ) -> ObjectWithMapOfMap: """ Parameters @@ -213,13 +232,18 @@ def get_and_return_with_map_of_map( _response = self._client_wrapper.httpx_client.request( "object/get-and-return-with-map-of-map", method="POST", - json={"map": map_}, + json={ + "map": map_, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithMapOfMap, parse_obj_as(type_=ObjectWithMapOfMap, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithMapOfMap, + parse_obj_as(type_=ObjectWithMapOfMap, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -286,13 +310,21 @@ def get_and_return_nested_with_optional_field( _response = self._client_wrapper.httpx_client.request( "object/get-and-return-nested-with-optional-field", method="POST", - json={"string": string, "NestedObject": nested_object}, + json={ + "string": string, + "NestedObject": nested_object, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(NestedObjectWithOptionalField, parse_obj_as(type_=NestedObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + NestedObjectWithOptionalField, + parse_obj_as( + type_=NestedObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -363,13 +395,21 @@ def get_and_return_nested_with_required_field( _response = self._client_wrapper.httpx_client.request( f"object/get-and-return-nested-with-required-field/{jsonable_encoder(string_)}", method="POST", - json={"string": string, "NestedObject": nested_object}, + json={ + "string": string, + "NestedObject": nested_object, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(NestedObjectWithRequiredField, parse_obj_as(type_=NestedObjectWithRequiredField, object_=_response.json())) # type: ignore + return typing.cast( + NestedObjectWithRequiredField, + parse_obj_as( + type_=NestedObjectWithRequiredField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -446,7 +486,12 @@ def get_and_return_nested_with_required_field_as_list( ) try: if 200 <= _response.status_code < 300: - return typing.cast(NestedObjectWithRequiredField, parse_obj_as(type_=NestedObjectWithRequiredField, object_=_response.json())) # type: ignore + return typing.cast( + NestedObjectWithRequiredField, + parse_obj_as( + type_=NestedObjectWithRequiredField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -575,7 +620,12 @@ async def main() -> None: ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -619,20 +669,30 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( "object/get-and-return-with-required-field", method="POST", - json={"string": string}, + json={ + "string": string, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithRequiredField, parse_obj_as(type_=ObjectWithRequiredField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithRequiredField, + parse_obj_as( + type_=ObjectWithRequiredField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_and_return_with_map_of_map( - self, *, map_: typing.Dict[str, typing.Dict[str, str]], request_options: typing.Optional[RequestOptions] = None + self, + *, + map_: typing.Dict[str, typing.Dict[str, str]], + request_options: typing.Optional[RequestOptions] = None, ) -> ObjectWithMapOfMap: """ Parameters @@ -669,13 +729,18 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( "object/get-and-return-with-map-of-map", method="POST", - json={"map": map_}, + json={ + "map": map_, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithMapOfMap, parse_obj_as(type_=ObjectWithMapOfMap, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithMapOfMap, + parse_obj_as(type_=ObjectWithMapOfMap, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -749,13 +814,21 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( "object/get-and-return-nested-with-optional-field", method="POST", - json={"string": string, "NestedObject": nested_object}, + json={ + "string": string, + "NestedObject": nested_object, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(NestedObjectWithOptionalField, parse_obj_as(type_=NestedObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + NestedObjectWithOptionalField, + parse_obj_as( + type_=NestedObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -833,13 +906,21 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( f"object/get-and-return-nested-with-required-field/{jsonable_encoder(string_)}", method="POST", - json={"string": string, "NestedObject": nested_object}, + json={ + "string": string, + "NestedObject": nested_object, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(NestedObjectWithRequiredField, parse_obj_as(type_=NestedObjectWithRequiredField, object_=_response.json())) # type: ignore + return typing.cast( + NestedObjectWithRequiredField, + parse_obj_as( + type_=NestedObjectWithRequiredField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -923,7 +1004,12 @@ async def main() -> None: ) try: if 200 <= _response.status_code < 300: - return typing.cast(NestedObjectWithRequiredField, parse_obj_as(type_=NestedObjectWithRequiredField, object_=_response.json())) # type: ignore + return typing.cast( + NestedObjectWithRequiredField, + parse_obj_as( + type_=NestedObjectWithRequiredField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/inline_request_params/src/seed/endpoints/params/client.py b/seed/python-sdk/exhaustive/inline_request_params/src/seed/endpoints/params/client.py index 5cd7ceef42a..a9187ac94b8 100644 --- a/seed/python-sdk/exhaustive/inline_request_params/src/seed/endpoints/params/client.py +++ b/seed/python-sdk/exhaustive/inline_request_params/src/seed/endpoints/params/client.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. import typing -from json.decoder import JSONDecodeError - -from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper +from ...core.client_wrapper import SyncClientWrapper +from ...core.request_options import RequestOptions from ...core.jsonable_encoder import jsonable_encoder from ...core.pydantic_utilities import parse_obj_as -from ...core.request_options import RequestOptions +from json.decoder import JSONDecodeError +from ...core.api_error import ApiError +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -17,7 +17,9 @@ class ParamsClient: def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper - def get_with_path(self, param: str, *, request_options: typing.Optional[RequestOptions] = None) -> str: + def get_with_path( + self, param: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ GET with path param @@ -45,18 +47,26 @@ def get_with_path(self, param: str, *, request_options: typing.Optional[RequestO ) """ _response = self._client_wrapper.httpx_client.request( - f"params/path/{jsonable_encoder(param)}", method="GET", request_options=request_options + f"params/path/{jsonable_encoder(param)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_with_query( - self, *, query: str, number: int, request_options: typing.Optional[RequestOptions] = None + self, + *, + query: str, + number: int, + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ GET with query param @@ -88,7 +98,13 @@ def get_with_query( ) """ _response = self._client_wrapper.httpx_client.request( - "params", method="GET", params={"query": query, "number": number}, request_options=request_options + "params", + method="GET", + params={ + "query": query, + "number": number, + }, + request_options=request_options, ) try: if 200 <= _response.status_code < 300: @@ -135,7 +151,13 @@ def get_with_allow_multiple_query( ) """ _response = self._client_wrapper.httpx_client.request( - "params", method="GET", params={"query": query, "numer": numer}, request_options=request_options + "params", + method="GET", + params={ + "query": query, + "numer": numer, + }, + request_options=request_options, ) try: if 200 <= _response.status_code < 300: @@ -146,7 +168,11 @@ def get_with_allow_multiple_query( raise ApiError(status_code=_response.status_code, body=_response_json) def get_with_path_and_query( - self, param: str, *, query: str, request_options: typing.Optional[RequestOptions] = None + self, + param: str, + *, + query: str, + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ GET with path and query params @@ -180,7 +206,9 @@ def get_with_path_and_query( _response = self._client_wrapper.httpx_client.request( f"params/path-query/{jsonable_encoder(param)}", method="GET", - params={"query": query}, + params={ + "query": query, + }, request_options=request_options, ) try: @@ -192,7 +220,11 @@ def get_with_path_and_query( raise ApiError(status_code=_response.status_code, body=_response_json) def modify_with_path( - self, param: str, *, request: str, request_options: typing.Optional[RequestOptions] = None + self, + param: str, + *, + request: str, + request_options: typing.Optional[RequestOptions] = None, ) -> str: """ PUT to update with path param @@ -232,7 +264,9 @@ def modify_with_path( ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -243,7 +277,9 @@ class AsyncParamsClient: def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper - async def get_with_path(self, param: str, *, request_options: typing.Optional[RequestOptions] = None) -> str: + async def get_with_path( + self, param: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ GET with path param @@ -279,18 +315,26 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - f"params/path/{jsonable_encoder(param)}", method="GET", request_options=request_options + f"params/path/{jsonable_encoder(param)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_with_query( - self, *, query: str, number: int, request_options: typing.Optional[RequestOptions] = None + self, + *, + query: str, + number: int, + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ GET with query param @@ -330,7 +374,13 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "params", method="GET", params={"query": query, "number": number}, request_options=request_options + "params", + method="GET", + params={ + "query": query, + "number": number, + }, + request_options=request_options, ) try: if 200 <= _response.status_code < 300: @@ -385,7 +435,13 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "params", method="GET", params={"query": query, "numer": numer}, request_options=request_options + "params", + method="GET", + params={ + "query": query, + "numer": numer, + }, + request_options=request_options, ) try: if 200 <= _response.status_code < 300: @@ -396,7 +452,11 @@ async def main() -> None: raise ApiError(status_code=_response.status_code, body=_response_json) async def get_with_path_and_query( - self, param: str, *, query: str, request_options: typing.Optional[RequestOptions] = None + self, + param: str, + *, + query: str, + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ GET with path and query params @@ -438,7 +498,9 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( f"params/path-query/{jsonable_encoder(param)}", method="GET", - params={"query": query}, + params={ + "query": query, + }, request_options=request_options, ) try: @@ -450,7 +512,11 @@ async def main() -> None: raise ApiError(status_code=_response.status_code, body=_response_json) async def modify_with_path( - self, param: str, *, request: str, request_options: typing.Optional[RequestOptions] = None + self, + param: str, + *, + request: str, + request_options: typing.Optional[RequestOptions] = None, ) -> str: """ PUT to update with path param @@ -498,7 +564,9 @@ async def main() -> None: ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/inline_request_params/src/seed/endpoints/primitive/client.py b/seed/python-sdk/exhaustive/inline_request_params/src/seed/endpoints/primitive/client.py index 844b6a782f0..20a66f049b4 100644 --- a/seed/python-sdk/exhaustive/inline_request_params/src/seed/endpoints/primitive/client.py +++ b/seed/python-sdk/exhaustive/inline_request_params/src/seed/endpoints/primitive/client.py @@ -1,14 +1,14 @@ # This file was auto-generated by Fern from our API Definition. -import datetime as dt import typing -import uuid +from ...core.client_wrapper import SyncClientWrapper +from ...core.request_options import RequestOptions +from ...core.pydantic_utilities import parse_obj_as from json.decoder import JSONDecodeError - from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ...core.pydantic_utilities import parse_obj_as -from ...core.request_options import RequestOptions +import datetime as dt +import uuid +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -18,7 +18,9 @@ class PrimitiveClient: def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper - def get_and_return_string(self, *, request: str, request_options: typing.Optional[RequestOptions] = None) -> str: + def get_and_return_string( + self, *, request: str, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -44,17 +46,25 @@ def get_and_return_string(self, *, request: str, request_options: typing.Optiona ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/string", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/string", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def get_and_return_int(self, *, request: int, request_options: typing.Optional[RequestOptions] = None) -> int: + def get_and_return_int( + self, *, request: int, request_options: typing.Optional[RequestOptions] = None + ) -> int: """ Parameters ---------- @@ -80,17 +90,25 @@ def get_and_return_int(self, *, request: int, request_options: typing.Optional[R ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/integer", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/integer", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(int, parse_obj_as(type_=int, object_=_response.json())) # type: ignore + return typing.cast( + int, parse_obj_as(type_=int, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def get_and_return_long(self, *, request: int, request_options: typing.Optional[RequestOptions] = None) -> int: + def get_and_return_long( + self, *, request: int, request_options: typing.Optional[RequestOptions] = None + ) -> int: """ Parameters ---------- @@ -116,11 +134,17 @@ def get_and_return_long(self, *, request: int, request_options: typing.Optional[ ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/long", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/long", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(int, parse_obj_as(type_=int, object_=_response.json())) # type: ignore + return typing.cast( + int, parse_obj_as(type_=int, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -154,17 +178,25 @@ def get_and_return_double( ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/double", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/double", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(float, parse_obj_as(type_=float, object_=_response.json())) # type: ignore + return typing.cast( + float, parse_obj_as(type_=float, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def get_and_return_bool(self, *, request: bool, request_options: typing.Optional[RequestOptions] = None) -> bool: + def get_and_return_bool( + self, *, request: bool, request_options: typing.Optional[RequestOptions] = None + ) -> bool: """ Parameters ---------- @@ -190,18 +222,27 @@ def get_and_return_bool(self, *, request: bool, request_options: typing.Optional ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/boolean", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/boolean", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_and_return_datetime( - self, *, request: dt.datetime, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: dt.datetime, + request_options: typing.Optional[RequestOptions] = None, ) -> dt.datetime: """ Parameters @@ -232,18 +273,28 @@ def get_and_return_datetime( ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/datetime", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/datetime", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(dt.datetime, parse_obj_as(type_=dt.datetime, object_=_response.json())) # type: ignore + return typing.cast( + dt.datetime, + parse_obj_as(type_=dt.datetime, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_and_return_date( - self, *, request: dt.date, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: dt.date, + request_options: typing.Optional[RequestOptions] = None, ) -> dt.date: """ Parameters @@ -274,18 +325,27 @@ def get_and_return_date( ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/date", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/date", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(dt.date, parse_obj_as(type_=dt.date, object_=_response.json())) # type: ignore + return typing.cast( + dt.date, parse_obj_as(type_=dt.date, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_and_return_uuid( - self, *, request: uuid.UUID, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: uuid.UUID, + request_options: typing.Optional[RequestOptions] = None, ) -> uuid.UUID: """ Parameters @@ -316,17 +376,25 @@ def get_and_return_uuid( ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/uuid", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/uuid", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(uuid.UUID, parse_obj_as(type_=uuid.UUID, object_=_response.json())) # type: ignore + return typing.cast( + uuid.UUID, parse_obj_as(type_=uuid.UUID, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def get_and_return_base_64(self, *, request: str, request_options: typing.Optional[RequestOptions] = None) -> str: + def get_and_return_base_64( + self, *, request: str, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -352,11 +420,17 @@ def get_and_return_base_64(self, *, request: str, request_options: typing.Option ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/base64", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/base64", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -403,17 +477,25 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/string", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/string", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - async def get_and_return_int(self, *, request: int, request_options: typing.Optional[RequestOptions] = None) -> int: + async def get_and_return_int( + self, *, request: int, request_options: typing.Optional[RequestOptions] = None + ) -> int: """ Parameters ---------- @@ -447,11 +529,17 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/integer", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/integer", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(int, parse_obj_as(type_=int, object_=_response.json())) # type: ignore + return typing.cast( + int, parse_obj_as(type_=int, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -493,11 +581,17 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/long", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/long", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(int, parse_obj_as(type_=int, object_=_response.json())) # type: ignore + return typing.cast( + int, parse_obj_as(type_=int, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -539,11 +633,17 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/double", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/double", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(float, parse_obj_as(type_=float, object_=_response.json())) # type: ignore + return typing.cast( + float, parse_obj_as(type_=float, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -585,18 +685,27 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/boolean", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/boolean", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_and_return_datetime( - self, *, request: dt.datetime, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: dt.datetime, + request_options: typing.Optional[RequestOptions] = None, ) -> dt.datetime: """ Parameters @@ -634,18 +743,28 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/datetime", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/datetime", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(dt.datetime, parse_obj_as(type_=dt.datetime, object_=_response.json())) # type: ignore + return typing.cast( + dt.datetime, + parse_obj_as(type_=dt.datetime, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_and_return_date( - self, *, request: dt.date, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: dt.date, + request_options: typing.Optional[RequestOptions] = None, ) -> dt.date: """ Parameters @@ -683,18 +802,27 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/date", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/date", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(dt.date, parse_obj_as(type_=dt.date, object_=_response.json())) # type: ignore + return typing.cast( + dt.date, parse_obj_as(type_=dt.date, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_and_return_uuid( - self, *, request: uuid.UUID, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: uuid.UUID, + request_options: typing.Optional[RequestOptions] = None, ) -> uuid.UUID: """ Parameters @@ -732,11 +860,17 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/uuid", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/uuid", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(uuid.UUID, parse_obj_as(type_=uuid.UUID, object_=_response.json())) # type: ignore + return typing.cast( + uuid.UUID, parse_obj_as(type_=uuid.UUID, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -778,11 +912,17 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/base64", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/base64", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/inline_request_params/src/seed/endpoints/union/client.py b/seed/python-sdk/exhaustive/inline_request_params/src/seed/endpoints/union/client.py index 77153587a27..f4c3d9312de 100644 --- a/seed/python-sdk/exhaustive/inline_request_params/src/seed/endpoints/union/client.py +++ b/seed/python-sdk/exhaustive/inline_request_params/src/seed/endpoints/union/client.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. import typing +from ...core.client_wrapper import SyncClientWrapper +from ...types.union.types.animal import Animal +from ...core.request_options import RequestOptions +from ...core.pydantic_utilities import parse_obj_as from json.decoder import JSONDecodeError - from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ...core.pydantic_utilities import parse_obj_as -from ...core.request_options import RequestOptions -from ...types.union.types.animal import Animal +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -18,7 +18,10 @@ def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper def get_and_return_union( - self, *, request: Animal, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: Animal, + request_options: typing.Optional[RequestOptions] = None, ) -> Animal: """ Parameters @@ -49,11 +52,17 @@ def get_and_return_union( ) """ _response = self._client_wrapper.httpx_client.request( - "union", method="POST", json=request, request_options=request_options, omit=OMIT + "union", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(Animal, parse_obj_as(type_=Animal, object_=_response.json())) # type: ignore + return typing.cast( + Animal, parse_obj_as(type_=Animal, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -65,7 +74,10 @@ def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper async def get_and_return_union( - self, *, request: Animal, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: Animal, + request_options: typing.Optional[RequestOptions] = None, ) -> Animal: """ Parameters @@ -104,11 +116,17 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "union", method="POST", json=request, request_options=request_options, omit=OMIT + "union", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(Animal, parse_obj_as(type_=Animal, object_=_response.json())) # type: ignore + return typing.cast( + Animal, parse_obj_as(type_=Animal, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/inline_request_params/src/seed/general_errors/types/bad_object_request_info.py b/seed/python-sdk/exhaustive/inline_request_params/src/seed/general_errors/types/bad_object_request_info.py index 7f03429e922..73c44b89531 100644 --- a/seed/python-sdk/exhaustive/inline_request_params/src/seed/general_errors/types/bad_object_request_info.py +++ b/seed/python-sdk/exhaustive/inline_request_params/src/seed/general_errors/types/bad_object_request_info.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class BadObjectRequestInfo(UniversalBaseModel): message: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/inline_request_params/src/seed/inlined_requests/client.py b/seed/python-sdk/exhaustive/inline_request_params/src/seed/inlined_requests/client.py index f7c46698eb9..39e0c8fe637 100644 --- a/seed/python-sdk/exhaustive/inline_request_params/src/seed/inlined_requests/client.py +++ b/seed/python-sdk/exhaustive/inline_request_params/src/seed/inlined_requests/client.py @@ -1,15 +1,15 @@ # This file was auto-generated by Fern from our API Definition. import typing -from json.decoder import JSONDecodeError - -from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.pydantic_utilities import parse_obj_as +from ..core.client_wrapper import SyncClientWrapper +from ..types.object.types.object_with_optional_field import ObjectWithOptionalField from ..core.request_options import RequestOptions +from ..core.pydantic_utilities import parse_obj_as from ..general_errors.errors.bad_request_body import BadRequestBody from ..general_errors.types.bad_object_request_info import BadObjectRequestInfo -from ..types.object.types.object_with_optional_field import ObjectWithOptionalField +from json.decoder import JSONDecodeError +from ..core.api_error import ApiError +from ..core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -25,7 +25,7 @@ def post_with_object_bodyand_response( string: str, integer: int, nested_object: ObjectWithOptionalField, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> ObjectWithOptionalField: """ POST with custom object in request body, response is an object @@ -86,16 +86,30 @@ def post_with_object_bodyand_response( _response = self._client_wrapper.httpx_client.request( "req-bodies/object", method="POST", - json={"string": string, "integer": integer, "NestedObject": nested_object}, + json={ + "string": string, + "integer": integer, + "NestedObject": nested_object, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore if _response.status_code == 400: raise BadRequestBody( - typing.cast(BadObjectRequestInfo, parse_obj_as(type_=BadObjectRequestInfo, object_=_response.json())) # type: ignore + typing.cast( + BadObjectRequestInfo, + parse_obj_as( + type_=BadObjectRequestInfo, object_=_response.json() + ), + ) # type: ignore ) _response_json = _response.json() except JSONDecodeError: @@ -113,7 +127,7 @@ async def post_with_object_bodyand_response( string: str, integer: int, nested_object: ObjectWithOptionalField, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> ObjectWithOptionalField: """ POST with custom object in request body, response is an object @@ -181,16 +195,30 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( "req-bodies/object", method="POST", - json={"string": string, "integer": integer, "NestedObject": nested_object}, + json={ + "string": string, + "integer": integer, + "NestedObject": nested_object, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore if _response.status_code == 400: raise BadRequestBody( - typing.cast(BadObjectRequestInfo, parse_obj_as(type_=BadObjectRequestInfo, object_=_response.json())) # type: ignore + typing.cast( + BadObjectRequestInfo, + parse_obj_as( + type_=BadObjectRequestInfo, object_=_response.json() + ), + ) # type: ignore ) _response_json = _response.json() except JSONDecodeError: diff --git a/seed/python-sdk/exhaustive/inline_request_params/src/seed/no_auth/client.py b/seed/python-sdk/exhaustive/inline_request_params/src/seed/no_auth/client.py index 3d203bcea34..e5590cde0df 100644 --- a/seed/python-sdk/exhaustive/inline_request_params/src/seed/no_auth/client.py +++ b/seed/python-sdk/exhaustive/inline_request_params/src/seed/no_auth/client.py @@ -1,14 +1,14 @@ # This file was auto-generated by Fern from our API Definition. import typing -from json.decoder import JSONDecodeError - -from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.pydantic_utilities import parse_obj_as +from ..core.client_wrapper import SyncClientWrapper from ..core.request_options import RequestOptions +from ..core.pydantic_utilities import parse_obj_as from ..general_errors.errors.bad_request_body import BadRequestBody from ..general_errors.types.bad_object_request_info import BadObjectRequestInfo +from json.decoder import JSONDecodeError +from ..core.api_error import ApiError +from ..core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -19,7 +19,10 @@ def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper def post_with_no_auth( - self, *, request: typing.Any, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Any, + request_options: typing.Optional[RequestOptions] = None, ) -> bool: """ POST request with no auth @@ -48,14 +51,25 @@ def post_with_no_auth( ) """ _response = self._client_wrapper.httpx_client.request( - "no-auth", method="POST", json=request, request_options=request_options, omit=OMIT + "no-auth", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore if _response.status_code == 400: raise BadRequestBody( - typing.cast(BadObjectRequestInfo, parse_obj_as(type_=BadObjectRequestInfo, object_=_response.json())) # type: ignore + typing.cast( + BadObjectRequestInfo, + parse_obj_as( + type_=BadObjectRequestInfo, object_=_response.json() + ), + ) # type: ignore ) _response_json = _response.json() except JSONDecodeError: @@ -68,7 +82,10 @@ def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper async def post_with_no_auth( - self, *, request: typing.Any, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Any, + request_options: typing.Optional[RequestOptions] = None, ) -> bool: """ POST request with no auth @@ -105,14 +122,25 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "no-auth", method="POST", json=request, request_options=request_options, omit=OMIT + "no-auth", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore if _response.status_code == 400: raise BadRequestBody( - typing.cast(BadObjectRequestInfo, parse_obj_as(type_=BadObjectRequestInfo, object_=_response.json())) # type: ignore + typing.cast( + BadObjectRequestInfo, + parse_obj_as( + type_=BadObjectRequestInfo, object_=_response.json() + ), + ) # type: ignore ) _response_json = _response.json() except JSONDecodeError: diff --git a/seed/python-sdk/exhaustive/inline_request_params/src/seed/no_req_body/client.py b/seed/python-sdk/exhaustive/inline_request_params/src/seed/no_req_body/client.py index 33fa0c77d27..5afdd703fdc 100644 --- a/seed/python-sdk/exhaustive/inline_request_params/src/seed/no_req_body/client.py +++ b/seed/python-sdk/exhaustive/inline_request_params/src/seed/no_req_body/client.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. +from ..core.client_wrapper import SyncClientWrapper import typing -from json.decoder import JSONDecodeError - -from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.pydantic_utilities import parse_obj_as from ..core.request_options import RequestOptions from ..types.object.types.object_with_optional_field import ObjectWithOptionalField +from ..core.pydantic_utilities import parse_obj_as +from json.decoder import JSONDecodeError +from ..core.api_error import ApiError +from ..core.client_wrapper import AsyncClientWrapper class NoReqBodyClient: @@ -38,17 +38,26 @@ def get_with_no_request_body( client.no_req_body.get_with_no_request_body() """ _response = self._client_wrapper.httpx_client.request( - "no-req-body", method="GET", request_options=request_options + "no-req-body", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def post_with_no_request_body(self, *, request_options: typing.Optional[RequestOptions] = None) -> str: + def post_with_no_request_body( + self, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -70,11 +79,15 @@ def post_with_no_request_body(self, *, request_options: typing.Optional[RequestO client.no_req_body.post_with_no_request_body() """ _response = self._client_wrapper.httpx_client.request( - "no-req-body", method="POST", request_options=request_options + "no-req-body", + method="POST", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -117,17 +130,26 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "no-req-body", method="GET", request_options=request_options + "no-req-body", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - async def post_with_no_request_body(self, *, request_options: typing.Optional[RequestOptions] = None) -> str: + async def post_with_no_request_body( + self, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -157,11 +179,15 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "no-req-body", method="POST", request_options=request_options + "no-req-body", + method="POST", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/inline_request_params/src/seed/req_with_headers/client.py b/seed/python-sdk/exhaustive/inline_request_params/src/seed/req_with_headers/client.py index 655402249e9..984428516e3 100644 --- a/seed/python-sdk/exhaustive/inline_request_params/src/seed/req_with_headers/client.py +++ b/seed/python-sdk/exhaustive/inline_request_params/src/seed/req_with_headers/client.py @@ -1,11 +1,11 @@ # This file was auto-generated by Fern from our API Definition. import typing +from ..core.client_wrapper import SyncClientWrapper +from ..core.request_options import RequestOptions from json.decoder import JSONDecodeError - from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.request_options import RequestOptions +from ..core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -21,7 +21,7 @@ def get_with_custom_header( x_test_service_header: str, x_test_endpoint_header: str, request: str, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ Parameters @@ -58,8 +58,12 @@ def get_with_custom_header( method="POST", json=request, headers={ - "X-TEST-SERVICE-HEADER": str(x_test_service_header) if x_test_service_header is not None else None, - "X-TEST-ENDPOINT-HEADER": str(x_test_endpoint_header) if x_test_endpoint_header is not None else None, + "X-TEST-SERVICE-HEADER": str(x_test_service_header) + if x_test_service_header is not None + else None, + "X-TEST-ENDPOINT-HEADER": str(x_test_endpoint_header) + if x_test_endpoint_header is not None + else None, }, request_options=request_options, omit=OMIT, @@ -83,7 +87,7 @@ async def get_with_custom_header( x_test_service_header: str, x_test_endpoint_header: str, request: str, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ Parameters @@ -128,8 +132,12 @@ async def main() -> None: method="POST", json=request, headers={ - "X-TEST-SERVICE-HEADER": str(x_test_service_header) if x_test_service_header is not None else None, - "X-TEST-ENDPOINT-HEADER": str(x_test_endpoint_header) if x_test_endpoint_header is not None else None, + "X-TEST-SERVICE-HEADER": str(x_test_service_header) + if x_test_service_header is not None + else None, + "X-TEST-ENDPOINT-HEADER": str(x_test_endpoint_header) + if x_test_endpoint_header is not None + else None, }, request_options=request_options, omit=OMIT, diff --git a/seed/python-sdk/exhaustive/inline_request_params/src/seed/types/enum/types/weather_report.py b/seed/python-sdk/exhaustive/inline_request_params/src/seed/types/enum/types/weather_report.py index 2d54965dc22..84017ef161d 100644 --- a/seed/python-sdk/exhaustive/inline_request_params/src/seed/types/enum/types/weather_report.py +++ b/seed/python-sdk/exhaustive/inline_request_params/src/seed/types/enum/types/weather_report.py @@ -2,4 +2,6 @@ import typing -WeatherReport = typing.Union[typing.Literal["SUNNY", "CLOUDY", "RAINING", "SNOWING"], typing.Any] +WeatherReport = typing.Union[ + typing.Literal["SUNNY", "CLOUDY", "RAINING", "SNOWING"], typing.Any +] diff --git a/seed/python-sdk/exhaustive/inline_request_params/src/seed/types/object/types/double_optional.py b/seed/python-sdk/exhaustive/inline_request_params/src/seed/types/object/types/double_optional.py index ddf165b13bd..ed236347357 100644 --- a/seed/python-sdk/exhaustive/inline_request_params/src/seed/types/object/types/double_optional.py +++ b/seed/python-sdk/exhaustive/inline_request_params/src/seed/types/object/types/double_optional.py @@ -1,18 +1,21 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .optional_alias import OptionalAlias +import pydantic +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class DoubleOptional(UniversalBaseModel): - optional_alias: typing.Optional[OptionalAlias] = pydantic.Field(alias="optionalAlias", default=None) + optional_alias: typing.Optional[OptionalAlias] = pydantic.Field( + alias="optionalAlias", default=None + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/inline_request_params/src/seed/types/object/types/nested_object_with_optional_field.py b/seed/python-sdk/exhaustive/inline_request_params/src/seed/types/object/types/nested_object_with_optional_field.py index 81669c0dd39..20a4d40a714 100644 --- a/seed/python-sdk/exhaustive/inline_request_params/src/seed/types/object/types/nested_object_with_optional_field.py +++ b/seed/python-sdk/exhaustive/inline_request_params/src/seed/types/object/types/nested_object_with_optional_field.py @@ -1,19 +1,22 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .object_with_optional_field import ObjectWithOptionalField +import pydantic +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class NestedObjectWithOptionalField(UniversalBaseModel): string: typing.Optional[str] = None - nested_object: typing.Optional[ObjectWithOptionalField] = pydantic.Field(alias="NestedObject", default=None) + nested_object: typing.Optional[ObjectWithOptionalField] = pydantic.Field( + alias="NestedObject", default=None + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/inline_request_params/src/seed/types/object/types/nested_object_with_required_field.py b/seed/python-sdk/exhaustive/inline_request_params/src/seed/types/object/types/nested_object_with_required_field.py index 1a621942c6c..a6ca8781190 100644 --- a/seed/python-sdk/exhaustive/inline_request_params/src/seed/types/object/types/nested_object_with_required_field.py +++ b/seed/python-sdk/exhaustive/inline_request_params/src/seed/types/object/types/nested_object_with_required_field.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import UniversalBaseModel from .object_with_optional_field import ObjectWithOptionalField +import pydantic +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class NestedObjectWithRequiredField(UniversalBaseModel): @@ -13,7 +12,9 @@ class NestedObjectWithRequiredField(UniversalBaseModel): nested_object: ObjectWithOptionalField = pydantic.Field(alias="NestedObject") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/inline_request_params/src/seed/types/object/types/object_with_map_of_map.py b/seed/python-sdk/exhaustive/inline_request_params/src/seed/types/object/types/object_with_map_of_map.py index 8883cc1d498..313cd25ceb8 100644 --- a/seed/python-sdk/exhaustive/inline_request_params/src/seed/types/object/types/object_with_map_of_map.py +++ b/seed/python-sdk/exhaustive/inline_request_params/src/seed/types/object/types/object_with_map_of_map.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class ObjectWithMapOfMap(UniversalBaseModel): map_: typing.Dict[str, typing.Dict[str, str]] = pydantic.Field(alias="map") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/inline_request_params/src/seed/types/object/types/object_with_optional_field.py b/seed/python-sdk/exhaustive/inline_request_params/src/seed/types/object/types/object_with_optional_field.py index 6aab170be0c..9131f0e91d7 100644 --- a/seed/python-sdk/exhaustive/inline_request_params/src/seed/types/object/types/object_with_optional_field.py +++ b/seed/python-sdk/exhaustive/inline_request_params/src/seed/types/object/types/object_with_optional_field.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. -import datetime as dt +from ....core.pydantic_utilities import UniversalBaseModel import typing -import uuid - import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +import datetime as dt +import uuid +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class ObjectWithOptionalField(UniversalBaseModel): @@ -23,13 +22,19 @@ class ObjectWithOptionalField(UniversalBaseModel): date: typing.Optional[dt.date] = None uuid_: typing.Optional[uuid.UUID] = pydantic.Field(alias="uuid", default=None) base_64: typing.Optional[str] = pydantic.Field(alias="base64", default=None) - list_: typing.Optional[typing.List[str]] = pydantic.Field(alias="list", default=None) + list_: typing.Optional[typing.List[str]] = pydantic.Field( + alias="list", default=None + ) set_: typing.Optional[typing.Set[str]] = pydantic.Field(alias="set", default=None) - map_: typing.Optional[typing.Dict[int, str]] = pydantic.Field(alias="map", default=None) + map_: typing.Optional[typing.Dict[int, str]] = pydantic.Field( + alias="map", default=None + ) bigint: typing.Optional[str] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/inline_request_params/src/seed/types/object/types/object_with_required_field.py b/seed/python-sdk/exhaustive/inline_request_params/src/seed/types/object/types/object_with_required_field.py index 61b98867984..24db26a3cf8 100644 --- a/seed/python-sdk/exhaustive/inline_request_params/src/seed/types/object/types/object_with_required_field.py +++ b/seed/python-sdk/exhaustive/inline_request_params/src/seed/types/object/types/object_with_required_field.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class ObjectWithRequiredField(UniversalBaseModel): string: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/inline_request_params/src/seed/types/union/types/animal.py b/seed/python-sdk/exhaustive/inline_request_params/src/seed/types/union/types/animal.py index 1ae43d1663e..84c71d2009a 100644 --- a/seed/python-sdk/exhaustive/inline_request_params/src/seed/types/union/types/animal.py +++ b/seed/python-sdk/exhaustive/inline_request_params/src/seed/types/union/types/animal.py @@ -1,12 +1,10 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ....core.pydantic_utilities import UniversalBaseModel import typing - import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class Animal_Dog(UniversalBaseModel): @@ -15,7 +13,9 @@ class Animal_Dog(UniversalBaseModel): likes_to_woof: bool = pydantic.Field(alias="likesToWoof") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: @@ -30,7 +30,9 @@ class Animal_Cat(UniversalBaseModel): likes_to_meow: bool = pydantic.Field(alias="likesToMeow") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/inline_request_params/src/seed/types/union/types/cat.py b/seed/python-sdk/exhaustive/inline_request_params/src/seed/types/union/types/cat.py index 61fc5527b1f..c59b78523c9 100644 --- a/seed/python-sdk/exhaustive/inline_request_params/src/seed/types/union/types/cat.py +++ b/seed/python-sdk/exhaustive/inline_request_params/src/seed/types/union/types/cat.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ....core.pydantic_utilities import UniversalBaseModel import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class Cat(UniversalBaseModel): @@ -12,7 +11,9 @@ class Cat(UniversalBaseModel): likes_to_meow: bool = pydantic.Field(alias="likesToMeow") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/inline_request_params/src/seed/types/union/types/dog.py b/seed/python-sdk/exhaustive/inline_request_params/src/seed/types/union/types/dog.py index c1ff5339dfe..e250c72edef 100644 --- a/seed/python-sdk/exhaustive/inline_request_params/src/seed/types/union/types/dog.py +++ b/seed/python-sdk/exhaustive/inline_request_params/src/seed/types/union/types/dog.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ....core.pydantic_utilities import UniversalBaseModel import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class Dog(UniversalBaseModel): @@ -12,7 +11,9 @@ class Dog(UniversalBaseModel): likes_to_woof: bool = pydantic.Field(alias="likesToWoof") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/inline_request_params/src/seed/version.py b/seed/python-sdk/exhaustive/inline_request_params/src/seed/version.py index 63ba170685a..ac44536abdb 100644 --- a/seed/python-sdk/exhaustive/inline_request_params/src/seed/version.py +++ b/seed/python-sdk/exhaustive/inline_request_params/src/seed/version.py @@ -1,4 +1,3 @@ - from importlib import metadata __version__ = metadata.version("fern_exhaustive") diff --git a/seed/python-sdk/exhaustive/inline_request_params/tests/conftest.py b/seed/python-sdk/exhaustive/inline_request_params/tests/conftest.py index b5b50383b94..86cb2b41af8 100644 --- a/seed/python-sdk/exhaustive/inline_request_params/tests/conftest.py +++ b/seed/python-sdk/exhaustive/inline_request_params/tests/conftest.py @@ -1,16 +1,22 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive import os - import pytest -from seed import AsyncSeedExhaustive, SeedExhaustive +from seed import AsyncSeedExhaustive @pytest.fixture def client() -> SeedExhaustive: - return SeedExhaustive(token=os.getenv("ENV_TOKEN", "token"), base_url=os.getenv("TESTS_BASE_URL", "base_url")) + return SeedExhaustive( + token=os.getenv("ENV_TOKEN", "token"), + base_url=os.getenv("TESTS_BASE_URL", "base_url"), + ) @pytest.fixture def async_client() -> AsyncSeedExhaustive: - return AsyncSeedExhaustive(token=os.getenv("ENV_TOKEN", "token"), base_url=os.getenv("TESTS_BASE_URL", "base_url")) + return AsyncSeedExhaustive( + token=os.getenv("ENV_TOKEN", "token"), + base_url=os.getenv("TESTS_BASE_URL", "base_url"), + ) diff --git a/seed/python-sdk/exhaustive/inline_request_params/tests/custom/test_client.py b/seed/python-sdk/exhaustive/inline_request_params/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/python-sdk/exhaustive/inline_request_params/tests/custom/test_client.py +++ b/seed/python-sdk/exhaustive/inline_request_params/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/python-sdk/exhaustive/inline_request_params/tests/endpoints/test_container.py b/seed/python-sdk/exhaustive/inline_request_params/tests/endpoints/test_container.py index 17d9d75240d..240f16f2a8c 100644 --- a/seed/python-sdk/exhaustive/inline_request_params/tests/endpoints/test_container.py +++ b/seed/python-sdk/exhaustive/inline_request_params/tests/endpoints/test_container.py @@ -1,91 +1,137 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing - -from seed import AsyncSeedExhaustive, SeedExhaustive -from seed.types.object import ObjectWithRequiredField - from ..utilities import validate_response +from seed.types.object import ObjectWithRequiredField -async def test_get_and_return_list_of_primitives(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_list_of_primitives( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = ["string"] expected_types: typing.Tuple[typing.Any, typing.Any] = ("list", {0: None}) - response = client.endpoints.container.get_and_return_list_of_primitives(request=["string"]) + response = client.endpoints.container.get_and_return_list_of_primitives( + request=["string"] + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.container.get_and_return_list_of_primitives(request=["string"]) + async_response = ( + await async_client.endpoints.container.get_and_return_list_of_primitives( + request=["string"] + ) + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_list_of_objects(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_list_of_objects( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = [{"string": "string"}] - expected_types: typing.Tuple[typing.Any, typing.Any] = ("list", {0: {"string": None}}) + expected_types: typing.Tuple[typing.Any, typing.Any] = ( + "list", + {0: {"string": None}}, + ) response = client.endpoints.container.get_and_return_list_of_objects( request=[ObjectWithRequiredField(string="string")] ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.container.get_and_return_list_of_objects( - request=[ObjectWithRequiredField(string="string")] + async_response = ( + await async_client.endpoints.container.get_and_return_list_of_objects( + request=[ObjectWithRequiredField(string="string")] + ) ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_set_of_primitives(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_set_of_primitives( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = ["string"] expected_types: typing.Tuple[typing.Any, typing.Any] = ("set", {0: None}) - response = client.endpoints.container.get_and_return_set_of_primitives(request={"string"}) + response = client.endpoints.container.get_and_return_set_of_primitives( + request={"string"} + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.container.get_and_return_set_of_primitives(request={"string"}) + async_response = ( + await async_client.endpoints.container.get_and_return_set_of_primitives( + request={"string"} + ) + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_set_of_objects(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_set_of_objects( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = [{"string": "string"}] - expected_types: typing.Tuple[typing.Any, typing.Any] = ("set", {0: {"string": None}}) + expected_types: typing.Tuple[typing.Any, typing.Any] = ( + "set", + {0: {"string": None}}, + ) response = client.endpoints.container.get_and_return_set_of_objects( request=[ObjectWithRequiredField(string="string")] ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.container.get_and_return_set_of_objects( - request=[ObjectWithRequiredField(string="string")] + async_response = ( + await async_client.endpoints.container.get_and_return_set_of_objects( + request=[ObjectWithRequiredField(string="string")] + ) ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_map_prim_to_prim(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_map_prim_to_prim( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = {"string": "string"} expected_types: typing.Tuple[typing.Any, typing.Any] = ("dict", {0: (None, None)}) - response = client.endpoints.container.get_and_return_map_prim_to_prim(request={"string": "string"}) + response = client.endpoints.container.get_and_return_map_prim_to_prim( + request={"string": "string"} + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.container.get_and_return_map_prim_to_prim( - request={"string": "string"} + async_response = ( + await async_client.endpoints.container.get_and_return_map_prim_to_prim( + request={"string": "string"} + ) ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_map_of_prim_to_object(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_map_of_prim_to_object( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = {"string": {"string": "string"}} - expected_types: typing.Tuple[typing.Any, typing.Any] = ("dict", {0: (None, {"string": None})}) + expected_types: typing.Tuple[typing.Any, typing.Any] = ( + "dict", + {0: (None, {"string": None})}, + ) response = client.endpoints.container.get_and_return_map_of_prim_to_object( request={"string": ObjectWithRequiredField(string="string")} ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.container.get_and_return_map_of_prim_to_object( - request={"string": ObjectWithRequiredField(string="string")} + async_response = ( + await async_client.endpoints.container.get_and_return_map_of_prim_to_object( + request={"string": ObjectWithRequiredField(string="string")} + ) ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_optional(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_optional( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = {"string": "string"} expected_types: typing.Any = {"string": None} - response = client.endpoints.container.get_and_return_optional(request=ObjectWithRequiredField(string="string")) + response = client.endpoints.container.get_and_return_optional( + request=ObjectWithRequiredField(string="string") + ) validate_response(response, expected_response, expected_types) async_response = await async_client.endpoints.container.get_and_return_optional( diff --git a/seed/python-sdk/exhaustive/inline_request_params/tests/endpoints/test_enum.py b/seed/python-sdk/exhaustive/inline_request_params/tests/endpoints/test_enum.py index 890aada5ce4..ca3fca30b5a 100644 --- a/seed/python-sdk/exhaustive/inline_request_params/tests/endpoints/test_enum.py +++ b/seed/python-sdk/exhaustive/inline_request_params/tests/endpoints/test_enum.py @@ -1,17 +1,20 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing - -from seed import AsyncSeedExhaustive, SeedExhaustive - from ..utilities import validate_response -async def test_get_and_return_enum(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_enum( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "SUNNY" expected_types: typing.Any = None response = client.endpoints.enum.get_and_return_enum(request="SUNNY") validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.enum.get_and_return_enum(request="SUNNY") + async_response = await async_client.endpoints.enum.get_and_return_enum( + request="SUNNY" + ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/exhaustive/inline_request_params/tests/endpoints/test_http_methods.py b/seed/python-sdk/exhaustive/inline_request_params/tests/endpoints/test_http_methods.py index dc01bafcf6f..77131fc6e8b 100644 --- a/seed/python-sdk/exhaustive/inline_request_params/tests/endpoints/test_http_methods.py +++ b/seed/python-sdk/exhaustive/inline_request_params/tests/endpoints/test_http_methods.py @@ -1,15 +1,16 @@ # This file was auto-generated by Fern from our API Definition. -import datetime +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing -import uuid - -from seed import AsyncSeedExhaustive, SeedExhaustive - from ..utilities import validate_response +import datetime +import uuid -async def test_test_get(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_test_get( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "string" expected_types: typing.Any = None response = client.endpoints.http_methods.test_get(id="string") @@ -19,7 +20,9 @@ async def test_test_get(client: SeedExhaustive, async_client: AsyncSeedExhaustiv validate_response(async_response, expected_response, expected_types) -async def test_test_post(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_test_post( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = { "string": "string", "integer": 1, @@ -53,11 +56,15 @@ async def test_test_post(client: SeedExhaustive, async_client: AsyncSeedExhausti response = client.endpoints.http_methods.test_post(string="string") validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.http_methods.test_post(string="string") + async_response = await async_client.endpoints.http_methods.test_post( + string="string" + ) validate_response(async_response, expected_response, expected_types) -async def test_test_put(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_test_put( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = { "string": "string", "integer": 1, @@ -91,11 +98,15 @@ async def test_test_put(client: SeedExhaustive, async_client: AsyncSeedExhaustiv response = client.endpoints.http_methods.test_put(id="string", string="string") validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.http_methods.test_put(id="string", string="string") + async_response = await async_client.endpoints.http_methods.test_put( + id="string", string="string" + ) validate_response(async_response, expected_response, expected_types) -async def test_test_patch(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_test_patch( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = { "string": "string", "integer": 1, @@ -163,7 +174,9 @@ async def test_test_patch(client: SeedExhaustive, async_client: AsyncSeedExhaust validate_response(async_response, expected_response, expected_types) -async def test_test_delete(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_test_delete( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = True expected_types: typing.Any = None response = client.endpoints.http_methods.test_delete(id="string") diff --git a/seed/python-sdk/exhaustive/inline_request_params/tests/endpoints/test_object.py b/seed/python-sdk/exhaustive/inline_request_params/tests/endpoints/test_object.py index a9098b6e9ef..c48c4332b22 100644 --- a/seed/python-sdk/exhaustive/inline_request_params/tests/endpoints/test_object.py +++ b/seed/python-sdk/exhaustive/inline_request_params/tests/endpoints/test_object.py @@ -1,16 +1,18 @@ # This file was auto-generated by Fern from our API Definition. -import datetime +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing +import datetime import uuid - -from seed import AsyncSeedExhaustive, SeedExhaustive -from seed.types.object import NestedObjectWithRequiredField, ObjectWithOptionalField - from ..utilities import validate_response +from seed.types.object import ObjectWithOptionalField +from seed.types.object import NestedObjectWithRequiredField -async def test_get_and_return_with_optional_field(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_with_optional_field( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = { "string": "string", "integer": 1, @@ -58,38 +60,54 @@ async def test_get_and_return_with_optional_field(client: SeedExhaustive, async_ ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.object.get_and_return_with_optional_field( - string="string", - integer=1, - long_=1000000, - double=1.1, - bool_=True, - datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), - date=datetime.date.fromisoformat("2023-01-15"), - uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), - base_64="SGVsbG8gd29ybGQh", - list_=["string"], - set_={"string"}, - map_={1: "string"}, - bigint="123456789123456789", + async_response = ( + await async_client.endpoints.object.get_and_return_with_optional_field( + string="string", + integer=1, + long_=1000000, + double=1.1, + bool_=True, + datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), + date=datetime.date.fromisoformat("2023-01-15"), + uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + base_64="SGVsbG8gd29ybGQh", + list_=["string"], + set_={"string"}, + map_={1: "string"}, + bigint="123456789123456789", + ) ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_with_required_field(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_with_required_field( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = {"string": "string"} expected_types: typing.Any = {"string": None} - response = client.endpoints.object.get_and_return_with_required_field(string="string") + response = client.endpoints.object.get_and_return_with_required_field( + string="string" + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.object.get_and_return_with_required_field(string="string") + async_response = ( + await async_client.endpoints.object.get_and_return_with_required_field( + string="string" + ) + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_with_map_of_map(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_with_map_of_map( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = {"map": {"string": {"string": "string"}}} - expected_types: typing.Any = {"map": ("dict", {0: (None, ("dict", {0: (None, None)}))})} - response = client.endpoints.object.get_and_return_with_map_of_map(map_={"string": {"string": "string"}}) + expected_types: typing.Any = { + "map": ("dict", {0: (None, ("dict", {0: (None, None)}))}) + } + response = client.endpoints.object.get_and_return_with_map_of_map( + map_={"string": {"string": "string"}} + ) validate_response(response, expected_response, expected_types) async_response = await async_client.endpoints.object.get_and_return_with_map_of_map( @@ -157,23 +175,25 @@ async def test_get_and_return_nested_with_optional_field( ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.object.get_and_return_nested_with_optional_field( - string="string", - nested_object=ObjectWithOptionalField( + async_response = ( + await async_client.endpoints.object.get_and_return_nested_with_optional_field( string="string", - integer=1, - long_=1000000, - double=1.1, - bool_=True, - datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), - date=datetime.date.fromisoformat("2023-01-15"), - uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), - base_64="SGVsbG8gd29ybGQh", - list_=["string"], - set_={"string"}, - map_={1: "string"}, - bigint="123456789123456789", - ), + nested_object=ObjectWithOptionalField( + string="string", + integer=1, + long_=1000000, + double=1.1, + bool_=True, + datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), + date=datetime.date.fromisoformat("2023-01-15"), + uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + base_64="SGVsbG8gd29ybGQh", + list_=["string"], + set_={"string"}, + map_={1: "string"}, + bigint="123456789123456789", + ), + ) ) validate_response(async_response, expected_response, expected_types) @@ -238,24 +258,26 @@ async def test_get_and_return_nested_with_required_field( ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.object.get_and_return_nested_with_required_field( - string_="string", - string="string", - nested_object=ObjectWithOptionalField( + async_response = ( + await async_client.endpoints.object.get_and_return_nested_with_required_field( + string_="string", string="string", - integer=1, - long_=1000000, - double=1.1, - bool_=True, - datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), - date=datetime.date.fromisoformat("2023-01-15"), - uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), - base_64="SGVsbG8gd29ybGQh", - list_=["string"], - set_={"string"}, - map_={1: "string"}, - bigint="123456789123456789", - ), + nested_object=ObjectWithOptionalField( + string="string", + integer=1, + long_=1000000, + double=1.1, + bool_=True, + datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), + date=datetime.date.fromisoformat("2023-01-15"), + uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + base_64="SGVsbG8gd29ybGQh", + list_=["string"], + set_={"string"}, + map_={1: "string"}, + bigint="123456789123456789", + ), + ) ) validate_response(async_response, expected_response, expected_types) @@ -299,27 +321,31 @@ async def test_get_and_return_nested_with_required_field_as_list( "bigint": None, }, } - response = client.endpoints.object.get_and_return_nested_with_required_field_as_list( - request=[ - NestedObjectWithRequiredField( - string="string", - nested_object=ObjectWithOptionalField( + response = ( + client.endpoints.object.get_and_return_nested_with_required_field_as_list( + request=[ + NestedObjectWithRequiredField( string="string", - integer=1, - long_=1000000, - double=1.1, - bool_=True, - datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), - date=datetime.date.fromisoformat("2023-01-15"), - uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), - base_64="SGVsbG8gd29ybGQh", - list_=["string"], - set_={"string"}, - map_={1: "string"}, - bigint="123456789123456789", - ), - ) - ] + nested_object=ObjectWithOptionalField( + string="string", + integer=1, + long_=1000000, + double=1.1, + bool_=True, + datetime=datetime.datetime.fromisoformat( + "2024-01-15 09:30:00+00:00" + ), + date=datetime.date.fromisoformat("2023-01-15"), + uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + base_64="SGVsbG8gd29ybGQh", + list_=["string"], + set_={"string"}, + map_={1: "string"}, + bigint="123456789123456789", + ), + ) + ] + ) ) validate_response(response, expected_response, expected_types) @@ -333,7 +359,9 @@ async def test_get_and_return_nested_with_required_field_as_list( long_=1000000, double=1.1, bool_=True, - datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), + datetime=datetime.datetime.fromisoformat( + "2024-01-15 09:30:00+00:00" + ), date=datetime.date.fromisoformat("2023-01-15"), uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), base_64="SGVsbG8gd29ybGQh", diff --git a/seed/python-sdk/exhaustive/inline_request_params/tests/endpoints/test_params.py b/seed/python-sdk/exhaustive/inline_request_params/tests/endpoints/test_params.py index 163d7b9161d..d8ffb00c0a0 100644 --- a/seed/python-sdk/exhaustive/inline_request_params/tests/endpoints/test_params.py +++ b/seed/python-sdk/exhaustive/inline_request_params/tests/endpoints/test_params.py @@ -1,13 +1,14 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing - -from seed import AsyncSeedExhaustive, SeedExhaustive - from ..utilities import validate_response -async def test_get_with_path(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_with_path( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "string" expected_types: typing.Any = None response = client.endpoints.params.get_with_path(param="string") @@ -17,32 +18,63 @@ async def test_get_with_path(client: SeedExhaustive, async_client: AsyncSeedExha validate_response(async_response, expected_response, expected_types) -async def test_get_with_query(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_with_query( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: # Type ignore to avoid mypy complaining about the function not being meant to return a value assert client.endpoints.params.get_with_query(query="string", number=1) is None # type: ignore[func-returns-value] - assert await async_client.endpoints.params.get_with_query(query="string", number=1) is None # type: ignore[func-returns-value] + assert ( + await async_client.endpoints.params.get_with_query(query="string", number=1) + is None + ) # type: ignore[func-returns-value] -async def test_get_with_allow_multiple_query(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_with_allow_multiple_query( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: # Type ignore to avoid mypy complaining about the function not being meant to return a value - assert client.endpoints.params.get_with_allow_multiple_query(query="string", numer=1) is None # type: ignore[func-returns-value] - - assert await async_client.endpoints.params.get_with_allow_multiple_query(query="string", numer=1) is None # type: ignore[func-returns-value] - - -async def test_get_with_path_and_query(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: + assert ( + client.endpoints.params.get_with_allow_multiple_query(query="string", numer=1) + is None + ) # type: ignore[func-returns-value] + + assert ( + await async_client.endpoints.params.get_with_allow_multiple_query( + query="string", numer=1 + ) + is None + ) # type: ignore[func-returns-value] + + +async def test_get_with_path_and_query( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: # Type ignore to avoid mypy complaining about the function not being meant to return a value - assert client.endpoints.params.get_with_path_and_query(param="string", query="string") is None # type: ignore[func-returns-value] - - assert await async_client.endpoints.params.get_with_path_and_query(param="string", query="string") is None # type: ignore[func-returns-value] - - -async def test_modify_with_path(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: + assert ( + client.endpoints.params.get_with_path_and_query(param="string", query="string") + is None + ) # type: ignore[func-returns-value] + + assert ( + await async_client.endpoints.params.get_with_path_and_query( + param="string", query="string" + ) + is None + ) # type: ignore[func-returns-value] + + +async def test_modify_with_path( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "string" expected_types: typing.Any = None - response = client.endpoints.params.modify_with_path(param="string", request="string") + response = client.endpoints.params.modify_with_path( + param="string", request="string" + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.params.modify_with_path(param="string", request="string") + async_response = await async_client.endpoints.params.modify_with_path( + param="string", request="string" + ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/exhaustive/inline_request_params/tests/endpoints/test_primitive.py b/seed/python-sdk/exhaustive/inline_request_params/tests/endpoints/test_primitive.py index ba3bc7e29e5..26cbcf45d2f 100644 --- a/seed/python-sdk/exhaustive/inline_request_params/tests/endpoints/test_primitive.py +++ b/seed/python-sdk/exhaustive/inline_request_params/tests/endpoints/test_primitive.py @@ -1,65 +1,86 @@ # This file was auto-generated by Fern from our API Definition. -import datetime +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing -import uuid - -from seed import AsyncSeedExhaustive, SeedExhaustive - from ..utilities import validate_response +import datetime +import uuid -async def test_get_and_return_string(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_string( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "string" expected_types: typing.Any = None response = client.endpoints.primitive.get_and_return_string(request="string") validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.primitive.get_and_return_string(request="string") + async_response = await async_client.endpoints.primitive.get_and_return_string( + request="string" + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_int(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_int( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = 1 expected_types: typing.Any = "integer" response = client.endpoints.primitive.get_and_return_int(request=1) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.primitive.get_and_return_int(request=1) + async_response = await async_client.endpoints.primitive.get_and_return_int( + request=1 + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_long(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_long( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = 1000000 expected_types: typing.Any = None response = client.endpoints.primitive.get_and_return_long(request=1000000) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.primitive.get_and_return_long(request=1000000) + async_response = await async_client.endpoints.primitive.get_and_return_long( + request=1000000 + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_double(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_double( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = 1.1 expected_types: typing.Any = None response = client.endpoints.primitive.get_and_return_double(request=1.1) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.primitive.get_and_return_double(request=1.1) + async_response = await async_client.endpoints.primitive.get_and_return_double( + request=1.1 + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_bool(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_bool( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = True expected_types: typing.Any = None response = client.endpoints.primitive.get_and_return_bool(request=True) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.primitive.get_and_return_bool(request=True) + async_response = await async_client.endpoints.primitive.get_and_return_bool( + request=True + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_datetime(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_datetime( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "2024-01-15T09:30:00Z" expected_types: typing.Any = "datetime" response = client.endpoints.primitive.get_and_return_datetime( @@ -73,10 +94,14 @@ async def test_get_and_return_datetime(client: SeedExhaustive, async_client: Asy validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_date(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_date( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "2023-01-15" expected_types: typing.Any = "date" - response = client.endpoints.primitive.get_and_return_date(request=datetime.date.fromisoformat("2023-01-15")) + response = client.endpoints.primitive.get_and_return_date( + request=datetime.date.fromisoformat("2023-01-15") + ) validate_response(response, expected_response, expected_types) async_response = await async_client.endpoints.primitive.get_and_return_date( @@ -85,10 +110,14 @@ async def test_get_and_return_date(client: SeedExhaustive, async_client: AsyncSe validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_uuid(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_uuid( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32" expected_types: typing.Any = "uuid" - response = client.endpoints.primitive.get_and_return_uuid(request=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32")) + response = client.endpoints.primitive.get_and_return_uuid( + request=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32") + ) validate_response(response, expected_response, expected_types) async_response = await async_client.endpoints.primitive.get_and_return_uuid( @@ -97,11 +126,17 @@ async def test_get_and_return_uuid(client: SeedExhaustive, async_client: AsyncSe validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_base_64(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_base_64( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "SGVsbG8gd29ybGQh" expected_types: typing.Any = None - response = client.endpoints.primitive.get_and_return_base_64(request="SGVsbG8gd29ybGQh") + response = client.endpoints.primitive.get_and_return_base_64( + request="SGVsbG8gd29ybGQh" + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.primitive.get_and_return_base_64(request="SGVsbG8gd29ybGQh") + async_response = await async_client.endpoints.primitive.get_and_return_base_64( + request="SGVsbG8gd29ybGQh" + ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/exhaustive/inline_request_params/tests/endpoints/test_union.py b/seed/python-sdk/exhaustive/inline_request_params/tests/endpoints/test_union.py index 14e34c2a6df..ceb84928cd9 100644 --- a/seed/python-sdk/exhaustive/inline_request_params/tests/endpoints/test_union.py +++ b/seed/python-sdk/exhaustive/inline_request_params/tests/endpoints/test_union.py @@ -1,17 +1,24 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing - -from seed import AsyncSeedExhaustive, SeedExhaustive from seed.types.union import Animal_Dog - from ..utilities import validate_response -async def test_get_and_return_union(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: - expected_response: typing.Any = {"animal": "dog", "name": "string", "likesToWoof": True} +async def test_get_and_return_union( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: + expected_response: typing.Any = { + "animal": "dog", + "name": "string", + "likesToWoof": True, + } expected_types: typing.Any = "no_validate" - response = client.endpoints.union.get_and_return_union(request=Animal_Dog(name="string", likes_to_woof=True)) + response = client.endpoints.union.get_and_return_union( + request=Animal_Dog(name="string", likes_to_woof=True) + ) validate_response(response, expected_response, expected_types) async_response = await async_client.endpoints.union.get_and_return_union( diff --git a/seed/python-sdk/exhaustive/inline_request_params/tests/test_inlined_requests.py b/seed/python-sdk/exhaustive/inline_request_params/tests/test_inlined_requests.py index bb9390d3845..03f46b31cc9 100644 --- a/seed/python-sdk/exhaustive/inline_request_params/tests/test_inlined_requests.py +++ b/seed/python-sdk/exhaustive/inline_request_params/tests/test_inlined_requests.py @@ -1,16 +1,17 @@ # This file was auto-generated by Fern from our API Definition. -import datetime +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing -import uuid - -from seed import AsyncSeedExhaustive, SeedExhaustive from seed.types.object import ObjectWithOptionalField - +import datetime +import uuid from .utilities import validate_response -async def test_post_with_object_bodyand_response(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_post_with_object_bodyand_response( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = { "string": "string", "integer": 1, @@ -62,23 +63,25 @@ async def test_post_with_object_bodyand_response(client: SeedExhaustive, async_c ) validate_response(response, expected_response, expected_types) - async_response = await async_client.inlined_requests.post_with_object_bodyand_response( - string="string", - integer=1, - nested_object=ObjectWithOptionalField( + async_response = ( + await async_client.inlined_requests.post_with_object_bodyand_response( string="string", integer=1, - long_=1000000, - double=1.1, - bool_=True, - datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), - date=datetime.date.fromisoformat("2023-01-15"), - uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), - base_64="SGVsbG8gd29ybGQh", - list_=["string"], - set_={"string"}, - map_={1: "string"}, - bigint="123456789123456789", - ), + nested_object=ObjectWithOptionalField( + string="string", + integer=1, + long_=1000000, + double=1.1, + bool_=True, + datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), + date=datetime.date.fromisoformat("2023-01-15"), + uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + base_64="SGVsbG8gd29ybGQh", + list_=["string"], + set_={"string"}, + map_={1: "string"}, + bigint="123456789123456789", + ), + ) ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/exhaustive/inline_request_params/tests/test_no_auth.py b/seed/python-sdk/exhaustive/inline_request_params/tests/test_no_auth.py index 3328661bb48..fc475f4b6fb 100644 --- a/seed/python-sdk/exhaustive/inline_request_params/tests/test_no_auth.py +++ b/seed/python-sdk/exhaustive/inline_request_params/tests/test_no_auth.py @@ -1,17 +1,20 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing - -from seed import AsyncSeedExhaustive, SeedExhaustive - from .utilities import validate_response -async def test_post_with_no_auth(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_post_with_no_auth( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = True expected_types: typing.Any = None response = client.no_auth.post_with_no_auth(request={"key": "value"}) validate_response(response, expected_response, expected_types) - async_response = await async_client.no_auth.post_with_no_auth(request={"key": "value"}) + async_response = await async_client.no_auth.post_with_no_auth( + request={"key": "value"} + ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/exhaustive/inline_request_params/tests/test_no_req_body.py b/seed/python-sdk/exhaustive/inline_request_params/tests/test_no_req_body.py index 73abac9d2d8..07061a0e99e 100644 --- a/seed/python-sdk/exhaustive/inline_request_params/tests/test_no_req_body.py +++ b/seed/python-sdk/exhaustive/inline_request_params/tests/test_no_req_body.py @@ -1,13 +1,14 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing - -from seed import AsyncSeedExhaustive, SeedExhaustive - from .utilities import validate_response -async def test_get_with_no_request_body(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_with_no_request_body( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = { "string": "string", "integer": 1, @@ -45,7 +46,9 @@ async def test_get_with_no_request_body(client: SeedExhaustive, async_client: As validate_response(async_response, expected_response, expected_types) -async def test_post_with_no_request_body(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_post_with_no_request_body( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "string" expected_types: typing.Any = None response = client.no_req_body.post_with_no_request_body() diff --git a/seed/python-sdk/exhaustive/inline_request_params/tests/test_req_with_headers.py b/seed/python-sdk/exhaustive/inline_request_params/tests/test_req_with_headers.py index bba3b5b5507..75ce9d00c03 100644 --- a/seed/python-sdk/exhaustive/inline_request_params/tests/test_req_with_headers.py +++ b/seed/python-sdk/exhaustive/inline_request_params/tests/test_req_with_headers.py @@ -1,10 +1,27 @@ # This file was auto-generated by Fern from our API Definition. -from seed import AsyncSeedExhaustive, SeedExhaustive +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive -async def test_get_with_custom_header(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_with_custom_header( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: # Type ignore to avoid mypy complaining about the function not being meant to return a value - assert client.req_with_headers.get_with_custom_header(x_test_service_header="string", x_test_endpoint_header="string", request="string") is None # type: ignore[func-returns-value] + assert ( + client.req_with_headers.get_with_custom_header( + x_test_service_header="string", + x_test_endpoint_header="string", + request="string", + ) + is None + ) # type: ignore[func-returns-value] - assert await async_client.req_with_headers.get_with_custom_header(x_test_service_header="string", x_test_endpoint_header="string", request="string") is None # type: ignore[func-returns-value] + assert ( + await async_client.req_with_headers.get_with_custom_header( + x_test_service_header="string", + x_test_endpoint_header="string", + request="string", + ) + is None + ) # type: ignore[func-returns-value] diff --git a/seed/python-sdk/exhaustive/inline_request_params/tests/utilities.py b/seed/python-sdk/exhaustive/inline_request_params/tests/utilities.py index 13da208eb3a..e8f4472564c 100644 --- a/seed/python-sdk/exhaustive/inline_request_params/tests/utilities.py +++ b/seed/python-sdk/exhaustive/inline_request_params/tests/utilities.py @@ -3,11 +3,14 @@ import typing import uuid -import pydantic from dateutil import parser +import pydantic + -def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> typing.Any: +def cast_field( + json_expectation: typing.Any, type_expectation: typing.Any +) -> typing.Any: # Cast these specific types which come through as string and expect our # models to cast to the correct type. if type_expectation == "uuid": @@ -25,7 +28,9 @@ def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> ty return json_expectation -def validate_field(response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any) -> None: +def validate_field( + response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectation == "no_validate": return @@ -44,7 +49,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(entry_expectation, dict): is_container_of_complex_type = True validate_response( - response=response[idx], json_expectation=ex, type_expectations=entry_expectation + response=response[idx], + json_expectation=ex, + type_expectations=entry_expectation, ) else: cast_json_expectation.append(cast_field(ex, entry_expectation)) @@ -56,7 +63,10 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # if any of the values of the set have a type_expectation of a dict, we're assuming it's a pydantic # model and keeping it a list. if container_expectation != "set" or not any( - map(lambda value: isinstance(value, dict), list(contents_expectation.values())) + map( + lambda value: isinstance(value, dict), + list(contents_expectation.values()), + ) ): json_expectation = cast_field(json_expectation, container_expectation) elif isinstance(type_expectation, tuple): @@ -65,9 +75,15 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(contents_expectation, dict): json_expectation = { cast_field( - key, contents_expectation.get(idx)[0] if contents_expectation.get(idx) is not None else None # type: ignore + key, + contents_expectation.get(idx)[0] + if contents_expectation.get(idx) is not None + else None, # type: ignore ): cast_field( - value, contents_expectation.get(idx)[1] if contents_expectation.get(idx) is not None else None # type: ignore + value, + contents_expectation.get(idx)[1] + if contents_expectation.get(idx) is not None + else None, # type: ignore ) for idx, (key, value) in enumerate(json_expectation.items()) } @@ -86,7 +102,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # Arg type_expectations is a deeply nested structure that matches the response, but with the values replaced with the expected types -def validate_response(response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any) -> None: +def validate_response( + response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectations == "no_validate": return @@ -96,11 +114,17 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e and not isinstance(response, dict) and not issubclass(type(response), pydantic.BaseModel) ): - validate_field(response=response, json_expectation=json_expectation, type_expectation=type_expectations) + validate_field( + response=response, + json_expectation=json_expectation, + type_expectation=type_expectations, + ) return if isinstance(response, list): - assert len(response) == len(json_expectation), "Length mismatch, expected: {0}, Actual: {1}".format( + assert len(response) == len( + json_expectation + ), "Length mismatch, expected: {0}, Actual: {1}".format( len(response), len(json_expectation) ) content_expectation = type_expectations @@ -108,7 +132,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e content_expectation = type_expectations[1] for idx, item in enumerate(response): validate_response( - response=item, json_expectation=json_expectation[idx], type_expectations=content_expectation[idx] + response=item, + json_expectation=json_expectation[idx], + type_expectations=content_expectation[idx], ) else: response_json = response @@ -116,7 +142,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e response_json = response.dict(by_alias=True) for key, value in json_expectation.items(): - assert key in response_json, "Field {0} not found within the response object: {1}".format( + assert ( + key in response_json + ), "Field {0} not found within the response object: {1}".format( key, response_json ) @@ -128,11 +156,19 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e # Otherwise, we're just validating a single field that's a pydantic model. if isinstance(value, dict) and not isinstance(type_expectation, tuple): validate_response( - response=response_json[key], json_expectation=value, type_expectations=type_expectation + response=response_json[key], + json_expectation=value, + type_expectations=type_expectation, ) else: - validate_field(response=response_json[key], json_expectation=value, type_expectation=type_expectation) + validate_field( + response=response_json[key], + json_expectation=value, + type_expectation=type_expectation, + ) # Ensure there are no additional fields here either del response_json[key] - assert len(response_json) == 0, "Additional fields found, expected None: {0}".format(response_json) + assert ( + len(response_json) == 0 + ), "Additional fields found, expected None: {0}".format(response_json) diff --git a/seed/python-sdk/exhaustive/inline_request_params/tests/utils/assets/models/__init__.py b/seed/python-sdk/exhaustive/inline_request_params/tests/utils/assets/models/__init__.py index 2cf01263529..3a1c852e71e 100644 --- a/seed/python-sdk/exhaustive/inline_request_params/tests/utils/assets/models/__init__.py +++ b/seed/python-sdk/exhaustive/inline_request_params/tests/utils/assets/models/__init__.py @@ -5,7 +5,7 @@ from .circle import CircleParams from .object_with_defaults import ObjectWithDefaultsParams from .object_with_optional_field import ObjectWithOptionalFieldParams -from .shape import Shape_CircleParams, Shape_SquareParams, ShapeParams +from .shape import ShapeParams, Shape_CircleParams, Shape_SquareParams from .square import SquareParams from .undiscriminated_shape import UndiscriminatedShapeParams diff --git a/seed/python-sdk/exhaustive/inline_request_params/tests/utils/assets/models/circle.py b/seed/python-sdk/exhaustive/inline_request_params/tests/utils/assets/models/circle.py index af7a1bf8a8e..253f12d38b3 100644 --- a/seed/python-sdk/exhaustive/inline_request_params/tests/utils/assets/models/circle.py +++ b/seed/python-sdk/exhaustive/inline_request_params/tests/utils/assets/models/circle.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class CircleParams(typing_extensions.TypedDict): - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] diff --git a/seed/python-sdk/exhaustive/inline_request_params/tests/utils/assets/models/object_with_optional_field.py b/seed/python-sdk/exhaustive/inline_request_params/tests/utils/assets/models/object_with_optional_field.py index 3ad93d5f305..ebe7dc80547 100644 --- a/seed/python-sdk/exhaustive/inline_request_params/tests/utils/assets/models/object_with_optional_field.py +++ b/seed/python-sdk/exhaustive/inline_request_params/tests/utils/assets/models/object_with_optional_field.py @@ -7,8 +7,8 @@ import uuid import typing_extensions -from seed.core.serialization import FieldMetadata +from seed.core.serialization import FieldMetadata from .color import Color from .shape import ShapeParams from .undiscriminated_shape import UndiscriminatedShapeParams @@ -18,16 +18,30 @@ class ObjectWithOptionalFieldParams(typing_extensions.TypedDict): literal: typing.Literal["lit_one"] string: typing_extensions.NotRequired[str] integer: typing_extensions.NotRequired[int] - long_: typing_extensions.NotRequired[typing_extensions.Annotated[int, FieldMetadata(alias="long")]] + long_: typing_extensions.NotRequired[ + typing_extensions.Annotated[int, FieldMetadata(alias="long")] + ] double: typing_extensions.NotRequired[float] - bool_: typing_extensions.NotRequired[typing_extensions.Annotated[bool, FieldMetadata(alias="bool")]] + bool_: typing_extensions.NotRequired[ + typing_extensions.Annotated[bool, FieldMetadata(alias="bool")] + ] datetime: typing_extensions.NotRequired[dt.datetime] date: typing_extensions.NotRequired[dt.date] - uuid_: typing_extensions.NotRequired[typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")]] - base_64: typing_extensions.NotRequired[typing_extensions.Annotated[str, FieldMetadata(alias="base64")]] - list_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")]] - set_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")]] - map_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")]] + uuid_: typing_extensions.NotRequired[ + typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")] + ] + base_64: typing_extensions.NotRequired[ + typing_extensions.Annotated[str, FieldMetadata(alias="base64")] + ] + list_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")] + ] + set_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")] + ] + map_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")] + ] enum: typing_extensions.NotRequired[Color] union: typing_extensions.NotRequired[ShapeParams] second_union: typing_extensions.NotRequired[ShapeParams] diff --git a/seed/python-sdk/exhaustive/inline_request_params/tests/utils/assets/models/shape.py b/seed/python-sdk/exhaustive/inline_request_params/tests/utils/assets/models/shape.py index 2c33c877951..816ffc51bdc 100644 --- a/seed/python-sdk/exhaustive/inline_request_params/tests/utils/assets/models/shape.py +++ b/seed/python-sdk/exhaustive/inline_request_params/tests/utils/assets/models/shape.py @@ -7,6 +7,7 @@ import typing import typing_extensions + from seed.core.serialization import FieldMetadata @@ -15,13 +16,21 @@ class Base(typing_extensions.TypedDict): class Shape_CircleParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["circle"], FieldMetadata(alias="shapeType")] - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["circle"], FieldMetadata(alias="shapeType") + ] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] class Shape_SquareParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["square"], FieldMetadata(alias="shapeType")] - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["square"], FieldMetadata(alias="shapeType") + ] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] ShapeParams = typing.Union[Shape_CircleParams, Shape_SquareParams] diff --git a/seed/python-sdk/exhaustive/inline_request_params/tests/utils/assets/models/square.py b/seed/python-sdk/exhaustive/inline_request_params/tests/utils/assets/models/square.py index b9b7dd319bc..bcf08a723c5 100644 --- a/seed/python-sdk/exhaustive/inline_request_params/tests/utils/assets/models/square.py +++ b/seed/python-sdk/exhaustive/inline_request_params/tests/utils/assets/models/square.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class SquareParams(typing_extensions.TypedDict): - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] diff --git a/seed/python-sdk/exhaustive/inline_request_params/tests/utils/test_http_client.py b/seed/python-sdk/exhaustive/inline_request_params/tests/utils/test_http_client.py index edd11ca7afb..f5a874a75f3 100644 --- a/seed/python-sdk/exhaustive/inline_request_params/tests/utils/test_http_client.py +++ b/seed/python-sdk/exhaustive/inline_request_params/tests/utils/test_http_client.py @@ -9,12 +9,17 @@ def get_request_options() -> RequestOptions: def test_get_json_request_body() -> None: - json_body, data_body = get_request_body(json={"hello": "world"}, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json={"hello": "world"}, data=None, request_options=None, omit=None + ) assert json_body == {"hello": "world"} assert data_body is None json_body_extras, data_body_extras = get_request_body( - json={"goodbye": "world"}, data=None, request_options=get_request_options(), omit=None + json={"goodbye": "world"}, + data=None, + request_options=get_request_options(), + omit=None, ) assert json_body_extras == {"goodbye": "world", "see you": "later"} @@ -22,12 +27,17 @@ def test_get_json_request_body() -> None: def test_get_files_request_body() -> None: - json_body, data_body = get_request_body(json=None, data={"hello": "world"}, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data={"hello": "world"}, request_options=None, omit=None + ) assert data_body == {"hello": "world"} assert json_body is None json_body_extras, data_body_extras = get_request_body( - json=None, data={"goodbye": "world"}, request_options=get_request_options(), omit=None + json=None, + data={"goodbye": "world"}, + request_options=get_request_options(), + omit=None, ) assert data_body_extras == {"goodbye": "world", "see you": "later"} @@ -35,7 +45,9 @@ def test_get_files_request_body() -> None: def test_get_none_request_body() -> None: - json_body, data_body = get_request_body(json=None, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data=None, request_options=None, omit=None + ) assert data_body is None assert json_body is None diff --git a/seed/python-sdk/exhaustive/inline_request_params/tests/utils/test_query_encoding.py b/seed/python-sdk/exhaustive/inline_request_params/tests/utils/test_query_encoding.py index 247e1551b46..fbc8f402167 100644 --- a/seed/python-sdk/exhaustive/inline_request_params/tests/utils/test_query_encoding.py +++ b/seed/python-sdk/exhaustive/inline_request_params/tests/utils/test_query_encoding.py @@ -4,9 +4,15 @@ def test_query_encoding() -> None: - assert encode_query({"hello world": "hello world"}) == {"hello world": "hello world"} - assert encode_query({"hello_world": {"hello": "world"}}) == {"hello_world[hello]": "world"} - assert encode_query({"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"}) == { + assert encode_query({"hello world": "hello world"}) == { + "hello world": "hello world" + } + assert encode_query({"hello_world": {"hello": "world"}}) == { + "hello_world[hello]": "world" + } + assert encode_query( + {"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"} + ) == { "hello_world[hello][world]": "today", "hello_world[test]": "this", "hi": "there", diff --git a/seed/python-sdk/exhaustive/inline_request_params/tests/utils/test_serialization.py b/seed/python-sdk/exhaustive/inline_request_params/tests/utils/test_serialization.py index 58b1ed66e6d..5ca956916dd 100644 --- a/seed/python-sdk/exhaustive/inline_request_params/tests/utils/test_serialization.py +++ b/seed/python-sdk/exhaustive/inline_request_params/tests/utils/test_serialization.py @@ -1,10 +1,12 @@ # This file was auto-generated by Fern from our API Definition. -from typing import Any, List +from typing import List, Any -from seed.core.serialization import convert_and_respect_annotation_metadata +from seed.core.serialization import ( + convert_and_respect_annotation_metadata, +) +from .assets.models import ShapeParams, ObjectWithOptionalFieldParams -from .assets.models import ObjectWithOptionalFieldParams, ShapeParams UNION_TEST: ShapeParams = {"radius_measurement": 1.0, "shape_type": "circle", "id": "1"} UNION_TEST_CONVERTED = {"shapeType": "circle", "radiusMeasurement": 1.0, "id": "1"} @@ -18,20 +20,54 @@ def test_convert_and_respect_annotation_metadata() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) - assert converted == {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"} + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) + assert converted == { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + } def test_convert_and_respect_annotation_metadata_in_list() -> None: data: List[ObjectWithOptionalFieldParams] = [ - {"string": "string", "long_": 12345, "bool_": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long_": 67890, "list_": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long_": 12345, + "bool_": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long_": 67890, + "list_": [], + "literal": "lit_one", + "any": "any", + }, ] - converted = convert_and_respect_annotation_metadata(object_=data, annotation=List[ObjectWithOptionalFieldParams]) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=List[ObjectWithOptionalFieldParams] + ) assert converted == [ - {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long": 67890, "list": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long": 67890, + "list": [], + "literal": "lit_one", + "any": "any", + }, ] @@ -43,7 +79,9 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) assert converted == { "string": "string", @@ -55,12 +93,16 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: def test_convert_and_respect_annotation_metadata_in_union() -> None: - converted = convert_and_respect_annotation_metadata(object_=UNION_TEST, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=UNION_TEST, annotation=ShapeParams + ) assert converted == UNION_TEST_CONVERTED def test_convert_and_respect_annotation_metadata_with_empty_object() -> None: data: Any = {} - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ShapeParams + ) assert converted == data diff --git a/seed/python-sdk/exhaustive/no-custom-config/pyproject.toml b/seed/python-sdk/exhaustive/no-custom-config/pyproject.toml index c6cd3a2b7b9..fc29a237334 100644 --- a/seed/python-sdk/exhaustive/no-custom-config/pyproject.toml +++ b/seed/python-sdk/exhaustive/no-custom-config/pyproject.toml @@ -43,6 +43,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/python-sdk/exhaustive/no-custom-config/src/seed/__init__.py b/seed/python-sdk/exhaustive/no-custom-config/src/seed/__init__.py index eb56b0ce275..dc1ef03a650 100644 --- a/seed/python-sdk/exhaustive/no-custom-config/src/seed/__init__.py +++ b/seed/python-sdk/exhaustive/no-custom-config/src/seed/__init__.py @@ -1,6 +1,14 @@ # This file was auto-generated by Fern from our API Definition. -from . import endpoints, general_errors, inlined_requests, no_auth, no_req_body, req_with_headers, types +from . import ( + endpoints, + general_errors, + inlined_requests, + no_auth, + no_req_body, + req_with_headers, + types, +) from .client import AsyncSeedExhaustive, SeedExhaustive from .general_errors import BadObjectRequestInfo, BadRequestBody from .version import __version__ diff --git a/seed/python-sdk/exhaustive/no-custom-config/src/seed/client.py b/seed/python-sdk/exhaustive/no-custom-config/src/seed/client.py index b1b9764c7a7..f5ab292af6b 100644 --- a/seed/python-sdk/exhaustive/no-custom-config/src/seed/client.py +++ b/seed/python-sdk/exhaustive/no-custom-config/src/seed/client.py @@ -1,15 +1,19 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from .endpoints.client import AsyncEndpointsClient, EndpointsClient -from .inlined_requests.client import AsyncInlinedRequestsClient, InlinedRequestsClient -from .no_auth.client import AsyncNoAuthClient, NoAuthClient -from .no_req_body.client import AsyncNoReqBodyClient, NoReqBodyClient -from .req_with_headers.client import AsyncReqWithHeadersClient, ReqWithHeadersClient +from .core.client_wrapper import SyncClientWrapper +from .endpoints.client import EndpointsClient +from .inlined_requests.client import InlinedRequestsClient +from .no_auth.client import NoAuthClient +from .no_req_body.client import NoReqBodyClient +from .req_with_headers.client import ReqWithHeadersClient +from .core.client_wrapper import AsyncClientWrapper +from .endpoints.client import AsyncEndpointsClient +from .inlined_requests.client import AsyncInlinedRequestsClient +from .no_auth.client import AsyncNoAuthClient +from .no_req_body.client import AsyncNoReqBodyClient +from .req_with_headers.client import AsyncReqWithHeadersClient class SeedExhaustive: @@ -48,24 +52,32 @@ def __init__( token: typing.Optional[typing.Union[str, typing.Callable[[], str]]] = None, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.Client] = None + httpx_client: typing.Optional[httpx.Client] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = SyncClientWrapper( base_url=base_url, token=token, httpx_client=httpx_client if httpx_client is not None - else httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.Client( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.Client(timeout=_defaulted_timeout), timeout=_defaulted_timeout, ) self.endpoints = EndpointsClient(client_wrapper=self._client_wrapper) - self.inlined_requests = InlinedRequestsClient(client_wrapper=self._client_wrapper) + self.inlined_requests = InlinedRequestsClient( + client_wrapper=self._client_wrapper + ) self.no_auth = NoAuthClient(client_wrapper=self._client_wrapper) self.no_req_body = NoReqBodyClient(client_wrapper=self._client_wrapper) - self.req_with_headers = ReqWithHeadersClient(client_wrapper=self._client_wrapper) + self.req_with_headers = ReqWithHeadersClient( + client_wrapper=self._client_wrapper + ) class AsyncSeedExhaustive: @@ -104,21 +116,29 @@ def __init__( token: typing.Optional[typing.Union[str, typing.Callable[[], str]]] = None, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.AsyncClient] = None + httpx_client: typing.Optional[httpx.AsyncClient] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = AsyncClientWrapper( base_url=base_url, token=token, httpx_client=httpx_client if httpx_client is not None - else httpx.AsyncClient(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.AsyncClient( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.AsyncClient(timeout=_defaulted_timeout), timeout=_defaulted_timeout, ) self.endpoints = AsyncEndpointsClient(client_wrapper=self._client_wrapper) - self.inlined_requests = AsyncInlinedRequestsClient(client_wrapper=self._client_wrapper) + self.inlined_requests = AsyncInlinedRequestsClient( + client_wrapper=self._client_wrapper + ) self.no_auth = AsyncNoAuthClient(client_wrapper=self._client_wrapper) self.no_req_body = AsyncNoReqBodyClient(client_wrapper=self._client_wrapper) - self.req_with_headers = AsyncReqWithHeadersClient(client_wrapper=self._client_wrapper) + self.req_with_headers = AsyncReqWithHeadersClient( + client_wrapper=self._client_wrapper + ) diff --git a/seed/python-sdk/exhaustive/no-custom-config/src/seed/core/api_error.py b/seed/python-sdk/exhaustive/no-custom-config/src/seed/core/api_error.py index 2e9fc5431cd..da734b58068 100644 --- a/seed/python-sdk/exhaustive/no-custom-config/src/seed/core/api_error.py +++ b/seed/python-sdk/exhaustive/no-custom-config/src/seed/core/api_error.py @@ -7,7 +7,9 @@ class ApiError(Exception): status_code: typing.Optional[int] body: typing.Any - def __init__(self, *, status_code: typing.Optional[int] = None, body: typing.Any = None): + def __init__( + self, *, status_code: typing.Optional[int] = None, body: typing.Any = None + ): self.status_code = status_code self.body = body diff --git a/seed/python-sdk/exhaustive/no-custom-config/src/seed/core/client_wrapper.py b/seed/python-sdk/exhaustive/no-custom-config/src/seed/core/client_wrapper.py index 8d01b584b82..d037184a816 100644 --- a/seed/python-sdk/exhaustive/no-custom-config/src/seed/core/client_wrapper.py +++ b/seed/python-sdk/exhaustive/no-custom-config/src/seed/core/client_wrapper.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .http_client import AsyncHttpClient, HttpClient +from .http_client import HttpClient +from .http_client import AsyncHttpClient class BaseClientWrapper: diff --git a/seed/python-sdk/exhaustive/no-custom-config/src/seed/core/datetime_utils.py b/seed/python-sdk/exhaustive/no-custom-config/src/seed/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/python-sdk/exhaustive/no-custom-config/src/seed/core/datetime_utils.py +++ b/seed/python-sdk/exhaustive/no-custom-config/src/seed/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/python-sdk/exhaustive/no-custom-config/src/seed/core/file.py b/seed/python-sdk/exhaustive/no-custom-config/src/seed/core/file.py index cb0d40bbbf3..6e0f92bfcb1 100644 --- a/seed/python-sdk/exhaustive/no-custom-config/src/seed/core/file.py +++ b/seed/python-sdk/exhaustive/no-custom-config/src/seed/core/file.py @@ -13,12 +13,17 @@ # (filename, file (or bytes), content_type) typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str]], # (filename, file (or bytes), content_type, headers) - typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str], typing.Mapping[str, str]], + typing.Tuple[ + typing.Optional[str], + FileContent, + typing.Optional[str], + typing.Mapping[str, str], + ], ] def convert_file_dict_to_httpx_tuples( - d: typing.Dict[str, typing.Union[File, typing.List[File]]] + d: typing.Dict[str, typing.Union[File, typing.List[File]]], ) -> typing.List[typing.Tuple[str, File]]: """ The format we use is a list of tuples, where the first element is the diff --git a/seed/python-sdk/exhaustive/no-custom-config/src/seed/core/http_client.py b/seed/python-sdk/exhaustive/no-custom-config/src/seed/core/http_client.py index 9333d8a7f15..091f71bc185 100644 --- a/seed/python-sdk/exhaustive/no-custom-config/src/seed/core/http_client.py +++ b/seed/python-sdk/exhaustive/no-custom-config/src/seed/core/http_client.py @@ -77,7 +77,9 @@ def _retry_timeout(response: httpx.Response, retries: int) -> float: return retry_after # Apply exponential backoff, capped at MAX_RETRY_DELAY_SECONDS. - retry_delay = min(INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS) + retry_delay = min( + INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS + ) # Add a randomness / jitter to the retry delay to avoid overwhelming the server with retries. timeout = retry_delay * (1 - 0.25 * random()) @@ -90,7 +92,8 @@ def _should_retry(response: httpx.Response) -> bool: def remove_omit_from_dict( - original: typing.Dict[str, typing.Optional[typing.Any]], omit: typing.Optional[typing.Any] + original: typing.Dict[str, typing.Optional[typing.Any]], + omit: typing.Optional[typing.Any], ) -> typing.Dict[str, typing.Any]: if omit is None: return original @@ -108,7 +111,8 @@ def maybe_filter_request_body( ) -> typing.Optional[typing.Any]: if data is None: return ( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else None ) @@ -118,7 +122,8 @@ def maybe_filter_request_body( data_content = { **(jsonable_encoder(remove_omit_from_dict(data, omit))), # type: ignore **( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else {} ), @@ -162,7 +167,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url def request( @@ -174,8 +181,12 @@ def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -184,11 +195,14 @@ def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) response = self.httpx_client.request( method=method, @@ -198,7 +212,11 @@ def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -209,7 +227,10 @@ def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -222,11 +243,15 @@ def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: time.sleep(_retry_timeout(response=response, retries=retries)) @@ -256,8 +281,12 @@ def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -266,11 +295,14 @@ def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) with self.httpx_client.stream( method=method, @@ -280,7 +312,11 @@ def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -291,7 +327,9 @@ def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -304,7 +342,9 @@ def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream @@ -327,7 +367,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url async def request( @@ -339,8 +381,12 @@ async def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -349,11 +395,14 @@ async def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) # Add the input to each of these and do None-safety checks response = await self.httpx_client.request( @@ -364,7 +413,11 @@ async def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -375,7 +428,10 @@ async def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -388,11 +444,15 @@ async def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: await asyncio.sleep(_retry_timeout(response=response, retries=retries)) @@ -421,8 +481,12 @@ async def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -431,11 +495,14 @@ async def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) async with self.httpx_client.stream( method=method, @@ -445,7 +512,11 @@ async def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -456,7 +527,9 @@ async def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -469,7 +542,9 @@ async def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream diff --git a/seed/python-sdk/exhaustive/no-custom-config/src/seed/core/jsonable_encoder.py b/seed/python-sdk/exhaustive/no-custom-config/src/seed/core/jsonable_encoder.py index d3fd328fd41..12a8b52fc22 100644 --- a/seed/python-sdk/exhaustive/no-custom-config/src/seed/core/jsonable_encoder.py +++ b/seed/python-sdk/exhaustive/no-custom-config/src/seed/core/jsonable_encoder.py @@ -19,13 +19,19 @@ import pydantic from .datetime_utils import serialize_datetime -from .pydantic_utilities import IS_PYDANTIC_V2, encode_by_type, to_jsonable_with_fallback +from .pydantic_utilities import ( + IS_PYDANTIC_V2, + encode_by_type, + to_jsonable_with_fallback, +) SetIntStr = Set[Union[int, str]] DictIntStrAny = Dict[Union[int, str], Any] -def jsonable_encoder(obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None) -> Any: +def jsonable_encoder( + obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None +) -> Any: custom_encoder = custom_encoder or {} if custom_encoder: if type(obj) in custom_encoder: diff --git a/seed/python-sdk/exhaustive/no-custom-config/src/seed/core/pydantic_utilities.py b/seed/python-sdk/exhaustive/no-custom-config/src/seed/core/pydantic_utilities.py index 170a563d6eb..c63935c32a2 100644 --- a/seed/python-sdk/exhaustive/no-custom-config/src/seed/core/pydantic_utilities.py +++ b/seed/python-sdk/exhaustive/no-custom-config/src/seed/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) # type: ignore # Pydantic v1 diff --git a/seed/python-sdk/exhaustive/no-custom-config/src/seed/core/query_encoder.py b/seed/python-sdk/exhaustive/no-custom-config/src/seed/core/query_encoder.py index 24076d72ee9..7cb98f52cd7 100644 --- a/seed/python-sdk/exhaustive/no-custom-config/src/seed/core/query_encoder.py +++ b/seed/python-sdk/exhaustive/no-custom-config/src/seed/core/query_encoder.py @@ -7,7 +7,9 @@ # Flattens dicts to be of the form {"key[subkey][subkey2]": value} where value is not a dict -def traverse_query_dict(dict_flat: Dict[str, Any], key_prefix: Optional[str] = None) -> Dict[str, Any]: +def traverse_query_dict( + dict_flat: Dict[str, Any], key_prefix: Optional[str] = None +) -> Dict[str, Any]: result = {} for k, v in dict_flat.items(): key = f"{key_prefix}[{k}]" if key_prefix is not None else k @@ -30,4 +32,8 @@ def single_query_encoder(query_key: str, query_value: Any) -> Dict[str, Any]: def encode_query(query: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: - return dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) if query is not None else None + return ( + dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) + if query is not None + else None + ) diff --git a/seed/python-sdk/exhaustive/no-custom-config/src/seed/core/serialization.py b/seed/python-sdk/exhaustive/no-custom-config/src/seed/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/python-sdk/exhaustive/no-custom-config/src/seed/core/serialization.py +++ b/seed/python-sdk/exhaustive/no-custom-config/src/seed/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/python-sdk/exhaustive/no-custom-config/src/seed/endpoints/__init__.py b/seed/python-sdk/exhaustive/no-custom-config/src/seed/endpoints/__init__.py index 92307cab7fe..a9496ece178 100644 --- a/seed/python-sdk/exhaustive/no-custom-config/src/seed/endpoints/__init__.py +++ b/seed/python-sdk/exhaustive/no-custom-config/src/seed/endpoints/__init__.py @@ -2,4 +2,12 @@ from . import container, enum, http_methods, object, params, primitive, union -__all__ = ["container", "enum", "http_methods", "object", "params", "primitive", "union"] +__all__ = [ + "container", + "enum", + "http_methods", + "object", + "params", + "primitive", + "union", +] diff --git a/seed/python-sdk/exhaustive/no-custom-config/src/seed/endpoints/client.py b/seed/python-sdk/exhaustive/no-custom-config/src/seed/endpoints/client.py index 18dc397fdf1..69930de54d7 100644 --- a/seed/python-sdk/exhaustive/no-custom-config/src/seed/endpoints/client.py +++ b/seed/python-sdk/exhaustive/no-custom-config/src/seed/endpoints/client.py @@ -1,13 +1,21 @@ # This file was auto-generated by Fern from our API Definition. -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from .container.client import AsyncContainerClient, ContainerClient -from .enum.client import AsyncEnumClient, EnumClient -from .http_methods.client import AsyncHttpMethodsClient, HttpMethodsClient -from .object.client import AsyncObjectClient, ObjectClient -from .params.client import AsyncParamsClient, ParamsClient -from .primitive.client import AsyncPrimitiveClient, PrimitiveClient -from .union.client import AsyncUnionClient, UnionClient +from ..core.client_wrapper import SyncClientWrapper +from .container.client import ContainerClient +from .enum.client import EnumClient +from .http_methods.client import HttpMethodsClient +from .object.client import ObjectClient +from .params.client import ParamsClient +from .primitive.client import PrimitiveClient +from .union.client import UnionClient +from ..core.client_wrapper import AsyncClientWrapper +from .container.client import AsyncContainerClient +from .enum.client import AsyncEnumClient +from .http_methods.client import AsyncHttpMethodsClient +from .object.client import AsyncObjectClient +from .params.client import AsyncParamsClient +from .primitive.client import AsyncPrimitiveClient +from .union.client import AsyncUnionClient class EndpointsClient: diff --git a/seed/python-sdk/exhaustive/no-custom-config/src/seed/endpoints/container/client.py b/seed/python-sdk/exhaustive/no-custom-config/src/seed/endpoints/container/client.py index c6cf14f63ac..4af9c12d534 100644 --- a/seed/python-sdk/exhaustive/no-custom-config/src/seed/endpoints/container/client.py +++ b/seed/python-sdk/exhaustive/no-custom-config/src/seed/endpoints/container/client.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. import typing +from ...core.client_wrapper import SyncClientWrapper +from ...core.request_options import RequestOptions +from ...core.pydantic_utilities import parse_obj_as from json.decoder import JSONDecodeError - from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ...core.pydantic_utilities import parse_obj_as -from ...core.request_options import RequestOptions from ...types.object.types.object_with_required_field import ObjectWithRequiredField +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -18,7 +18,10 @@ def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper def get_and_return_list_of_primitives( - self, *, request: typing.Sequence[str], request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Sequence[str], + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[str]: """ Parameters @@ -45,11 +48,18 @@ def get_and_return_list_of_primitives( ) """ _response = self._client_wrapper.httpx_client.request( - "container/list-of-primitives", method="POST", json=request, request_options=request_options, omit=OMIT + "container/list-of-primitives", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.List[str], parse_obj_as(type_=typing.List[str], object_=_response.json())) # type: ignore + return typing.cast( + typing.List[str], + parse_obj_as(type_=typing.List[str], object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -59,7 +69,7 @@ def get_and_return_list_of_objects( self, *, request: typing.Sequence[ObjectWithRequiredField], - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[ObjectWithRequiredField]: """ Parameters @@ -91,18 +101,31 @@ def get_and_return_list_of_objects( ) """ _response = self._client_wrapper.httpx_client.request( - "container/list-of-objects", method="POST", json=request, request_options=request_options, omit=OMIT + "container/list-of-objects", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.List[ObjectWithRequiredField], parse_obj_as(type_=typing.List[ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.List[ObjectWithRequiredField], + parse_obj_as( + type_=typing.List[ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_and_return_set_of_primitives( - self, *, request: typing.Set[str], request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Set[str], + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Set[str]: """ Parameters @@ -129,11 +152,18 @@ def get_and_return_set_of_primitives( ) """ _response = self._client_wrapper.httpx_client.request( - "container/set-of-primitives", method="POST", json=request, request_options=request_options, omit=OMIT + "container/set-of-primitives", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Set[str], parse_obj_as(type_=typing.Set[str], object_=_response.json())) # type: ignore + return typing.cast( + typing.Set[str], + parse_obj_as(type_=typing.Set[str], object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -143,7 +173,7 @@ def get_and_return_set_of_objects( self, *, request: typing.Sequence[ObjectWithRequiredField], - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[ObjectWithRequiredField]: """ Parameters @@ -175,18 +205,31 @@ def get_and_return_set_of_objects( ) """ _response = self._client_wrapper.httpx_client.request( - "container/set-of-objects", method="POST", json=request, request_options=request_options, omit=OMIT + "container/set-of-objects", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.List[ObjectWithRequiredField], parse_obj_as(type_=typing.List[ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.List[ObjectWithRequiredField], + parse_obj_as( + type_=typing.List[ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_and_return_map_prim_to_prim( - self, *, request: typing.Dict[str, str], request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Dict[str, str], + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Dict[str, str]: """ Parameters @@ -213,11 +256,18 @@ def get_and_return_map_prim_to_prim( ) """ _response = self._client_wrapper.httpx_client.request( - "container/map-prim-to-prim", method="POST", json=request, request_options=request_options, omit=OMIT + "container/map-prim-to-prim", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Dict[str, str], parse_obj_as(type_=typing.Dict[str, str], object_=_response.json())) # type: ignore + return typing.cast( + typing.Dict[str, str], + parse_obj_as(type_=typing.Dict[str, str], object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -227,7 +277,7 @@ def get_and_return_map_of_prim_to_object( self, *, request: typing.Dict[str, ObjectWithRequiredField], - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Dict[str, ObjectWithRequiredField]: """ Parameters @@ -259,11 +309,21 @@ def get_and_return_map_of_prim_to_object( ) """ _response = self._client_wrapper.httpx_client.request( - "container/map-prim-to-object", method="POST", json=request, request_options=request_options, omit=OMIT + "container/map-prim-to-object", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Dict[str, ObjectWithRequiredField], parse_obj_as(type_=typing.Dict[str, ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.Dict[str, ObjectWithRequiredField], + parse_obj_as( + type_=typing.Dict[str, ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -273,7 +333,7 @@ def get_and_return_optional( self, *, request: typing.Optional[ObjectWithRequiredField] = None, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Optional[ObjectWithRequiredField]: """ Parameters @@ -303,11 +363,21 @@ def get_and_return_optional( ) """ _response = self._client_wrapper.httpx_client.request( - "container/opt-objects", method="POST", json=request, request_options=request_options, omit=OMIT + "container/opt-objects", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Optional[ObjectWithRequiredField], parse_obj_as(type_=typing.Optional[ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.Optional[ObjectWithRequiredField], + parse_obj_as( + type_=typing.Optional[ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -319,7 +389,10 @@ def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper async def get_and_return_list_of_primitives( - self, *, request: typing.Sequence[str], request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Sequence[str], + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[str]: """ Parameters @@ -354,11 +427,18 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/list-of-primitives", method="POST", json=request, request_options=request_options, omit=OMIT + "container/list-of-primitives", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.List[str], parse_obj_as(type_=typing.List[str], object_=_response.json())) # type: ignore + return typing.cast( + typing.List[str], + parse_obj_as(type_=typing.List[str], object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -368,7 +448,7 @@ async def get_and_return_list_of_objects( self, *, request: typing.Sequence[ObjectWithRequiredField], - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[ObjectWithRequiredField]: """ Parameters @@ -408,18 +488,31 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/list-of-objects", method="POST", json=request, request_options=request_options, omit=OMIT + "container/list-of-objects", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.List[ObjectWithRequiredField], parse_obj_as(type_=typing.List[ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.List[ObjectWithRequiredField], + parse_obj_as( + type_=typing.List[ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_and_return_set_of_primitives( - self, *, request: typing.Set[str], request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Set[str], + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Set[str]: """ Parameters @@ -454,11 +547,18 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/set-of-primitives", method="POST", json=request, request_options=request_options, omit=OMIT + "container/set-of-primitives", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Set[str], parse_obj_as(type_=typing.Set[str], object_=_response.json())) # type: ignore + return typing.cast( + typing.Set[str], + parse_obj_as(type_=typing.Set[str], object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -468,7 +568,7 @@ async def get_and_return_set_of_objects( self, *, request: typing.Sequence[ObjectWithRequiredField], - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[ObjectWithRequiredField]: """ Parameters @@ -508,18 +608,31 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/set-of-objects", method="POST", json=request, request_options=request_options, omit=OMIT + "container/set-of-objects", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.List[ObjectWithRequiredField], parse_obj_as(type_=typing.List[ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.List[ObjectWithRequiredField], + parse_obj_as( + type_=typing.List[ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_and_return_map_prim_to_prim( - self, *, request: typing.Dict[str, str], request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Dict[str, str], + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Dict[str, str]: """ Parameters @@ -554,11 +667,18 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/map-prim-to-prim", method="POST", json=request, request_options=request_options, omit=OMIT + "container/map-prim-to-prim", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Dict[str, str], parse_obj_as(type_=typing.Dict[str, str], object_=_response.json())) # type: ignore + return typing.cast( + typing.Dict[str, str], + parse_obj_as(type_=typing.Dict[str, str], object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -568,7 +688,7 @@ async def get_and_return_map_of_prim_to_object( self, *, request: typing.Dict[str, ObjectWithRequiredField], - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Dict[str, ObjectWithRequiredField]: """ Parameters @@ -608,11 +728,21 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/map-prim-to-object", method="POST", json=request, request_options=request_options, omit=OMIT + "container/map-prim-to-object", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Dict[str, ObjectWithRequiredField], parse_obj_as(type_=typing.Dict[str, ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.Dict[str, ObjectWithRequiredField], + parse_obj_as( + type_=typing.Dict[str, ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -622,7 +752,7 @@ async def get_and_return_optional( self, *, request: typing.Optional[ObjectWithRequiredField] = None, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Optional[ObjectWithRequiredField]: """ Parameters @@ -660,11 +790,21 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/opt-objects", method="POST", json=request, request_options=request_options, omit=OMIT + "container/opt-objects", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Optional[ObjectWithRequiredField], parse_obj_as(type_=typing.Optional[ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.Optional[ObjectWithRequiredField], + parse_obj_as( + type_=typing.Optional[ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/no-custom-config/src/seed/endpoints/enum/client.py b/seed/python-sdk/exhaustive/no-custom-config/src/seed/endpoints/enum/client.py index 44e2690ff6c..3e3208e3bcf 100644 --- a/seed/python-sdk/exhaustive/no-custom-config/src/seed/endpoints/enum/client.py +++ b/seed/python-sdk/exhaustive/no-custom-config/src/seed/endpoints/enum/client.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. import typing +from ...core.client_wrapper import SyncClientWrapper +from ...types.enum.types.weather_report import WeatherReport +from ...core.request_options import RequestOptions +from ...core.pydantic_utilities import parse_obj_as from json.decoder import JSONDecodeError - from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ...core.pydantic_utilities import parse_obj_as -from ...core.request_options import RequestOptions -from ...types.enum.types.weather_report import WeatherReport +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -18,7 +18,10 @@ def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper def get_and_return_enum( - self, *, request: WeatherReport, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: WeatherReport, + request_options: typing.Optional[RequestOptions] = None, ) -> WeatherReport: """ Parameters @@ -45,11 +48,18 @@ def get_and_return_enum( ) """ _response = self._client_wrapper.httpx_client.request( - "enum", method="POST", json=request, request_options=request_options, omit=OMIT + "enum", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(WeatherReport, parse_obj_as(type_=WeatherReport, object_=_response.json())) # type: ignore + return typing.cast( + WeatherReport, + parse_obj_as(type_=WeatherReport, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -61,7 +71,10 @@ def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper async def get_and_return_enum( - self, *, request: WeatherReport, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: WeatherReport, + request_options: typing.Optional[RequestOptions] = None, ) -> WeatherReport: """ Parameters @@ -96,11 +109,18 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "enum", method="POST", json=request, request_options=request_options, omit=OMIT + "enum", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(WeatherReport, parse_obj_as(type_=WeatherReport, object_=_response.json())) # type: ignore + return typing.cast( + WeatherReport, + parse_obj_as(type_=WeatherReport, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/no-custom-config/src/seed/endpoints/http_methods/client.py b/seed/python-sdk/exhaustive/no-custom-config/src/seed/endpoints/http_methods/client.py index a2549280a1b..570a227844f 100644 --- a/seed/python-sdk/exhaustive/no-custom-config/src/seed/endpoints/http_methods/client.py +++ b/seed/python-sdk/exhaustive/no-custom-config/src/seed/endpoints/http_methods/client.py @@ -1,16 +1,16 @@ # This file was auto-generated by Fern from our API Definition. -import datetime as dt import typing -import uuid -from json.decoder import JSONDecodeError - -from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper +from ...core.client_wrapper import SyncClientWrapper +from ...core.request_options import RequestOptions from ...core.jsonable_encoder import jsonable_encoder from ...core.pydantic_utilities import parse_obj_as -from ...core.request_options import RequestOptions +from json.decoder import JSONDecodeError +from ...core.api_error import ApiError from ...types.object.types.object_with_optional_field import ObjectWithOptionalField +import datetime as dt +import uuid +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -20,7 +20,9 @@ class HttpMethodsClient: def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper - def test_get(self, id: str, *, request_options: typing.Optional[RequestOptions] = None) -> str: + def test_get( + self, id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -46,11 +48,15 @@ def test_get(self, id: str, *, request_options: typing.Optional[RequestOptions] ) """ _response = self._client_wrapper.httpx_client.request( - f"http-methods/{jsonable_encoder(id)}", method="GET", request_options=request_options + f"http-methods/{jsonable_encoder(id)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -84,18 +90,33 @@ def test_post( ) """ _response = self._client_wrapper.httpx_client.request( - "http-methods", method="POST", json={"string": string}, request_options=request_options, omit=OMIT + "http-methods", + method="POST", + json={ + "string": string, + }, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def test_put( - self, id: str, *, string: str, request_options: typing.Optional[RequestOptions] = None + self, + id: str, + *, + string: str, + request_options: typing.Optional[RequestOptions] = None, ) -> ObjectWithOptionalField: """ Parameters @@ -127,13 +148,20 @@ def test_put( _response = self._client_wrapper.httpx_client.request( f"http-methods/{jsonable_encoder(id)}", method="PUT", - json={"string": string}, + json={ + "string": string, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -254,13 +282,20 @@ def test_patch( ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def test_delete(self, id: str, *, request_options: typing.Optional[RequestOptions] = None) -> bool: + def test_delete( + self, id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> bool: """ Parameters ---------- @@ -286,11 +321,15 @@ def test_delete(self, id: str, *, request_options: typing.Optional[RequestOption ) """ _response = self._client_wrapper.httpx_client.request( - f"http-methods/{jsonable_encoder(id)}", method="DELETE", request_options=request_options + f"http-methods/{jsonable_encoder(id)}", + method="DELETE", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -301,7 +340,9 @@ class AsyncHttpMethodsClient: def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper - async def test_get(self, id: str, *, request_options: typing.Optional[RequestOptions] = None) -> str: + async def test_get( + self, id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -335,11 +376,15 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - f"http-methods/{jsonable_encoder(id)}", method="GET", request_options=request_options + f"http-methods/{jsonable_encoder(id)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -381,18 +426,33 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "http-methods", method="POST", json={"string": string}, request_options=request_options, omit=OMIT + "http-methods", + method="POST", + json={ + "string": string, + }, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def test_put( - self, id: str, *, string: str, request_options: typing.Optional[RequestOptions] = None + self, + id: str, + *, + string: str, + request_options: typing.Optional[RequestOptions] = None, ) -> ObjectWithOptionalField: """ Parameters @@ -432,13 +492,20 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( f"http-methods/{jsonable_encoder(id)}", method="PUT", - json={"string": string}, + json={ + "string": string, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -566,13 +633,20 @@ async def main() -> None: ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - async def test_delete(self, id: str, *, request_options: typing.Optional[RequestOptions] = None) -> bool: + async def test_delete( + self, id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> bool: """ Parameters ---------- @@ -606,11 +680,15 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - f"http-methods/{jsonable_encoder(id)}", method="DELETE", request_options=request_options + f"http-methods/{jsonable_encoder(id)}", + method="DELETE", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/no-custom-config/src/seed/endpoints/object/client.py b/seed/python-sdk/exhaustive/no-custom-config/src/seed/endpoints/object/client.py index a724f959193..dcb1324b74b 100644 --- a/seed/python-sdk/exhaustive/no-custom-config/src/seed/endpoints/object/client.py +++ b/seed/python-sdk/exhaustive/no-custom-config/src/seed/endpoints/object/client.py @@ -1,20 +1,24 @@ # This file was auto-generated by Fern from our API Definition. -import datetime as dt import typing +from ...core.client_wrapper import SyncClientWrapper +import datetime as dt import uuid -from json.decoder import JSONDecodeError - -from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ...core.jsonable_encoder import jsonable_encoder -from ...core.pydantic_utilities import parse_obj_as from ...core.request_options import RequestOptions -from ...types.object.types.nested_object_with_optional_field import NestedObjectWithOptionalField -from ...types.object.types.nested_object_with_required_field import NestedObjectWithRequiredField -from ...types.object.types.object_with_map_of_map import ObjectWithMapOfMap from ...types.object.types.object_with_optional_field import ObjectWithOptionalField +from ...core.pydantic_utilities import parse_obj_as +from json.decoder import JSONDecodeError +from ...core.api_error import ApiError from ...types.object.types.object_with_required_field import ObjectWithRequiredField +from ...types.object.types.object_with_map_of_map import ObjectWithMapOfMap +from ...types.object.types.nested_object_with_optional_field import ( + NestedObjectWithOptionalField, +) +from ...types.object.types.nested_object_with_required_field import ( + NestedObjectWithRequiredField, +) +from ...core.jsonable_encoder import jsonable_encoder +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -135,7 +139,12 @@ def get_and_return_with_optional_field( ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -171,20 +180,30 @@ def get_and_return_with_required_field( _response = self._client_wrapper.httpx_client.request( "object/get-and-return-with-required-field", method="POST", - json={"string": string}, + json={ + "string": string, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithRequiredField, parse_obj_as(type_=ObjectWithRequiredField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithRequiredField, + parse_obj_as( + type_=ObjectWithRequiredField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_and_return_with_map_of_map( - self, *, map_: typing.Dict[str, typing.Dict[str, str]], request_options: typing.Optional[RequestOptions] = None + self, + *, + map_: typing.Dict[str, typing.Dict[str, str]], + request_options: typing.Optional[RequestOptions] = None, ) -> ObjectWithMapOfMap: """ Parameters @@ -213,13 +232,18 @@ def get_and_return_with_map_of_map( _response = self._client_wrapper.httpx_client.request( "object/get-and-return-with-map-of-map", method="POST", - json={"map": map_}, + json={ + "map": map_, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithMapOfMap, parse_obj_as(type_=ObjectWithMapOfMap, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithMapOfMap, + parse_obj_as(type_=ObjectWithMapOfMap, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -286,13 +310,21 @@ def get_and_return_nested_with_optional_field( _response = self._client_wrapper.httpx_client.request( "object/get-and-return-nested-with-optional-field", method="POST", - json={"string": string, "NestedObject": nested_object}, + json={ + "string": string, + "NestedObject": nested_object, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(NestedObjectWithOptionalField, parse_obj_as(type_=NestedObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + NestedObjectWithOptionalField, + parse_obj_as( + type_=NestedObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -363,13 +395,21 @@ def get_and_return_nested_with_required_field( _response = self._client_wrapper.httpx_client.request( f"object/get-and-return-nested-with-required-field/{jsonable_encoder(string_)}", method="POST", - json={"string": string, "NestedObject": nested_object}, + json={ + "string": string, + "NestedObject": nested_object, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(NestedObjectWithRequiredField, parse_obj_as(type_=NestedObjectWithRequiredField, object_=_response.json())) # type: ignore + return typing.cast( + NestedObjectWithRequiredField, + parse_obj_as( + type_=NestedObjectWithRequiredField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -446,7 +486,12 @@ def get_and_return_nested_with_required_field_as_list( ) try: if 200 <= _response.status_code < 300: - return typing.cast(NestedObjectWithRequiredField, parse_obj_as(type_=NestedObjectWithRequiredField, object_=_response.json())) # type: ignore + return typing.cast( + NestedObjectWithRequiredField, + parse_obj_as( + type_=NestedObjectWithRequiredField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -575,7 +620,12 @@ async def main() -> None: ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -619,20 +669,30 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( "object/get-and-return-with-required-field", method="POST", - json={"string": string}, + json={ + "string": string, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithRequiredField, parse_obj_as(type_=ObjectWithRequiredField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithRequiredField, + parse_obj_as( + type_=ObjectWithRequiredField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_and_return_with_map_of_map( - self, *, map_: typing.Dict[str, typing.Dict[str, str]], request_options: typing.Optional[RequestOptions] = None + self, + *, + map_: typing.Dict[str, typing.Dict[str, str]], + request_options: typing.Optional[RequestOptions] = None, ) -> ObjectWithMapOfMap: """ Parameters @@ -669,13 +729,18 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( "object/get-and-return-with-map-of-map", method="POST", - json={"map": map_}, + json={ + "map": map_, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithMapOfMap, parse_obj_as(type_=ObjectWithMapOfMap, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithMapOfMap, + parse_obj_as(type_=ObjectWithMapOfMap, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -749,13 +814,21 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( "object/get-and-return-nested-with-optional-field", method="POST", - json={"string": string, "NestedObject": nested_object}, + json={ + "string": string, + "NestedObject": nested_object, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(NestedObjectWithOptionalField, parse_obj_as(type_=NestedObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + NestedObjectWithOptionalField, + parse_obj_as( + type_=NestedObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -833,13 +906,21 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( f"object/get-and-return-nested-with-required-field/{jsonable_encoder(string_)}", method="POST", - json={"string": string, "NestedObject": nested_object}, + json={ + "string": string, + "NestedObject": nested_object, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(NestedObjectWithRequiredField, parse_obj_as(type_=NestedObjectWithRequiredField, object_=_response.json())) # type: ignore + return typing.cast( + NestedObjectWithRequiredField, + parse_obj_as( + type_=NestedObjectWithRequiredField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -923,7 +1004,12 @@ async def main() -> None: ) try: if 200 <= _response.status_code < 300: - return typing.cast(NestedObjectWithRequiredField, parse_obj_as(type_=NestedObjectWithRequiredField, object_=_response.json())) # type: ignore + return typing.cast( + NestedObjectWithRequiredField, + parse_obj_as( + type_=NestedObjectWithRequiredField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/no-custom-config/src/seed/endpoints/params/client.py b/seed/python-sdk/exhaustive/no-custom-config/src/seed/endpoints/params/client.py index 5cd7ceef42a..a9187ac94b8 100644 --- a/seed/python-sdk/exhaustive/no-custom-config/src/seed/endpoints/params/client.py +++ b/seed/python-sdk/exhaustive/no-custom-config/src/seed/endpoints/params/client.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. import typing -from json.decoder import JSONDecodeError - -from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper +from ...core.client_wrapper import SyncClientWrapper +from ...core.request_options import RequestOptions from ...core.jsonable_encoder import jsonable_encoder from ...core.pydantic_utilities import parse_obj_as -from ...core.request_options import RequestOptions +from json.decoder import JSONDecodeError +from ...core.api_error import ApiError +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -17,7 +17,9 @@ class ParamsClient: def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper - def get_with_path(self, param: str, *, request_options: typing.Optional[RequestOptions] = None) -> str: + def get_with_path( + self, param: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ GET with path param @@ -45,18 +47,26 @@ def get_with_path(self, param: str, *, request_options: typing.Optional[RequestO ) """ _response = self._client_wrapper.httpx_client.request( - f"params/path/{jsonable_encoder(param)}", method="GET", request_options=request_options + f"params/path/{jsonable_encoder(param)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_with_query( - self, *, query: str, number: int, request_options: typing.Optional[RequestOptions] = None + self, + *, + query: str, + number: int, + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ GET with query param @@ -88,7 +98,13 @@ def get_with_query( ) """ _response = self._client_wrapper.httpx_client.request( - "params", method="GET", params={"query": query, "number": number}, request_options=request_options + "params", + method="GET", + params={ + "query": query, + "number": number, + }, + request_options=request_options, ) try: if 200 <= _response.status_code < 300: @@ -135,7 +151,13 @@ def get_with_allow_multiple_query( ) """ _response = self._client_wrapper.httpx_client.request( - "params", method="GET", params={"query": query, "numer": numer}, request_options=request_options + "params", + method="GET", + params={ + "query": query, + "numer": numer, + }, + request_options=request_options, ) try: if 200 <= _response.status_code < 300: @@ -146,7 +168,11 @@ def get_with_allow_multiple_query( raise ApiError(status_code=_response.status_code, body=_response_json) def get_with_path_and_query( - self, param: str, *, query: str, request_options: typing.Optional[RequestOptions] = None + self, + param: str, + *, + query: str, + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ GET with path and query params @@ -180,7 +206,9 @@ def get_with_path_and_query( _response = self._client_wrapper.httpx_client.request( f"params/path-query/{jsonable_encoder(param)}", method="GET", - params={"query": query}, + params={ + "query": query, + }, request_options=request_options, ) try: @@ -192,7 +220,11 @@ def get_with_path_and_query( raise ApiError(status_code=_response.status_code, body=_response_json) def modify_with_path( - self, param: str, *, request: str, request_options: typing.Optional[RequestOptions] = None + self, + param: str, + *, + request: str, + request_options: typing.Optional[RequestOptions] = None, ) -> str: """ PUT to update with path param @@ -232,7 +264,9 @@ def modify_with_path( ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -243,7 +277,9 @@ class AsyncParamsClient: def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper - async def get_with_path(self, param: str, *, request_options: typing.Optional[RequestOptions] = None) -> str: + async def get_with_path( + self, param: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ GET with path param @@ -279,18 +315,26 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - f"params/path/{jsonable_encoder(param)}", method="GET", request_options=request_options + f"params/path/{jsonable_encoder(param)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_with_query( - self, *, query: str, number: int, request_options: typing.Optional[RequestOptions] = None + self, + *, + query: str, + number: int, + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ GET with query param @@ -330,7 +374,13 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "params", method="GET", params={"query": query, "number": number}, request_options=request_options + "params", + method="GET", + params={ + "query": query, + "number": number, + }, + request_options=request_options, ) try: if 200 <= _response.status_code < 300: @@ -385,7 +435,13 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "params", method="GET", params={"query": query, "numer": numer}, request_options=request_options + "params", + method="GET", + params={ + "query": query, + "numer": numer, + }, + request_options=request_options, ) try: if 200 <= _response.status_code < 300: @@ -396,7 +452,11 @@ async def main() -> None: raise ApiError(status_code=_response.status_code, body=_response_json) async def get_with_path_and_query( - self, param: str, *, query: str, request_options: typing.Optional[RequestOptions] = None + self, + param: str, + *, + query: str, + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ GET with path and query params @@ -438,7 +498,9 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( f"params/path-query/{jsonable_encoder(param)}", method="GET", - params={"query": query}, + params={ + "query": query, + }, request_options=request_options, ) try: @@ -450,7 +512,11 @@ async def main() -> None: raise ApiError(status_code=_response.status_code, body=_response_json) async def modify_with_path( - self, param: str, *, request: str, request_options: typing.Optional[RequestOptions] = None + self, + param: str, + *, + request: str, + request_options: typing.Optional[RequestOptions] = None, ) -> str: """ PUT to update with path param @@ -498,7 +564,9 @@ async def main() -> None: ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/no-custom-config/src/seed/endpoints/primitive/client.py b/seed/python-sdk/exhaustive/no-custom-config/src/seed/endpoints/primitive/client.py index 844b6a782f0..20a66f049b4 100644 --- a/seed/python-sdk/exhaustive/no-custom-config/src/seed/endpoints/primitive/client.py +++ b/seed/python-sdk/exhaustive/no-custom-config/src/seed/endpoints/primitive/client.py @@ -1,14 +1,14 @@ # This file was auto-generated by Fern from our API Definition. -import datetime as dt import typing -import uuid +from ...core.client_wrapper import SyncClientWrapper +from ...core.request_options import RequestOptions +from ...core.pydantic_utilities import parse_obj_as from json.decoder import JSONDecodeError - from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ...core.pydantic_utilities import parse_obj_as -from ...core.request_options import RequestOptions +import datetime as dt +import uuid +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -18,7 +18,9 @@ class PrimitiveClient: def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper - def get_and_return_string(self, *, request: str, request_options: typing.Optional[RequestOptions] = None) -> str: + def get_and_return_string( + self, *, request: str, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -44,17 +46,25 @@ def get_and_return_string(self, *, request: str, request_options: typing.Optiona ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/string", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/string", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def get_and_return_int(self, *, request: int, request_options: typing.Optional[RequestOptions] = None) -> int: + def get_and_return_int( + self, *, request: int, request_options: typing.Optional[RequestOptions] = None + ) -> int: """ Parameters ---------- @@ -80,17 +90,25 @@ def get_and_return_int(self, *, request: int, request_options: typing.Optional[R ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/integer", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/integer", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(int, parse_obj_as(type_=int, object_=_response.json())) # type: ignore + return typing.cast( + int, parse_obj_as(type_=int, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def get_and_return_long(self, *, request: int, request_options: typing.Optional[RequestOptions] = None) -> int: + def get_and_return_long( + self, *, request: int, request_options: typing.Optional[RequestOptions] = None + ) -> int: """ Parameters ---------- @@ -116,11 +134,17 @@ def get_and_return_long(self, *, request: int, request_options: typing.Optional[ ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/long", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/long", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(int, parse_obj_as(type_=int, object_=_response.json())) # type: ignore + return typing.cast( + int, parse_obj_as(type_=int, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -154,17 +178,25 @@ def get_and_return_double( ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/double", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/double", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(float, parse_obj_as(type_=float, object_=_response.json())) # type: ignore + return typing.cast( + float, parse_obj_as(type_=float, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def get_and_return_bool(self, *, request: bool, request_options: typing.Optional[RequestOptions] = None) -> bool: + def get_and_return_bool( + self, *, request: bool, request_options: typing.Optional[RequestOptions] = None + ) -> bool: """ Parameters ---------- @@ -190,18 +222,27 @@ def get_and_return_bool(self, *, request: bool, request_options: typing.Optional ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/boolean", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/boolean", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_and_return_datetime( - self, *, request: dt.datetime, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: dt.datetime, + request_options: typing.Optional[RequestOptions] = None, ) -> dt.datetime: """ Parameters @@ -232,18 +273,28 @@ def get_and_return_datetime( ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/datetime", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/datetime", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(dt.datetime, parse_obj_as(type_=dt.datetime, object_=_response.json())) # type: ignore + return typing.cast( + dt.datetime, + parse_obj_as(type_=dt.datetime, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_and_return_date( - self, *, request: dt.date, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: dt.date, + request_options: typing.Optional[RequestOptions] = None, ) -> dt.date: """ Parameters @@ -274,18 +325,27 @@ def get_and_return_date( ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/date", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/date", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(dt.date, parse_obj_as(type_=dt.date, object_=_response.json())) # type: ignore + return typing.cast( + dt.date, parse_obj_as(type_=dt.date, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_and_return_uuid( - self, *, request: uuid.UUID, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: uuid.UUID, + request_options: typing.Optional[RequestOptions] = None, ) -> uuid.UUID: """ Parameters @@ -316,17 +376,25 @@ def get_and_return_uuid( ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/uuid", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/uuid", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(uuid.UUID, parse_obj_as(type_=uuid.UUID, object_=_response.json())) # type: ignore + return typing.cast( + uuid.UUID, parse_obj_as(type_=uuid.UUID, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def get_and_return_base_64(self, *, request: str, request_options: typing.Optional[RequestOptions] = None) -> str: + def get_and_return_base_64( + self, *, request: str, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -352,11 +420,17 @@ def get_and_return_base_64(self, *, request: str, request_options: typing.Option ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/base64", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/base64", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -403,17 +477,25 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/string", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/string", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - async def get_and_return_int(self, *, request: int, request_options: typing.Optional[RequestOptions] = None) -> int: + async def get_and_return_int( + self, *, request: int, request_options: typing.Optional[RequestOptions] = None + ) -> int: """ Parameters ---------- @@ -447,11 +529,17 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/integer", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/integer", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(int, parse_obj_as(type_=int, object_=_response.json())) # type: ignore + return typing.cast( + int, parse_obj_as(type_=int, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -493,11 +581,17 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/long", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/long", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(int, parse_obj_as(type_=int, object_=_response.json())) # type: ignore + return typing.cast( + int, parse_obj_as(type_=int, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -539,11 +633,17 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/double", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/double", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(float, parse_obj_as(type_=float, object_=_response.json())) # type: ignore + return typing.cast( + float, parse_obj_as(type_=float, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -585,18 +685,27 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/boolean", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/boolean", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_and_return_datetime( - self, *, request: dt.datetime, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: dt.datetime, + request_options: typing.Optional[RequestOptions] = None, ) -> dt.datetime: """ Parameters @@ -634,18 +743,28 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/datetime", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/datetime", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(dt.datetime, parse_obj_as(type_=dt.datetime, object_=_response.json())) # type: ignore + return typing.cast( + dt.datetime, + parse_obj_as(type_=dt.datetime, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_and_return_date( - self, *, request: dt.date, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: dt.date, + request_options: typing.Optional[RequestOptions] = None, ) -> dt.date: """ Parameters @@ -683,18 +802,27 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/date", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/date", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(dt.date, parse_obj_as(type_=dt.date, object_=_response.json())) # type: ignore + return typing.cast( + dt.date, parse_obj_as(type_=dt.date, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_and_return_uuid( - self, *, request: uuid.UUID, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: uuid.UUID, + request_options: typing.Optional[RequestOptions] = None, ) -> uuid.UUID: """ Parameters @@ -732,11 +860,17 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/uuid", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/uuid", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(uuid.UUID, parse_obj_as(type_=uuid.UUID, object_=_response.json())) # type: ignore + return typing.cast( + uuid.UUID, parse_obj_as(type_=uuid.UUID, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -778,11 +912,17 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/base64", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/base64", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/no-custom-config/src/seed/endpoints/union/client.py b/seed/python-sdk/exhaustive/no-custom-config/src/seed/endpoints/union/client.py index 77153587a27..f4c3d9312de 100644 --- a/seed/python-sdk/exhaustive/no-custom-config/src/seed/endpoints/union/client.py +++ b/seed/python-sdk/exhaustive/no-custom-config/src/seed/endpoints/union/client.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. import typing +from ...core.client_wrapper import SyncClientWrapper +from ...types.union.types.animal import Animal +from ...core.request_options import RequestOptions +from ...core.pydantic_utilities import parse_obj_as from json.decoder import JSONDecodeError - from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ...core.pydantic_utilities import parse_obj_as -from ...core.request_options import RequestOptions -from ...types.union.types.animal import Animal +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -18,7 +18,10 @@ def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper def get_and_return_union( - self, *, request: Animal, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: Animal, + request_options: typing.Optional[RequestOptions] = None, ) -> Animal: """ Parameters @@ -49,11 +52,17 @@ def get_and_return_union( ) """ _response = self._client_wrapper.httpx_client.request( - "union", method="POST", json=request, request_options=request_options, omit=OMIT + "union", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(Animal, parse_obj_as(type_=Animal, object_=_response.json())) # type: ignore + return typing.cast( + Animal, parse_obj_as(type_=Animal, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -65,7 +74,10 @@ def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper async def get_and_return_union( - self, *, request: Animal, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: Animal, + request_options: typing.Optional[RequestOptions] = None, ) -> Animal: """ Parameters @@ -104,11 +116,17 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "union", method="POST", json=request, request_options=request_options, omit=OMIT + "union", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(Animal, parse_obj_as(type_=Animal, object_=_response.json())) # type: ignore + return typing.cast( + Animal, parse_obj_as(type_=Animal, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/no-custom-config/src/seed/general_errors/types/bad_object_request_info.py b/seed/python-sdk/exhaustive/no-custom-config/src/seed/general_errors/types/bad_object_request_info.py index 7f03429e922..73c44b89531 100644 --- a/seed/python-sdk/exhaustive/no-custom-config/src/seed/general_errors/types/bad_object_request_info.py +++ b/seed/python-sdk/exhaustive/no-custom-config/src/seed/general_errors/types/bad_object_request_info.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class BadObjectRequestInfo(UniversalBaseModel): message: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/no-custom-config/src/seed/inlined_requests/client.py b/seed/python-sdk/exhaustive/no-custom-config/src/seed/inlined_requests/client.py index f7c46698eb9..39e0c8fe637 100644 --- a/seed/python-sdk/exhaustive/no-custom-config/src/seed/inlined_requests/client.py +++ b/seed/python-sdk/exhaustive/no-custom-config/src/seed/inlined_requests/client.py @@ -1,15 +1,15 @@ # This file was auto-generated by Fern from our API Definition. import typing -from json.decoder import JSONDecodeError - -from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.pydantic_utilities import parse_obj_as +from ..core.client_wrapper import SyncClientWrapper +from ..types.object.types.object_with_optional_field import ObjectWithOptionalField from ..core.request_options import RequestOptions +from ..core.pydantic_utilities import parse_obj_as from ..general_errors.errors.bad_request_body import BadRequestBody from ..general_errors.types.bad_object_request_info import BadObjectRequestInfo -from ..types.object.types.object_with_optional_field import ObjectWithOptionalField +from json.decoder import JSONDecodeError +from ..core.api_error import ApiError +from ..core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -25,7 +25,7 @@ def post_with_object_bodyand_response( string: str, integer: int, nested_object: ObjectWithOptionalField, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> ObjectWithOptionalField: """ POST with custom object in request body, response is an object @@ -86,16 +86,30 @@ def post_with_object_bodyand_response( _response = self._client_wrapper.httpx_client.request( "req-bodies/object", method="POST", - json={"string": string, "integer": integer, "NestedObject": nested_object}, + json={ + "string": string, + "integer": integer, + "NestedObject": nested_object, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore if _response.status_code == 400: raise BadRequestBody( - typing.cast(BadObjectRequestInfo, parse_obj_as(type_=BadObjectRequestInfo, object_=_response.json())) # type: ignore + typing.cast( + BadObjectRequestInfo, + parse_obj_as( + type_=BadObjectRequestInfo, object_=_response.json() + ), + ) # type: ignore ) _response_json = _response.json() except JSONDecodeError: @@ -113,7 +127,7 @@ async def post_with_object_bodyand_response( string: str, integer: int, nested_object: ObjectWithOptionalField, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> ObjectWithOptionalField: """ POST with custom object in request body, response is an object @@ -181,16 +195,30 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( "req-bodies/object", method="POST", - json={"string": string, "integer": integer, "NestedObject": nested_object}, + json={ + "string": string, + "integer": integer, + "NestedObject": nested_object, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore if _response.status_code == 400: raise BadRequestBody( - typing.cast(BadObjectRequestInfo, parse_obj_as(type_=BadObjectRequestInfo, object_=_response.json())) # type: ignore + typing.cast( + BadObjectRequestInfo, + parse_obj_as( + type_=BadObjectRequestInfo, object_=_response.json() + ), + ) # type: ignore ) _response_json = _response.json() except JSONDecodeError: diff --git a/seed/python-sdk/exhaustive/no-custom-config/src/seed/no_auth/client.py b/seed/python-sdk/exhaustive/no-custom-config/src/seed/no_auth/client.py index 3d203bcea34..e5590cde0df 100644 --- a/seed/python-sdk/exhaustive/no-custom-config/src/seed/no_auth/client.py +++ b/seed/python-sdk/exhaustive/no-custom-config/src/seed/no_auth/client.py @@ -1,14 +1,14 @@ # This file was auto-generated by Fern from our API Definition. import typing -from json.decoder import JSONDecodeError - -from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.pydantic_utilities import parse_obj_as +from ..core.client_wrapper import SyncClientWrapper from ..core.request_options import RequestOptions +from ..core.pydantic_utilities import parse_obj_as from ..general_errors.errors.bad_request_body import BadRequestBody from ..general_errors.types.bad_object_request_info import BadObjectRequestInfo +from json.decoder import JSONDecodeError +from ..core.api_error import ApiError +from ..core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -19,7 +19,10 @@ def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper def post_with_no_auth( - self, *, request: typing.Any, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Any, + request_options: typing.Optional[RequestOptions] = None, ) -> bool: """ POST request with no auth @@ -48,14 +51,25 @@ def post_with_no_auth( ) """ _response = self._client_wrapper.httpx_client.request( - "no-auth", method="POST", json=request, request_options=request_options, omit=OMIT + "no-auth", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore if _response.status_code == 400: raise BadRequestBody( - typing.cast(BadObjectRequestInfo, parse_obj_as(type_=BadObjectRequestInfo, object_=_response.json())) # type: ignore + typing.cast( + BadObjectRequestInfo, + parse_obj_as( + type_=BadObjectRequestInfo, object_=_response.json() + ), + ) # type: ignore ) _response_json = _response.json() except JSONDecodeError: @@ -68,7 +82,10 @@ def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper async def post_with_no_auth( - self, *, request: typing.Any, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Any, + request_options: typing.Optional[RequestOptions] = None, ) -> bool: """ POST request with no auth @@ -105,14 +122,25 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "no-auth", method="POST", json=request, request_options=request_options, omit=OMIT + "no-auth", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore if _response.status_code == 400: raise BadRequestBody( - typing.cast(BadObjectRequestInfo, parse_obj_as(type_=BadObjectRequestInfo, object_=_response.json())) # type: ignore + typing.cast( + BadObjectRequestInfo, + parse_obj_as( + type_=BadObjectRequestInfo, object_=_response.json() + ), + ) # type: ignore ) _response_json = _response.json() except JSONDecodeError: diff --git a/seed/python-sdk/exhaustive/no-custom-config/src/seed/no_req_body/client.py b/seed/python-sdk/exhaustive/no-custom-config/src/seed/no_req_body/client.py index 33fa0c77d27..5afdd703fdc 100644 --- a/seed/python-sdk/exhaustive/no-custom-config/src/seed/no_req_body/client.py +++ b/seed/python-sdk/exhaustive/no-custom-config/src/seed/no_req_body/client.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. +from ..core.client_wrapper import SyncClientWrapper import typing -from json.decoder import JSONDecodeError - -from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.pydantic_utilities import parse_obj_as from ..core.request_options import RequestOptions from ..types.object.types.object_with_optional_field import ObjectWithOptionalField +from ..core.pydantic_utilities import parse_obj_as +from json.decoder import JSONDecodeError +from ..core.api_error import ApiError +from ..core.client_wrapper import AsyncClientWrapper class NoReqBodyClient: @@ -38,17 +38,26 @@ def get_with_no_request_body( client.no_req_body.get_with_no_request_body() """ _response = self._client_wrapper.httpx_client.request( - "no-req-body", method="GET", request_options=request_options + "no-req-body", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def post_with_no_request_body(self, *, request_options: typing.Optional[RequestOptions] = None) -> str: + def post_with_no_request_body( + self, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -70,11 +79,15 @@ def post_with_no_request_body(self, *, request_options: typing.Optional[RequestO client.no_req_body.post_with_no_request_body() """ _response = self._client_wrapper.httpx_client.request( - "no-req-body", method="POST", request_options=request_options + "no-req-body", + method="POST", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -117,17 +130,26 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "no-req-body", method="GET", request_options=request_options + "no-req-body", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - async def post_with_no_request_body(self, *, request_options: typing.Optional[RequestOptions] = None) -> str: + async def post_with_no_request_body( + self, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -157,11 +179,15 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "no-req-body", method="POST", request_options=request_options + "no-req-body", + method="POST", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/no-custom-config/src/seed/req_with_headers/client.py b/seed/python-sdk/exhaustive/no-custom-config/src/seed/req_with_headers/client.py index 655402249e9..984428516e3 100644 --- a/seed/python-sdk/exhaustive/no-custom-config/src/seed/req_with_headers/client.py +++ b/seed/python-sdk/exhaustive/no-custom-config/src/seed/req_with_headers/client.py @@ -1,11 +1,11 @@ # This file was auto-generated by Fern from our API Definition. import typing +from ..core.client_wrapper import SyncClientWrapper +from ..core.request_options import RequestOptions from json.decoder import JSONDecodeError - from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.request_options import RequestOptions +from ..core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -21,7 +21,7 @@ def get_with_custom_header( x_test_service_header: str, x_test_endpoint_header: str, request: str, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ Parameters @@ -58,8 +58,12 @@ def get_with_custom_header( method="POST", json=request, headers={ - "X-TEST-SERVICE-HEADER": str(x_test_service_header) if x_test_service_header is not None else None, - "X-TEST-ENDPOINT-HEADER": str(x_test_endpoint_header) if x_test_endpoint_header is not None else None, + "X-TEST-SERVICE-HEADER": str(x_test_service_header) + if x_test_service_header is not None + else None, + "X-TEST-ENDPOINT-HEADER": str(x_test_endpoint_header) + if x_test_endpoint_header is not None + else None, }, request_options=request_options, omit=OMIT, @@ -83,7 +87,7 @@ async def get_with_custom_header( x_test_service_header: str, x_test_endpoint_header: str, request: str, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ Parameters @@ -128,8 +132,12 @@ async def main() -> None: method="POST", json=request, headers={ - "X-TEST-SERVICE-HEADER": str(x_test_service_header) if x_test_service_header is not None else None, - "X-TEST-ENDPOINT-HEADER": str(x_test_endpoint_header) if x_test_endpoint_header is not None else None, + "X-TEST-SERVICE-HEADER": str(x_test_service_header) + if x_test_service_header is not None + else None, + "X-TEST-ENDPOINT-HEADER": str(x_test_endpoint_header) + if x_test_endpoint_header is not None + else None, }, request_options=request_options, omit=OMIT, diff --git a/seed/python-sdk/exhaustive/no-custom-config/src/seed/types/enum/types/weather_report.py b/seed/python-sdk/exhaustive/no-custom-config/src/seed/types/enum/types/weather_report.py index 2d54965dc22..84017ef161d 100644 --- a/seed/python-sdk/exhaustive/no-custom-config/src/seed/types/enum/types/weather_report.py +++ b/seed/python-sdk/exhaustive/no-custom-config/src/seed/types/enum/types/weather_report.py @@ -2,4 +2,6 @@ import typing -WeatherReport = typing.Union[typing.Literal["SUNNY", "CLOUDY", "RAINING", "SNOWING"], typing.Any] +WeatherReport = typing.Union[ + typing.Literal["SUNNY", "CLOUDY", "RAINING", "SNOWING"], typing.Any +] diff --git a/seed/python-sdk/exhaustive/no-custom-config/src/seed/types/object/types/double_optional.py b/seed/python-sdk/exhaustive/no-custom-config/src/seed/types/object/types/double_optional.py index ddf165b13bd..ed236347357 100644 --- a/seed/python-sdk/exhaustive/no-custom-config/src/seed/types/object/types/double_optional.py +++ b/seed/python-sdk/exhaustive/no-custom-config/src/seed/types/object/types/double_optional.py @@ -1,18 +1,21 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .optional_alias import OptionalAlias +import pydantic +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class DoubleOptional(UniversalBaseModel): - optional_alias: typing.Optional[OptionalAlias] = pydantic.Field(alias="optionalAlias", default=None) + optional_alias: typing.Optional[OptionalAlias] = pydantic.Field( + alias="optionalAlias", default=None + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/no-custom-config/src/seed/types/object/types/nested_object_with_optional_field.py b/seed/python-sdk/exhaustive/no-custom-config/src/seed/types/object/types/nested_object_with_optional_field.py index 81669c0dd39..20a4d40a714 100644 --- a/seed/python-sdk/exhaustive/no-custom-config/src/seed/types/object/types/nested_object_with_optional_field.py +++ b/seed/python-sdk/exhaustive/no-custom-config/src/seed/types/object/types/nested_object_with_optional_field.py @@ -1,19 +1,22 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .object_with_optional_field import ObjectWithOptionalField +import pydantic +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class NestedObjectWithOptionalField(UniversalBaseModel): string: typing.Optional[str] = None - nested_object: typing.Optional[ObjectWithOptionalField] = pydantic.Field(alias="NestedObject", default=None) + nested_object: typing.Optional[ObjectWithOptionalField] = pydantic.Field( + alias="NestedObject", default=None + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/no-custom-config/src/seed/types/object/types/nested_object_with_required_field.py b/seed/python-sdk/exhaustive/no-custom-config/src/seed/types/object/types/nested_object_with_required_field.py index 1a621942c6c..a6ca8781190 100644 --- a/seed/python-sdk/exhaustive/no-custom-config/src/seed/types/object/types/nested_object_with_required_field.py +++ b/seed/python-sdk/exhaustive/no-custom-config/src/seed/types/object/types/nested_object_with_required_field.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import UniversalBaseModel from .object_with_optional_field import ObjectWithOptionalField +import pydantic +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class NestedObjectWithRequiredField(UniversalBaseModel): @@ -13,7 +12,9 @@ class NestedObjectWithRequiredField(UniversalBaseModel): nested_object: ObjectWithOptionalField = pydantic.Field(alias="NestedObject") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/no-custom-config/src/seed/types/object/types/object_with_map_of_map.py b/seed/python-sdk/exhaustive/no-custom-config/src/seed/types/object/types/object_with_map_of_map.py index 8883cc1d498..313cd25ceb8 100644 --- a/seed/python-sdk/exhaustive/no-custom-config/src/seed/types/object/types/object_with_map_of_map.py +++ b/seed/python-sdk/exhaustive/no-custom-config/src/seed/types/object/types/object_with_map_of_map.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class ObjectWithMapOfMap(UniversalBaseModel): map_: typing.Dict[str, typing.Dict[str, str]] = pydantic.Field(alias="map") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/no-custom-config/src/seed/types/object/types/object_with_optional_field.py b/seed/python-sdk/exhaustive/no-custom-config/src/seed/types/object/types/object_with_optional_field.py index 6aab170be0c..9131f0e91d7 100644 --- a/seed/python-sdk/exhaustive/no-custom-config/src/seed/types/object/types/object_with_optional_field.py +++ b/seed/python-sdk/exhaustive/no-custom-config/src/seed/types/object/types/object_with_optional_field.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. -import datetime as dt +from ....core.pydantic_utilities import UniversalBaseModel import typing -import uuid - import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +import datetime as dt +import uuid +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class ObjectWithOptionalField(UniversalBaseModel): @@ -23,13 +22,19 @@ class ObjectWithOptionalField(UniversalBaseModel): date: typing.Optional[dt.date] = None uuid_: typing.Optional[uuid.UUID] = pydantic.Field(alias="uuid", default=None) base_64: typing.Optional[str] = pydantic.Field(alias="base64", default=None) - list_: typing.Optional[typing.List[str]] = pydantic.Field(alias="list", default=None) + list_: typing.Optional[typing.List[str]] = pydantic.Field( + alias="list", default=None + ) set_: typing.Optional[typing.Set[str]] = pydantic.Field(alias="set", default=None) - map_: typing.Optional[typing.Dict[int, str]] = pydantic.Field(alias="map", default=None) + map_: typing.Optional[typing.Dict[int, str]] = pydantic.Field( + alias="map", default=None + ) bigint: typing.Optional[str] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/no-custom-config/src/seed/types/object/types/object_with_required_field.py b/seed/python-sdk/exhaustive/no-custom-config/src/seed/types/object/types/object_with_required_field.py index 61b98867984..24db26a3cf8 100644 --- a/seed/python-sdk/exhaustive/no-custom-config/src/seed/types/object/types/object_with_required_field.py +++ b/seed/python-sdk/exhaustive/no-custom-config/src/seed/types/object/types/object_with_required_field.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class ObjectWithRequiredField(UniversalBaseModel): string: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/no-custom-config/src/seed/types/union/types/animal.py b/seed/python-sdk/exhaustive/no-custom-config/src/seed/types/union/types/animal.py index 1ae43d1663e..84c71d2009a 100644 --- a/seed/python-sdk/exhaustive/no-custom-config/src/seed/types/union/types/animal.py +++ b/seed/python-sdk/exhaustive/no-custom-config/src/seed/types/union/types/animal.py @@ -1,12 +1,10 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ....core.pydantic_utilities import UniversalBaseModel import typing - import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class Animal_Dog(UniversalBaseModel): @@ -15,7 +13,9 @@ class Animal_Dog(UniversalBaseModel): likes_to_woof: bool = pydantic.Field(alias="likesToWoof") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: @@ -30,7 +30,9 @@ class Animal_Cat(UniversalBaseModel): likes_to_meow: bool = pydantic.Field(alias="likesToMeow") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/no-custom-config/src/seed/types/union/types/cat.py b/seed/python-sdk/exhaustive/no-custom-config/src/seed/types/union/types/cat.py index 61fc5527b1f..c59b78523c9 100644 --- a/seed/python-sdk/exhaustive/no-custom-config/src/seed/types/union/types/cat.py +++ b/seed/python-sdk/exhaustive/no-custom-config/src/seed/types/union/types/cat.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ....core.pydantic_utilities import UniversalBaseModel import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class Cat(UniversalBaseModel): @@ -12,7 +11,9 @@ class Cat(UniversalBaseModel): likes_to_meow: bool = pydantic.Field(alias="likesToMeow") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/no-custom-config/src/seed/types/union/types/dog.py b/seed/python-sdk/exhaustive/no-custom-config/src/seed/types/union/types/dog.py index c1ff5339dfe..e250c72edef 100644 --- a/seed/python-sdk/exhaustive/no-custom-config/src/seed/types/union/types/dog.py +++ b/seed/python-sdk/exhaustive/no-custom-config/src/seed/types/union/types/dog.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ....core.pydantic_utilities import UniversalBaseModel import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class Dog(UniversalBaseModel): @@ -12,7 +11,9 @@ class Dog(UniversalBaseModel): likes_to_woof: bool = pydantic.Field(alias="likesToWoof") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/no-custom-config/src/seed/version.py b/seed/python-sdk/exhaustive/no-custom-config/src/seed/version.py index 63ba170685a..ac44536abdb 100644 --- a/seed/python-sdk/exhaustive/no-custom-config/src/seed/version.py +++ b/seed/python-sdk/exhaustive/no-custom-config/src/seed/version.py @@ -1,4 +1,3 @@ - from importlib import metadata __version__ = metadata.version("fern_exhaustive") diff --git a/seed/python-sdk/exhaustive/no-custom-config/tests/conftest.py b/seed/python-sdk/exhaustive/no-custom-config/tests/conftest.py index b5b50383b94..86cb2b41af8 100644 --- a/seed/python-sdk/exhaustive/no-custom-config/tests/conftest.py +++ b/seed/python-sdk/exhaustive/no-custom-config/tests/conftest.py @@ -1,16 +1,22 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive import os - import pytest -from seed import AsyncSeedExhaustive, SeedExhaustive +from seed import AsyncSeedExhaustive @pytest.fixture def client() -> SeedExhaustive: - return SeedExhaustive(token=os.getenv("ENV_TOKEN", "token"), base_url=os.getenv("TESTS_BASE_URL", "base_url")) + return SeedExhaustive( + token=os.getenv("ENV_TOKEN", "token"), + base_url=os.getenv("TESTS_BASE_URL", "base_url"), + ) @pytest.fixture def async_client() -> AsyncSeedExhaustive: - return AsyncSeedExhaustive(token=os.getenv("ENV_TOKEN", "token"), base_url=os.getenv("TESTS_BASE_URL", "base_url")) + return AsyncSeedExhaustive( + token=os.getenv("ENV_TOKEN", "token"), + base_url=os.getenv("TESTS_BASE_URL", "base_url"), + ) diff --git a/seed/python-sdk/exhaustive/no-custom-config/tests/custom/test_client.py b/seed/python-sdk/exhaustive/no-custom-config/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/python-sdk/exhaustive/no-custom-config/tests/custom/test_client.py +++ b/seed/python-sdk/exhaustive/no-custom-config/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/python-sdk/exhaustive/no-custom-config/tests/endpoints/test_container.py b/seed/python-sdk/exhaustive/no-custom-config/tests/endpoints/test_container.py index 17d9d75240d..240f16f2a8c 100644 --- a/seed/python-sdk/exhaustive/no-custom-config/tests/endpoints/test_container.py +++ b/seed/python-sdk/exhaustive/no-custom-config/tests/endpoints/test_container.py @@ -1,91 +1,137 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing - -from seed import AsyncSeedExhaustive, SeedExhaustive -from seed.types.object import ObjectWithRequiredField - from ..utilities import validate_response +from seed.types.object import ObjectWithRequiredField -async def test_get_and_return_list_of_primitives(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_list_of_primitives( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = ["string"] expected_types: typing.Tuple[typing.Any, typing.Any] = ("list", {0: None}) - response = client.endpoints.container.get_and_return_list_of_primitives(request=["string"]) + response = client.endpoints.container.get_and_return_list_of_primitives( + request=["string"] + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.container.get_and_return_list_of_primitives(request=["string"]) + async_response = ( + await async_client.endpoints.container.get_and_return_list_of_primitives( + request=["string"] + ) + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_list_of_objects(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_list_of_objects( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = [{"string": "string"}] - expected_types: typing.Tuple[typing.Any, typing.Any] = ("list", {0: {"string": None}}) + expected_types: typing.Tuple[typing.Any, typing.Any] = ( + "list", + {0: {"string": None}}, + ) response = client.endpoints.container.get_and_return_list_of_objects( request=[ObjectWithRequiredField(string="string")] ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.container.get_and_return_list_of_objects( - request=[ObjectWithRequiredField(string="string")] + async_response = ( + await async_client.endpoints.container.get_and_return_list_of_objects( + request=[ObjectWithRequiredField(string="string")] + ) ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_set_of_primitives(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_set_of_primitives( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = ["string"] expected_types: typing.Tuple[typing.Any, typing.Any] = ("set", {0: None}) - response = client.endpoints.container.get_and_return_set_of_primitives(request={"string"}) + response = client.endpoints.container.get_and_return_set_of_primitives( + request={"string"} + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.container.get_and_return_set_of_primitives(request={"string"}) + async_response = ( + await async_client.endpoints.container.get_and_return_set_of_primitives( + request={"string"} + ) + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_set_of_objects(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_set_of_objects( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = [{"string": "string"}] - expected_types: typing.Tuple[typing.Any, typing.Any] = ("set", {0: {"string": None}}) + expected_types: typing.Tuple[typing.Any, typing.Any] = ( + "set", + {0: {"string": None}}, + ) response = client.endpoints.container.get_and_return_set_of_objects( request=[ObjectWithRequiredField(string="string")] ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.container.get_and_return_set_of_objects( - request=[ObjectWithRequiredField(string="string")] + async_response = ( + await async_client.endpoints.container.get_and_return_set_of_objects( + request=[ObjectWithRequiredField(string="string")] + ) ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_map_prim_to_prim(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_map_prim_to_prim( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = {"string": "string"} expected_types: typing.Tuple[typing.Any, typing.Any] = ("dict", {0: (None, None)}) - response = client.endpoints.container.get_and_return_map_prim_to_prim(request={"string": "string"}) + response = client.endpoints.container.get_and_return_map_prim_to_prim( + request={"string": "string"} + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.container.get_and_return_map_prim_to_prim( - request={"string": "string"} + async_response = ( + await async_client.endpoints.container.get_and_return_map_prim_to_prim( + request={"string": "string"} + ) ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_map_of_prim_to_object(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_map_of_prim_to_object( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = {"string": {"string": "string"}} - expected_types: typing.Tuple[typing.Any, typing.Any] = ("dict", {0: (None, {"string": None})}) + expected_types: typing.Tuple[typing.Any, typing.Any] = ( + "dict", + {0: (None, {"string": None})}, + ) response = client.endpoints.container.get_and_return_map_of_prim_to_object( request={"string": ObjectWithRequiredField(string="string")} ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.container.get_and_return_map_of_prim_to_object( - request={"string": ObjectWithRequiredField(string="string")} + async_response = ( + await async_client.endpoints.container.get_and_return_map_of_prim_to_object( + request={"string": ObjectWithRequiredField(string="string")} + ) ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_optional(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_optional( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = {"string": "string"} expected_types: typing.Any = {"string": None} - response = client.endpoints.container.get_and_return_optional(request=ObjectWithRequiredField(string="string")) + response = client.endpoints.container.get_and_return_optional( + request=ObjectWithRequiredField(string="string") + ) validate_response(response, expected_response, expected_types) async_response = await async_client.endpoints.container.get_and_return_optional( diff --git a/seed/python-sdk/exhaustive/no-custom-config/tests/endpoints/test_enum.py b/seed/python-sdk/exhaustive/no-custom-config/tests/endpoints/test_enum.py index 890aada5ce4..ca3fca30b5a 100644 --- a/seed/python-sdk/exhaustive/no-custom-config/tests/endpoints/test_enum.py +++ b/seed/python-sdk/exhaustive/no-custom-config/tests/endpoints/test_enum.py @@ -1,17 +1,20 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing - -from seed import AsyncSeedExhaustive, SeedExhaustive - from ..utilities import validate_response -async def test_get_and_return_enum(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_enum( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "SUNNY" expected_types: typing.Any = None response = client.endpoints.enum.get_and_return_enum(request="SUNNY") validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.enum.get_and_return_enum(request="SUNNY") + async_response = await async_client.endpoints.enum.get_and_return_enum( + request="SUNNY" + ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/exhaustive/no-custom-config/tests/endpoints/test_http_methods.py b/seed/python-sdk/exhaustive/no-custom-config/tests/endpoints/test_http_methods.py index dc01bafcf6f..77131fc6e8b 100644 --- a/seed/python-sdk/exhaustive/no-custom-config/tests/endpoints/test_http_methods.py +++ b/seed/python-sdk/exhaustive/no-custom-config/tests/endpoints/test_http_methods.py @@ -1,15 +1,16 @@ # This file was auto-generated by Fern from our API Definition. -import datetime +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing -import uuid - -from seed import AsyncSeedExhaustive, SeedExhaustive - from ..utilities import validate_response +import datetime +import uuid -async def test_test_get(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_test_get( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "string" expected_types: typing.Any = None response = client.endpoints.http_methods.test_get(id="string") @@ -19,7 +20,9 @@ async def test_test_get(client: SeedExhaustive, async_client: AsyncSeedExhaustiv validate_response(async_response, expected_response, expected_types) -async def test_test_post(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_test_post( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = { "string": "string", "integer": 1, @@ -53,11 +56,15 @@ async def test_test_post(client: SeedExhaustive, async_client: AsyncSeedExhausti response = client.endpoints.http_methods.test_post(string="string") validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.http_methods.test_post(string="string") + async_response = await async_client.endpoints.http_methods.test_post( + string="string" + ) validate_response(async_response, expected_response, expected_types) -async def test_test_put(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_test_put( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = { "string": "string", "integer": 1, @@ -91,11 +98,15 @@ async def test_test_put(client: SeedExhaustive, async_client: AsyncSeedExhaustiv response = client.endpoints.http_methods.test_put(id="string", string="string") validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.http_methods.test_put(id="string", string="string") + async_response = await async_client.endpoints.http_methods.test_put( + id="string", string="string" + ) validate_response(async_response, expected_response, expected_types) -async def test_test_patch(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_test_patch( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = { "string": "string", "integer": 1, @@ -163,7 +174,9 @@ async def test_test_patch(client: SeedExhaustive, async_client: AsyncSeedExhaust validate_response(async_response, expected_response, expected_types) -async def test_test_delete(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_test_delete( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = True expected_types: typing.Any = None response = client.endpoints.http_methods.test_delete(id="string") diff --git a/seed/python-sdk/exhaustive/no-custom-config/tests/endpoints/test_object.py b/seed/python-sdk/exhaustive/no-custom-config/tests/endpoints/test_object.py index a9098b6e9ef..c48c4332b22 100644 --- a/seed/python-sdk/exhaustive/no-custom-config/tests/endpoints/test_object.py +++ b/seed/python-sdk/exhaustive/no-custom-config/tests/endpoints/test_object.py @@ -1,16 +1,18 @@ # This file was auto-generated by Fern from our API Definition. -import datetime +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing +import datetime import uuid - -from seed import AsyncSeedExhaustive, SeedExhaustive -from seed.types.object import NestedObjectWithRequiredField, ObjectWithOptionalField - from ..utilities import validate_response +from seed.types.object import ObjectWithOptionalField +from seed.types.object import NestedObjectWithRequiredField -async def test_get_and_return_with_optional_field(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_with_optional_field( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = { "string": "string", "integer": 1, @@ -58,38 +60,54 @@ async def test_get_and_return_with_optional_field(client: SeedExhaustive, async_ ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.object.get_and_return_with_optional_field( - string="string", - integer=1, - long_=1000000, - double=1.1, - bool_=True, - datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), - date=datetime.date.fromisoformat("2023-01-15"), - uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), - base_64="SGVsbG8gd29ybGQh", - list_=["string"], - set_={"string"}, - map_={1: "string"}, - bigint="123456789123456789", + async_response = ( + await async_client.endpoints.object.get_and_return_with_optional_field( + string="string", + integer=1, + long_=1000000, + double=1.1, + bool_=True, + datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), + date=datetime.date.fromisoformat("2023-01-15"), + uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + base_64="SGVsbG8gd29ybGQh", + list_=["string"], + set_={"string"}, + map_={1: "string"}, + bigint="123456789123456789", + ) ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_with_required_field(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_with_required_field( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = {"string": "string"} expected_types: typing.Any = {"string": None} - response = client.endpoints.object.get_and_return_with_required_field(string="string") + response = client.endpoints.object.get_and_return_with_required_field( + string="string" + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.object.get_and_return_with_required_field(string="string") + async_response = ( + await async_client.endpoints.object.get_and_return_with_required_field( + string="string" + ) + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_with_map_of_map(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_with_map_of_map( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = {"map": {"string": {"string": "string"}}} - expected_types: typing.Any = {"map": ("dict", {0: (None, ("dict", {0: (None, None)}))})} - response = client.endpoints.object.get_and_return_with_map_of_map(map_={"string": {"string": "string"}}) + expected_types: typing.Any = { + "map": ("dict", {0: (None, ("dict", {0: (None, None)}))}) + } + response = client.endpoints.object.get_and_return_with_map_of_map( + map_={"string": {"string": "string"}} + ) validate_response(response, expected_response, expected_types) async_response = await async_client.endpoints.object.get_and_return_with_map_of_map( @@ -157,23 +175,25 @@ async def test_get_and_return_nested_with_optional_field( ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.object.get_and_return_nested_with_optional_field( - string="string", - nested_object=ObjectWithOptionalField( + async_response = ( + await async_client.endpoints.object.get_and_return_nested_with_optional_field( string="string", - integer=1, - long_=1000000, - double=1.1, - bool_=True, - datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), - date=datetime.date.fromisoformat("2023-01-15"), - uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), - base_64="SGVsbG8gd29ybGQh", - list_=["string"], - set_={"string"}, - map_={1: "string"}, - bigint="123456789123456789", - ), + nested_object=ObjectWithOptionalField( + string="string", + integer=1, + long_=1000000, + double=1.1, + bool_=True, + datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), + date=datetime.date.fromisoformat("2023-01-15"), + uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + base_64="SGVsbG8gd29ybGQh", + list_=["string"], + set_={"string"}, + map_={1: "string"}, + bigint="123456789123456789", + ), + ) ) validate_response(async_response, expected_response, expected_types) @@ -238,24 +258,26 @@ async def test_get_and_return_nested_with_required_field( ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.object.get_and_return_nested_with_required_field( - string_="string", - string="string", - nested_object=ObjectWithOptionalField( + async_response = ( + await async_client.endpoints.object.get_and_return_nested_with_required_field( + string_="string", string="string", - integer=1, - long_=1000000, - double=1.1, - bool_=True, - datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), - date=datetime.date.fromisoformat("2023-01-15"), - uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), - base_64="SGVsbG8gd29ybGQh", - list_=["string"], - set_={"string"}, - map_={1: "string"}, - bigint="123456789123456789", - ), + nested_object=ObjectWithOptionalField( + string="string", + integer=1, + long_=1000000, + double=1.1, + bool_=True, + datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), + date=datetime.date.fromisoformat("2023-01-15"), + uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + base_64="SGVsbG8gd29ybGQh", + list_=["string"], + set_={"string"}, + map_={1: "string"}, + bigint="123456789123456789", + ), + ) ) validate_response(async_response, expected_response, expected_types) @@ -299,27 +321,31 @@ async def test_get_and_return_nested_with_required_field_as_list( "bigint": None, }, } - response = client.endpoints.object.get_and_return_nested_with_required_field_as_list( - request=[ - NestedObjectWithRequiredField( - string="string", - nested_object=ObjectWithOptionalField( + response = ( + client.endpoints.object.get_and_return_nested_with_required_field_as_list( + request=[ + NestedObjectWithRequiredField( string="string", - integer=1, - long_=1000000, - double=1.1, - bool_=True, - datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), - date=datetime.date.fromisoformat("2023-01-15"), - uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), - base_64="SGVsbG8gd29ybGQh", - list_=["string"], - set_={"string"}, - map_={1: "string"}, - bigint="123456789123456789", - ), - ) - ] + nested_object=ObjectWithOptionalField( + string="string", + integer=1, + long_=1000000, + double=1.1, + bool_=True, + datetime=datetime.datetime.fromisoformat( + "2024-01-15 09:30:00+00:00" + ), + date=datetime.date.fromisoformat("2023-01-15"), + uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + base_64="SGVsbG8gd29ybGQh", + list_=["string"], + set_={"string"}, + map_={1: "string"}, + bigint="123456789123456789", + ), + ) + ] + ) ) validate_response(response, expected_response, expected_types) @@ -333,7 +359,9 @@ async def test_get_and_return_nested_with_required_field_as_list( long_=1000000, double=1.1, bool_=True, - datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), + datetime=datetime.datetime.fromisoformat( + "2024-01-15 09:30:00+00:00" + ), date=datetime.date.fromisoformat("2023-01-15"), uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), base_64="SGVsbG8gd29ybGQh", diff --git a/seed/python-sdk/exhaustive/no-custom-config/tests/endpoints/test_params.py b/seed/python-sdk/exhaustive/no-custom-config/tests/endpoints/test_params.py index 163d7b9161d..d8ffb00c0a0 100644 --- a/seed/python-sdk/exhaustive/no-custom-config/tests/endpoints/test_params.py +++ b/seed/python-sdk/exhaustive/no-custom-config/tests/endpoints/test_params.py @@ -1,13 +1,14 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing - -from seed import AsyncSeedExhaustive, SeedExhaustive - from ..utilities import validate_response -async def test_get_with_path(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_with_path( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "string" expected_types: typing.Any = None response = client.endpoints.params.get_with_path(param="string") @@ -17,32 +18,63 @@ async def test_get_with_path(client: SeedExhaustive, async_client: AsyncSeedExha validate_response(async_response, expected_response, expected_types) -async def test_get_with_query(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_with_query( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: # Type ignore to avoid mypy complaining about the function not being meant to return a value assert client.endpoints.params.get_with_query(query="string", number=1) is None # type: ignore[func-returns-value] - assert await async_client.endpoints.params.get_with_query(query="string", number=1) is None # type: ignore[func-returns-value] + assert ( + await async_client.endpoints.params.get_with_query(query="string", number=1) + is None + ) # type: ignore[func-returns-value] -async def test_get_with_allow_multiple_query(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_with_allow_multiple_query( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: # Type ignore to avoid mypy complaining about the function not being meant to return a value - assert client.endpoints.params.get_with_allow_multiple_query(query="string", numer=1) is None # type: ignore[func-returns-value] - - assert await async_client.endpoints.params.get_with_allow_multiple_query(query="string", numer=1) is None # type: ignore[func-returns-value] - - -async def test_get_with_path_and_query(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: + assert ( + client.endpoints.params.get_with_allow_multiple_query(query="string", numer=1) + is None + ) # type: ignore[func-returns-value] + + assert ( + await async_client.endpoints.params.get_with_allow_multiple_query( + query="string", numer=1 + ) + is None + ) # type: ignore[func-returns-value] + + +async def test_get_with_path_and_query( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: # Type ignore to avoid mypy complaining about the function not being meant to return a value - assert client.endpoints.params.get_with_path_and_query(param="string", query="string") is None # type: ignore[func-returns-value] - - assert await async_client.endpoints.params.get_with_path_and_query(param="string", query="string") is None # type: ignore[func-returns-value] - - -async def test_modify_with_path(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: + assert ( + client.endpoints.params.get_with_path_and_query(param="string", query="string") + is None + ) # type: ignore[func-returns-value] + + assert ( + await async_client.endpoints.params.get_with_path_and_query( + param="string", query="string" + ) + is None + ) # type: ignore[func-returns-value] + + +async def test_modify_with_path( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "string" expected_types: typing.Any = None - response = client.endpoints.params.modify_with_path(param="string", request="string") + response = client.endpoints.params.modify_with_path( + param="string", request="string" + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.params.modify_with_path(param="string", request="string") + async_response = await async_client.endpoints.params.modify_with_path( + param="string", request="string" + ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/exhaustive/no-custom-config/tests/endpoints/test_primitive.py b/seed/python-sdk/exhaustive/no-custom-config/tests/endpoints/test_primitive.py index ba3bc7e29e5..26cbcf45d2f 100644 --- a/seed/python-sdk/exhaustive/no-custom-config/tests/endpoints/test_primitive.py +++ b/seed/python-sdk/exhaustive/no-custom-config/tests/endpoints/test_primitive.py @@ -1,65 +1,86 @@ # This file was auto-generated by Fern from our API Definition. -import datetime +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing -import uuid - -from seed import AsyncSeedExhaustive, SeedExhaustive - from ..utilities import validate_response +import datetime +import uuid -async def test_get_and_return_string(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_string( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "string" expected_types: typing.Any = None response = client.endpoints.primitive.get_and_return_string(request="string") validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.primitive.get_and_return_string(request="string") + async_response = await async_client.endpoints.primitive.get_and_return_string( + request="string" + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_int(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_int( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = 1 expected_types: typing.Any = "integer" response = client.endpoints.primitive.get_and_return_int(request=1) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.primitive.get_and_return_int(request=1) + async_response = await async_client.endpoints.primitive.get_and_return_int( + request=1 + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_long(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_long( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = 1000000 expected_types: typing.Any = None response = client.endpoints.primitive.get_and_return_long(request=1000000) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.primitive.get_and_return_long(request=1000000) + async_response = await async_client.endpoints.primitive.get_and_return_long( + request=1000000 + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_double(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_double( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = 1.1 expected_types: typing.Any = None response = client.endpoints.primitive.get_and_return_double(request=1.1) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.primitive.get_and_return_double(request=1.1) + async_response = await async_client.endpoints.primitive.get_and_return_double( + request=1.1 + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_bool(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_bool( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = True expected_types: typing.Any = None response = client.endpoints.primitive.get_and_return_bool(request=True) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.primitive.get_and_return_bool(request=True) + async_response = await async_client.endpoints.primitive.get_and_return_bool( + request=True + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_datetime(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_datetime( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "2024-01-15T09:30:00Z" expected_types: typing.Any = "datetime" response = client.endpoints.primitive.get_and_return_datetime( @@ -73,10 +94,14 @@ async def test_get_and_return_datetime(client: SeedExhaustive, async_client: Asy validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_date(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_date( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "2023-01-15" expected_types: typing.Any = "date" - response = client.endpoints.primitive.get_and_return_date(request=datetime.date.fromisoformat("2023-01-15")) + response = client.endpoints.primitive.get_and_return_date( + request=datetime.date.fromisoformat("2023-01-15") + ) validate_response(response, expected_response, expected_types) async_response = await async_client.endpoints.primitive.get_and_return_date( @@ -85,10 +110,14 @@ async def test_get_and_return_date(client: SeedExhaustive, async_client: AsyncSe validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_uuid(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_uuid( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32" expected_types: typing.Any = "uuid" - response = client.endpoints.primitive.get_and_return_uuid(request=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32")) + response = client.endpoints.primitive.get_and_return_uuid( + request=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32") + ) validate_response(response, expected_response, expected_types) async_response = await async_client.endpoints.primitive.get_and_return_uuid( @@ -97,11 +126,17 @@ async def test_get_and_return_uuid(client: SeedExhaustive, async_client: AsyncSe validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_base_64(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_base_64( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "SGVsbG8gd29ybGQh" expected_types: typing.Any = None - response = client.endpoints.primitive.get_and_return_base_64(request="SGVsbG8gd29ybGQh") + response = client.endpoints.primitive.get_and_return_base_64( + request="SGVsbG8gd29ybGQh" + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.primitive.get_and_return_base_64(request="SGVsbG8gd29ybGQh") + async_response = await async_client.endpoints.primitive.get_and_return_base_64( + request="SGVsbG8gd29ybGQh" + ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/exhaustive/no-custom-config/tests/endpoints/test_union.py b/seed/python-sdk/exhaustive/no-custom-config/tests/endpoints/test_union.py index 14e34c2a6df..ceb84928cd9 100644 --- a/seed/python-sdk/exhaustive/no-custom-config/tests/endpoints/test_union.py +++ b/seed/python-sdk/exhaustive/no-custom-config/tests/endpoints/test_union.py @@ -1,17 +1,24 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing - -from seed import AsyncSeedExhaustive, SeedExhaustive from seed.types.union import Animal_Dog - from ..utilities import validate_response -async def test_get_and_return_union(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: - expected_response: typing.Any = {"animal": "dog", "name": "string", "likesToWoof": True} +async def test_get_and_return_union( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: + expected_response: typing.Any = { + "animal": "dog", + "name": "string", + "likesToWoof": True, + } expected_types: typing.Any = "no_validate" - response = client.endpoints.union.get_and_return_union(request=Animal_Dog(name="string", likes_to_woof=True)) + response = client.endpoints.union.get_and_return_union( + request=Animal_Dog(name="string", likes_to_woof=True) + ) validate_response(response, expected_response, expected_types) async_response = await async_client.endpoints.union.get_and_return_union( diff --git a/seed/python-sdk/exhaustive/no-custom-config/tests/test_inlined_requests.py b/seed/python-sdk/exhaustive/no-custom-config/tests/test_inlined_requests.py index bb9390d3845..03f46b31cc9 100644 --- a/seed/python-sdk/exhaustive/no-custom-config/tests/test_inlined_requests.py +++ b/seed/python-sdk/exhaustive/no-custom-config/tests/test_inlined_requests.py @@ -1,16 +1,17 @@ # This file was auto-generated by Fern from our API Definition. -import datetime +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing -import uuid - -from seed import AsyncSeedExhaustive, SeedExhaustive from seed.types.object import ObjectWithOptionalField - +import datetime +import uuid from .utilities import validate_response -async def test_post_with_object_bodyand_response(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_post_with_object_bodyand_response( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = { "string": "string", "integer": 1, @@ -62,23 +63,25 @@ async def test_post_with_object_bodyand_response(client: SeedExhaustive, async_c ) validate_response(response, expected_response, expected_types) - async_response = await async_client.inlined_requests.post_with_object_bodyand_response( - string="string", - integer=1, - nested_object=ObjectWithOptionalField( + async_response = ( + await async_client.inlined_requests.post_with_object_bodyand_response( string="string", integer=1, - long_=1000000, - double=1.1, - bool_=True, - datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), - date=datetime.date.fromisoformat("2023-01-15"), - uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), - base_64="SGVsbG8gd29ybGQh", - list_=["string"], - set_={"string"}, - map_={1: "string"}, - bigint="123456789123456789", - ), + nested_object=ObjectWithOptionalField( + string="string", + integer=1, + long_=1000000, + double=1.1, + bool_=True, + datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), + date=datetime.date.fromisoformat("2023-01-15"), + uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + base_64="SGVsbG8gd29ybGQh", + list_=["string"], + set_={"string"}, + map_={1: "string"}, + bigint="123456789123456789", + ), + ) ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/exhaustive/no-custom-config/tests/test_no_auth.py b/seed/python-sdk/exhaustive/no-custom-config/tests/test_no_auth.py index 3328661bb48..fc475f4b6fb 100644 --- a/seed/python-sdk/exhaustive/no-custom-config/tests/test_no_auth.py +++ b/seed/python-sdk/exhaustive/no-custom-config/tests/test_no_auth.py @@ -1,17 +1,20 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing - -from seed import AsyncSeedExhaustive, SeedExhaustive - from .utilities import validate_response -async def test_post_with_no_auth(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_post_with_no_auth( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = True expected_types: typing.Any = None response = client.no_auth.post_with_no_auth(request={"key": "value"}) validate_response(response, expected_response, expected_types) - async_response = await async_client.no_auth.post_with_no_auth(request={"key": "value"}) + async_response = await async_client.no_auth.post_with_no_auth( + request={"key": "value"} + ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/exhaustive/no-custom-config/tests/test_no_req_body.py b/seed/python-sdk/exhaustive/no-custom-config/tests/test_no_req_body.py index 73abac9d2d8..07061a0e99e 100644 --- a/seed/python-sdk/exhaustive/no-custom-config/tests/test_no_req_body.py +++ b/seed/python-sdk/exhaustive/no-custom-config/tests/test_no_req_body.py @@ -1,13 +1,14 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing - -from seed import AsyncSeedExhaustive, SeedExhaustive - from .utilities import validate_response -async def test_get_with_no_request_body(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_with_no_request_body( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = { "string": "string", "integer": 1, @@ -45,7 +46,9 @@ async def test_get_with_no_request_body(client: SeedExhaustive, async_client: As validate_response(async_response, expected_response, expected_types) -async def test_post_with_no_request_body(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_post_with_no_request_body( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "string" expected_types: typing.Any = None response = client.no_req_body.post_with_no_request_body() diff --git a/seed/python-sdk/exhaustive/no-custom-config/tests/test_req_with_headers.py b/seed/python-sdk/exhaustive/no-custom-config/tests/test_req_with_headers.py index bba3b5b5507..75ce9d00c03 100644 --- a/seed/python-sdk/exhaustive/no-custom-config/tests/test_req_with_headers.py +++ b/seed/python-sdk/exhaustive/no-custom-config/tests/test_req_with_headers.py @@ -1,10 +1,27 @@ # This file was auto-generated by Fern from our API Definition. -from seed import AsyncSeedExhaustive, SeedExhaustive +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive -async def test_get_with_custom_header(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_with_custom_header( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: # Type ignore to avoid mypy complaining about the function not being meant to return a value - assert client.req_with_headers.get_with_custom_header(x_test_service_header="string", x_test_endpoint_header="string", request="string") is None # type: ignore[func-returns-value] + assert ( + client.req_with_headers.get_with_custom_header( + x_test_service_header="string", + x_test_endpoint_header="string", + request="string", + ) + is None + ) # type: ignore[func-returns-value] - assert await async_client.req_with_headers.get_with_custom_header(x_test_service_header="string", x_test_endpoint_header="string", request="string") is None # type: ignore[func-returns-value] + assert ( + await async_client.req_with_headers.get_with_custom_header( + x_test_service_header="string", + x_test_endpoint_header="string", + request="string", + ) + is None + ) # type: ignore[func-returns-value] diff --git a/seed/python-sdk/exhaustive/no-custom-config/tests/utilities.py b/seed/python-sdk/exhaustive/no-custom-config/tests/utilities.py index 13da208eb3a..e8f4472564c 100644 --- a/seed/python-sdk/exhaustive/no-custom-config/tests/utilities.py +++ b/seed/python-sdk/exhaustive/no-custom-config/tests/utilities.py @@ -3,11 +3,14 @@ import typing import uuid -import pydantic from dateutil import parser +import pydantic + -def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> typing.Any: +def cast_field( + json_expectation: typing.Any, type_expectation: typing.Any +) -> typing.Any: # Cast these specific types which come through as string and expect our # models to cast to the correct type. if type_expectation == "uuid": @@ -25,7 +28,9 @@ def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> ty return json_expectation -def validate_field(response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any) -> None: +def validate_field( + response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectation == "no_validate": return @@ -44,7 +49,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(entry_expectation, dict): is_container_of_complex_type = True validate_response( - response=response[idx], json_expectation=ex, type_expectations=entry_expectation + response=response[idx], + json_expectation=ex, + type_expectations=entry_expectation, ) else: cast_json_expectation.append(cast_field(ex, entry_expectation)) @@ -56,7 +63,10 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # if any of the values of the set have a type_expectation of a dict, we're assuming it's a pydantic # model and keeping it a list. if container_expectation != "set" or not any( - map(lambda value: isinstance(value, dict), list(contents_expectation.values())) + map( + lambda value: isinstance(value, dict), + list(contents_expectation.values()), + ) ): json_expectation = cast_field(json_expectation, container_expectation) elif isinstance(type_expectation, tuple): @@ -65,9 +75,15 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(contents_expectation, dict): json_expectation = { cast_field( - key, contents_expectation.get(idx)[0] if contents_expectation.get(idx) is not None else None # type: ignore + key, + contents_expectation.get(idx)[0] + if contents_expectation.get(idx) is not None + else None, # type: ignore ): cast_field( - value, contents_expectation.get(idx)[1] if contents_expectation.get(idx) is not None else None # type: ignore + value, + contents_expectation.get(idx)[1] + if contents_expectation.get(idx) is not None + else None, # type: ignore ) for idx, (key, value) in enumerate(json_expectation.items()) } @@ -86,7 +102,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # Arg type_expectations is a deeply nested structure that matches the response, but with the values replaced with the expected types -def validate_response(response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any) -> None: +def validate_response( + response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectations == "no_validate": return @@ -96,11 +114,17 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e and not isinstance(response, dict) and not issubclass(type(response), pydantic.BaseModel) ): - validate_field(response=response, json_expectation=json_expectation, type_expectation=type_expectations) + validate_field( + response=response, + json_expectation=json_expectation, + type_expectation=type_expectations, + ) return if isinstance(response, list): - assert len(response) == len(json_expectation), "Length mismatch, expected: {0}, Actual: {1}".format( + assert len(response) == len( + json_expectation + ), "Length mismatch, expected: {0}, Actual: {1}".format( len(response), len(json_expectation) ) content_expectation = type_expectations @@ -108,7 +132,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e content_expectation = type_expectations[1] for idx, item in enumerate(response): validate_response( - response=item, json_expectation=json_expectation[idx], type_expectations=content_expectation[idx] + response=item, + json_expectation=json_expectation[idx], + type_expectations=content_expectation[idx], ) else: response_json = response @@ -116,7 +142,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e response_json = response.dict(by_alias=True) for key, value in json_expectation.items(): - assert key in response_json, "Field {0} not found within the response object: {1}".format( + assert ( + key in response_json + ), "Field {0} not found within the response object: {1}".format( key, response_json ) @@ -128,11 +156,19 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e # Otherwise, we're just validating a single field that's a pydantic model. if isinstance(value, dict) and not isinstance(type_expectation, tuple): validate_response( - response=response_json[key], json_expectation=value, type_expectations=type_expectation + response=response_json[key], + json_expectation=value, + type_expectations=type_expectation, ) else: - validate_field(response=response_json[key], json_expectation=value, type_expectation=type_expectation) + validate_field( + response=response_json[key], + json_expectation=value, + type_expectation=type_expectation, + ) # Ensure there are no additional fields here either del response_json[key] - assert len(response_json) == 0, "Additional fields found, expected None: {0}".format(response_json) + assert ( + len(response_json) == 0 + ), "Additional fields found, expected None: {0}".format(response_json) diff --git a/seed/python-sdk/exhaustive/no-custom-config/tests/utils/assets/models/__init__.py b/seed/python-sdk/exhaustive/no-custom-config/tests/utils/assets/models/__init__.py index 2cf01263529..3a1c852e71e 100644 --- a/seed/python-sdk/exhaustive/no-custom-config/tests/utils/assets/models/__init__.py +++ b/seed/python-sdk/exhaustive/no-custom-config/tests/utils/assets/models/__init__.py @@ -5,7 +5,7 @@ from .circle import CircleParams from .object_with_defaults import ObjectWithDefaultsParams from .object_with_optional_field import ObjectWithOptionalFieldParams -from .shape import Shape_CircleParams, Shape_SquareParams, ShapeParams +from .shape import ShapeParams, Shape_CircleParams, Shape_SquareParams from .square import SquareParams from .undiscriminated_shape import UndiscriminatedShapeParams diff --git a/seed/python-sdk/exhaustive/no-custom-config/tests/utils/assets/models/circle.py b/seed/python-sdk/exhaustive/no-custom-config/tests/utils/assets/models/circle.py index af7a1bf8a8e..253f12d38b3 100644 --- a/seed/python-sdk/exhaustive/no-custom-config/tests/utils/assets/models/circle.py +++ b/seed/python-sdk/exhaustive/no-custom-config/tests/utils/assets/models/circle.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class CircleParams(typing_extensions.TypedDict): - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] diff --git a/seed/python-sdk/exhaustive/no-custom-config/tests/utils/assets/models/object_with_optional_field.py b/seed/python-sdk/exhaustive/no-custom-config/tests/utils/assets/models/object_with_optional_field.py index 3ad93d5f305..ebe7dc80547 100644 --- a/seed/python-sdk/exhaustive/no-custom-config/tests/utils/assets/models/object_with_optional_field.py +++ b/seed/python-sdk/exhaustive/no-custom-config/tests/utils/assets/models/object_with_optional_field.py @@ -7,8 +7,8 @@ import uuid import typing_extensions -from seed.core.serialization import FieldMetadata +from seed.core.serialization import FieldMetadata from .color import Color from .shape import ShapeParams from .undiscriminated_shape import UndiscriminatedShapeParams @@ -18,16 +18,30 @@ class ObjectWithOptionalFieldParams(typing_extensions.TypedDict): literal: typing.Literal["lit_one"] string: typing_extensions.NotRequired[str] integer: typing_extensions.NotRequired[int] - long_: typing_extensions.NotRequired[typing_extensions.Annotated[int, FieldMetadata(alias="long")]] + long_: typing_extensions.NotRequired[ + typing_extensions.Annotated[int, FieldMetadata(alias="long")] + ] double: typing_extensions.NotRequired[float] - bool_: typing_extensions.NotRequired[typing_extensions.Annotated[bool, FieldMetadata(alias="bool")]] + bool_: typing_extensions.NotRequired[ + typing_extensions.Annotated[bool, FieldMetadata(alias="bool")] + ] datetime: typing_extensions.NotRequired[dt.datetime] date: typing_extensions.NotRequired[dt.date] - uuid_: typing_extensions.NotRequired[typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")]] - base_64: typing_extensions.NotRequired[typing_extensions.Annotated[str, FieldMetadata(alias="base64")]] - list_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")]] - set_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")]] - map_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")]] + uuid_: typing_extensions.NotRequired[ + typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")] + ] + base_64: typing_extensions.NotRequired[ + typing_extensions.Annotated[str, FieldMetadata(alias="base64")] + ] + list_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")] + ] + set_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")] + ] + map_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")] + ] enum: typing_extensions.NotRequired[Color] union: typing_extensions.NotRequired[ShapeParams] second_union: typing_extensions.NotRequired[ShapeParams] diff --git a/seed/python-sdk/exhaustive/no-custom-config/tests/utils/assets/models/shape.py b/seed/python-sdk/exhaustive/no-custom-config/tests/utils/assets/models/shape.py index 2c33c877951..816ffc51bdc 100644 --- a/seed/python-sdk/exhaustive/no-custom-config/tests/utils/assets/models/shape.py +++ b/seed/python-sdk/exhaustive/no-custom-config/tests/utils/assets/models/shape.py @@ -7,6 +7,7 @@ import typing import typing_extensions + from seed.core.serialization import FieldMetadata @@ -15,13 +16,21 @@ class Base(typing_extensions.TypedDict): class Shape_CircleParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["circle"], FieldMetadata(alias="shapeType")] - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["circle"], FieldMetadata(alias="shapeType") + ] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] class Shape_SquareParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["square"], FieldMetadata(alias="shapeType")] - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["square"], FieldMetadata(alias="shapeType") + ] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] ShapeParams = typing.Union[Shape_CircleParams, Shape_SquareParams] diff --git a/seed/python-sdk/exhaustive/no-custom-config/tests/utils/assets/models/square.py b/seed/python-sdk/exhaustive/no-custom-config/tests/utils/assets/models/square.py index b9b7dd319bc..bcf08a723c5 100644 --- a/seed/python-sdk/exhaustive/no-custom-config/tests/utils/assets/models/square.py +++ b/seed/python-sdk/exhaustive/no-custom-config/tests/utils/assets/models/square.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class SquareParams(typing_extensions.TypedDict): - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] diff --git a/seed/python-sdk/exhaustive/no-custom-config/tests/utils/test_http_client.py b/seed/python-sdk/exhaustive/no-custom-config/tests/utils/test_http_client.py index edd11ca7afb..f5a874a75f3 100644 --- a/seed/python-sdk/exhaustive/no-custom-config/tests/utils/test_http_client.py +++ b/seed/python-sdk/exhaustive/no-custom-config/tests/utils/test_http_client.py @@ -9,12 +9,17 @@ def get_request_options() -> RequestOptions: def test_get_json_request_body() -> None: - json_body, data_body = get_request_body(json={"hello": "world"}, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json={"hello": "world"}, data=None, request_options=None, omit=None + ) assert json_body == {"hello": "world"} assert data_body is None json_body_extras, data_body_extras = get_request_body( - json={"goodbye": "world"}, data=None, request_options=get_request_options(), omit=None + json={"goodbye": "world"}, + data=None, + request_options=get_request_options(), + omit=None, ) assert json_body_extras == {"goodbye": "world", "see you": "later"} @@ -22,12 +27,17 @@ def test_get_json_request_body() -> None: def test_get_files_request_body() -> None: - json_body, data_body = get_request_body(json=None, data={"hello": "world"}, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data={"hello": "world"}, request_options=None, omit=None + ) assert data_body == {"hello": "world"} assert json_body is None json_body_extras, data_body_extras = get_request_body( - json=None, data={"goodbye": "world"}, request_options=get_request_options(), omit=None + json=None, + data={"goodbye": "world"}, + request_options=get_request_options(), + omit=None, ) assert data_body_extras == {"goodbye": "world", "see you": "later"} @@ -35,7 +45,9 @@ def test_get_files_request_body() -> None: def test_get_none_request_body() -> None: - json_body, data_body = get_request_body(json=None, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data=None, request_options=None, omit=None + ) assert data_body is None assert json_body is None diff --git a/seed/python-sdk/exhaustive/no-custom-config/tests/utils/test_query_encoding.py b/seed/python-sdk/exhaustive/no-custom-config/tests/utils/test_query_encoding.py index 247e1551b46..fbc8f402167 100644 --- a/seed/python-sdk/exhaustive/no-custom-config/tests/utils/test_query_encoding.py +++ b/seed/python-sdk/exhaustive/no-custom-config/tests/utils/test_query_encoding.py @@ -4,9 +4,15 @@ def test_query_encoding() -> None: - assert encode_query({"hello world": "hello world"}) == {"hello world": "hello world"} - assert encode_query({"hello_world": {"hello": "world"}}) == {"hello_world[hello]": "world"} - assert encode_query({"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"}) == { + assert encode_query({"hello world": "hello world"}) == { + "hello world": "hello world" + } + assert encode_query({"hello_world": {"hello": "world"}}) == { + "hello_world[hello]": "world" + } + assert encode_query( + {"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"} + ) == { "hello_world[hello][world]": "today", "hello_world[test]": "this", "hi": "there", diff --git a/seed/python-sdk/exhaustive/no-custom-config/tests/utils/test_serialization.py b/seed/python-sdk/exhaustive/no-custom-config/tests/utils/test_serialization.py index 58b1ed66e6d..5ca956916dd 100644 --- a/seed/python-sdk/exhaustive/no-custom-config/tests/utils/test_serialization.py +++ b/seed/python-sdk/exhaustive/no-custom-config/tests/utils/test_serialization.py @@ -1,10 +1,12 @@ # This file was auto-generated by Fern from our API Definition. -from typing import Any, List +from typing import List, Any -from seed.core.serialization import convert_and_respect_annotation_metadata +from seed.core.serialization import ( + convert_and_respect_annotation_metadata, +) +from .assets.models import ShapeParams, ObjectWithOptionalFieldParams -from .assets.models import ObjectWithOptionalFieldParams, ShapeParams UNION_TEST: ShapeParams = {"radius_measurement": 1.0, "shape_type": "circle", "id": "1"} UNION_TEST_CONVERTED = {"shapeType": "circle", "radiusMeasurement": 1.0, "id": "1"} @@ -18,20 +20,54 @@ def test_convert_and_respect_annotation_metadata() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) - assert converted == {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"} + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) + assert converted == { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + } def test_convert_and_respect_annotation_metadata_in_list() -> None: data: List[ObjectWithOptionalFieldParams] = [ - {"string": "string", "long_": 12345, "bool_": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long_": 67890, "list_": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long_": 12345, + "bool_": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long_": 67890, + "list_": [], + "literal": "lit_one", + "any": "any", + }, ] - converted = convert_and_respect_annotation_metadata(object_=data, annotation=List[ObjectWithOptionalFieldParams]) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=List[ObjectWithOptionalFieldParams] + ) assert converted == [ - {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long": 67890, "list": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long": 67890, + "list": [], + "literal": "lit_one", + "any": "any", + }, ] @@ -43,7 +79,9 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) assert converted == { "string": "string", @@ -55,12 +93,16 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: def test_convert_and_respect_annotation_metadata_in_union() -> None: - converted = convert_and_respect_annotation_metadata(object_=UNION_TEST, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=UNION_TEST, annotation=ShapeParams + ) assert converted == UNION_TEST_CONVERTED def test_convert_and_respect_annotation_metadata_with_empty_object() -> None: data: Any = {} - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ShapeParams + ) assert converted == data diff --git a/seed/python-sdk/exhaustive/pydantic-extra-fields/pyproject.toml b/seed/python-sdk/exhaustive/pydantic-extra-fields/pyproject.toml index c6cd3a2b7b9..fc29a237334 100644 --- a/seed/python-sdk/exhaustive/pydantic-extra-fields/pyproject.toml +++ b/seed/python-sdk/exhaustive/pydantic-extra-fields/pyproject.toml @@ -43,6 +43,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/__init__.py b/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/__init__.py index eb56b0ce275..dc1ef03a650 100644 --- a/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/__init__.py +++ b/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/__init__.py @@ -1,6 +1,14 @@ # This file was auto-generated by Fern from our API Definition. -from . import endpoints, general_errors, inlined_requests, no_auth, no_req_body, req_with_headers, types +from . import ( + endpoints, + general_errors, + inlined_requests, + no_auth, + no_req_body, + req_with_headers, + types, +) from .client import AsyncSeedExhaustive, SeedExhaustive from .general_errors import BadObjectRequestInfo, BadRequestBody from .version import __version__ diff --git a/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/client.py b/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/client.py index b1b9764c7a7..f5ab292af6b 100644 --- a/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/client.py +++ b/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/client.py @@ -1,15 +1,19 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from .endpoints.client import AsyncEndpointsClient, EndpointsClient -from .inlined_requests.client import AsyncInlinedRequestsClient, InlinedRequestsClient -from .no_auth.client import AsyncNoAuthClient, NoAuthClient -from .no_req_body.client import AsyncNoReqBodyClient, NoReqBodyClient -from .req_with_headers.client import AsyncReqWithHeadersClient, ReqWithHeadersClient +from .core.client_wrapper import SyncClientWrapper +from .endpoints.client import EndpointsClient +from .inlined_requests.client import InlinedRequestsClient +from .no_auth.client import NoAuthClient +from .no_req_body.client import NoReqBodyClient +from .req_with_headers.client import ReqWithHeadersClient +from .core.client_wrapper import AsyncClientWrapper +from .endpoints.client import AsyncEndpointsClient +from .inlined_requests.client import AsyncInlinedRequestsClient +from .no_auth.client import AsyncNoAuthClient +from .no_req_body.client import AsyncNoReqBodyClient +from .req_with_headers.client import AsyncReqWithHeadersClient class SeedExhaustive: @@ -48,24 +52,32 @@ def __init__( token: typing.Optional[typing.Union[str, typing.Callable[[], str]]] = None, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.Client] = None + httpx_client: typing.Optional[httpx.Client] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = SyncClientWrapper( base_url=base_url, token=token, httpx_client=httpx_client if httpx_client is not None - else httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.Client( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.Client(timeout=_defaulted_timeout), timeout=_defaulted_timeout, ) self.endpoints = EndpointsClient(client_wrapper=self._client_wrapper) - self.inlined_requests = InlinedRequestsClient(client_wrapper=self._client_wrapper) + self.inlined_requests = InlinedRequestsClient( + client_wrapper=self._client_wrapper + ) self.no_auth = NoAuthClient(client_wrapper=self._client_wrapper) self.no_req_body = NoReqBodyClient(client_wrapper=self._client_wrapper) - self.req_with_headers = ReqWithHeadersClient(client_wrapper=self._client_wrapper) + self.req_with_headers = ReqWithHeadersClient( + client_wrapper=self._client_wrapper + ) class AsyncSeedExhaustive: @@ -104,21 +116,29 @@ def __init__( token: typing.Optional[typing.Union[str, typing.Callable[[], str]]] = None, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.AsyncClient] = None + httpx_client: typing.Optional[httpx.AsyncClient] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = AsyncClientWrapper( base_url=base_url, token=token, httpx_client=httpx_client if httpx_client is not None - else httpx.AsyncClient(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.AsyncClient( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.AsyncClient(timeout=_defaulted_timeout), timeout=_defaulted_timeout, ) self.endpoints = AsyncEndpointsClient(client_wrapper=self._client_wrapper) - self.inlined_requests = AsyncInlinedRequestsClient(client_wrapper=self._client_wrapper) + self.inlined_requests = AsyncInlinedRequestsClient( + client_wrapper=self._client_wrapper + ) self.no_auth = AsyncNoAuthClient(client_wrapper=self._client_wrapper) self.no_req_body = AsyncNoReqBodyClient(client_wrapper=self._client_wrapper) - self.req_with_headers = AsyncReqWithHeadersClient(client_wrapper=self._client_wrapper) + self.req_with_headers = AsyncReqWithHeadersClient( + client_wrapper=self._client_wrapper + ) diff --git a/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/core/api_error.py b/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/core/api_error.py index 2e9fc5431cd..da734b58068 100644 --- a/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/core/api_error.py +++ b/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/core/api_error.py @@ -7,7 +7,9 @@ class ApiError(Exception): status_code: typing.Optional[int] body: typing.Any - def __init__(self, *, status_code: typing.Optional[int] = None, body: typing.Any = None): + def __init__( + self, *, status_code: typing.Optional[int] = None, body: typing.Any = None + ): self.status_code = status_code self.body = body diff --git a/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/core/client_wrapper.py b/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/core/client_wrapper.py index 8d01b584b82..d037184a816 100644 --- a/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/core/client_wrapper.py +++ b/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/core/client_wrapper.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .http_client import AsyncHttpClient, HttpClient +from .http_client import HttpClient +from .http_client import AsyncHttpClient class BaseClientWrapper: diff --git a/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/core/datetime_utils.py b/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/core/datetime_utils.py +++ b/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/core/file.py b/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/core/file.py index cb0d40bbbf3..6e0f92bfcb1 100644 --- a/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/core/file.py +++ b/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/core/file.py @@ -13,12 +13,17 @@ # (filename, file (or bytes), content_type) typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str]], # (filename, file (or bytes), content_type, headers) - typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str], typing.Mapping[str, str]], + typing.Tuple[ + typing.Optional[str], + FileContent, + typing.Optional[str], + typing.Mapping[str, str], + ], ] def convert_file_dict_to_httpx_tuples( - d: typing.Dict[str, typing.Union[File, typing.List[File]]] + d: typing.Dict[str, typing.Union[File, typing.List[File]]], ) -> typing.List[typing.Tuple[str, File]]: """ The format we use is a list of tuples, where the first element is the diff --git a/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/core/http_client.py b/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/core/http_client.py index 9333d8a7f15..091f71bc185 100644 --- a/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/core/http_client.py +++ b/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/core/http_client.py @@ -77,7 +77,9 @@ def _retry_timeout(response: httpx.Response, retries: int) -> float: return retry_after # Apply exponential backoff, capped at MAX_RETRY_DELAY_SECONDS. - retry_delay = min(INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS) + retry_delay = min( + INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS + ) # Add a randomness / jitter to the retry delay to avoid overwhelming the server with retries. timeout = retry_delay * (1 - 0.25 * random()) @@ -90,7 +92,8 @@ def _should_retry(response: httpx.Response) -> bool: def remove_omit_from_dict( - original: typing.Dict[str, typing.Optional[typing.Any]], omit: typing.Optional[typing.Any] + original: typing.Dict[str, typing.Optional[typing.Any]], + omit: typing.Optional[typing.Any], ) -> typing.Dict[str, typing.Any]: if omit is None: return original @@ -108,7 +111,8 @@ def maybe_filter_request_body( ) -> typing.Optional[typing.Any]: if data is None: return ( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else None ) @@ -118,7 +122,8 @@ def maybe_filter_request_body( data_content = { **(jsonable_encoder(remove_omit_from_dict(data, omit))), # type: ignore **( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else {} ), @@ -162,7 +167,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url def request( @@ -174,8 +181,12 @@ def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -184,11 +195,14 @@ def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) response = self.httpx_client.request( method=method, @@ -198,7 +212,11 @@ def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -209,7 +227,10 @@ def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -222,11 +243,15 @@ def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: time.sleep(_retry_timeout(response=response, retries=retries)) @@ -256,8 +281,12 @@ def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -266,11 +295,14 @@ def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) with self.httpx_client.stream( method=method, @@ -280,7 +312,11 @@ def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -291,7 +327,9 @@ def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -304,7 +342,9 @@ def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream @@ -327,7 +367,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url async def request( @@ -339,8 +381,12 @@ async def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -349,11 +395,14 @@ async def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) # Add the input to each of these and do None-safety checks response = await self.httpx_client.request( @@ -364,7 +413,11 @@ async def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -375,7 +428,10 @@ async def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -388,11 +444,15 @@ async def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: await asyncio.sleep(_retry_timeout(response=response, retries=retries)) @@ -421,8 +481,12 @@ async def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -431,11 +495,14 @@ async def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) async with self.httpx_client.stream( method=method, @@ -445,7 +512,11 @@ async def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -456,7 +527,9 @@ async def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -469,7 +542,9 @@ async def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream diff --git a/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/core/jsonable_encoder.py b/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/core/jsonable_encoder.py index d3fd328fd41..12a8b52fc22 100644 --- a/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/core/jsonable_encoder.py +++ b/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/core/jsonable_encoder.py @@ -19,13 +19,19 @@ import pydantic from .datetime_utils import serialize_datetime -from .pydantic_utilities import IS_PYDANTIC_V2, encode_by_type, to_jsonable_with_fallback +from .pydantic_utilities import ( + IS_PYDANTIC_V2, + encode_by_type, + to_jsonable_with_fallback, +) SetIntStr = Set[Union[int, str]] DictIntStrAny = Dict[Union[int, str], Any] -def jsonable_encoder(obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None) -> Any: +def jsonable_encoder( + obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None +) -> Any: custom_encoder = custom_encoder or {} if custom_encoder: if type(obj) in custom_encoder: diff --git a/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/core/pydantic_utilities.py b/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/core/pydantic_utilities.py index 170a563d6eb..c63935c32a2 100644 --- a/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/core/pydantic_utilities.py +++ b/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) # type: ignore # Pydantic v1 diff --git a/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/core/query_encoder.py b/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/core/query_encoder.py index 24076d72ee9..7cb98f52cd7 100644 --- a/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/core/query_encoder.py +++ b/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/core/query_encoder.py @@ -7,7 +7,9 @@ # Flattens dicts to be of the form {"key[subkey][subkey2]": value} where value is not a dict -def traverse_query_dict(dict_flat: Dict[str, Any], key_prefix: Optional[str] = None) -> Dict[str, Any]: +def traverse_query_dict( + dict_flat: Dict[str, Any], key_prefix: Optional[str] = None +) -> Dict[str, Any]: result = {} for k, v in dict_flat.items(): key = f"{key_prefix}[{k}]" if key_prefix is not None else k @@ -30,4 +32,8 @@ def single_query_encoder(query_key: str, query_value: Any) -> Dict[str, Any]: def encode_query(query: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: - return dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) if query is not None else None + return ( + dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) + if query is not None + else None + ) diff --git a/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/core/serialization.py b/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/core/serialization.py +++ b/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/endpoints/__init__.py b/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/endpoints/__init__.py index 92307cab7fe..a9496ece178 100644 --- a/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/endpoints/__init__.py +++ b/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/endpoints/__init__.py @@ -2,4 +2,12 @@ from . import container, enum, http_methods, object, params, primitive, union -__all__ = ["container", "enum", "http_methods", "object", "params", "primitive", "union"] +__all__ = [ + "container", + "enum", + "http_methods", + "object", + "params", + "primitive", + "union", +] diff --git a/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/endpoints/client.py b/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/endpoints/client.py index 18dc397fdf1..69930de54d7 100644 --- a/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/endpoints/client.py +++ b/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/endpoints/client.py @@ -1,13 +1,21 @@ # This file was auto-generated by Fern from our API Definition. -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from .container.client import AsyncContainerClient, ContainerClient -from .enum.client import AsyncEnumClient, EnumClient -from .http_methods.client import AsyncHttpMethodsClient, HttpMethodsClient -from .object.client import AsyncObjectClient, ObjectClient -from .params.client import AsyncParamsClient, ParamsClient -from .primitive.client import AsyncPrimitiveClient, PrimitiveClient -from .union.client import AsyncUnionClient, UnionClient +from ..core.client_wrapper import SyncClientWrapper +from .container.client import ContainerClient +from .enum.client import EnumClient +from .http_methods.client import HttpMethodsClient +from .object.client import ObjectClient +from .params.client import ParamsClient +from .primitive.client import PrimitiveClient +from .union.client import UnionClient +from ..core.client_wrapper import AsyncClientWrapper +from .container.client import AsyncContainerClient +from .enum.client import AsyncEnumClient +from .http_methods.client import AsyncHttpMethodsClient +from .object.client import AsyncObjectClient +from .params.client import AsyncParamsClient +from .primitive.client import AsyncPrimitiveClient +from .union.client import AsyncUnionClient class EndpointsClient: diff --git a/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/endpoints/container/client.py b/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/endpoints/container/client.py index c6cf14f63ac..4af9c12d534 100644 --- a/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/endpoints/container/client.py +++ b/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/endpoints/container/client.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. import typing +from ...core.client_wrapper import SyncClientWrapper +from ...core.request_options import RequestOptions +from ...core.pydantic_utilities import parse_obj_as from json.decoder import JSONDecodeError - from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ...core.pydantic_utilities import parse_obj_as -from ...core.request_options import RequestOptions from ...types.object.types.object_with_required_field import ObjectWithRequiredField +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -18,7 +18,10 @@ def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper def get_and_return_list_of_primitives( - self, *, request: typing.Sequence[str], request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Sequence[str], + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[str]: """ Parameters @@ -45,11 +48,18 @@ def get_and_return_list_of_primitives( ) """ _response = self._client_wrapper.httpx_client.request( - "container/list-of-primitives", method="POST", json=request, request_options=request_options, omit=OMIT + "container/list-of-primitives", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.List[str], parse_obj_as(type_=typing.List[str], object_=_response.json())) # type: ignore + return typing.cast( + typing.List[str], + parse_obj_as(type_=typing.List[str], object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -59,7 +69,7 @@ def get_and_return_list_of_objects( self, *, request: typing.Sequence[ObjectWithRequiredField], - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[ObjectWithRequiredField]: """ Parameters @@ -91,18 +101,31 @@ def get_and_return_list_of_objects( ) """ _response = self._client_wrapper.httpx_client.request( - "container/list-of-objects", method="POST", json=request, request_options=request_options, omit=OMIT + "container/list-of-objects", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.List[ObjectWithRequiredField], parse_obj_as(type_=typing.List[ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.List[ObjectWithRequiredField], + parse_obj_as( + type_=typing.List[ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_and_return_set_of_primitives( - self, *, request: typing.Set[str], request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Set[str], + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Set[str]: """ Parameters @@ -129,11 +152,18 @@ def get_and_return_set_of_primitives( ) """ _response = self._client_wrapper.httpx_client.request( - "container/set-of-primitives", method="POST", json=request, request_options=request_options, omit=OMIT + "container/set-of-primitives", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Set[str], parse_obj_as(type_=typing.Set[str], object_=_response.json())) # type: ignore + return typing.cast( + typing.Set[str], + parse_obj_as(type_=typing.Set[str], object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -143,7 +173,7 @@ def get_and_return_set_of_objects( self, *, request: typing.Sequence[ObjectWithRequiredField], - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[ObjectWithRequiredField]: """ Parameters @@ -175,18 +205,31 @@ def get_and_return_set_of_objects( ) """ _response = self._client_wrapper.httpx_client.request( - "container/set-of-objects", method="POST", json=request, request_options=request_options, omit=OMIT + "container/set-of-objects", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.List[ObjectWithRequiredField], parse_obj_as(type_=typing.List[ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.List[ObjectWithRequiredField], + parse_obj_as( + type_=typing.List[ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_and_return_map_prim_to_prim( - self, *, request: typing.Dict[str, str], request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Dict[str, str], + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Dict[str, str]: """ Parameters @@ -213,11 +256,18 @@ def get_and_return_map_prim_to_prim( ) """ _response = self._client_wrapper.httpx_client.request( - "container/map-prim-to-prim", method="POST", json=request, request_options=request_options, omit=OMIT + "container/map-prim-to-prim", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Dict[str, str], parse_obj_as(type_=typing.Dict[str, str], object_=_response.json())) # type: ignore + return typing.cast( + typing.Dict[str, str], + parse_obj_as(type_=typing.Dict[str, str], object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -227,7 +277,7 @@ def get_and_return_map_of_prim_to_object( self, *, request: typing.Dict[str, ObjectWithRequiredField], - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Dict[str, ObjectWithRequiredField]: """ Parameters @@ -259,11 +309,21 @@ def get_and_return_map_of_prim_to_object( ) """ _response = self._client_wrapper.httpx_client.request( - "container/map-prim-to-object", method="POST", json=request, request_options=request_options, omit=OMIT + "container/map-prim-to-object", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Dict[str, ObjectWithRequiredField], parse_obj_as(type_=typing.Dict[str, ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.Dict[str, ObjectWithRequiredField], + parse_obj_as( + type_=typing.Dict[str, ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -273,7 +333,7 @@ def get_and_return_optional( self, *, request: typing.Optional[ObjectWithRequiredField] = None, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Optional[ObjectWithRequiredField]: """ Parameters @@ -303,11 +363,21 @@ def get_and_return_optional( ) """ _response = self._client_wrapper.httpx_client.request( - "container/opt-objects", method="POST", json=request, request_options=request_options, omit=OMIT + "container/opt-objects", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Optional[ObjectWithRequiredField], parse_obj_as(type_=typing.Optional[ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.Optional[ObjectWithRequiredField], + parse_obj_as( + type_=typing.Optional[ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -319,7 +389,10 @@ def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper async def get_and_return_list_of_primitives( - self, *, request: typing.Sequence[str], request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Sequence[str], + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[str]: """ Parameters @@ -354,11 +427,18 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/list-of-primitives", method="POST", json=request, request_options=request_options, omit=OMIT + "container/list-of-primitives", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.List[str], parse_obj_as(type_=typing.List[str], object_=_response.json())) # type: ignore + return typing.cast( + typing.List[str], + parse_obj_as(type_=typing.List[str], object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -368,7 +448,7 @@ async def get_and_return_list_of_objects( self, *, request: typing.Sequence[ObjectWithRequiredField], - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[ObjectWithRequiredField]: """ Parameters @@ -408,18 +488,31 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/list-of-objects", method="POST", json=request, request_options=request_options, omit=OMIT + "container/list-of-objects", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.List[ObjectWithRequiredField], parse_obj_as(type_=typing.List[ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.List[ObjectWithRequiredField], + parse_obj_as( + type_=typing.List[ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_and_return_set_of_primitives( - self, *, request: typing.Set[str], request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Set[str], + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Set[str]: """ Parameters @@ -454,11 +547,18 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/set-of-primitives", method="POST", json=request, request_options=request_options, omit=OMIT + "container/set-of-primitives", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Set[str], parse_obj_as(type_=typing.Set[str], object_=_response.json())) # type: ignore + return typing.cast( + typing.Set[str], + parse_obj_as(type_=typing.Set[str], object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -468,7 +568,7 @@ async def get_and_return_set_of_objects( self, *, request: typing.Sequence[ObjectWithRequiredField], - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[ObjectWithRequiredField]: """ Parameters @@ -508,18 +608,31 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/set-of-objects", method="POST", json=request, request_options=request_options, omit=OMIT + "container/set-of-objects", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.List[ObjectWithRequiredField], parse_obj_as(type_=typing.List[ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.List[ObjectWithRequiredField], + parse_obj_as( + type_=typing.List[ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_and_return_map_prim_to_prim( - self, *, request: typing.Dict[str, str], request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Dict[str, str], + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Dict[str, str]: """ Parameters @@ -554,11 +667,18 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/map-prim-to-prim", method="POST", json=request, request_options=request_options, omit=OMIT + "container/map-prim-to-prim", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Dict[str, str], parse_obj_as(type_=typing.Dict[str, str], object_=_response.json())) # type: ignore + return typing.cast( + typing.Dict[str, str], + parse_obj_as(type_=typing.Dict[str, str], object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -568,7 +688,7 @@ async def get_and_return_map_of_prim_to_object( self, *, request: typing.Dict[str, ObjectWithRequiredField], - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Dict[str, ObjectWithRequiredField]: """ Parameters @@ -608,11 +728,21 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/map-prim-to-object", method="POST", json=request, request_options=request_options, omit=OMIT + "container/map-prim-to-object", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Dict[str, ObjectWithRequiredField], parse_obj_as(type_=typing.Dict[str, ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.Dict[str, ObjectWithRequiredField], + parse_obj_as( + type_=typing.Dict[str, ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -622,7 +752,7 @@ async def get_and_return_optional( self, *, request: typing.Optional[ObjectWithRequiredField] = None, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Optional[ObjectWithRequiredField]: """ Parameters @@ -660,11 +790,21 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/opt-objects", method="POST", json=request, request_options=request_options, omit=OMIT + "container/opt-objects", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Optional[ObjectWithRequiredField], parse_obj_as(type_=typing.Optional[ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.Optional[ObjectWithRequiredField], + parse_obj_as( + type_=typing.Optional[ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/endpoints/enum/client.py b/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/endpoints/enum/client.py index 44e2690ff6c..3e3208e3bcf 100644 --- a/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/endpoints/enum/client.py +++ b/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/endpoints/enum/client.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. import typing +from ...core.client_wrapper import SyncClientWrapper +from ...types.enum.types.weather_report import WeatherReport +from ...core.request_options import RequestOptions +from ...core.pydantic_utilities import parse_obj_as from json.decoder import JSONDecodeError - from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ...core.pydantic_utilities import parse_obj_as -from ...core.request_options import RequestOptions -from ...types.enum.types.weather_report import WeatherReport +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -18,7 +18,10 @@ def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper def get_and_return_enum( - self, *, request: WeatherReport, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: WeatherReport, + request_options: typing.Optional[RequestOptions] = None, ) -> WeatherReport: """ Parameters @@ -45,11 +48,18 @@ def get_and_return_enum( ) """ _response = self._client_wrapper.httpx_client.request( - "enum", method="POST", json=request, request_options=request_options, omit=OMIT + "enum", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(WeatherReport, parse_obj_as(type_=WeatherReport, object_=_response.json())) # type: ignore + return typing.cast( + WeatherReport, + parse_obj_as(type_=WeatherReport, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -61,7 +71,10 @@ def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper async def get_and_return_enum( - self, *, request: WeatherReport, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: WeatherReport, + request_options: typing.Optional[RequestOptions] = None, ) -> WeatherReport: """ Parameters @@ -96,11 +109,18 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "enum", method="POST", json=request, request_options=request_options, omit=OMIT + "enum", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(WeatherReport, parse_obj_as(type_=WeatherReport, object_=_response.json())) # type: ignore + return typing.cast( + WeatherReport, + parse_obj_as(type_=WeatherReport, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/endpoints/http_methods/client.py b/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/endpoints/http_methods/client.py index a2549280a1b..570a227844f 100644 --- a/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/endpoints/http_methods/client.py +++ b/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/endpoints/http_methods/client.py @@ -1,16 +1,16 @@ # This file was auto-generated by Fern from our API Definition. -import datetime as dt import typing -import uuid -from json.decoder import JSONDecodeError - -from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper +from ...core.client_wrapper import SyncClientWrapper +from ...core.request_options import RequestOptions from ...core.jsonable_encoder import jsonable_encoder from ...core.pydantic_utilities import parse_obj_as -from ...core.request_options import RequestOptions +from json.decoder import JSONDecodeError +from ...core.api_error import ApiError from ...types.object.types.object_with_optional_field import ObjectWithOptionalField +import datetime as dt +import uuid +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -20,7 +20,9 @@ class HttpMethodsClient: def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper - def test_get(self, id: str, *, request_options: typing.Optional[RequestOptions] = None) -> str: + def test_get( + self, id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -46,11 +48,15 @@ def test_get(self, id: str, *, request_options: typing.Optional[RequestOptions] ) """ _response = self._client_wrapper.httpx_client.request( - f"http-methods/{jsonable_encoder(id)}", method="GET", request_options=request_options + f"http-methods/{jsonable_encoder(id)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -84,18 +90,33 @@ def test_post( ) """ _response = self._client_wrapper.httpx_client.request( - "http-methods", method="POST", json={"string": string}, request_options=request_options, omit=OMIT + "http-methods", + method="POST", + json={ + "string": string, + }, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def test_put( - self, id: str, *, string: str, request_options: typing.Optional[RequestOptions] = None + self, + id: str, + *, + string: str, + request_options: typing.Optional[RequestOptions] = None, ) -> ObjectWithOptionalField: """ Parameters @@ -127,13 +148,20 @@ def test_put( _response = self._client_wrapper.httpx_client.request( f"http-methods/{jsonable_encoder(id)}", method="PUT", - json={"string": string}, + json={ + "string": string, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -254,13 +282,20 @@ def test_patch( ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def test_delete(self, id: str, *, request_options: typing.Optional[RequestOptions] = None) -> bool: + def test_delete( + self, id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> bool: """ Parameters ---------- @@ -286,11 +321,15 @@ def test_delete(self, id: str, *, request_options: typing.Optional[RequestOption ) """ _response = self._client_wrapper.httpx_client.request( - f"http-methods/{jsonable_encoder(id)}", method="DELETE", request_options=request_options + f"http-methods/{jsonable_encoder(id)}", + method="DELETE", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -301,7 +340,9 @@ class AsyncHttpMethodsClient: def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper - async def test_get(self, id: str, *, request_options: typing.Optional[RequestOptions] = None) -> str: + async def test_get( + self, id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -335,11 +376,15 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - f"http-methods/{jsonable_encoder(id)}", method="GET", request_options=request_options + f"http-methods/{jsonable_encoder(id)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -381,18 +426,33 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "http-methods", method="POST", json={"string": string}, request_options=request_options, omit=OMIT + "http-methods", + method="POST", + json={ + "string": string, + }, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def test_put( - self, id: str, *, string: str, request_options: typing.Optional[RequestOptions] = None + self, + id: str, + *, + string: str, + request_options: typing.Optional[RequestOptions] = None, ) -> ObjectWithOptionalField: """ Parameters @@ -432,13 +492,20 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( f"http-methods/{jsonable_encoder(id)}", method="PUT", - json={"string": string}, + json={ + "string": string, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -566,13 +633,20 @@ async def main() -> None: ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - async def test_delete(self, id: str, *, request_options: typing.Optional[RequestOptions] = None) -> bool: + async def test_delete( + self, id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> bool: """ Parameters ---------- @@ -606,11 +680,15 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - f"http-methods/{jsonable_encoder(id)}", method="DELETE", request_options=request_options + f"http-methods/{jsonable_encoder(id)}", + method="DELETE", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/endpoints/object/client.py b/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/endpoints/object/client.py index a724f959193..dcb1324b74b 100644 --- a/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/endpoints/object/client.py +++ b/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/endpoints/object/client.py @@ -1,20 +1,24 @@ # This file was auto-generated by Fern from our API Definition. -import datetime as dt import typing +from ...core.client_wrapper import SyncClientWrapper +import datetime as dt import uuid -from json.decoder import JSONDecodeError - -from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ...core.jsonable_encoder import jsonable_encoder -from ...core.pydantic_utilities import parse_obj_as from ...core.request_options import RequestOptions -from ...types.object.types.nested_object_with_optional_field import NestedObjectWithOptionalField -from ...types.object.types.nested_object_with_required_field import NestedObjectWithRequiredField -from ...types.object.types.object_with_map_of_map import ObjectWithMapOfMap from ...types.object.types.object_with_optional_field import ObjectWithOptionalField +from ...core.pydantic_utilities import parse_obj_as +from json.decoder import JSONDecodeError +from ...core.api_error import ApiError from ...types.object.types.object_with_required_field import ObjectWithRequiredField +from ...types.object.types.object_with_map_of_map import ObjectWithMapOfMap +from ...types.object.types.nested_object_with_optional_field import ( + NestedObjectWithOptionalField, +) +from ...types.object.types.nested_object_with_required_field import ( + NestedObjectWithRequiredField, +) +from ...core.jsonable_encoder import jsonable_encoder +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -135,7 +139,12 @@ def get_and_return_with_optional_field( ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -171,20 +180,30 @@ def get_and_return_with_required_field( _response = self._client_wrapper.httpx_client.request( "object/get-and-return-with-required-field", method="POST", - json={"string": string}, + json={ + "string": string, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithRequiredField, parse_obj_as(type_=ObjectWithRequiredField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithRequiredField, + parse_obj_as( + type_=ObjectWithRequiredField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_and_return_with_map_of_map( - self, *, map_: typing.Dict[str, typing.Dict[str, str]], request_options: typing.Optional[RequestOptions] = None + self, + *, + map_: typing.Dict[str, typing.Dict[str, str]], + request_options: typing.Optional[RequestOptions] = None, ) -> ObjectWithMapOfMap: """ Parameters @@ -213,13 +232,18 @@ def get_and_return_with_map_of_map( _response = self._client_wrapper.httpx_client.request( "object/get-and-return-with-map-of-map", method="POST", - json={"map": map_}, + json={ + "map": map_, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithMapOfMap, parse_obj_as(type_=ObjectWithMapOfMap, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithMapOfMap, + parse_obj_as(type_=ObjectWithMapOfMap, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -286,13 +310,21 @@ def get_and_return_nested_with_optional_field( _response = self._client_wrapper.httpx_client.request( "object/get-and-return-nested-with-optional-field", method="POST", - json={"string": string, "NestedObject": nested_object}, + json={ + "string": string, + "NestedObject": nested_object, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(NestedObjectWithOptionalField, parse_obj_as(type_=NestedObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + NestedObjectWithOptionalField, + parse_obj_as( + type_=NestedObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -363,13 +395,21 @@ def get_and_return_nested_with_required_field( _response = self._client_wrapper.httpx_client.request( f"object/get-and-return-nested-with-required-field/{jsonable_encoder(string_)}", method="POST", - json={"string": string, "NestedObject": nested_object}, + json={ + "string": string, + "NestedObject": nested_object, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(NestedObjectWithRequiredField, parse_obj_as(type_=NestedObjectWithRequiredField, object_=_response.json())) # type: ignore + return typing.cast( + NestedObjectWithRequiredField, + parse_obj_as( + type_=NestedObjectWithRequiredField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -446,7 +486,12 @@ def get_and_return_nested_with_required_field_as_list( ) try: if 200 <= _response.status_code < 300: - return typing.cast(NestedObjectWithRequiredField, parse_obj_as(type_=NestedObjectWithRequiredField, object_=_response.json())) # type: ignore + return typing.cast( + NestedObjectWithRequiredField, + parse_obj_as( + type_=NestedObjectWithRequiredField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -575,7 +620,12 @@ async def main() -> None: ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -619,20 +669,30 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( "object/get-and-return-with-required-field", method="POST", - json={"string": string}, + json={ + "string": string, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithRequiredField, parse_obj_as(type_=ObjectWithRequiredField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithRequiredField, + parse_obj_as( + type_=ObjectWithRequiredField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_and_return_with_map_of_map( - self, *, map_: typing.Dict[str, typing.Dict[str, str]], request_options: typing.Optional[RequestOptions] = None + self, + *, + map_: typing.Dict[str, typing.Dict[str, str]], + request_options: typing.Optional[RequestOptions] = None, ) -> ObjectWithMapOfMap: """ Parameters @@ -669,13 +729,18 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( "object/get-and-return-with-map-of-map", method="POST", - json={"map": map_}, + json={ + "map": map_, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithMapOfMap, parse_obj_as(type_=ObjectWithMapOfMap, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithMapOfMap, + parse_obj_as(type_=ObjectWithMapOfMap, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -749,13 +814,21 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( "object/get-and-return-nested-with-optional-field", method="POST", - json={"string": string, "NestedObject": nested_object}, + json={ + "string": string, + "NestedObject": nested_object, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(NestedObjectWithOptionalField, parse_obj_as(type_=NestedObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + NestedObjectWithOptionalField, + parse_obj_as( + type_=NestedObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -833,13 +906,21 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( f"object/get-and-return-nested-with-required-field/{jsonable_encoder(string_)}", method="POST", - json={"string": string, "NestedObject": nested_object}, + json={ + "string": string, + "NestedObject": nested_object, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(NestedObjectWithRequiredField, parse_obj_as(type_=NestedObjectWithRequiredField, object_=_response.json())) # type: ignore + return typing.cast( + NestedObjectWithRequiredField, + parse_obj_as( + type_=NestedObjectWithRequiredField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -923,7 +1004,12 @@ async def main() -> None: ) try: if 200 <= _response.status_code < 300: - return typing.cast(NestedObjectWithRequiredField, parse_obj_as(type_=NestedObjectWithRequiredField, object_=_response.json())) # type: ignore + return typing.cast( + NestedObjectWithRequiredField, + parse_obj_as( + type_=NestedObjectWithRequiredField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/endpoints/params/client.py b/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/endpoints/params/client.py index 5cd7ceef42a..a9187ac94b8 100644 --- a/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/endpoints/params/client.py +++ b/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/endpoints/params/client.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. import typing -from json.decoder import JSONDecodeError - -from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper +from ...core.client_wrapper import SyncClientWrapper +from ...core.request_options import RequestOptions from ...core.jsonable_encoder import jsonable_encoder from ...core.pydantic_utilities import parse_obj_as -from ...core.request_options import RequestOptions +from json.decoder import JSONDecodeError +from ...core.api_error import ApiError +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -17,7 +17,9 @@ class ParamsClient: def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper - def get_with_path(self, param: str, *, request_options: typing.Optional[RequestOptions] = None) -> str: + def get_with_path( + self, param: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ GET with path param @@ -45,18 +47,26 @@ def get_with_path(self, param: str, *, request_options: typing.Optional[RequestO ) """ _response = self._client_wrapper.httpx_client.request( - f"params/path/{jsonable_encoder(param)}", method="GET", request_options=request_options + f"params/path/{jsonable_encoder(param)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_with_query( - self, *, query: str, number: int, request_options: typing.Optional[RequestOptions] = None + self, + *, + query: str, + number: int, + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ GET with query param @@ -88,7 +98,13 @@ def get_with_query( ) """ _response = self._client_wrapper.httpx_client.request( - "params", method="GET", params={"query": query, "number": number}, request_options=request_options + "params", + method="GET", + params={ + "query": query, + "number": number, + }, + request_options=request_options, ) try: if 200 <= _response.status_code < 300: @@ -135,7 +151,13 @@ def get_with_allow_multiple_query( ) """ _response = self._client_wrapper.httpx_client.request( - "params", method="GET", params={"query": query, "numer": numer}, request_options=request_options + "params", + method="GET", + params={ + "query": query, + "numer": numer, + }, + request_options=request_options, ) try: if 200 <= _response.status_code < 300: @@ -146,7 +168,11 @@ def get_with_allow_multiple_query( raise ApiError(status_code=_response.status_code, body=_response_json) def get_with_path_and_query( - self, param: str, *, query: str, request_options: typing.Optional[RequestOptions] = None + self, + param: str, + *, + query: str, + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ GET with path and query params @@ -180,7 +206,9 @@ def get_with_path_and_query( _response = self._client_wrapper.httpx_client.request( f"params/path-query/{jsonable_encoder(param)}", method="GET", - params={"query": query}, + params={ + "query": query, + }, request_options=request_options, ) try: @@ -192,7 +220,11 @@ def get_with_path_and_query( raise ApiError(status_code=_response.status_code, body=_response_json) def modify_with_path( - self, param: str, *, request: str, request_options: typing.Optional[RequestOptions] = None + self, + param: str, + *, + request: str, + request_options: typing.Optional[RequestOptions] = None, ) -> str: """ PUT to update with path param @@ -232,7 +264,9 @@ def modify_with_path( ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -243,7 +277,9 @@ class AsyncParamsClient: def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper - async def get_with_path(self, param: str, *, request_options: typing.Optional[RequestOptions] = None) -> str: + async def get_with_path( + self, param: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ GET with path param @@ -279,18 +315,26 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - f"params/path/{jsonable_encoder(param)}", method="GET", request_options=request_options + f"params/path/{jsonable_encoder(param)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_with_query( - self, *, query: str, number: int, request_options: typing.Optional[RequestOptions] = None + self, + *, + query: str, + number: int, + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ GET with query param @@ -330,7 +374,13 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "params", method="GET", params={"query": query, "number": number}, request_options=request_options + "params", + method="GET", + params={ + "query": query, + "number": number, + }, + request_options=request_options, ) try: if 200 <= _response.status_code < 300: @@ -385,7 +435,13 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "params", method="GET", params={"query": query, "numer": numer}, request_options=request_options + "params", + method="GET", + params={ + "query": query, + "numer": numer, + }, + request_options=request_options, ) try: if 200 <= _response.status_code < 300: @@ -396,7 +452,11 @@ async def main() -> None: raise ApiError(status_code=_response.status_code, body=_response_json) async def get_with_path_and_query( - self, param: str, *, query: str, request_options: typing.Optional[RequestOptions] = None + self, + param: str, + *, + query: str, + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ GET with path and query params @@ -438,7 +498,9 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( f"params/path-query/{jsonable_encoder(param)}", method="GET", - params={"query": query}, + params={ + "query": query, + }, request_options=request_options, ) try: @@ -450,7 +512,11 @@ async def main() -> None: raise ApiError(status_code=_response.status_code, body=_response_json) async def modify_with_path( - self, param: str, *, request: str, request_options: typing.Optional[RequestOptions] = None + self, + param: str, + *, + request: str, + request_options: typing.Optional[RequestOptions] = None, ) -> str: """ PUT to update with path param @@ -498,7 +564,9 @@ async def main() -> None: ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/endpoints/primitive/client.py b/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/endpoints/primitive/client.py index 844b6a782f0..20a66f049b4 100644 --- a/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/endpoints/primitive/client.py +++ b/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/endpoints/primitive/client.py @@ -1,14 +1,14 @@ # This file was auto-generated by Fern from our API Definition. -import datetime as dt import typing -import uuid +from ...core.client_wrapper import SyncClientWrapper +from ...core.request_options import RequestOptions +from ...core.pydantic_utilities import parse_obj_as from json.decoder import JSONDecodeError - from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ...core.pydantic_utilities import parse_obj_as -from ...core.request_options import RequestOptions +import datetime as dt +import uuid +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -18,7 +18,9 @@ class PrimitiveClient: def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper - def get_and_return_string(self, *, request: str, request_options: typing.Optional[RequestOptions] = None) -> str: + def get_and_return_string( + self, *, request: str, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -44,17 +46,25 @@ def get_and_return_string(self, *, request: str, request_options: typing.Optiona ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/string", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/string", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def get_and_return_int(self, *, request: int, request_options: typing.Optional[RequestOptions] = None) -> int: + def get_and_return_int( + self, *, request: int, request_options: typing.Optional[RequestOptions] = None + ) -> int: """ Parameters ---------- @@ -80,17 +90,25 @@ def get_and_return_int(self, *, request: int, request_options: typing.Optional[R ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/integer", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/integer", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(int, parse_obj_as(type_=int, object_=_response.json())) # type: ignore + return typing.cast( + int, parse_obj_as(type_=int, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def get_and_return_long(self, *, request: int, request_options: typing.Optional[RequestOptions] = None) -> int: + def get_and_return_long( + self, *, request: int, request_options: typing.Optional[RequestOptions] = None + ) -> int: """ Parameters ---------- @@ -116,11 +134,17 @@ def get_and_return_long(self, *, request: int, request_options: typing.Optional[ ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/long", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/long", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(int, parse_obj_as(type_=int, object_=_response.json())) # type: ignore + return typing.cast( + int, parse_obj_as(type_=int, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -154,17 +178,25 @@ def get_and_return_double( ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/double", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/double", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(float, parse_obj_as(type_=float, object_=_response.json())) # type: ignore + return typing.cast( + float, parse_obj_as(type_=float, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def get_and_return_bool(self, *, request: bool, request_options: typing.Optional[RequestOptions] = None) -> bool: + def get_and_return_bool( + self, *, request: bool, request_options: typing.Optional[RequestOptions] = None + ) -> bool: """ Parameters ---------- @@ -190,18 +222,27 @@ def get_and_return_bool(self, *, request: bool, request_options: typing.Optional ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/boolean", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/boolean", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_and_return_datetime( - self, *, request: dt.datetime, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: dt.datetime, + request_options: typing.Optional[RequestOptions] = None, ) -> dt.datetime: """ Parameters @@ -232,18 +273,28 @@ def get_and_return_datetime( ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/datetime", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/datetime", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(dt.datetime, parse_obj_as(type_=dt.datetime, object_=_response.json())) # type: ignore + return typing.cast( + dt.datetime, + parse_obj_as(type_=dt.datetime, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_and_return_date( - self, *, request: dt.date, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: dt.date, + request_options: typing.Optional[RequestOptions] = None, ) -> dt.date: """ Parameters @@ -274,18 +325,27 @@ def get_and_return_date( ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/date", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/date", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(dt.date, parse_obj_as(type_=dt.date, object_=_response.json())) # type: ignore + return typing.cast( + dt.date, parse_obj_as(type_=dt.date, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_and_return_uuid( - self, *, request: uuid.UUID, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: uuid.UUID, + request_options: typing.Optional[RequestOptions] = None, ) -> uuid.UUID: """ Parameters @@ -316,17 +376,25 @@ def get_and_return_uuid( ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/uuid", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/uuid", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(uuid.UUID, parse_obj_as(type_=uuid.UUID, object_=_response.json())) # type: ignore + return typing.cast( + uuid.UUID, parse_obj_as(type_=uuid.UUID, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def get_and_return_base_64(self, *, request: str, request_options: typing.Optional[RequestOptions] = None) -> str: + def get_and_return_base_64( + self, *, request: str, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -352,11 +420,17 @@ def get_and_return_base_64(self, *, request: str, request_options: typing.Option ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/base64", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/base64", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -403,17 +477,25 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/string", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/string", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - async def get_and_return_int(self, *, request: int, request_options: typing.Optional[RequestOptions] = None) -> int: + async def get_and_return_int( + self, *, request: int, request_options: typing.Optional[RequestOptions] = None + ) -> int: """ Parameters ---------- @@ -447,11 +529,17 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/integer", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/integer", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(int, parse_obj_as(type_=int, object_=_response.json())) # type: ignore + return typing.cast( + int, parse_obj_as(type_=int, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -493,11 +581,17 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/long", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/long", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(int, parse_obj_as(type_=int, object_=_response.json())) # type: ignore + return typing.cast( + int, parse_obj_as(type_=int, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -539,11 +633,17 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/double", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/double", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(float, parse_obj_as(type_=float, object_=_response.json())) # type: ignore + return typing.cast( + float, parse_obj_as(type_=float, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -585,18 +685,27 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/boolean", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/boolean", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_and_return_datetime( - self, *, request: dt.datetime, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: dt.datetime, + request_options: typing.Optional[RequestOptions] = None, ) -> dt.datetime: """ Parameters @@ -634,18 +743,28 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/datetime", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/datetime", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(dt.datetime, parse_obj_as(type_=dt.datetime, object_=_response.json())) # type: ignore + return typing.cast( + dt.datetime, + parse_obj_as(type_=dt.datetime, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_and_return_date( - self, *, request: dt.date, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: dt.date, + request_options: typing.Optional[RequestOptions] = None, ) -> dt.date: """ Parameters @@ -683,18 +802,27 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/date", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/date", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(dt.date, parse_obj_as(type_=dt.date, object_=_response.json())) # type: ignore + return typing.cast( + dt.date, parse_obj_as(type_=dt.date, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_and_return_uuid( - self, *, request: uuid.UUID, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: uuid.UUID, + request_options: typing.Optional[RequestOptions] = None, ) -> uuid.UUID: """ Parameters @@ -732,11 +860,17 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/uuid", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/uuid", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(uuid.UUID, parse_obj_as(type_=uuid.UUID, object_=_response.json())) # type: ignore + return typing.cast( + uuid.UUID, parse_obj_as(type_=uuid.UUID, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -778,11 +912,17 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/base64", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/base64", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/endpoints/union/client.py b/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/endpoints/union/client.py index 77153587a27..f4c3d9312de 100644 --- a/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/endpoints/union/client.py +++ b/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/endpoints/union/client.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. import typing +from ...core.client_wrapper import SyncClientWrapper +from ...types.union.types.animal import Animal +from ...core.request_options import RequestOptions +from ...core.pydantic_utilities import parse_obj_as from json.decoder import JSONDecodeError - from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ...core.pydantic_utilities import parse_obj_as -from ...core.request_options import RequestOptions -from ...types.union.types.animal import Animal +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -18,7 +18,10 @@ def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper def get_and_return_union( - self, *, request: Animal, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: Animal, + request_options: typing.Optional[RequestOptions] = None, ) -> Animal: """ Parameters @@ -49,11 +52,17 @@ def get_and_return_union( ) """ _response = self._client_wrapper.httpx_client.request( - "union", method="POST", json=request, request_options=request_options, omit=OMIT + "union", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(Animal, parse_obj_as(type_=Animal, object_=_response.json())) # type: ignore + return typing.cast( + Animal, parse_obj_as(type_=Animal, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -65,7 +74,10 @@ def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper async def get_and_return_union( - self, *, request: Animal, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: Animal, + request_options: typing.Optional[RequestOptions] = None, ) -> Animal: """ Parameters @@ -104,11 +116,17 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "union", method="POST", json=request, request_options=request_options, omit=OMIT + "union", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(Animal, parse_obj_as(type_=Animal, object_=_response.json())) # type: ignore + return typing.cast( + Animal, parse_obj_as(type_=Animal, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/general_errors/types/bad_object_request_info.py b/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/general_errors/types/bad_object_request_info.py index 7f03429e922..73c44b89531 100644 --- a/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/general_errors/types/bad_object_request_info.py +++ b/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/general_errors/types/bad_object_request_info.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class BadObjectRequestInfo(UniversalBaseModel): message: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/inlined_requests/client.py b/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/inlined_requests/client.py index f7c46698eb9..39e0c8fe637 100644 --- a/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/inlined_requests/client.py +++ b/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/inlined_requests/client.py @@ -1,15 +1,15 @@ # This file was auto-generated by Fern from our API Definition. import typing -from json.decoder import JSONDecodeError - -from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.pydantic_utilities import parse_obj_as +from ..core.client_wrapper import SyncClientWrapper +from ..types.object.types.object_with_optional_field import ObjectWithOptionalField from ..core.request_options import RequestOptions +from ..core.pydantic_utilities import parse_obj_as from ..general_errors.errors.bad_request_body import BadRequestBody from ..general_errors.types.bad_object_request_info import BadObjectRequestInfo -from ..types.object.types.object_with_optional_field import ObjectWithOptionalField +from json.decoder import JSONDecodeError +from ..core.api_error import ApiError +from ..core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -25,7 +25,7 @@ def post_with_object_bodyand_response( string: str, integer: int, nested_object: ObjectWithOptionalField, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> ObjectWithOptionalField: """ POST with custom object in request body, response is an object @@ -86,16 +86,30 @@ def post_with_object_bodyand_response( _response = self._client_wrapper.httpx_client.request( "req-bodies/object", method="POST", - json={"string": string, "integer": integer, "NestedObject": nested_object}, + json={ + "string": string, + "integer": integer, + "NestedObject": nested_object, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore if _response.status_code == 400: raise BadRequestBody( - typing.cast(BadObjectRequestInfo, parse_obj_as(type_=BadObjectRequestInfo, object_=_response.json())) # type: ignore + typing.cast( + BadObjectRequestInfo, + parse_obj_as( + type_=BadObjectRequestInfo, object_=_response.json() + ), + ) # type: ignore ) _response_json = _response.json() except JSONDecodeError: @@ -113,7 +127,7 @@ async def post_with_object_bodyand_response( string: str, integer: int, nested_object: ObjectWithOptionalField, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> ObjectWithOptionalField: """ POST with custom object in request body, response is an object @@ -181,16 +195,30 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( "req-bodies/object", method="POST", - json={"string": string, "integer": integer, "NestedObject": nested_object}, + json={ + "string": string, + "integer": integer, + "NestedObject": nested_object, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore if _response.status_code == 400: raise BadRequestBody( - typing.cast(BadObjectRequestInfo, parse_obj_as(type_=BadObjectRequestInfo, object_=_response.json())) # type: ignore + typing.cast( + BadObjectRequestInfo, + parse_obj_as( + type_=BadObjectRequestInfo, object_=_response.json() + ), + ) # type: ignore ) _response_json = _response.json() except JSONDecodeError: diff --git a/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/no_auth/client.py b/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/no_auth/client.py index 3d203bcea34..e5590cde0df 100644 --- a/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/no_auth/client.py +++ b/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/no_auth/client.py @@ -1,14 +1,14 @@ # This file was auto-generated by Fern from our API Definition. import typing -from json.decoder import JSONDecodeError - -from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.pydantic_utilities import parse_obj_as +from ..core.client_wrapper import SyncClientWrapper from ..core.request_options import RequestOptions +from ..core.pydantic_utilities import parse_obj_as from ..general_errors.errors.bad_request_body import BadRequestBody from ..general_errors.types.bad_object_request_info import BadObjectRequestInfo +from json.decoder import JSONDecodeError +from ..core.api_error import ApiError +from ..core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -19,7 +19,10 @@ def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper def post_with_no_auth( - self, *, request: typing.Any, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Any, + request_options: typing.Optional[RequestOptions] = None, ) -> bool: """ POST request with no auth @@ -48,14 +51,25 @@ def post_with_no_auth( ) """ _response = self._client_wrapper.httpx_client.request( - "no-auth", method="POST", json=request, request_options=request_options, omit=OMIT + "no-auth", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore if _response.status_code == 400: raise BadRequestBody( - typing.cast(BadObjectRequestInfo, parse_obj_as(type_=BadObjectRequestInfo, object_=_response.json())) # type: ignore + typing.cast( + BadObjectRequestInfo, + parse_obj_as( + type_=BadObjectRequestInfo, object_=_response.json() + ), + ) # type: ignore ) _response_json = _response.json() except JSONDecodeError: @@ -68,7 +82,10 @@ def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper async def post_with_no_auth( - self, *, request: typing.Any, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Any, + request_options: typing.Optional[RequestOptions] = None, ) -> bool: """ POST request with no auth @@ -105,14 +122,25 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "no-auth", method="POST", json=request, request_options=request_options, omit=OMIT + "no-auth", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore if _response.status_code == 400: raise BadRequestBody( - typing.cast(BadObjectRequestInfo, parse_obj_as(type_=BadObjectRequestInfo, object_=_response.json())) # type: ignore + typing.cast( + BadObjectRequestInfo, + parse_obj_as( + type_=BadObjectRequestInfo, object_=_response.json() + ), + ) # type: ignore ) _response_json = _response.json() except JSONDecodeError: diff --git a/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/no_req_body/client.py b/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/no_req_body/client.py index 33fa0c77d27..5afdd703fdc 100644 --- a/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/no_req_body/client.py +++ b/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/no_req_body/client.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. +from ..core.client_wrapper import SyncClientWrapper import typing -from json.decoder import JSONDecodeError - -from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.pydantic_utilities import parse_obj_as from ..core.request_options import RequestOptions from ..types.object.types.object_with_optional_field import ObjectWithOptionalField +from ..core.pydantic_utilities import parse_obj_as +from json.decoder import JSONDecodeError +from ..core.api_error import ApiError +from ..core.client_wrapper import AsyncClientWrapper class NoReqBodyClient: @@ -38,17 +38,26 @@ def get_with_no_request_body( client.no_req_body.get_with_no_request_body() """ _response = self._client_wrapper.httpx_client.request( - "no-req-body", method="GET", request_options=request_options + "no-req-body", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def post_with_no_request_body(self, *, request_options: typing.Optional[RequestOptions] = None) -> str: + def post_with_no_request_body( + self, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -70,11 +79,15 @@ def post_with_no_request_body(self, *, request_options: typing.Optional[RequestO client.no_req_body.post_with_no_request_body() """ _response = self._client_wrapper.httpx_client.request( - "no-req-body", method="POST", request_options=request_options + "no-req-body", + method="POST", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -117,17 +130,26 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "no-req-body", method="GET", request_options=request_options + "no-req-body", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - async def post_with_no_request_body(self, *, request_options: typing.Optional[RequestOptions] = None) -> str: + async def post_with_no_request_body( + self, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -157,11 +179,15 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "no-req-body", method="POST", request_options=request_options + "no-req-body", + method="POST", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/req_with_headers/client.py b/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/req_with_headers/client.py index 655402249e9..984428516e3 100644 --- a/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/req_with_headers/client.py +++ b/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/req_with_headers/client.py @@ -1,11 +1,11 @@ # This file was auto-generated by Fern from our API Definition. import typing +from ..core.client_wrapper import SyncClientWrapper +from ..core.request_options import RequestOptions from json.decoder import JSONDecodeError - from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.request_options import RequestOptions +from ..core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -21,7 +21,7 @@ def get_with_custom_header( x_test_service_header: str, x_test_endpoint_header: str, request: str, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ Parameters @@ -58,8 +58,12 @@ def get_with_custom_header( method="POST", json=request, headers={ - "X-TEST-SERVICE-HEADER": str(x_test_service_header) if x_test_service_header is not None else None, - "X-TEST-ENDPOINT-HEADER": str(x_test_endpoint_header) if x_test_endpoint_header is not None else None, + "X-TEST-SERVICE-HEADER": str(x_test_service_header) + if x_test_service_header is not None + else None, + "X-TEST-ENDPOINT-HEADER": str(x_test_endpoint_header) + if x_test_endpoint_header is not None + else None, }, request_options=request_options, omit=OMIT, @@ -83,7 +87,7 @@ async def get_with_custom_header( x_test_service_header: str, x_test_endpoint_header: str, request: str, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ Parameters @@ -128,8 +132,12 @@ async def main() -> None: method="POST", json=request, headers={ - "X-TEST-SERVICE-HEADER": str(x_test_service_header) if x_test_service_header is not None else None, - "X-TEST-ENDPOINT-HEADER": str(x_test_endpoint_header) if x_test_endpoint_header is not None else None, + "X-TEST-SERVICE-HEADER": str(x_test_service_header) + if x_test_service_header is not None + else None, + "X-TEST-ENDPOINT-HEADER": str(x_test_endpoint_header) + if x_test_endpoint_header is not None + else None, }, request_options=request_options, omit=OMIT, diff --git a/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/types/enum/types/weather_report.py b/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/types/enum/types/weather_report.py index 2d54965dc22..84017ef161d 100644 --- a/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/types/enum/types/weather_report.py +++ b/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/types/enum/types/weather_report.py @@ -2,4 +2,6 @@ import typing -WeatherReport = typing.Union[typing.Literal["SUNNY", "CLOUDY", "RAINING", "SNOWING"], typing.Any] +WeatherReport = typing.Union[ + typing.Literal["SUNNY", "CLOUDY", "RAINING", "SNOWING"], typing.Any +] diff --git a/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/types/object/types/double_optional.py b/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/types/object/types/double_optional.py index ddf165b13bd..ed236347357 100644 --- a/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/types/object/types/double_optional.py +++ b/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/types/object/types/double_optional.py @@ -1,18 +1,21 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .optional_alias import OptionalAlias +import pydantic +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class DoubleOptional(UniversalBaseModel): - optional_alias: typing.Optional[OptionalAlias] = pydantic.Field(alias="optionalAlias", default=None) + optional_alias: typing.Optional[OptionalAlias] = pydantic.Field( + alias="optionalAlias", default=None + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/types/object/types/nested_object_with_optional_field.py b/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/types/object/types/nested_object_with_optional_field.py index 81669c0dd39..20a4d40a714 100644 --- a/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/types/object/types/nested_object_with_optional_field.py +++ b/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/types/object/types/nested_object_with_optional_field.py @@ -1,19 +1,22 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .object_with_optional_field import ObjectWithOptionalField +import pydantic +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class NestedObjectWithOptionalField(UniversalBaseModel): string: typing.Optional[str] = None - nested_object: typing.Optional[ObjectWithOptionalField] = pydantic.Field(alias="NestedObject", default=None) + nested_object: typing.Optional[ObjectWithOptionalField] = pydantic.Field( + alias="NestedObject", default=None + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/types/object/types/nested_object_with_required_field.py b/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/types/object/types/nested_object_with_required_field.py index 1a621942c6c..a6ca8781190 100644 --- a/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/types/object/types/nested_object_with_required_field.py +++ b/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/types/object/types/nested_object_with_required_field.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import UniversalBaseModel from .object_with_optional_field import ObjectWithOptionalField +import pydantic +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class NestedObjectWithRequiredField(UniversalBaseModel): @@ -13,7 +12,9 @@ class NestedObjectWithRequiredField(UniversalBaseModel): nested_object: ObjectWithOptionalField = pydantic.Field(alias="NestedObject") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/types/object/types/object_with_map_of_map.py b/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/types/object/types/object_with_map_of_map.py index 8883cc1d498..313cd25ceb8 100644 --- a/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/types/object/types/object_with_map_of_map.py +++ b/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/types/object/types/object_with_map_of_map.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class ObjectWithMapOfMap(UniversalBaseModel): map_: typing.Dict[str, typing.Dict[str, str]] = pydantic.Field(alias="map") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/types/object/types/object_with_optional_field.py b/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/types/object/types/object_with_optional_field.py index 6aab170be0c..9131f0e91d7 100644 --- a/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/types/object/types/object_with_optional_field.py +++ b/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/types/object/types/object_with_optional_field.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. -import datetime as dt +from ....core.pydantic_utilities import UniversalBaseModel import typing -import uuid - import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +import datetime as dt +import uuid +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class ObjectWithOptionalField(UniversalBaseModel): @@ -23,13 +22,19 @@ class ObjectWithOptionalField(UniversalBaseModel): date: typing.Optional[dt.date] = None uuid_: typing.Optional[uuid.UUID] = pydantic.Field(alias="uuid", default=None) base_64: typing.Optional[str] = pydantic.Field(alias="base64", default=None) - list_: typing.Optional[typing.List[str]] = pydantic.Field(alias="list", default=None) + list_: typing.Optional[typing.List[str]] = pydantic.Field( + alias="list", default=None + ) set_: typing.Optional[typing.Set[str]] = pydantic.Field(alias="set", default=None) - map_: typing.Optional[typing.Dict[int, str]] = pydantic.Field(alias="map", default=None) + map_: typing.Optional[typing.Dict[int, str]] = pydantic.Field( + alias="map", default=None + ) bigint: typing.Optional[str] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/types/object/types/object_with_required_field.py b/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/types/object/types/object_with_required_field.py index 61b98867984..24db26a3cf8 100644 --- a/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/types/object/types/object_with_required_field.py +++ b/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/types/object/types/object_with_required_field.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class ObjectWithRequiredField(UniversalBaseModel): string: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/types/union/types/animal.py b/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/types/union/types/animal.py index 1ae43d1663e..84c71d2009a 100644 --- a/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/types/union/types/animal.py +++ b/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/types/union/types/animal.py @@ -1,12 +1,10 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ....core.pydantic_utilities import UniversalBaseModel import typing - import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class Animal_Dog(UniversalBaseModel): @@ -15,7 +13,9 @@ class Animal_Dog(UniversalBaseModel): likes_to_woof: bool = pydantic.Field(alias="likesToWoof") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: @@ -30,7 +30,9 @@ class Animal_Cat(UniversalBaseModel): likes_to_meow: bool = pydantic.Field(alias="likesToMeow") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/types/union/types/cat.py b/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/types/union/types/cat.py index 61fc5527b1f..c59b78523c9 100644 --- a/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/types/union/types/cat.py +++ b/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/types/union/types/cat.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ....core.pydantic_utilities import UniversalBaseModel import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class Cat(UniversalBaseModel): @@ -12,7 +11,9 @@ class Cat(UniversalBaseModel): likes_to_meow: bool = pydantic.Field(alias="likesToMeow") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/types/union/types/dog.py b/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/types/union/types/dog.py index c1ff5339dfe..e250c72edef 100644 --- a/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/types/union/types/dog.py +++ b/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/types/union/types/dog.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ....core.pydantic_utilities import UniversalBaseModel import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class Dog(UniversalBaseModel): @@ -12,7 +11,9 @@ class Dog(UniversalBaseModel): likes_to_woof: bool = pydantic.Field(alias="likesToWoof") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/version.py b/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/version.py index 63ba170685a..ac44536abdb 100644 --- a/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/version.py +++ b/seed/python-sdk/exhaustive/pydantic-extra-fields/src/seed/version.py @@ -1,4 +1,3 @@ - from importlib import metadata __version__ = metadata.version("fern_exhaustive") diff --git a/seed/python-sdk/exhaustive/pydantic-extra-fields/tests/conftest.py b/seed/python-sdk/exhaustive/pydantic-extra-fields/tests/conftest.py index b5b50383b94..86cb2b41af8 100644 --- a/seed/python-sdk/exhaustive/pydantic-extra-fields/tests/conftest.py +++ b/seed/python-sdk/exhaustive/pydantic-extra-fields/tests/conftest.py @@ -1,16 +1,22 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive import os - import pytest -from seed import AsyncSeedExhaustive, SeedExhaustive +from seed import AsyncSeedExhaustive @pytest.fixture def client() -> SeedExhaustive: - return SeedExhaustive(token=os.getenv("ENV_TOKEN", "token"), base_url=os.getenv("TESTS_BASE_URL", "base_url")) + return SeedExhaustive( + token=os.getenv("ENV_TOKEN", "token"), + base_url=os.getenv("TESTS_BASE_URL", "base_url"), + ) @pytest.fixture def async_client() -> AsyncSeedExhaustive: - return AsyncSeedExhaustive(token=os.getenv("ENV_TOKEN", "token"), base_url=os.getenv("TESTS_BASE_URL", "base_url")) + return AsyncSeedExhaustive( + token=os.getenv("ENV_TOKEN", "token"), + base_url=os.getenv("TESTS_BASE_URL", "base_url"), + ) diff --git a/seed/python-sdk/exhaustive/pydantic-extra-fields/tests/custom/test_client.py b/seed/python-sdk/exhaustive/pydantic-extra-fields/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/python-sdk/exhaustive/pydantic-extra-fields/tests/custom/test_client.py +++ b/seed/python-sdk/exhaustive/pydantic-extra-fields/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/python-sdk/exhaustive/pydantic-extra-fields/tests/endpoints/test_container.py b/seed/python-sdk/exhaustive/pydantic-extra-fields/tests/endpoints/test_container.py index 17d9d75240d..240f16f2a8c 100644 --- a/seed/python-sdk/exhaustive/pydantic-extra-fields/tests/endpoints/test_container.py +++ b/seed/python-sdk/exhaustive/pydantic-extra-fields/tests/endpoints/test_container.py @@ -1,91 +1,137 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing - -from seed import AsyncSeedExhaustive, SeedExhaustive -from seed.types.object import ObjectWithRequiredField - from ..utilities import validate_response +from seed.types.object import ObjectWithRequiredField -async def test_get_and_return_list_of_primitives(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_list_of_primitives( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = ["string"] expected_types: typing.Tuple[typing.Any, typing.Any] = ("list", {0: None}) - response = client.endpoints.container.get_and_return_list_of_primitives(request=["string"]) + response = client.endpoints.container.get_and_return_list_of_primitives( + request=["string"] + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.container.get_and_return_list_of_primitives(request=["string"]) + async_response = ( + await async_client.endpoints.container.get_and_return_list_of_primitives( + request=["string"] + ) + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_list_of_objects(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_list_of_objects( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = [{"string": "string"}] - expected_types: typing.Tuple[typing.Any, typing.Any] = ("list", {0: {"string": None}}) + expected_types: typing.Tuple[typing.Any, typing.Any] = ( + "list", + {0: {"string": None}}, + ) response = client.endpoints.container.get_and_return_list_of_objects( request=[ObjectWithRequiredField(string="string")] ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.container.get_and_return_list_of_objects( - request=[ObjectWithRequiredField(string="string")] + async_response = ( + await async_client.endpoints.container.get_and_return_list_of_objects( + request=[ObjectWithRequiredField(string="string")] + ) ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_set_of_primitives(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_set_of_primitives( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = ["string"] expected_types: typing.Tuple[typing.Any, typing.Any] = ("set", {0: None}) - response = client.endpoints.container.get_and_return_set_of_primitives(request={"string"}) + response = client.endpoints.container.get_and_return_set_of_primitives( + request={"string"} + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.container.get_and_return_set_of_primitives(request={"string"}) + async_response = ( + await async_client.endpoints.container.get_and_return_set_of_primitives( + request={"string"} + ) + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_set_of_objects(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_set_of_objects( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = [{"string": "string"}] - expected_types: typing.Tuple[typing.Any, typing.Any] = ("set", {0: {"string": None}}) + expected_types: typing.Tuple[typing.Any, typing.Any] = ( + "set", + {0: {"string": None}}, + ) response = client.endpoints.container.get_and_return_set_of_objects( request=[ObjectWithRequiredField(string="string")] ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.container.get_and_return_set_of_objects( - request=[ObjectWithRequiredField(string="string")] + async_response = ( + await async_client.endpoints.container.get_and_return_set_of_objects( + request=[ObjectWithRequiredField(string="string")] + ) ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_map_prim_to_prim(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_map_prim_to_prim( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = {"string": "string"} expected_types: typing.Tuple[typing.Any, typing.Any] = ("dict", {0: (None, None)}) - response = client.endpoints.container.get_and_return_map_prim_to_prim(request={"string": "string"}) + response = client.endpoints.container.get_and_return_map_prim_to_prim( + request={"string": "string"} + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.container.get_and_return_map_prim_to_prim( - request={"string": "string"} + async_response = ( + await async_client.endpoints.container.get_and_return_map_prim_to_prim( + request={"string": "string"} + ) ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_map_of_prim_to_object(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_map_of_prim_to_object( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = {"string": {"string": "string"}} - expected_types: typing.Tuple[typing.Any, typing.Any] = ("dict", {0: (None, {"string": None})}) + expected_types: typing.Tuple[typing.Any, typing.Any] = ( + "dict", + {0: (None, {"string": None})}, + ) response = client.endpoints.container.get_and_return_map_of_prim_to_object( request={"string": ObjectWithRequiredField(string="string")} ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.container.get_and_return_map_of_prim_to_object( - request={"string": ObjectWithRequiredField(string="string")} + async_response = ( + await async_client.endpoints.container.get_and_return_map_of_prim_to_object( + request={"string": ObjectWithRequiredField(string="string")} + ) ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_optional(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_optional( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = {"string": "string"} expected_types: typing.Any = {"string": None} - response = client.endpoints.container.get_and_return_optional(request=ObjectWithRequiredField(string="string")) + response = client.endpoints.container.get_and_return_optional( + request=ObjectWithRequiredField(string="string") + ) validate_response(response, expected_response, expected_types) async_response = await async_client.endpoints.container.get_and_return_optional( diff --git a/seed/python-sdk/exhaustive/pydantic-extra-fields/tests/endpoints/test_enum.py b/seed/python-sdk/exhaustive/pydantic-extra-fields/tests/endpoints/test_enum.py index 890aada5ce4..ca3fca30b5a 100644 --- a/seed/python-sdk/exhaustive/pydantic-extra-fields/tests/endpoints/test_enum.py +++ b/seed/python-sdk/exhaustive/pydantic-extra-fields/tests/endpoints/test_enum.py @@ -1,17 +1,20 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing - -from seed import AsyncSeedExhaustive, SeedExhaustive - from ..utilities import validate_response -async def test_get_and_return_enum(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_enum( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "SUNNY" expected_types: typing.Any = None response = client.endpoints.enum.get_and_return_enum(request="SUNNY") validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.enum.get_and_return_enum(request="SUNNY") + async_response = await async_client.endpoints.enum.get_and_return_enum( + request="SUNNY" + ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/exhaustive/pydantic-extra-fields/tests/endpoints/test_http_methods.py b/seed/python-sdk/exhaustive/pydantic-extra-fields/tests/endpoints/test_http_methods.py index dc01bafcf6f..77131fc6e8b 100644 --- a/seed/python-sdk/exhaustive/pydantic-extra-fields/tests/endpoints/test_http_methods.py +++ b/seed/python-sdk/exhaustive/pydantic-extra-fields/tests/endpoints/test_http_methods.py @@ -1,15 +1,16 @@ # This file was auto-generated by Fern from our API Definition. -import datetime +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing -import uuid - -from seed import AsyncSeedExhaustive, SeedExhaustive - from ..utilities import validate_response +import datetime +import uuid -async def test_test_get(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_test_get( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "string" expected_types: typing.Any = None response = client.endpoints.http_methods.test_get(id="string") @@ -19,7 +20,9 @@ async def test_test_get(client: SeedExhaustive, async_client: AsyncSeedExhaustiv validate_response(async_response, expected_response, expected_types) -async def test_test_post(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_test_post( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = { "string": "string", "integer": 1, @@ -53,11 +56,15 @@ async def test_test_post(client: SeedExhaustive, async_client: AsyncSeedExhausti response = client.endpoints.http_methods.test_post(string="string") validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.http_methods.test_post(string="string") + async_response = await async_client.endpoints.http_methods.test_post( + string="string" + ) validate_response(async_response, expected_response, expected_types) -async def test_test_put(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_test_put( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = { "string": "string", "integer": 1, @@ -91,11 +98,15 @@ async def test_test_put(client: SeedExhaustive, async_client: AsyncSeedExhaustiv response = client.endpoints.http_methods.test_put(id="string", string="string") validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.http_methods.test_put(id="string", string="string") + async_response = await async_client.endpoints.http_methods.test_put( + id="string", string="string" + ) validate_response(async_response, expected_response, expected_types) -async def test_test_patch(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_test_patch( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = { "string": "string", "integer": 1, @@ -163,7 +174,9 @@ async def test_test_patch(client: SeedExhaustive, async_client: AsyncSeedExhaust validate_response(async_response, expected_response, expected_types) -async def test_test_delete(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_test_delete( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = True expected_types: typing.Any = None response = client.endpoints.http_methods.test_delete(id="string") diff --git a/seed/python-sdk/exhaustive/pydantic-extra-fields/tests/endpoints/test_object.py b/seed/python-sdk/exhaustive/pydantic-extra-fields/tests/endpoints/test_object.py index a9098b6e9ef..c48c4332b22 100644 --- a/seed/python-sdk/exhaustive/pydantic-extra-fields/tests/endpoints/test_object.py +++ b/seed/python-sdk/exhaustive/pydantic-extra-fields/tests/endpoints/test_object.py @@ -1,16 +1,18 @@ # This file was auto-generated by Fern from our API Definition. -import datetime +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing +import datetime import uuid - -from seed import AsyncSeedExhaustive, SeedExhaustive -from seed.types.object import NestedObjectWithRequiredField, ObjectWithOptionalField - from ..utilities import validate_response +from seed.types.object import ObjectWithOptionalField +from seed.types.object import NestedObjectWithRequiredField -async def test_get_and_return_with_optional_field(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_with_optional_field( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = { "string": "string", "integer": 1, @@ -58,38 +60,54 @@ async def test_get_and_return_with_optional_field(client: SeedExhaustive, async_ ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.object.get_and_return_with_optional_field( - string="string", - integer=1, - long_=1000000, - double=1.1, - bool_=True, - datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), - date=datetime.date.fromisoformat("2023-01-15"), - uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), - base_64="SGVsbG8gd29ybGQh", - list_=["string"], - set_={"string"}, - map_={1: "string"}, - bigint="123456789123456789", + async_response = ( + await async_client.endpoints.object.get_and_return_with_optional_field( + string="string", + integer=1, + long_=1000000, + double=1.1, + bool_=True, + datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), + date=datetime.date.fromisoformat("2023-01-15"), + uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + base_64="SGVsbG8gd29ybGQh", + list_=["string"], + set_={"string"}, + map_={1: "string"}, + bigint="123456789123456789", + ) ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_with_required_field(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_with_required_field( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = {"string": "string"} expected_types: typing.Any = {"string": None} - response = client.endpoints.object.get_and_return_with_required_field(string="string") + response = client.endpoints.object.get_and_return_with_required_field( + string="string" + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.object.get_and_return_with_required_field(string="string") + async_response = ( + await async_client.endpoints.object.get_and_return_with_required_field( + string="string" + ) + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_with_map_of_map(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_with_map_of_map( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = {"map": {"string": {"string": "string"}}} - expected_types: typing.Any = {"map": ("dict", {0: (None, ("dict", {0: (None, None)}))})} - response = client.endpoints.object.get_and_return_with_map_of_map(map_={"string": {"string": "string"}}) + expected_types: typing.Any = { + "map": ("dict", {0: (None, ("dict", {0: (None, None)}))}) + } + response = client.endpoints.object.get_and_return_with_map_of_map( + map_={"string": {"string": "string"}} + ) validate_response(response, expected_response, expected_types) async_response = await async_client.endpoints.object.get_and_return_with_map_of_map( @@ -157,23 +175,25 @@ async def test_get_and_return_nested_with_optional_field( ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.object.get_and_return_nested_with_optional_field( - string="string", - nested_object=ObjectWithOptionalField( + async_response = ( + await async_client.endpoints.object.get_and_return_nested_with_optional_field( string="string", - integer=1, - long_=1000000, - double=1.1, - bool_=True, - datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), - date=datetime.date.fromisoformat("2023-01-15"), - uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), - base_64="SGVsbG8gd29ybGQh", - list_=["string"], - set_={"string"}, - map_={1: "string"}, - bigint="123456789123456789", - ), + nested_object=ObjectWithOptionalField( + string="string", + integer=1, + long_=1000000, + double=1.1, + bool_=True, + datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), + date=datetime.date.fromisoformat("2023-01-15"), + uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + base_64="SGVsbG8gd29ybGQh", + list_=["string"], + set_={"string"}, + map_={1: "string"}, + bigint="123456789123456789", + ), + ) ) validate_response(async_response, expected_response, expected_types) @@ -238,24 +258,26 @@ async def test_get_and_return_nested_with_required_field( ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.object.get_and_return_nested_with_required_field( - string_="string", - string="string", - nested_object=ObjectWithOptionalField( + async_response = ( + await async_client.endpoints.object.get_and_return_nested_with_required_field( + string_="string", string="string", - integer=1, - long_=1000000, - double=1.1, - bool_=True, - datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), - date=datetime.date.fromisoformat("2023-01-15"), - uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), - base_64="SGVsbG8gd29ybGQh", - list_=["string"], - set_={"string"}, - map_={1: "string"}, - bigint="123456789123456789", - ), + nested_object=ObjectWithOptionalField( + string="string", + integer=1, + long_=1000000, + double=1.1, + bool_=True, + datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), + date=datetime.date.fromisoformat("2023-01-15"), + uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + base_64="SGVsbG8gd29ybGQh", + list_=["string"], + set_={"string"}, + map_={1: "string"}, + bigint="123456789123456789", + ), + ) ) validate_response(async_response, expected_response, expected_types) @@ -299,27 +321,31 @@ async def test_get_and_return_nested_with_required_field_as_list( "bigint": None, }, } - response = client.endpoints.object.get_and_return_nested_with_required_field_as_list( - request=[ - NestedObjectWithRequiredField( - string="string", - nested_object=ObjectWithOptionalField( + response = ( + client.endpoints.object.get_and_return_nested_with_required_field_as_list( + request=[ + NestedObjectWithRequiredField( string="string", - integer=1, - long_=1000000, - double=1.1, - bool_=True, - datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), - date=datetime.date.fromisoformat("2023-01-15"), - uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), - base_64="SGVsbG8gd29ybGQh", - list_=["string"], - set_={"string"}, - map_={1: "string"}, - bigint="123456789123456789", - ), - ) - ] + nested_object=ObjectWithOptionalField( + string="string", + integer=1, + long_=1000000, + double=1.1, + bool_=True, + datetime=datetime.datetime.fromisoformat( + "2024-01-15 09:30:00+00:00" + ), + date=datetime.date.fromisoformat("2023-01-15"), + uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + base_64="SGVsbG8gd29ybGQh", + list_=["string"], + set_={"string"}, + map_={1: "string"}, + bigint="123456789123456789", + ), + ) + ] + ) ) validate_response(response, expected_response, expected_types) @@ -333,7 +359,9 @@ async def test_get_and_return_nested_with_required_field_as_list( long_=1000000, double=1.1, bool_=True, - datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), + datetime=datetime.datetime.fromisoformat( + "2024-01-15 09:30:00+00:00" + ), date=datetime.date.fromisoformat("2023-01-15"), uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), base_64="SGVsbG8gd29ybGQh", diff --git a/seed/python-sdk/exhaustive/pydantic-extra-fields/tests/endpoints/test_params.py b/seed/python-sdk/exhaustive/pydantic-extra-fields/tests/endpoints/test_params.py index 163d7b9161d..d8ffb00c0a0 100644 --- a/seed/python-sdk/exhaustive/pydantic-extra-fields/tests/endpoints/test_params.py +++ b/seed/python-sdk/exhaustive/pydantic-extra-fields/tests/endpoints/test_params.py @@ -1,13 +1,14 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing - -from seed import AsyncSeedExhaustive, SeedExhaustive - from ..utilities import validate_response -async def test_get_with_path(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_with_path( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "string" expected_types: typing.Any = None response = client.endpoints.params.get_with_path(param="string") @@ -17,32 +18,63 @@ async def test_get_with_path(client: SeedExhaustive, async_client: AsyncSeedExha validate_response(async_response, expected_response, expected_types) -async def test_get_with_query(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_with_query( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: # Type ignore to avoid mypy complaining about the function not being meant to return a value assert client.endpoints.params.get_with_query(query="string", number=1) is None # type: ignore[func-returns-value] - assert await async_client.endpoints.params.get_with_query(query="string", number=1) is None # type: ignore[func-returns-value] + assert ( + await async_client.endpoints.params.get_with_query(query="string", number=1) + is None + ) # type: ignore[func-returns-value] -async def test_get_with_allow_multiple_query(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_with_allow_multiple_query( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: # Type ignore to avoid mypy complaining about the function not being meant to return a value - assert client.endpoints.params.get_with_allow_multiple_query(query="string", numer=1) is None # type: ignore[func-returns-value] - - assert await async_client.endpoints.params.get_with_allow_multiple_query(query="string", numer=1) is None # type: ignore[func-returns-value] - - -async def test_get_with_path_and_query(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: + assert ( + client.endpoints.params.get_with_allow_multiple_query(query="string", numer=1) + is None + ) # type: ignore[func-returns-value] + + assert ( + await async_client.endpoints.params.get_with_allow_multiple_query( + query="string", numer=1 + ) + is None + ) # type: ignore[func-returns-value] + + +async def test_get_with_path_and_query( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: # Type ignore to avoid mypy complaining about the function not being meant to return a value - assert client.endpoints.params.get_with_path_and_query(param="string", query="string") is None # type: ignore[func-returns-value] - - assert await async_client.endpoints.params.get_with_path_and_query(param="string", query="string") is None # type: ignore[func-returns-value] - - -async def test_modify_with_path(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: + assert ( + client.endpoints.params.get_with_path_and_query(param="string", query="string") + is None + ) # type: ignore[func-returns-value] + + assert ( + await async_client.endpoints.params.get_with_path_and_query( + param="string", query="string" + ) + is None + ) # type: ignore[func-returns-value] + + +async def test_modify_with_path( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "string" expected_types: typing.Any = None - response = client.endpoints.params.modify_with_path(param="string", request="string") + response = client.endpoints.params.modify_with_path( + param="string", request="string" + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.params.modify_with_path(param="string", request="string") + async_response = await async_client.endpoints.params.modify_with_path( + param="string", request="string" + ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/exhaustive/pydantic-extra-fields/tests/endpoints/test_primitive.py b/seed/python-sdk/exhaustive/pydantic-extra-fields/tests/endpoints/test_primitive.py index ba3bc7e29e5..26cbcf45d2f 100644 --- a/seed/python-sdk/exhaustive/pydantic-extra-fields/tests/endpoints/test_primitive.py +++ b/seed/python-sdk/exhaustive/pydantic-extra-fields/tests/endpoints/test_primitive.py @@ -1,65 +1,86 @@ # This file was auto-generated by Fern from our API Definition. -import datetime +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing -import uuid - -from seed import AsyncSeedExhaustive, SeedExhaustive - from ..utilities import validate_response +import datetime +import uuid -async def test_get_and_return_string(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_string( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "string" expected_types: typing.Any = None response = client.endpoints.primitive.get_and_return_string(request="string") validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.primitive.get_and_return_string(request="string") + async_response = await async_client.endpoints.primitive.get_and_return_string( + request="string" + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_int(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_int( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = 1 expected_types: typing.Any = "integer" response = client.endpoints.primitive.get_and_return_int(request=1) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.primitive.get_and_return_int(request=1) + async_response = await async_client.endpoints.primitive.get_and_return_int( + request=1 + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_long(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_long( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = 1000000 expected_types: typing.Any = None response = client.endpoints.primitive.get_and_return_long(request=1000000) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.primitive.get_and_return_long(request=1000000) + async_response = await async_client.endpoints.primitive.get_and_return_long( + request=1000000 + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_double(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_double( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = 1.1 expected_types: typing.Any = None response = client.endpoints.primitive.get_and_return_double(request=1.1) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.primitive.get_and_return_double(request=1.1) + async_response = await async_client.endpoints.primitive.get_and_return_double( + request=1.1 + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_bool(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_bool( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = True expected_types: typing.Any = None response = client.endpoints.primitive.get_and_return_bool(request=True) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.primitive.get_and_return_bool(request=True) + async_response = await async_client.endpoints.primitive.get_and_return_bool( + request=True + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_datetime(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_datetime( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "2024-01-15T09:30:00Z" expected_types: typing.Any = "datetime" response = client.endpoints.primitive.get_and_return_datetime( @@ -73,10 +94,14 @@ async def test_get_and_return_datetime(client: SeedExhaustive, async_client: Asy validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_date(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_date( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "2023-01-15" expected_types: typing.Any = "date" - response = client.endpoints.primitive.get_and_return_date(request=datetime.date.fromisoformat("2023-01-15")) + response = client.endpoints.primitive.get_and_return_date( + request=datetime.date.fromisoformat("2023-01-15") + ) validate_response(response, expected_response, expected_types) async_response = await async_client.endpoints.primitive.get_and_return_date( @@ -85,10 +110,14 @@ async def test_get_and_return_date(client: SeedExhaustive, async_client: AsyncSe validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_uuid(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_uuid( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32" expected_types: typing.Any = "uuid" - response = client.endpoints.primitive.get_and_return_uuid(request=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32")) + response = client.endpoints.primitive.get_and_return_uuid( + request=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32") + ) validate_response(response, expected_response, expected_types) async_response = await async_client.endpoints.primitive.get_and_return_uuid( @@ -97,11 +126,17 @@ async def test_get_and_return_uuid(client: SeedExhaustive, async_client: AsyncSe validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_base_64(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_base_64( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "SGVsbG8gd29ybGQh" expected_types: typing.Any = None - response = client.endpoints.primitive.get_and_return_base_64(request="SGVsbG8gd29ybGQh") + response = client.endpoints.primitive.get_and_return_base_64( + request="SGVsbG8gd29ybGQh" + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.primitive.get_and_return_base_64(request="SGVsbG8gd29ybGQh") + async_response = await async_client.endpoints.primitive.get_and_return_base_64( + request="SGVsbG8gd29ybGQh" + ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/exhaustive/pydantic-extra-fields/tests/endpoints/test_union.py b/seed/python-sdk/exhaustive/pydantic-extra-fields/tests/endpoints/test_union.py index 14e34c2a6df..ceb84928cd9 100644 --- a/seed/python-sdk/exhaustive/pydantic-extra-fields/tests/endpoints/test_union.py +++ b/seed/python-sdk/exhaustive/pydantic-extra-fields/tests/endpoints/test_union.py @@ -1,17 +1,24 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing - -from seed import AsyncSeedExhaustive, SeedExhaustive from seed.types.union import Animal_Dog - from ..utilities import validate_response -async def test_get_and_return_union(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: - expected_response: typing.Any = {"animal": "dog", "name": "string", "likesToWoof": True} +async def test_get_and_return_union( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: + expected_response: typing.Any = { + "animal": "dog", + "name": "string", + "likesToWoof": True, + } expected_types: typing.Any = "no_validate" - response = client.endpoints.union.get_and_return_union(request=Animal_Dog(name="string", likes_to_woof=True)) + response = client.endpoints.union.get_and_return_union( + request=Animal_Dog(name="string", likes_to_woof=True) + ) validate_response(response, expected_response, expected_types) async_response = await async_client.endpoints.union.get_and_return_union( diff --git a/seed/python-sdk/exhaustive/pydantic-extra-fields/tests/test_inlined_requests.py b/seed/python-sdk/exhaustive/pydantic-extra-fields/tests/test_inlined_requests.py index bb9390d3845..03f46b31cc9 100644 --- a/seed/python-sdk/exhaustive/pydantic-extra-fields/tests/test_inlined_requests.py +++ b/seed/python-sdk/exhaustive/pydantic-extra-fields/tests/test_inlined_requests.py @@ -1,16 +1,17 @@ # This file was auto-generated by Fern from our API Definition. -import datetime +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing -import uuid - -from seed import AsyncSeedExhaustive, SeedExhaustive from seed.types.object import ObjectWithOptionalField - +import datetime +import uuid from .utilities import validate_response -async def test_post_with_object_bodyand_response(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_post_with_object_bodyand_response( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = { "string": "string", "integer": 1, @@ -62,23 +63,25 @@ async def test_post_with_object_bodyand_response(client: SeedExhaustive, async_c ) validate_response(response, expected_response, expected_types) - async_response = await async_client.inlined_requests.post_with_object_bodyand_response( - string="string", - integer=1, - nested_object=ObjectWithOptionalField( + async_response = ( + await async_client.inlined_requests.post_with_object_bodyand_response( string="string", integer=1, - long_=1000000, - double=1.1, - bool_=True, - datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), - date=datetime.date.fromisoformat("2023-01-15"), - uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), - base_64="SGVsbG8gd29ybGQh", - list_=["string"], - set_={"string"}, - map_={1: "string"}, - bigint="123456789123456789", - ), + nested_object=ObjectWithOptionalField( + string="string", + integer=1, + long_=1000000, + double=1.1, + bool_=True, + datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), + date=datetime.date.fromisoformat("2023-01-15"), + uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + base_64="SGVsbG8gd29ybGQh", + list_=["string"], + set_={"string"}, + map_={1: "string"}, + bigint="123456789123456789", + ), + ) ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/exhaustive/pydantic-extra-fields/tests/test_no_auth.py b/seed/python-sdk/exhaustive/pydantic-extra-fields/tests/test_no_auth.py index 3328661bb48..fc475f4b6fb 100644 --- a/seed/python-sdk/exhaustive/pydantic-extra-fields/tests/test_no_auth.py +++ b/seed/python-sdk/exhaustive/pydantic-extra-fields/tests/test_no_auth.py @@ -1,17 +1,20 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing - -from seed import AsyncSeedExhaustive, SeedExhaustive - from .utilities import validate_response -async def test_post_with_no_auth(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_post_with_no_auth( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = True expected_types: typing.Any = None response = client.no_auth.post_with_no_auth(request={"key": "value"}) validate_response(response, expected_response, expected_types) - async_response = await async_client.no_auth.post_with_no_auth(request={"key": "value"}) + async_response = await async_client.no_auth.post_with_no_auth( + request={"key": "value"} + ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/exhaustive/pydantic-extra-fields/tests/test_no_req_body.py b/seed/python-sdk/exhaustive/pydantic-extra-fields/tests/test_no_req_body.py index 73abac9d2d8..07061a0e99e 100644 --- a/seed/python-sdk/exhaustive/pydantic-extra-fields/tests/test_no_req_body.py +++ b/seed/python-sdk/exhaustive/pydantic-extra-fields/tests/test_no_req_body.py @@ -1,13 +1,14 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing - -from seed import AsyncSeedExhaustive, SeedExhaustive - from .utilities import validate_response -async def test_get_with_no_request_body(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_with_no_request_body( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = { "string": "string", "integer": 1, @@ -45,7 +46,9 @@ async def test_get_with_no_request_body(client: SeedExhaustive, async_client: As validate_response(async_response, expected_response, expected_types) -async def test_post_with_no_request_body(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_post_with_no_request_body( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "string" expected_types: typing.Any = None response = client.no_req_body.post_with_no_request_body() diff --git a/seed/python-sdk/exhaustive/pydantic-extra-fields/tests/test_req_with_headers.py b/seed/python-sdk/exhaustive/pydantic-extra-fields/tests/test_req_with_headers.py index bba3b5b5507..75ce9d00c03 100644 --- a/seed/python-sdk/exhaustive/pydantic-extra-fields/tests/test_req_with_headers.py +++ b/seed/python-sdk/exhaustive/pydantic-extra-fields/tests/test_req_with_headers.py @@ -1,10 +1,27 @@ # This file was auto-generated by Fern from our API Definition. -from seed import AsyncSeedExhaustive, SeedExhaustive +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive -async def test_get_with_custom_header(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_with_custom_header( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: # Type ignore to avoid mypy complaining about the function not being meant to return a value - assert client.req_with_headers.get_with_custom_header(x_test_service_header="string", x_test_endpoint_header="string", request="string") is None # type: ignore[func-returns-value] + assert ( + client.req_with_headers.get_with_custom_header( + x_test_service_header="string", + x_test_endpoint_header="string", + request="string", + ) + is None + ) # type: ignore[func-returns-value] - assert await async_client.req_with_headers.get_with_custom_header(x_test_service_header="string", x_test_endpoint_header="string", request="string") is None # type: ignore[func-returns-value] + assert ( + await async_client.req_with_headers.get_with_custom_header( + x_test_service_header="string", + x_test_endpoint_header="string", + request="string", + ) + is None + ) # type: ignore[func-returns-value] diff --git a/seed/python-sdk/exhaustive/pydantic-extra-fields/tests/utilities.py b/seed/python-sdk/exhaustive/pydantic-extra-fields/tests/utilities.py index 13da208eb3a..e8f4472564c 100644 --- a/seed/python-sdk/exhaustive/pydantic-extra-fields/tests/utilities.py +++ b/seed/python-sdk/exhaustive/pydantic-extra-fields/tests/utilities.py @@ -3,11 +3,14 @@ import typing import uuid -import pydantic from dateutil import parser +import pydantic + -def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> typing.Any: +def cast_field( + json_expectation: typing.Any, type_expectation: typing.Any +) -> typing.Any: # Cast these specific types which come through as string and expect our # models to cast to the correct type. if type_expectation == "uuid": @@ -25,7 +28,9 @@ def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> ty return json_expectation -def validate_field(response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any) -> None: +def validate_field( + response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectation == "no_validate": return @@ -44,7 +49,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(entry_expectation, dict): is_container_of_complex_type = True validate_response( - response=response[idx], json_expectation=ex, type_expectations=entry_expectation + response=response[idx], + json_expectation=ex, + type_expectations=entry_expectation, ) else: cast_json_expectation.append(cast_field(ex, entry_expectation)) @@ -56,7 +63,10 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # if any of the values of the set have a type_expectation of a dict, we're assuming it's a pydantic # model and keeping it a list. if container_expectation != "set" or not any( - map(lambda value: isinstance(value, dict), list(contents_expectation.values())) + map( + lambda value: isinstance(value, dict), + list(contents_expectation.values()), + ) ): json_expectation = cast_field(json_expectation, container_expectation) elif isinstance(type_expectation, tuple): @@ -65,9 +75,15 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(contents_expectation, dict): json_expectation = { cast_field( - key, contents_expectation.get(idx)[0] if contents_expectation.get(idx) is not None else None # type: ignore + key, + contents_expectation.get(idx)[0] + if contents_expectation.get(idx) is not None + else None, # type: ignore ): cast_field( - value, contents_expectation.get(idx)[1] if contents_expectation.get(idx) is not None else None # type: ignore + value, + contents_expectation.get(idx)[1] + if contents_expectation.get(idx) is not None + else None, # type: ignore ) for idx, (key, value) in enumerate(json_expectation.items()) } @@ -86,7 +102,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # Arg type_expectations is a deeply nested structure that matches the response, but with the values replaced with the expected types -def validate_response(response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any) -> None: +def validate_response( + response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectations == "no_validate": return @@ -96,11 +114,17 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e and not isinstance(response, dict) and not issubclass(type(response), pydantic.BaseModel) ): - validate_field(response=response, json_expectation=json_expectation, type_expectation=type_expectations) + validate_field( + response=response, + json_expectation=json_expectation, + type_expectation=type_expectations, + ) return if isinstance(response, list): - assert len(response) == len(json_expectation), "Length mismatch, expected: {0}, Actual: {1}".format( + assert len(response) == len( + json_expectation + ), "Length mismatch, expected: {0}, Actual: {1}".format( len(response), len(json_expectation) ) content_expectation = type_expectations @@ -108,7 +132,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e content_expectation = type_expectations[1] for idx, item in enumerate(response): validate_response( - response=item, json_expectation=json_expectation[idx], type_expectations=content_expectation[idx] + response=item, + json_expectation=json_expectation[idx], + type_expectations=content_expectation[idx], ) else: response_json = response @@ -116,7 +142,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e response_json = response.dict(by_alias=True) for key, value in json_expectation.items(): - assert key in response_json, "Field {0} not found within the response object: {1}".format( + assert ( + key in response_json + ), "Field {0} not found within the response object: {1}".format( key, response_json ) @@ -128,11 +156,19 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e # Otherwise, we're just validating a single field that's a pydantic model. if isinstance(value, dict) and not isinstance(type_expectation, tuple): validate_response( - response=response_json[key], json_expectation=value, type_expectations=type_expectation + response=response_json[key], + json_expectation=value, + type_expectations=type_expectation, ) else: - validate_field(response=response_json[key], json_expectation=value, type_expectation=type_expectation) + validate_field( + response=response_json[key], + json_expectation=value, + type_expectation=type_expectation, + ) # Ensure there are no additional fields here either del response_json[key] - assert len(response_json) == 0, "Additional fields found, expected None: {0}".format(response_json) + assert ( + len(response_json) == 0 + ), "Additional fields found, expected None: {0}".format(response_json) diff --git a/seed/python-sdk/exhaustive/pydantic-extra-fields/tests/utils/assets/models/__init__.py b/seed/python-sdk/exhaustive/pydantic-extra-fields/tests/utils/assets/models/__init__.py index 2cf01263529..3a1c852e71e 100644 --- a/seed/python-sdk/exhaustive/pydantic-extra-fields/tests/utils/assets/models/__init__.py +++ b/seed/python-sdk/exhaustive/pydantic-extra-fields/tests/utils/assets/models/__init__.py @@ -5,7 +5,7 @@ from .circle import CircleParams from .object_with_defaults import ObjectWithDefaultsParams from .object_with_optional_field import ObjectWithOptionalFieldParams -from .shape import Shape_CircleParams, Shape_SquareParams, ShapeParams +from .shape import ShapeParams, Shape_CircleParams, Shape_SquareParams from .square import SquareParams from .undiscriminated_shape import UndiscriminatedShapeParams diff --git a/seed/python-sdk/exhaustive/pydantic-extra-fields/tests/utils/assets/models/circle.py b/seed/python-sdk/exhaustive/pydantic-extra-fields/tests/utils/assets/models/circle.py index af7a1bf8a8e..253f12d38b3 100644 --- a/seed/python-sdk/exhaustive/pydantic-extra-fields/tests/utils/assets/models/circle.py +++ b/seed/python-sdk/exhaustive/pydantic-extra-fields/tests/utils/assets/models/circle.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class CircleParams(typing_extensions.TypedDict): - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] diff --git a/seed/python-sdk/exhaustive/pydantic-extra-fields/tests/utils/assets/models/object_with_optional_field.py b/seed/python-sdk/exhaustive/pydantic-extra-fields/tests/utils/assets/models/object_with_optional_field.py index 3ad93d5f305..ebe7dc80547 100644 --- a/seed/python-sdk/exhaustive/pydantic-extra-fields/tests/utils/assets/models/object_with_optional_field.py +++ b/seed/python-sdk/exhaustive/pydantic-extra-fields/tests/utils/assets/models/object_with_optional_field.py @@ -7,8 +7,8 @@ import uuid import typing_extensions -from seed.core.serialization import FieldMetadata +from seed.core.serialization import FieldMetadata from .color import Color from .shape import ShapeParams from .undiscriminated_shape import UndiscriminatedShapeParams @@ -18,16 +18,30 @@ class ObjectWithOptionalFieldParams(typing_extensions.TypedDict): literal: typing.Literal["lit_one"] string: typing_extensions.NotRequired[str] integer: typing_extensions.NotRequired[int] - long_: typing_extensions.NotRequired[typing_extensions.Annotated[int, FieldMetadata(alias="long")]] + long_: typing_extensions.NotRequired[ + typing_extensions.Annotated[int, FieldMetadata(alias="long")] + ] double: typing_extensions.NotRequired[float] - bool_: typing_extensions.NotRequired[typing_extensions.Annotated[bool, FieldMetadata(alias="bool")]] + bool_: typing_extensions.NotRequired[ + typing_extensions.Annotated[bool, FieldMetadata(alias="bool")] + ] datetime: typing_extensions.NotRequired[dt.datetime] date: typing_extensions.NotRequired[dt.date] - uuid_: typing_extensions.NotRequired[typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")]] - base_64: typing_extensions.NotRequired[typing_extensions.Annotated[str, FieldMetadata(alias="base64")]] - list_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")]] - set_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")]] - map_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")]] + uuid_: typing_extensions.NotRequired[ + typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")] + ] + base_64: typing_extensions.NotRequired[ + typing_extensions.Annotated[str, FieldMetadata(alias="base64")] + ] + list_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")] + ] + set_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")] + ] + map_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")] + ] enum: typing_extensions.NotRequired[Color] union: typing_extensions.NotRequired[ShapeParams] second_union: typing_extensions.NotRequired[ShapeParams] diff --git a/seed/python-sdk/exhaustive/pydantic-extra-fields/tests/utils/assets/models/shape.py b/seed/python-sdk/exhaustive/pydantic-extra-fields/tests/utils/assets/models/shape.py index 2c33c877951..816ffc51bdc 100644 --- a/seed/python-sdk/exhaustive/pydantic-extra-fields/tests/utils/assets/models/shape.py +++ b/seed/python-sdk/exhaustive/pydantic-extra-fields/tests/utils/assets/models/shape.py @@ -7,6 +7,7 @@ import typing import typing_extensions + from seed.core.serialization import FieldMetadata @@ -15,13 +16,21 @@ class Base(typing_extensions.TypedDict): class Shape_CircleParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["circle"], FieldMetadata(alias="shapeType")] - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["circle"], FieldMetadata(alias="shapeType") + ] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] class Shape_SquareParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["square"], FieldMetadata(alias="shapeType")] - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["square"], FieldMetadata(alias="shapeType") + ] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] ShapeParams = typing.Union[Shape_CircleParams, Shape_SquareParams] diff --git a/seed/python-sdk/exhaustive/pydantic-extra-fields/tests/utils/assets/models/square.py b/seed/python-sdk/exhaustive/pydantic-extra-fields/tests/utils/assets/models/square.py index b9b7dd319bc..bcf08a723c5 100644 --- a/seed/python-sdk/exhaustive/pydantic-extra-fields/tests/utils/assets/models/square.py +++ b/seed/python-sdk/exhaustive/pydantic-extra-fields/tests/utils/assets/models/square.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class SquareParams(typing_extensions.TypedDict): - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] diff --git a/seed/python-sdk/exhaustive/pydantic-extra-fields/tests/utils/test_http_client.py b/seed/python-sdk/exhaustive/pydantic-extra-fields/tests/utils/test_http_client.py index edd11ca7afb..f5a874a75f3 100644 --- a/seed/python-sdk/exhaustive/pydantic-extra-fields/tests/utils/test_http_client.py +++ b/seed/python-sdk/exhaustive/pydantic-extra-fields/tests/utils/test_http_client.py @@ -9,12 +9,17 @@ def get_request_options() -> RequestOptions: def test_get_json_request_body() -> None: - json_body, data_body = get_request_body(json={"hello": "world"}, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json={"hello": "world"}, data=None, request_options=None, omit=None + ) assert json_body == {"hello": "world"} assert data_body is None json_body_extras, data_body_extras = get_request_body( - json={"goodbye": "world"}, data=None, request_options=get_request_options(), omit=None + json={"goodbye": "world"}, + data=None, + request_options=get_request_options(), + omit=None, ) assert json_body_extras == {"goodbye": "world", "see you": "later"} @@ -22,12 +27,17 @@ def test_get_json_request_body() -> None: def test_get_files_request_body() -> None: - json_body, data_body = get_request_body(json=None, data={"hello": "world"}, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data={"hello": "world"}, request_options=None, omit=None + ) assert data_body == {"hello": "world"} assert json_body is None json_body_extras, data_body_extras = get_request_body( - json=None, data={"goodbye": "world"}, request_options=get_request_options(), omit=None + json=None, + data={"goodbye": "world"}, + request_options=get_request_options(), + omit=None, ) assert data_body_extras == {"goodbye": "world", "see you": "later"} @@ -35,7 +45,9 @@ def test_get_files_request_body() -> None: def test_get_none_request_body() -> None: - json_body, data_body = get_request_body(json=None, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data=None, request_options=None, omit=None + ) assert data_body is None assert json_body is None diff --git a/seed/python-sdk/exhaustive/pydantic-extra-fields/tests/utils/test_query_encoding.py b/seed/python-sdk/exhaustive/pydantic-extra-fields/tests/utils/test_query_encoding.py index 247e1551b46..fbc8f402167 100644 --- a/seed/python-sdk/exhaustive/pydantic-extra-fields/tests/utils/test_query_encoding.py +++ b/seed/python-sdk/exhaustive/pydantic-extra-fields/tests/utils/test_query_encoding.py @@ -4,9 +4,15 @@ def test_query_encoding() -> None: - assert encode_query({"hello world": "hello world"}) == {"hello world": "hello world"} - assert encode_query({"hello_world": {"hello": "world"}}) == {"hello_world[hello]": "world"} - assert encode_query({"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"}) == { + assert encode_query({"hello world": "hello world"}) == { + "hello world": "hello world" + } + assert encode_query({"hello_world": {"hello": "world"}}) == { + "hello_world[hello]": "world" + } + assert encode_query( + {"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"} + ) == { "hello_world[hello][world]": "today", "hello_world[test]": "this", "hi": "there", diff --git a/seed/python-sdk/exhaustive/pydantic-extra-fields/tests/utils/test_serialization.py b/seed/python-sdk/exhaustive/pydantic-extra-fields/tests/utils/test_serialization.py index 58b1ed66e6d..5ca956916dd 100644 --- a/seed/python-sdk/exhaustive/pydantic-extra-fields/tests/utils/test_serialization.py +++ b/seed/python-sdk/exhaustive/pydantic-extra-fields/tests/utils/test_serialization.py @@ -1,10 +1,12 @@ # This file was auto-generated by Fern from our API Definition. -from typing import Any, List +from typing import List, Any -from seed.core.serialization import convert_and_respect_annotation_metadata +from seed.core.serialization import ( + convert_and_respect_annotation_metadata, +) +from .assets.models import ShapeParams, ObjectWithOptionalFieldParams -from .assets.models import ObjectWithOptionalFieldParams, ShapeParams UNION_TEST: ShapeParams = {"radius_measurement": 1.0, "shape_type": "circle", "id": "1"} UNION_TEST_CONVERTED = {"shapeType": "circle", "radiusMeasurement": 1.0, "id": "1"} @@ -18,20 +20,54 @@ def test_convert_and_respect_annotation_metadata() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) - assert converted == {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"} + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) + assert converted == { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + } def test_convert_and_respect_annotation_metadata_in_list() -> None: data: List[ObjectWithOptionalFieldParams] = [ - {"string": "string", "long_": 12345, "bool_": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long_": 67890, "list_": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long_": 12345, + "bool_": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long_": 67890, + "list_": [], + "literal": "lit_one", + "any": "any", + }, ] - converted = convert_and_respect_annotation_metadata(object_=data, annotation=List[ObjectWithOptionalFieldParams]) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=List[ObjectWithOptionalFieldParams] + ) assert converted == [ - {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long": 67890, "list": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long": 67890, + "list": [], + "literal": "lit_one", + "any": "any", + }, ] @@ -43,7 +79,9 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) assert converted == { "string": "string", @@ -55,12 +93,16 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: def test_convert_and_respect_annotation_metadata_in_union() -> None: - converted = convert_and_respect_annotation_metadata(object_=UNION_TEST, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=UNION_TEST, annotation=ShapeParams + ) assert converted == UNION_TEST_CONVERTED def test_convert_and_respect_annotation_metadata_with_empty_object() -> None: data: Any = {} - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ShapeParams + ) assert converted == data diff --git a/seed/python-sdk/exhaustive/pydantic-v1/pyproject.toml b/seed/python-sdk/exhaustive/pydantic-v1/pyproject.toml index d2b8e3aa278..64a2bb45b89 100644 --- a/seed/python-sdk/exhaustive/pydantic-v1/pyproject.toml +++ b/seed/python-sdk/exhaustive/pydantic-v1/pyproject.toml @@ -43,6 +43,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/python-sdk/exhaustive/pydantic-v1/src/seed/__init__.py b/seed/python-sdk/exhaustive/pydantic-v1/src/seed/__init__.py index eb56b0ce275..dc1ef03a650 100644 --- a/seed/python-sdk/exhaustive/pydantic-v1/src/seed/__init__.py +++ b/seed/python-sdk/exhaustive/pydantic-v1/src/seed/__init__.py @@ -1,6 +1,14 @@ # This file was auto-generated by Fern from our API Definition. -from . import endpoints, general_errors, inlined_requests, no_auth, no_req_body, req_with_headers, types +from . import ( + endpoints, + general_errors, + inlined_requests, + no_auth, + no_req_body, + req_with_headers, + types, +) from .client import AsyncSeedExhaustive, SeedExhaustive from .general_errors import BadObjectRequestInfo, BadRequestBody from .version import __version__ diff --git a/seed/python-sdk/exhaustive/pydantic-v1/src/seed/client.py b/seed/python-sdk/exhaustive/pydantic-v1/src/seed/client.py index b1b9764c7a7..f5ab292af6b 100644 --- a/seed/python-sdk/exhaustive/pydantic-v1/src/seed/client.py +++ b/seed/python-sdk/exhaustive/pydantic-v1/src/seed/client.py @@ -1,15 +1,19 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from .endpoints.client import AsyncEndpointsClient, EndpointsClient -from .inlined_requests.client import AsyncInlinedRequestsClient, InlinedRequestsClient -from .no_auth.client import AsyncNoAuthClient, NoAuthClient -from .no_req_body.client import AsyncNoReqBodyClient, NoReqBodyClient -from .req_with_headers.client import AsyncReqWithHeadersClient, ReqWithHeadersClient +from .core.client_wrapper import SyncClientWrapper +from .endpoints.client import EndpointsClient +from .inlined_requests.client import InlinedRequestsClient +from .no_auth.client import NoAuthClient +from .no_req_body.client import NoReqBodyClient +from .req_with_headers.client import ReqWithHeadersClient +from .core.client_wrapper import AsyncClientWrapper +from .endpoints.client import AsyncEndpointsClient +from .inlined_requests.client import AsyncInlinedRequestsClient +from .no_auth.client import AsyncNoAuthClient +from .no_req_body.client import AsyncNoReqBodyClient +from .req_with_headers.client import AsyncReqWithHeadersClient class SeedExhaustive: @@ -48,24 +52,32 @@ def __init__( token: typing.Optional[typing.Union[str, typing.Callable[[], str]]] = None, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.Client] = None + httpx_client: typing.Optional[httpx.Client] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = SyncClientWrapper( base_url=base_url, token=token, httpx_client=httpx_client if httpx_client is not None - else httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.Client( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.Client(timeout=_defaulted_timeout), timeout=_defaulted_timeout, ) self.endpoints = EndpointsClient(client_wrapper=self._client_wrapper) - self.inlined_requests = InlinedRequestsClient(client_wrapper=self._client_wrapper) + self.inlined_requests = InlinedRequestsClient( + client_wrapper=self._client_wrapper + ) self.no_auth = NoAuthClient(client_wrapper=self._client_wrapper) self.no_req_body = NoReqBodyClient(client_wrapper=self._client_wrapper) - self.req_with_headers = ReqWithHeadersClient(client_wrapper=self._client_wrapper) + self.req_with_headers = ReqWithHeadersClient( + client_wrapper=self._client_wrapper + ) class AsyncSeedExhaustive: @@ -104,21 +116,29 @@ def __init__( token: typing.Optional[typing.Union[str, typing.Callable[[], str]]] = None, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.AsyncClient] = None + httpx_client: typing.Optional[httpx.AsyncClient] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = AsyncClientWrapper( base_url=base_url, token=token, httpx_client=httpx_client if httpx_client is not None - else httpx.AsyncClient(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.AsyncClient( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.AsyncClient(timeout=_defaulted_timeout), timeout=_defaulted_timeout, ) self.endpoints = AsyncEndpointsClient(client_wrapper=self._client_wrapper) - self.inlined_requests = AsyncInlinedRequestsClient(client_wrapper=self._client_wrapper) + self.inlined_requests = AsyncInlinedRequestsClient( + client_wrapper=self._client_wrapper + ) self.no_auth = AsyncNoAuthClient(client_wrapper=self._client_wrapper) self.no_req_body = AsyncNoReqBodyClient(client_wrapper=self._client_wrapper) - self.req_with_headers = AsyncReqWithHeadersClient(client_wrapper=self._client_wrapper) + self.req_with_headers = AsyncReqWithHeadersClient( + client_wrapper=self._client_wrapper + ) diff --git a/seed/python-sdk/exhaustive/pydantic-v1/src/seed/core/api_error.py b/seed/python-sdk/exhaustive/pydantic-v1/src/seed/core/api_error.py index 2e9fc5431cd..da734b58068 100644 --- a/seed/python-sdk/exhaustive/pydantic-v1/src/seed/core/api_error.py +++ b/seed/python-sdk/exhaustive/pydantic-v1/src/seed/core/api_error.py @@ -7,7 +7,9 @@ class ApiError(Exception): status_code: typing.Optional[int] body: typing.Any - def __init__(self, *, status_code: typing.Optional[int] = None, body: typing.Any = None): + def __init__( + self, *, status_code: typing.Optional[int] = None, body: typing.Any = None + ): self.status_code = status_code self.body = body diff --git a/seed/python-sdk/exhaustive/pydantic-v1/src/seed/core/client_wrapper.py b/seed/python-sdk/exhaustive/pydantic-v1/src/seed/core/client_wrapper.py index 8d01b584b82..d037184a816 100644 --- a/seed/python-sdk/exhaustive/pydantic-v1/src/seed/core/client_wrapper.py +++ b/seed/python-sdk/exhaustive/pydantic-v1/src/seed/core/client_wrapper.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .http_client import AsyncHttpClient, HttpClient +from .http_client import HttpClient +from .http_client import AsyncHttpClient class BaseClientWrapper: diff --git a/seed/python-sdk/exhaustive/pydantic-v1/src/seed/core/datetime_utils.py b/seed/python-sdk/exhaustive/pydantic-v1/src/seed/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/python-sdk/exhaustive/pydantic-v1/src/seed/core/datetime_utils.py +++ b/seed/python-sdk/exhaustive/pydantic-v1/src/seed/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/python-sdk/exhaustive/pydantic-v1/src/seed/core/file.py b/seed/python-sdk/exhaustive/pydantic-v1/src/seed/core/file.py index cb0d40bbbf3..6e0f92bfcb1 100644 --- a/seed/python-sdk/exhaustive/pydantic-v1/src/seed/core/file.py +++ b/seed/python-sdk/exhaustive/pydantic-v1/src/seed/core/file.py @@ -13,12 +13,17 @@ # (filename, file (or bytes), content_type) typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str]], # (filename, file (or bytes), content_type, headers) - typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str], typing.Mapping[str, str]], + typing.Tuple[ + typing.Optional[str], + FileContent, + typing.Optional[str], + typing.Mapping[str, str], + ], ] def convert_file_dict_to_httpx_tuples( - d: typing.Dict[str, typing.Union[File, typing.List[File]]] + d: typing.Dict[str, typing.Union[File, typing.List[File]]], ) -> typing.List[typing.Tuple[str, File]]: """ The format we use is a list of tuples, where the first element is the diff --git a/seed/python-sdk/exhaustive/pydantic-v1/src/seed/core/http_client.py b/seed/python-sdk/exhaustive/pydantic-v1/src/seed/core/http_client.py index 9333d8a7f15..091f71bc185 100644 --- a/seed/python-sdk/exhaustive/pydantic-v1/src/seed/core/http_client.py +++ b/seed/python-sdk/exhaustive/pydantic-v1/src/seed/core/http_client.py @@ -77,7 +77,9 @@ def _retry_timeout(response: httpx.Response, retries: int) -> float: return retry_after # Apply exponential backoff, capped at MAX_RETRY_DELAY_SECONDS. - retry_delay = min(INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS) + retry_delay = min( + INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS + ) # Add a randomness / jitter to the retry delay to avoid overwhelming the server with retries. timeout = retry_delay * (1 - 0.25 * random()) @@ -90,7 +92,8 @@ def _should_retry(response: httpx.Response) -> bool: def remove_omit_from_dict( - original: typing.Dict[str, typing.Optional[typing.Any]], omit: typing.Optional[typing.Any] + original: typing.Dict[str, typing.Optional[typing.Any]], + omit: typing.Optional[typing.Any], ) -> typing.Dict[str, typing.Any]: if omit is None: return original @@ -108,7 +111,8 @@ def maybe_filter_request_body( ) -> typing.Optional[typing.Any]: if data is None: return ( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else None ) @@ -118,7 +122,8 @@ def maybe_filter_request_body( data_content = { **(jsonable_encoder(remove_omit_from_dict(data, omit))), # type: ignore **( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else {} ), @@ -162,7 +167,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url def request( @@ -174,8 +181,12 @@ def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -184,11 +195,14 @@ def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) response = self.httpx_client.request( method=method, @@ -198,7 +212,11 @@ def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -209,7 +227,10 @@ def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -222,11 +243,15 @@ def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: time.sleep(_retry_timeout(response=response, retries=retries)) @@ -256,8 +281,12 @@ def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -266,11 +295,14 @@ def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) with self.httpx_client.stream( method=method, @@ -280,7 +312,11 @@ def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -291,7 +327,9 @@ def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -304,7 +342,9 @@ def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream @@ -327,7 +367,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url async def request( @@ -339,8 +381,12 @@ async def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -349,11 +395,14 @@ async def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) # Add the input to each of these and do None-safety checks response = await self.httpx_client.request( @@ -364,7 +413,11 @@ async def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -375,7 +428,10 @@ async def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -388,11 +444,15 @@ async def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: await asyncio.sleep(_retry_timeout(response=response, retries=retries)) @@ -421,8 +481,12 @@ async def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -431,11 +495,14 @@ async def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) async with self.httpx_client.stream( method=method, @@ -445,7 +512,11 @@ async def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -456,7 +527,9 @@ async def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -469,7 +542,9 @@ async def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream diff --git a/seed/python-sdk/exhaustive/pydantic-v1/src/seed/core/jsonable_encoder.py b/seed/python-sdk/exhaustive/pydantic-v1/src/seed/core/jsonable_encoder.py index d3fd328fd41..12a8b52fc22 100644 --- a/seed/python-sdk/exhaustive/pydantic-v1/src/seed/core/jsonable_encoder.py +++ b/seed/python-sdk/exhaustive/pydantic-v1/src/seed/core/jsonable_encoder.py @@ -19,13 +19,19 @@ import pydantic from .datetime_utils import serialize_datetime -from .pydantic_utilities import IS_PYDANTIC_V2, encode_by_type, to_jsonable_with_fallback +from .pydantic_utilities import ( + IS_PYDANTIC_V2, + encode_by_type, + to_jsonable_with_fallback, +) SetIntStr = Set[Union[int, str]] DictIntStrAny = Dict[Union[int, str], Any] -def jsonable_encoder(obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None) -> Any: +def jsonable_encoder( + obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None +) -> Any: custom_encoder = custom_encoder or {} if custom_encoder: if type(obj) in custom_encoder: diff --git a/seed/python-sdk/exhaustive/pydantic-v1/src/seed/core/pydantic_utilities.py b/seed/python-sdk/exhaustive/pydantic-v1/src/seed/core/pydantic_utilities.py index 170a563d6eb..c63935c32a2 100644 --- a/seed/python-sdk/exhaustive/pydantic-v1/src/seed/core/pydantic_utilities.py +++ b/seed/python-sdk/exhaustive/pydantic-v1/src/seed/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) # type: ignore # Pydantic v1 diff --git a/seed/python-sdk/exhaustive/pydantic-v1/src/seed/core/query_encoder.py b/seed/python-sdk/exhaustive/pydantic-v1/src/seed/core/query_encoder.py index 24076d72ee9..7cb98f52cd7 100644 --- a/seed/python-sdk/exhaustive/pydantic-v1/src/seed/core/query_encoder.py +++ b/seed/python-sdk/exhaustive/pydantic-v1/src/seed/core/query_encoder.py @@ -7,7 +7,9 @@ # Flattens dicts to be of the form {"key[subkey][subkey2]": value} where value is not a dict -def traverse_query_dict(dict_flat: Dict[str, Any], key_prefix: Optional[str] = None) -> Dict[str, Any]: +def traverse_query_dict( + dict_flat: Dict[str, Any], key_prefix: Optional[str] = None +) -> Dict[str, Any]: result = {} for k, v in dict_flat.items(): key = f"{key_prefix}[{k}]" if key_prefix is not None else k @@ -30,4 +32,8 @@ def single_query_encoder(query_key: str, query_value: Any) -> Dict[str, Any]: def encode_query(query: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: - return dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) if query is not None else None + return ( + dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) + if query is not None + else None + ) diff --git a/seed/python-sdk/exhaustive/pydantic-v1/src/seed/core/serialization.py b/seed/python-sdk/exhaustive/pydantic-v1/src/seed/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/python-sdk/exhaustive/pydantic-v1/src/seed/core/serialization.py +++ b/seed/python-sdk/exhaustive/pydantic-v1/src/seed/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/python-sdk/exhaustive/pydantic-v1/src/seed/endpoints/__init__.py b/seed/python-sdk/exhaustive/pydantic-v1/src/seed/endpoints/__init__.py index 92307cab7fe..a9496ece178 100644 --- a/seed/python-sdk/exhaustive/pydantic-v1/src/seed/endpoints/__init__.py +++ b/seed/python-sdk/exhaustive/pydantic-v1/src/seed/endpoints/__init__.py @@ -2,4 +2,12 @@ from . import container, enum, http_methods, object, params, primitive, union -__all__ = ["container", "enum", "http_methods", "object", "params", "primitive", "union"] +__all__ = [ + "container", + "enum", + "http_methods", + "object", + "params", + "primitive", + "union", +] diff --git a/seed/python-sdk/exhaustive/pydantic-v1/src/seed/endpoints/client.py b/seed/python-sdk/exhaustive/pydantic-v1/src/seed/endpoints/client.py index 18dc397fdf1..69930de54d7 100644 --- a/seed/python-sdk/exhaustive/pydantic-v1/src/seed/endpoints/client.py +++ b/seed/python-sdk/exhaustive/pydantic-v1/src/seed/endpoints/client.py @@ -1,13 +1,21 @@ # This file was auto-generated by Fern from our API Definition. -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from .container.client import AsyncContainerClient, ContainerClient -from .enum.client import AsyncEnumClient, EnumClient -from .http_methods.client import AsyncHttpMethodsClient, HttpMethodsClient -from .object.client import AsyncObjectClient, ObjectClient -from .params.client import AsyncParamsClient, ParamsClient -from .primitive.client import AsyncPrimitiveClient, PrimitiveClient -from .union.client import AsyncUnionClient, UnionClient +from ..core.client_wrapper import SyncClientWrapper +from .container.client import ContainerClient +from .enum.client import EnumClient +from .http_methods.client import HttpMethodsClient +from .object.client import ObjectClient +from .params.client import ParamsClient +from .primitive.client import PrimitiveClient +from .union.client import UnionClient +from ..core.client_wrapper import AsyncClientWrapper +from .container.client import AsyncContainerClient +from .enum.client import AsyncEnumClient +from .http_methods.client import AsyncHttpMethodsClient +from .object.client import AsyncObjectClient +from .params.client import AsyncParamsClient +from .primitive.client import AsyncPrimitiveClient +from .union.client import AsyncUnionClient class EndpointsClient: diff --git a/seed/python-sdk/exhaustive/pydantic-v1/src/seed/endpoints/container/client.py b/seed/python-sdk/exhaustive/pydantic-v1/src/seed/endpoints/container/client.py index c6cf14f63ac..4af9c12d534 100644 --- a/seed/python-sdk/exhaustive/pydantic-v1/src/seed/endpoints/container/client.py +++ b/seed/python-sdk/exhaustive/pydantic-v1/src/seed/endpoints/container/client.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. import typing +from ...core.client_wrapper import SyncClientWrapper +from ...core.request_options import RequestOptions +from ...core.pydantic_utilities import parse_obj_as from json.decoder import JSONDecodeError - from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ...core.pydantic_utilities import parse_obj_as -from ...core.request_options import RequestOptions from ...types.object.types.object_with_required_field import ObjectWithRequiredField +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -18,7 +18,10 @@ def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper def get_and_return_list_of_primitives( - self, *, request: typing.Sequence[str], request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Sequence[str], + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[str]: """ Parameters @@ -45,11 +48,18 @@ def get_and_return_list_of_primitives( ) """ _response = self._client_wrapper.httpx_client.request( - "container/list-of-primitives", method="POST", json=request, request_options=request_options, omit=OMIT + "container/list-of-primitives", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.List[str], parse_obj_as(type_=typing.List[str], object_=_response.json())) # type: ignore + return typing.cast( + typing.List[str], + parse_obj_as(type_=typing.List[str], object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -59,7 +69,7 @@ def get_and_return_list_of_objects( self, *, request: typing.Sequence[ObjectWithRequiredField], - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[ObjectWithRequiredField]: """ Parameters @@ -91,18 +101,31 @@ def get_and_return_list_of_objects( ) """ _response = self._client_wrapper.httpx_client.request( - "container/list-of-objects", method="POST", json=request, request_options=request_options, omit=OMIT + "container/list-of-objects", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.List[ObjectWithRequiredField], parse_obj_as(type_=typing.List[ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.List[ObjectWithRequiredField], + parse_obj_as( + type_=typing.List[ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_and_return_set_of_primitives( - self, *, request: typing.Set[str], request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Set[str], + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Set[str]: """ Parameters @@ -129,11 +152,18 @@ def get_and_return_set_of_primitives( ) """ _response = self._client_wrapper.httpx_client.request( - "container/set-of-primitives", method="POST", json=request, request_options=request_options, omit=OMIT + "container/set-of-primitives", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Set[str], parse_obj_as(type_=typing.Set[str], object_=_response.json())) # type: ignore + return typing.cast( + typing.Set[str], + parse_obj_as(type_=typing.Set[str], object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -143,7 +173,7 @@ def get_and_return_set_of_objects( self, *, request: typing.Sequence[ObjectWithRequiredField], - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[ObjectWithRequiredField]: """ Parameters @@ -175,18 +205,31 @@ def get_and_return_set_of_objects( ) """ _response = self._client_wrapper.httpx_client.request( - "container/set-of-objects", method="POST", json=request, request_options=request_options, omit=OMIT + "container/set-of-objects", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.List[ObjectWithRequiredField], parse_obj_as(type_=typing.List[ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.List[ObjectWithRequiredField], + parse_obj_as( + type_=typing.List[ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_and_return_map_prim_to_prim( - self, *, request: typing.Dict[str, str], request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Dict[str, str], + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Dict[str, str]: """ Parameters @@ -213,11 +256,18 @@ def get_and_return_map_prim_to_prim( ) """ _response = self._client_wrapper.httpx_client.request( - "container/map-prim-to-prim", method="POST", json=request, request_options=request_options, omit=OMIT + "container/map-prim-to-prim", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Dict[str, str], parse_obj_as(type_=typing.Dict[str, str], object_=_response.json())) # type: ignore + return typing.cast( + typing.Dict[str, str], + parse_obj_as(type_=typing.Dict[str, str], object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -227,7 +277,7 @@ def get_and_return_map_of_prim_to_object( self, *, request: typing.Dict[str, ObjectWithRequiredField], - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Dict[str, ObjectWithRequiredField]: """ Parameters @@ -259,11 +309,21 @@ def get_and_return_map_of_prim_to_object( ) """ _response = self._client_wrapper.httpx_client.request( - "container/map-prim-to-object", method="POST", json=request, request_options=request_options, omit=OMIT + "container/map-prim-to-object", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Dict[str, ObjectWithRequiredField], parse_obj_as(type_=typing.Dict[str, ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.Dict[str, ObjectWithRequiredField], + parse_obj_as( + type_=typing.Dict[str, ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -273,7 +333,7 @@ def get_and_return_optional( self, *, request: typing.Optional[ObjectWithRequiredField] = None, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Optional[ObjectWithRequiredField]: """ Parameters @@ -303,11 +363,21 @@ def get_and_return_optional( ) """ _response = self._client_wrapper.httpx_client.request( - "container/opt-objects", method="POST", json=request, request_options=request_options, omit=OMIT + "container/opt-objects", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Optional[ObjectWithRequiredField], parse_obj_as(type_=typing.Optional[ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.Optional[ObjectWithRequiredField], + parse_obj_as( + type_=typing.Optional[ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -319,7 +389,10 @@ def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper async def get_and_return_list_of_primitives( - self, *, request: typing.Sequence[str], request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Sequence[str], + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[str]: """ Parameters @@ -354,11 +427,18 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/list-of-primitives", method="POST", json=request, request_options=request_options, omit=OMIT + "container/list-of-primitives", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.List[str], parse_obj_as(type_=typing.List[str], object_=_response.json())) # type: ignore + return typing.cast( + typing.List[str], + parse_obj_as(type_=typing.List[str], object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -368,7 +448,7 @@ async def get_and_return_list_of_objects( self, *, request: typing.Sequence[ObjectWithRequiredField], - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[ObjectWithRequiredField]: """ Parameters @@ -408,18 +488,31 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/list-of-objects", method="POST", json=request, request_options=request_options, omit=OMIT + "container/list-of-objects", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.List[ObjectWithRequiredField], parse_obj_as(type_=typing.List[ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.List[ObjectWithRequiredField], + parse_obj_as( + type_=typing.List[ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_and_return_set_of_primitives( - self, *, request: typing.Set[str], request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Set[str], + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Set[str]: """ Parameters @@ -454,11 +547,18 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/set-of-primitives", method="POST", json=request, request_options=request_options, omit=OMIT + "container/set-of-primitives", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Set[str], parse_obj_as(type_=typing.Set[str], object_=_response.json())) # type: ignore + return typing.cast( + typing.Set[str], + parse_obj_as(type_=typing.Set[str], object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -468,7 +568,7 @@ async def get_and_return_set_of_objects( self, *, request: typing.Sequence[ObjectWithRequiredField], - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[ObjectWithRequiredField]: """ Parameters @@ -508,18 +608,31 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/set-of-objects", method="POST", json=request, request_options=request_options, omit=OMIT + "container/set-of-objects", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.List[ObjectWithRequiredField], parse_obj_as(type_=typing.List[ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.List[ObjectWithRequiredField], + parse_obj_as( + type_=typing.List[ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_and_return_map_prim_to_prim( - self, *, request: typing.Dict[str, str], request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Dict[str, str], + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Dict[str, str]: """ Parameters @@ -554,11 +667,18 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/map-prim-to-prim", method="POST", json=request, request_options=request_options, omit=OMIT + "container/map-prim-to-prim", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Dict[str, str], parse_obj_as(type_=typing.Dict[str, str], object_=_response.json())) # type: ignore + return typing.cast( + typing.Dict[str, str], + parse_obj_as(type_=typing.Dict[str, str], object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -568,7 +688,7 @@ async def get_and_return_map_of_prim_to_object( self, *, request: typing.Dict[str, ObjectWithRequiredField], - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Dict[str, ObjectWithRequiredField]: """ Parameters @@ -608,11 +728,21 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/map-prim-to-object", method="POST", json=request, request_options=request_options, omit=OMIT + "container/map-prim-to-object", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Dict[str, ObjectWithRequiredField], parse_obj_as(type_=typing.Dict[str, ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.Dict[str, ObjectWithRequiredField], + parse_obj_as( + type_=typing.Dict[str, ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -622,7 +752,7 @@ async def get_and_return_optional( self, *, request: typing.Optional[ObjectWithRequiredField] = None, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Optional[ObjectWithRequiredField]: """ Parameters @@ -660,11 +790,21 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/opt-objects", method="POST", json=request, request_options=request_options, omit=OMIT + "container/opt-objects", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Optional[ObjectWithRequiredField], parse_obj_as(type_=typing.Optional[ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.Optional[ObjectWithRequiredField], + parse_obj_as( + type_=typing.Optional[ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/pydantic-v1/src/seed/endpoints/enum/client.py b/seed/python-sdk/exhaustive/pydantic-v1/src/seed/endpoints/enum/client.py index 44e2690ff6c..3e3208e3bcf 100644 --- a/seed/python-sdk/exhaustive/pydantic-v1/src/seed/endpoints/enum/client.py +++ b/seed/python-sdk/exhaustive/pydantic-v1/src/seed/endpoints/enum/client.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. import typing +from ...core.client_wrapper import SyncClientWrapper +from ...types.enum.types.weather_report import WeatherReport +from ...core.request_options import RequestOptions +from ...core.pydantic_utilities import parse_obj_as from json.decoder import JSONDecodeError - from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ...core.pydantic_utilities import parse_obj_as -from ...core.request_options import RequestOptions -from ...types.enum.types.weather_report import WeatherReport +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -18,7 +18,10 @@ def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper def get_and_return_enum( - self, *, request: WeatherReport, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: WeatherReport, + request_options: typing.Optional[RequestOptions] = None, ) -> WeatherReport: """ Parameters @@ -45,11 +48,18 @@ def get_and_return_enum( ) """ _response = self._client_wrapper.httpx_client.request( - "enum", method="POST", json=request, request_options=request_options, omit=OMIT + "enum", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(WeatherReport, parse_obj_as(type_=WeatherReport, object_=_response.json())) # type: ignore + return typing.cast( + WeatherReport, + parse_obj_as(type_=WeatherReport, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -61,7 +71,10 @@ def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper async def get_and_return_enum( - self, *, request: WeatherReport, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: WeatherReport, + request_options: typing.Optional[RequestOptions] = None, ) -> WeatherReport: """ Parameters @@ -96,11 +109,18 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "enum", method="POST", json=request, request_options=request_options, omit=OMIT + "enum", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(WeatherReport, parse_obj_as(type_=WeatherReport, object_=_response.json())) # type: ignore + return typing.cast( + WeatherReport, + parse_obj_as(type_=WeatherReport, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/pydantic-v1/src/seed/endpoints/http_methods/client.py b/seed/python-sdk/exhaustive/pydantic-v1/src/seed/endpoints/http_methods/client.py index a2549280a1b..570a227844f 100644 --- a/seed/python-sdk/exhaustive/pydantic-v1/src/seed/endpoints/http_methods/client.py +++ b/seed/python-sdk/exhaustive/pydantic-v1/src/seed/endpoints/http_methods/client.py @@ -1,16 +1,16 @@ # This file was auto-generated by Fern from our API Definition. -import datetime as dt import typing -import uuid -from json.decoder import JSONDecodeError - -from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper +from ...core.client_wrapper import SyncClientWrapper +from ...core.request_options import RequestOptions from ...core.jsonable_encoder import jsonable_encoder from ...core.pydantic_utilities import parse_obj_as -from ...core.request_options import RequestOptions +from json.decoder import JSONDecodeError +from ...core.api_error import ApiError from ...types.object.types.object_with_optional_field import ObjectWithOptionalField +import datetime as dt +import uuid +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -20,7 +20,9 @@ class HttpMethodsClient: def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper - def test_get(self, id: str, *, request_options: typing.Optional[RequestOptions] = None) -> str: + def test_get( + self, id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -46,11 +48,15 @@ def test_get(self, id: str, *, request_options: typing.Optional[RequestOptions] ) """ _response = self._client_wrapper.httpx_client.request( - f"http-methods/{jsonable_encoder(id)}", method="GET", request_options=request_options + f"http-methods/{jsonable_encoder(id)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -84,18 +90,33 @@ def test_post( ) """ _response = self._client_wrapper.httpx_client.request( - "http-methods", method="POST", json={"string": string}, request_options=request_options, omit=OMIT + "http-methods", + method="POST", + json={ + "string": string, + }, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def test_put( - self, id: str, *, string: str, request_options: typing.Optional[RequestOptions] = None + self, + id: str, + *, + string: str, + request_options: typing.Optional[RequestOptions] = None, ) -> ObjectWithOptionalField: """ Parameters @@ -127,13 +148,20 @@ def test_put( _response = self._client_wrapper.httpx_client.request( f"http-methods/{jsonable_encoder(id)}", method="PUT", - json={"string": string}, + json={ + "string": string, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -254,13 +282,20 @@ def test_patch( ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def test_delete(self, id: str, *, request_options: typing.Optional[RequestOptions] = None) -> bool: + def test_delete( + self, id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> bool: """ Parameters ---------- @@ -286,11 +321,15 @@ def test_delete(self, id: str, *, request_options: typing.Optional[RequestOption ) """ _response = self._client_wrapper.httpx_client.request( - f"http-methods/{jsonable_encoder(id)}", method="DELETE", request_options=request_options + f"http-methods/{jsonable_encoder(id)}", + method="DELETE", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -301,7 +340,9 @@ class AsyncHttpMethodsClient: def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper - async def test_get(self, id: str, *, request_options: typing.Optional[RequestOptions] = None) -> str: + async def test_get( + self, id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -335,11 +376,15 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - f"http-methods/{jsonable_encoder(id)}", method="GET", request_options=request_options + f"http-methods/{jsonable_encoder(id)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -381,18 +426,33 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "http-methods", method="POST", json={"string": string}, request_options=request_options, omit=OMIT + "http-methods", + method="POST", + json={ + "string": string, + }, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def test_put( - self, id: str, *, string: str, request_options: typing.Optional[RequestOptions] = None + self, + id: str, + *, + string: str, + request_options: typing.Optional[RequestOptions] = None, ) -> ObjectWithOptionalField: """ Parameters @@ -432,13 +492,20 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( f"http-methods/{jsonable_encoder(id)}", method="PUT", - json={"string": string}, + json={ + "string": string, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -566,13 +633,20 @@ async def main() -> None: ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - async def test_delete(self, id: str, *, request_options: typing.Optional[RequestOptions] = None) -> bool: + async def test_delete( + self, id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> bool: """ Parameters ---------- @@ -606,11 +680,15 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - f"http-methods/{jsonable_encoder(id)}", method="DELETE", request_options=request_options + f"http-methods/{jsonable_encoder(id)}", + method="DELETE", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/pydantic-v1/src/seed/endpoints/object/client.py b/seed/python-sdk/exhaustive/pydantic-v1/src/seed/endpoints/object/client.py index a724f959193..dcb1324b74b 100644 --- a/seed/python-sdk/exhaustive/pydantic-v1/src/seed/endpoints/object/client.py +++ b/seed/python-sdk/exhaustive/pydantic-v1/src/seed/endpoints/object/client.py @@ -1,20 +1,24 @@ # This file was auto-generated by Fern from our API Definition. -import datetime as dt import typing +from ...core.client_wrapper import SyncClientWrapper +import datetime as dt import uuid -from json.decoder import JSONDecodeError - -from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ...core.jsonable_encoder import jsonable_encoder -from ...core.pydantic_utilities import parse_obj_as from ...core.request_options import RequestOptions -from ...types.object.types.nested_object_with_optional_field import NestedObjectWithOptionalField -from ...types.object.types.nested_object_with_required_field import NestedObjectWithRequiredField -from ...types.object.types.object_with_map_of_map import ObjectWithMapOfMap from ...types.object.types.object_with_optional_field import ObjectWithOptionalField +from ...core.pydantic_utilities import parse_obj_as +from json.decoder import JSONDecodeError +from ...core.api_error import ApiError from ...types.object.types.object_with_required_field import ObjectWithRequiredField +from ...types.object.types.object_with_map_of_map import ObjectWithMapOfMap +from ...types.object.types.nested_object_with_optional_field import ( + NestedObjectWithOptionalField, +) +from ...types.object.types.nested_object_with_required_field import ( + NestedObjectWithRequiredField, +) +from ...core.jsonable_encoder import jsonable_encoder +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -135,7 +139,12 @@ def get_and_return_with_optional_field( ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -171,20 +180,30 @@ def get_and_return_with_required_field( _response = self._client_wrapper.httpx_client.request( "object/get-and-return-with-required-field", method="POST", - json={"string": string}, + json={ + "string": string, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithRequiredField, parse_obj_as(type_=ObjectWithRequiredField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithRequiredField, + parse_obj_as( + type_=ObjectWithRequiredField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_and_return_with_map_of_map( - self, *, map_: typing.Dict[str, typing.Dict[str, str]], request_options: typing.Optional[RequestOptions] = None + self, + *, + map_: typing.Dict[str, typing.Dict[str, str]], + request_options: typing.Optional[RequestOptions] = None, ) -> ObjectWithMapOfMap: """ Parameters @@ -213,13 +232,18 @@ def get_and_return_with_map_of_map( _response = self._client_wrapper.httpx_client.request( "object/get-and-return-with-map-of-map", method="POST", - json={"map": map_}, + json={ + "map": map_, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithMapOfMap, parse_obj_as(type_=ObjectWithMapOfMap, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithMapOfMap, + parse_obj_as(type_=ObjectWithMapOfMap, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -286,13 +310,21 @@ def get_and_return_nested_with_optional_field( _response = self._client_wrapper.httpx_client.request( "object/get-and-return-nested-with-optional-field", method="POST", - json={"string": string, "NestedObject": nested_object}, + json={ + "string": string, + "NestedObject": nested_object, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(NestedObjectWithOptionalField, parse_obj_as(type_=NestedObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + NestedObjectWithOptionalField, + parse_obj_as( + type_=NestedObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -363,13 +395,21 @@ def get_and_return_nested_with_required_field( _response = self._client_wrapper.httpx_client.request( f"object/get-and-return-nested-with-required-field/{jsonable_encoder(string_)}", method="POST", - json={"string": string, "NestedObject": nested_object}, + json={ + "string": string, + "NestedObject": nested_object, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(NestedObjectWithRequiredField, parse_obj_as(type_=NestedObjectWithRequiredField, object_=_response.json())) # type: ignore + return typing.cast( + NestedObjectWithRequiredField, + parse_obj_as( + type_=NestedObjectWithRequiredField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -446,7 +486,12 @@ def get_and_return_nested_with_required_field_as_list( ) try: if 200 <= _response.status_code < 300: - return typing.cast(NestedObjectWithRequiredField, parse_obj_as(type_=NestedObjectWithRequiredField, object_=_response.json())) # type: ignore + return typing.cast( + NestedObjectWithRequiredField, + parse_obj_as( + type_=NestedObjectWithRequiredField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -575,7 +620,12 @@ async def main() -> None: ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -619,20 +669,30 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( "object/get-and-return-with-required-field", method="POST", - json={"string": string}, + json={ + "string": string, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithRequiredField, parse_obj_as(type_=ObjectWithRequiredField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithRequiredField, + parse_obj_as( + type_=ObjectWithRequiredField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_and_return_with_map_of_map( - self, *, map_: typing.Dict[str, typing.Dict[str, str]], request_options: typing.Optional[RequestOptions] = None + self, + *, + map_: typing.Dict[str, typing.Dict[str, str]], + request_options: typing.Optional[RequestOptions] = None, ) -> ObjectWithMapOfMap: """ Parameters @@ -669,13 +729,18 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( "object/get-and-return-with-map-of-map", method="POST", - json={"map": map_}, + json={ + "map": map_, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithMapOfMap, parse_obj_as(type_=ObjectWithMapOfMap, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithMapOfMap, + parse_obj_as(type_=ObjectWithMapOfMap, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -749,13 +814,21 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( "object/get-and-return-nested-with-optional-field", method="POST", - json={"string": string, "NestedObject": nested_object}, + json={ + "string": string, + "NestedObject": nested_object, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(NestedObjectWithOptionalField, parse_obj_as(type_=NestedObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + NestedObjectWithOptionalField, + parse_obj_as( + type_=NestedObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -833,13 +906,21 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( f"object/get-and-return-nested-with-required-field/{jsonable_encoder(string_)}", method="POST", - json={"string": string, "NestedObject": nested_object}, + json={ + "string": string, + "NestedObject": nested_object, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(NestedObjectWithRequiredField, parse_obj_as(type_=NestedObjectWithRequiredField, object_=_response.json())) # type: ignore + return typing.cast( + NestedObjectWithRequiredField, + parse_obj_as( + type_=NestedObjectWithRequiredField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -923,7 +1004,12 @@ async def main() -> None: ) try: if 200 <= _response.status_code < 300: - return typing.cast(NestedObjectWithRequiredField, parse_obj_as(type_=NestedObjectWithRequiredField, object_=_response.json())) # type: ignore + return typing.cast( + NestedObjectWithRequiredField, + parse_obj_as( + type_=NestedObjectWithRequiredField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/pydantic-v1/src/seed/endpoints/params/client.py b/seed/python-sdk/exhaustive/pydantic-v1/src/seed/endpoints/params/client.py index 5cd7ceef42a..a9187ac94b8 100644 --- a/seed/python-sdk/exhaustive/pydantic-v1/src/seed/endpoints/params/client.py +++ b/seed/python-sdk/exhaustive/pydantic-v1/src/seed/endpoints/params/client.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. import typing -from json.decoder import JSONDecodeError - -from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper +from ...core.client_wrapper import SyncClientWrapper +from ...core.request_options import RequestOptions from ...core.jsonable_encoder import jsonable_encoder from ...core.pydantic_utilities import parse_obj_as -from ...core.request_options import RequestOptions +from json.decoder import JSONDecodeError +from ...core.api_error import ApiError +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -17,7 +17,9 @@ class ParamsClient: def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper - def get_with_path(self, param: str, *, request_options: typing.Optional[RequestOptions] = None) -> str: + def get_with_path( + self, param: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ GET with path param @@ -45,18 +47,26 @@ def get_with_path(self, param: str, *, request_options: typing.Optional[RequestO ) """ _response = self._client_wrapper.httpx_client.request( - f"params/path/{jsonable_encoder(param)}", method="GET", request_options=request_options + f"params/path/{jsonable_encoder(param)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_with_query( - self, *, query: str, number: int, request_options: typing.Optional[RequestOptions] = None + self, + *, + query: str, + number: int, + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ GET with query param @@ -88,7 +98,13 @@ def get_with_query( ) """ _response = self._client_wrapper.httpx_client.request( - "params", method="GET", params={"query": query, "number": number}, request_options=request_options + "params", + method="GET", + params={ + "query": query, + "number": number, + }, + request_options=request_options, ) try: if 200 <= _response.status_code < 300: @@ -135,7 +151,13 @@ def get_with_allow_multiple_query( ) """ _response = self._client_wrapper.httpx_client.request( - "params", method="GET", params={"query": query, "numer": numer}, request_options=request_options + "params", + method="GET", + params={ + "query": query, + "numer": numer, + }, + request_options=request_options, ) try: if 200 <= _response.status_code < 300: @@ -146,7 +168,11 @@ def get_with_allow_multiple_query( raise ApiError(status_code=_response.status_code, body=_response_json) def get_with_path_and_query( - self, param: str, *, query: str, request_options: typing.Optional[RequestOptions] = None + self, + param: str, + *, + query: str, + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ GET with path and query params @@ -180,7 +206,9 @@ def get_with_path_and_query( _response = self._client_wrapper.httpx_client.request( f"params/path-query/{jsonable_encoder(param)}", method="GET", - params={"query": query}, + params={ + "query": query, + }, request_options=request_options, ) try: @@ -192,7 +220,11 @@ def get_with_path_and_query( raise ApiError(status_code=_response.status_code, body=_response_json) def modify_with_path( - self, param: str, *, request: str, request_options: typing.Optional[RequestOptions] = None + self, + param: str, + *, + request: str, + request_options: typing.Optional[RequestOptions] = None, ) -> str: """ PUT to update with path param @@ -232,7 +264,9 @@ def modify_with_path( ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -243,7 +277,9 @@ class AsyncParamsClient: def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper - async def get_with_path(self, param: str, *, request_options: typing.Optional[RequestOptions] = None) -> str: + async def get_with_path( + self, param: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ GET with path param @@ -279,18 +315,26 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - f"params/path/{jsonable_encoder(param)}", method="GET", request_options=request_options + f"params/path/{jsonable_encoder(param)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_with_query( - self, *, query: str, number: int, request_options: typing.Optional[RequestOptions] = None + self, + *, + query: str, + number: int, + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ GET with query param @@ -330,7 +374,13 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "params", method="GET", params={"query": query, "number": number}, request_options=request_options + "params", + method="GET", + params={ + "query": query, + "number": number, + }, + request_options=request_options, ) try: if 200 <= _response.status_code < 300: @@ -385,7 +435,13 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "params", method="GET", params={"query": query, "numer": numer}, request_options=request_options + "params", + method="GET", + params={ + "query": query, + "numer": numer, + }, + request_options=request_options, ) try: if 200 <= _response.status_code < 300: @@ -396,7 +452,11 @@ async def main() -> None: raise ApiError(status_code=_response.status_code, body=_response_json) async def get_with_path_and_query( - self, param: str, *, query: str, request_options: typing.Optional[RequestOptions] = None + self, + param: str, + *, + query: str, + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ GET with path and query params @@ -438,7 +498,9 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( f"params/path-query/{jsonable_encoder(param)}", method="GET", - params={"query": query}, + params={ + "query": query, + }, request_options=request_options, ) try: @@ -450,7 +512,11 @@ async def main() -> None: raise ApiError(status_code=_response.status_code, body=_response_json) async def modify_with_path( - self, param: str, *, request: str, request_options: typing.Optional[RequestOptions] = None + self, + param: str, + *, + request: str, + request_options: typing.Optional[RequestOptions] = None, ) -> str: """ PUT to update with path param @@ -498,7 +564,9 @@ async def main() -> None: ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/pydantic-v1/src/seed/endpoints/primitive/client.py b/seed/python-sdk/exhaustive/pydantic-v1/src/seed/endpoints/primitive/client.py index 844b6a782f0..20a66f049b4 100644 --- a/seed/python-sdk/exhaustive/pydantic-v1/src/seed/endpoints/primitive/client.py +++ b/seed/python-sdk/exhaustive/pydantic-v1/src/seed/endpoints/primitive/client.py @@ -1,14 +1,14 @@ # This file was auto-generated by Fern from our API Definition. -import datetime as dt import typing -import uuid +from ...core.client_wrapper import SyncClientWrapper +from ...core.request_options import RequestOptions +from ...core.pydantic_utilities import parse_obj_as from json.decoder import JSONDecodeError - from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ...core.pydantic_utilities import parse_obj_as -from ...core.request_options import RequestOptions +import datetime as dt +import uuid +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -18,7 +18,9 @@ class PrimitiveClient: def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper - def get_and_return_string(self, *, request: str, request_options: typing.Optional[RequestOptions] = None) -> str: + def get_and_return_string( + self, *, request: str, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -44,17 +46,25 @@ def get_and_return_string(self, *, request: str, request_options: typing.Optiona ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/string", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/string", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def get_and_return_int(self, *, request: int, request_options: typing.Optional[RequestOptions] = None) -> int: + def get_and_return_int( + self, *, request: int, request_options: typing.Optional[RequestOptions] = None + ) -> int: """ Parameters ---------- @@ -80,17 +90,25 @@ def get_and_return_int(self, *, request: int, request_options: typing.Optional[R ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/integer", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/integer", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(int, parse_obj_as(type_=int, object_=_response.json())) # type: ignore + return typing.cast( + int, parse_obj_as(type_=int, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def get_and_return_long(self, *, request: int, request_options: typing.Optional[RequestOptions] = None) -> int: + def get_and_return_long( + self, *, request: int, request_options: typing.Optional[RequestOptions] = None + ) -> int: """ Parameters ---------- @@ -116,11 +134,17 @@ def get_and_return_long(self, *, request: int, request_options: typing.Optional[ ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/long", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/long", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(int, parse_obj_as(type_=int, object_=_response.json())) # type: ignore + return typing.cast( + int, parse_obj_as(type_=int, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -154,17 +178,25 @@ def get_and_return_double( ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/double", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/double", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(float, parse_obj_as(type_=float, object_=_response.json())) # type: ignore + return typing.cast( + float, parse_obj_as(type_=float, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def get_and_return_bool(self, *, request: bool, request_options: typing.Optional[RequestOptions] = None) -> bool: + def get_and_return_bool( + self, *, request: bool, request_options: typing.Optional[RequestOptions] = None + ) -> bool: """ Parameters ---------- @@ -190,18 +222,27 @@ def get_and_return_bool(self, *, request: bool, request_options: typing.Optional ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/boolean", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/boolean", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_and_return_datetime( - self, *, request: dt.datetime, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: dt.datetime, + request_options: typing.Optional[RequestOptions] = None, ) -> dt.datetime: """ Parameters @@ -232,18 +273,28 @@ def get_and_return_datetime( ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/datetime", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/datetime", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(dt.datetime, parse_obj_as(type_=dt.datetime, object_=_response.json())) # type: ignore + return typing.cast( + dt.datetime, + parse_obj_as(type_=dt.datetime, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_and_return_date( - self, *, request: dt.date, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: dt.date, + request_options: typing.Optional[RequestOptions] = None, ) -> dt.date: """ Parameters @@ -274,18 +325,27 @@ def get_and_return_date( ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/date", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/date", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(dt.date, parse_obj_as(type_=dt.date, object_=_response.json())) # type: ignore + return typing.cast( + dt.date, parse_obj_as(type_=dt.date, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_and_return_uuid( - self, *, request: uuid.UUID, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: uuid.UUID, + request_options: typing.Optional[RequestOptions] = None, ) -> uuid.UUID: """ Parameters @@ -316,17 +376,25 @@ def get_and_return_uuid( ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/uuid", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/uuid", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(uuid.UUID, parse_obj_as(type_=uuid.UUID, object_=_response.json())) # type: ignore + return typing.cast( + uuid.UUID, parse_obj_as(type_=uuid.UUID, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def get_and_return_base_64(self, *, request: str, request_options: typing.Optional[RequestOptions] = None) -> str: + def get_and_return_base_64( + self, *, request: str, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -352,11 +420,17 @@ def get_and_return_base_64(self, *, request: str, request_options: typing.Option ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/base64", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/base64", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -403,17 +477,25 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/string", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/string", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - async def get_and_return_int(self, *, request: int, request_options: typing.Optional[RequestOptions] = None) -> int: + async def get_and_return_int( + self, *, request: int, request_options: typing.Optional[RequestOptions] = None + ) -> int: """ Parameters ---------- @@ -447,11 +529,17 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/integer", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/integer", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(int, parse_obj_as(type_=int, object_=_response.json())) # type: ignore + return typing.cast( + int, parse_obj_as(type_=int, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -493,11 +581,17 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/long", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/long", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(int, parse_obj_as(type_=int, object_=_response.json())) # type: ignore + return typing.cast( + int, parse_obj_as(type_=int, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -539,11 +633,17 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/double", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/double", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(float, parse_obj_as(type_=float, object_=_response.json())) # type: ignore + return typing.cast( + float, parse_obj_as(type_=float, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -585,18 +685,27 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/boolean", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/boolean", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_and_return_datetime( - self, *, request: dt.datetime, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: dt.datetime, + request_options: typing.Optional[RequestOptions] = None, ) -> dt.datetime: """ Parameters @@ -634,18 +743,28 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/datetime", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/datetime", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(dt.datetime, parse_obj_as(type_=dt.datetime, object_=_response.json())) # type: ignore + return typing.cast( + dt.datetime, + parse_obj_as(type_=dt.datetime, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_and_return_date( - self, *, request: dt.date, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: dt.date, + request_options: typing.Optional[RequestOptions] = None, ) -> dt.date: """ Parameters @@ -683,18 +802,27 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/date", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/date", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(dt.date, parse_obj_as(type_=dt.date, object_=_response.json())) # type: ignore + return typing.cast( + dt.date, parse_obj_as(type_=dt.date, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_and_return_uuid( - self, *, request: uuid.UUID, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: uuid.UUID, + request_options: typing.Optional[RequestOptions] = None, ) -> uuid.UUID: """ Parameters @@ -732,11 +860,17 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/uuid", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/uuid", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(uuid.UUID, parse_obj_as(type_=uuid.UUID, object_=_response.json())) # type: ignore + return typing.cast( + uuid.UUID, parse_obj_as(type_=uuid.UUID, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -778,11 +912,17 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/base64", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/base64", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/pydantic-v1/src/seed/endpoints/union/client.py b/seed/python-sdk/exhaustive/pydantic-v1/src/seed/endpoints/union/client.py index 77153587a27..f4c3d9312de 100644 --- a/seed/python-sdk/exhaustive/pydantic-v1/src/seed/endpoints/union/client.py +++ b/seed/python-sdk/exhaustive/pydantic-v1/src/seed/endpoints/union/client.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. import typing +from ...core.client_wrapper import SyncClientWrapper +from ...types.union.types.animal import Animal +from ...core.request_options import RequestOptions +from ...core.pydantic_utilities import parse_obj_as from json.decoder import JSONDecodeError - from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ...core.pydantic_utilities import parse_obj_as -from ...core.request_options import RequestOptions -from ...types.union.types.animal import Animal +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -18,7 +18,10 @@ def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper def get_and_return_union( - self, *, request: Animal, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: Animal, + request_options: typing.Optional[RequestOptions] = None, ) -> Animal: """ Parameters @@ -49,11 +52,17 @@ def get_and_return_union( ) """ _response = self._client_wrapper.httpx_client.request( - "union", method="POST", json=request, request_options=request_options, omit=OMIT + "union", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(Animal, parse_obj_as(type_=Animal, object_=_response.json())) # type: ignore + return typing.cast( + Animal, parse_obj_as(type_=Animal, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -65,7 +74,10 @@ def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper async def get_and_return_union( - self, *, request: Animal, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: Animal, + request_options: typing.Optional[RequestOptions] = None, ) -> Animal: """ Parameters @@ -104,11 +116,17 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "union", method="POST", json=request, request_options=request_options, omit=OMIT + "union", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(Animal, parse_obj_as(type_=Animal, object_=_response.json())) # type: ignore + return typing.cast( + Animal, parse_obj_as(type_=Animal, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/pydantic-v1/src/seed/general_errors/types/bad_object_request_info.py b/seed/python-sdk/exhaustive/pydantic-v1/src/seed/general_errors/types/bad_object_request_info.py index 7f03429e922..73c44b89531 100644 --- a/seed/python-sdk/exhaustive/pydantic-v1/src/seed/general_errors/types/bad_object_request_info.py +++ b/seed/python-sdk/exhaustive/pydantic-v1/src/seed/general_errors/types/bad_object_request_info.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class BadObjectRequestInfo(UniversalBaseModel): message: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/pydantic-v1/src/seed/inlined_requests/client.py b/seed/python-sdk/exhaustive/pydantic-v1/src/seed/inlined_requests/client.py index f7c46698eb9..39e0c8fe637 100644 --- a/seed/python-sdk/exhaustive/pydantic-v1/src/seed/inlined_requests/client.py +++ b/seed/python-sdk/exhaustive/pydantic-v1/src/seed/inlined_requests/client.py @@ -1,15 +1,15 @@ # This file was auto-generated by Fern from our API Definition. import typing -from json.decoder import JSONDecodeError - -from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.pydantic_utilities import parse_obj_as +from ..core.client_wrapper import SyncClientWrapper +from ..types.object.types.object_with_optional_field import ObjectWithOptionalField from ..core.request_options import RequestOptions +from ..core.pydantic_utilities import parse_obj_as from ..general_errors.errors.bad_request_body import BadRequestBody from ..general_errors.types.bad_object_request_info import BadObjectRequestInfo -from ..types.object.types.object_with_optional_field import ObjectWithOptionalField +from json.decoder import JSONDecodeError +from ..core.api_error import ApiError +from ..core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -25,7 +25,7 @@ def post_with_object_bodyand_response( string: str, integer: int, nested_object: ObjectWithOptionalField, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> ObjectWithOptionalField: """ POST with custom object in request body, response is an object @@ -86,16 +86,30 @@ def post_with_object_bodyand_response( _response = self._client_wrapper.httpx_client.request( "req-bodies/object", method="POST", - json={"string": string, "integer": integer, "NestedObject": nested_object}, + json={ + "string": string, + "integer": integer, + "NestedObject": nested_object, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore if _response.status_code == 400: raise BadRequestBody( - typing.cast(BadObjectRequestInfo, parse_obj_as(type_=BadObjectRequestInfo, object_=_response.json())) # type: ignore + typing.cast( + BadObjectRequestInfo, + parse_obj_as( + type_=BadObjectRequestInfo, object_=_response.json() + ), + ) # type: ignore ) _response_json = _response.json() except JSONDecodeError: @@ -113,7 +127,7 @@ async def post_with_object_bodyand_response( string: str, integer: int, nested_object: ObjectWithOptionalField, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> ObjectWithOptionalField: """ POST with custom object in request body, response is an object @@ -181,16 +195,30 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( "req-bodies/object", method="POST", - json={"string": string, "integer": integer, "NestedObject": nested_object}, + json={ + "string": string, + "integer": integer, + "NestedObject": nested_object, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore if _response.status_code == 400: raise BadRequestBody( - typing.cast(BadObjectRequestInfo, parse_obj_as(type_=BadObjectRequestInfo, object_=_response.json())) # type: ignore + typing.cast( + BadObjectRequestInfo, + parse_obj_as( + type_=BadObjectRequestInfo, object_=_response.json() + ), + ) # type: ignore ) _response_json = _response.json() except JSONDecodeError: diff --git a/seed/python-sdk/exhaustive/pydantic-v1/src/seed/no_auth/client.py b/seed/python-sdk/exhaustive/pydantic-v1/src/seed/no_auth/client.py index 3d203bcea34..e5590cde0df 100644 --- a/seed/python-sdk/exhaustive/pydantic-v1/src/seed/no_auth/client.py +++ b/seed/python-sdk/exhaustive/pydantic-v1/src/seed/no_auth/client.py @@ -1,14 +1,14 @@ # This file was auto-generated by Fern from our API Definition. import typing -from json.decoder import JSONDecodeError - -from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.pydantic_utilities import parse_obj_as +from ..core.client_wrapper import SyncClientWrapper from ..core.request_options import RequestOptions +from ..core.pydantic_utilities import parse_obj_as from ..general_errors.errors.bad_request_body import BadRequestBody from ..general_errors.types.bad_object_request_info import BadObjectRequestInfo +from json.decoder import JSONDecodeError +from ..core.api_error import ApiError +from ..core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -19,7 +19,10 @@ def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper def post_with_no_auth( - self, *, request: typing.Any, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Any, + request_options: typing.Optional[RequestOptions] = None, ) -> bool: """ POST request with no auth @@ -48,14 +51,25 @@ def post_with_no_auth( ) """ _response = self._client_wrapper.httpx_client.request( - "no-auth", method="POST", json=request, request_options=request_options, omit=OMIT + "no-auth", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore if _response.status_code == 400: raise BadRequestBody( - typing.cast(BadObjectRequestInfo, parse_obj_as(type_=BadObjectRequestInfo, object_=_response.json())) # type: ignore + typing.cast( + BadObjectRequestInfo, + parse_obj_as( + type_=BadObjectRequestInfo, object_=_response.json() + ), + ) # type: ignore ) _response_json = _response.json() except JSONDecodeError: @@ -68,7 +82,10 @@ def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper async def post_with_no_auth( - self, *, request: typing.Any, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Any, + request_options: typing.Optional[RequestOptions] = None, ) -> bool: """ POST request with no auth @@ -105,14 +122,25 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "no-auth", method="POST", json=request, request_options=request_options, omit=OMIT + "no-auth", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore if _response.status_code == 400: raise BadRequestBody( - typing.cast(BadObjectRequestInfo, parse_obj_as(type_=BadObjectRequestInfo, object_=_response.json())) # type: ignore + typing.cast( + BadObjectRequestInfo, + parse_obj_as( + type_=BadObjectRequestInfo, object_=_response.json() + ), + ) # type: ignore ) _response_json = _response.json() except JSONDecodeError: diff --git a/seed/python-sdk/exhaustive/pydantic-v1/src/seed/no_req_body/client.py b/seed/python-sdk/exhaustive/pydantic-v1/src/seed/no_req_body/client.py index 33fa0c77d27..5afdd703fdc 100644 --- a/seed/python-sdk/exhaustive/pydantic-v1/src/seed/no_req_body/client.py +++ b/seed/python-sdk/exhaustive/pydantic-v1/src/seed/no_req_body/client.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. +from ..core.client_wrapper import SyncClientWrapper import typing -from json.decoder import JSONDecodeError - -from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.pydantic_utilities import parse_obj_as from ..core.request_options import RequestOptions from ..types.object.types.object_with_optional_field import ObjectWithOptionalField +from ..core.pydantic_utilities import parse_obj_as +from json.decoder import JSONDecodeError +from ..core.api_error import ApiError +from ..core.client_wrapper import AsyncClientWrapper class NoReqBodyClient: @@ -38,17 +38,26 @@ def get_with_no_request_body( client.no_req_body.get_with_no_request_body() """ _response = self._client_wrapper.httpx_client.request( - "no-req-body", method="GET", request_options=request_options + "no-req-body", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def post_with_no_request_body(self, *, request_options: typing.Optional[RequestOptions] = None) -> str: + def post_with_no_request_body( + self, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -70,11 +79,15 @@ def post_with_no_request_body(self, *, request_options: typing.Optional[RequestO client.no_req_body.post_with_no_request_body() """ _response = self._client_wrapper.httpx_client.request( - "no-req-body", method="POST", request_options=request_options + "no-req-body", + method="POST", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -117,17 +130,26 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "no-req-body", method="GET", request_options=request_options + "no-req-body", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - async def post_with_no_request_body(self, *, request_options: typing.Optional[RequestOptions] = None) -> str: + async def post_with_no_request_body( + self, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -157,11 +179,15 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "no-req-body", method="POST", request_options=request_options + "no-req-body", + method="POST", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/pydantic-v1/src/seed/req_with_headers/client.py b/seed/python-sdk/exhaustive/pydantic-v1/src/seed/req_with_headers/client.py index 655402249e9..984428516e3 100644 --- a/seed/python-sdk/exhaustive/pydantic-v1/src/seed/req_with_headers/client.py +++ b/seed/python-sdk/exhaustive/pydantic-v1/src/seed/req_with_headers/client.py @@ -1,11 +1,11 @@ # This file was auto-generated by Fern from our API Definition. import typing +from ..core.client_wrapper import SyncClientWrapper +from ..core.request_options import RequestOptions from json.decoder import JSONDecodeError - from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.request_options import RequestOptions +from ..core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -21,7 +21,7 @@ def get_with_custom_header( x_test_service_header: str, x_test_endpoint_header: str, request: str, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ Parameters @@ -58,8 +58,12 @@ def get_with_custom_header( method="POST", json=request, headers={ - "X-TEST-SERVICE-HEADER": str(x_test_service_header) if x_test_service_header is not None else None, - "X-TEST-ENDPOINT-HEADER": str(x_test_endpoint_header) if x_test_endpoint_header is not None else None, + "X-TEST-SERVICE-HEADER": str(x_test_service_header) + if x_test_service_header is not None + else None, + "X-TEST-ENDPOINT-HEADER": str(x_test_endpoint_header) + if x_test_endpoint_header is not None + else None, }, request_options=request_options, omit=OMIT, @@ -83,7 +87,7 @@ async def get_with_custom_header( x_test_service_header: str, x_test_endpoint_header: str, request: str, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ Parameters @@ -128,8 +132,12 @@ async def main() -> None: method="POST", json=request, headers={ - "X-TEST-SERVICE-HEADER": str(x_test_service_header) if x_test_service_header is not None else None, - "X-TEST-ENDPOINT-HEADER": str(x_test_endpoint_header) if x_test_endpoint_header is not None else None, + "X-TEST-SERVICE-HEADER": str(x_test_service_header) + if x_test_service_header is not None + else None, + "X-TEST-ENDPOINT-HEADER": str(x_test_endpoint_header) + if x_test_endpoint_header is not None + else None, }, request_options=request_options, omit=OMIT, diff --git a/seed/python-sdk/exhaustive/pydantic-v1/src/seed/types/enum/types/weather_report.py b/seed/python-sdk/exhaustive/pydantic-v1/src/seed/types/enum/types/weather_report.py index 2d54965dc22..84017ef161d 100644 --- a/seed/python-sdk/exhaustive/pydantic-v1/src/seed/types/enum/types/weather_report.py +++ b/seed/python-sdk/exhaustive/pydantic-v1/src/seed/types/enum/types/weather_report.py @@ -2,4 +2,6 @@ import typing -WeatherReport = typing.Union[typing.Literal["SUNNY", "CLOUDY", "RAINING", "SNOWING"], typing.Any] +WeatherReport = typing.Union[ + typing.Literal["SUNNY", "CLOUDY", "RAINING", "SNOWING"], typing.Any +] diff --git a/seed/python-sdk/exhaustive/pydantic-v1/src/seed/types/object/types/double_optional.py b/seed/python-sdk/exhaustive/pydantic-v1/src/seed/types/object/types/double_optional.py index ddf165b13bd..ed236347357 100644 --- a/seed/python-sdk/exhaustive/pydantic-v1/src/seed/types/object/types/double_optional.py +++ b/seed/python-sdk/exhaustive/pydantic-v1/src/seed/types/object/types/double_optional.py @@ -1,18 +1,21 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .optional_alias import OptionalAlias +import pydantic +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class DoubleOptional(UniversalBaseModel): - optional_alias: typing.Optional[OptionalAlias] = pydantic.Field(alias="optionalAlias", default=None) + optional_alias: typing.Optional[OptionalAlias] = pydantic.Field( + alias="optionalAlias", default=None + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/pydantic-v1/src/seed/types/object/types/nested_object_with_optional_field.py b/seed/python-sdk/exhaustive/pydantic-v1/src/seed/types/object/types/nested_object_with_optional_field.py index 81669c0dd39..20a4d40a714 100644 --- a/seed/python-sdk/exhaustive/pydantic-v1/src/seed/types/object/types/nested_object_with_optional_field.py +++ b/seed/python-sdk/exhaustive/pydantic-v1/src/seed/types/object/types/nested_object_with_optional_field.py @@ -1,19 +1,22 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .object_with_optional_field import ObjectWithOptionalField +import pydantic +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class NestedObjectWithOptionalField(UniversalBaseModel): string: typing.Optional[str] = None - nested_object: typing.Optional[ObjectWithOptionalField] = pydantic.Field(alias="NestedObject", default=None) + nested_object: typing.Optional[ObjectWithOptionalField] = pydantic.Field( + alias="NestedObject", default=None + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/pydantic-v1/src/seed/types/object/types/nested_object_with_required_field.py b/seed/python-sdk/exhaustive/pydantic-v1/src/seed/types/object/types/nested_object_with_required_field.py index 1a621942c6c..a6ca8781190 100644 --- a/seed/python-sdk/exhaustive/pydantic-v1/src/seed/types/object/types/nested_object_with_required_field.py +++ b/seed/python-sdk/exhaustive/pydantic-v1/src/seed/types/object/types/nested_object_with_required_field.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import UniversalBaseModel from .object_with_optional_field import ObjectWithOptionalField +import pydantic +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class NestedObjectWithRequiredField(UniversalBaseModel): @@ -13,7 +12,9 @@ class NestedObjectWithRequiredField(UniversalBaseModel): nested_object: ObjectWithOptionalField = pydantic.Field(alias="NestedObject") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/pydantic-v1/src/seed/types/object/types/object_with_map_of_map.py b/seed/python-sdk/exhaustive/pydantic-v1/src/seed/types/object/types/object_with_map_of_map.py index 8883cc1d498..313cd25ceb8 100644 --- a/seed/python-sdk/exhaustive/pydantic-v1/src/seed/types/object/types/object_with_map_of_map.py +++ b/seed/python-sdk/exhaustive/pydantic-v1/src/seed/types/object/types/object_with_map_of_map.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class ObjectWithMapOfMap(UniversalBaseModel): map_: typing.Dict[str, typing.Dict[str, str]] = pydantic.Field(alias="map") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/pydantic-v1/src/seed/types/object/types/object_with_optional_field.py b/seed/python-sdk/exhaustive/pydantic-v1/src/seed/types/object/types/object_with_optional_field.py index 6aab170be0c..9131f0e91d7 100644 --- a/seed/python-sdk/exhaustive/pydantic-v1/src/seed/types/object/types/object_with_optional_field.py +++ b/seed/python-sdk/exhaustive/pydantic-v1/src/seed/types/object/types/object_with_optional_field.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. -import datetime as dt +from ....core.pydantic_utilities import UniversalBaseModel import typing -import uuid - import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +import datetime as dt +import uuid +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class ObjectWithOptionalField(UniversalBaseModel): @@ -23,13 +22,19 @@ class ObjectWithOptionalField(UniversalBaseModel): date: typing.Optional[dt.date] = None uuid_: typing.Optional[uuid.UUID] = pydantic.Field(alias="uuid", default=None) base_64: typing.Optional[str] = pydantic.Field(alias="base64", default=None) - list_: typing.Optional[typing.List[str]] = pydantic.Field(alias="list", default=None) + list_: typing.Optional[typing.List[str]] = pydantic.Field( + alias="list", default=None + ) set_: typing.Optional[typing.Set[str]] = pydantic.Field(alias="set", default=None) - map_: typing.Optional[typing.Dict[int, str]] = pydantic.Field(alias="map", default=None) + map_: typing.Optional[typing.Dict[int, str]] = pydantic.Field( + alias="map", default=None + ) bigint: typing.Optional[str] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/pydantic-v1/src/seed/types/object/types/object_with_required_field.py b/seed/python-sdk/exhaustive/pydantic-v1/src/seed/types/object/types/object_with_required_field.py index 61b98867984..24db26a3cf8 100644 --- a/seed/python-sdk/exhaustive/pydantic-v1/src/seed/types/object/types/object_with_required_field.py +++ b/seed/python-sdk/exhaustive/pydantic-v1/src/seed/types/object/types/object_with_required_field.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class ObjectWithRequiredField(UniversalBaseModel): string: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/pydantic-v1/src/seed/types/union/types/animal.py b/seed/python-sdk/exhaustive/pydantic-v1/src/seed/types/union/types/animal.py index 1ae43d1663e..84c71d2009a 100644 --- a/seed/python-sdk/exhaustive/pydantic-v1/src/seed/types/union/types/animal.py +++ b/seed/python-sdk/exhaustive/pydantic-v1/src/seed/types/union/types/animal.py @@ -1,12 +1,10 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ....core.pydantic_utilities import UniversalBaseModel import typing - import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class Animal_Dog(UniversalBaseModel): @@ -15,7 +13,9 @@ class Animal_Dog(UniversalBaseModel): likes_to_woof: bool = pydantic.Field(alias="likesToWoof") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: @@ -30,7 +30,9 @@ class Animal_Cat(UniversalBaseModel): likes_to_meow: bool = pydantic.Field(alias="likesToMeow") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/pydantic-v1/src/seed/types/union/types/cat.py b/seed/python-sdk/exhaustive/pydantic-v1/src/seed/types/union/types/cat.py index 61fc5527b1f..c59b78523c9 100644 --- a/seed/python-sdk/exhaustive/pydantic-v1/src/seed/types/union/types/cat.py +++ b/seed/python-sdk/exhaustive/pydantic-v1/src/seed/types/union/types/cat.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ....core.pydantic_utilities import UniversalBaseModel import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class Cat(UniversalBaseModel): @@ -12,7 +11,9 @@ class Cat(UniversalBaseModel): likes_to_meow: bool = pydantic.Field(alias="likesToMeow") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/pydantic-v1/src/seed/types/union/types/dog.py b/seed/python-sdk/exhaustive/pydantic-v1/src/seed/types/union/types/dog.py index c1ff5339dfe..e250c72edef 100644 --- a/seed/python-sdk/exhaustive/pydantic-v1/src/seed/types/union/types/dog.py +++ b/seed/python-sdk/exhaustive/pydantic-v1/src/seed/types/union/types/dog.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ....core.pydantic_utilities import UniversalBaseModel import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class Dog(UniversalBaseModel): @@ -12,7 +11,9 @@ class Dog(UniversalBaseModel): likes_to_woof: bool = pydantic.Field(alias="likesToWoof") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/pydantic-v1/src/seed/version.py b/seed/python-sdk/exhaustive/pydantic-v1/src/seed/version.py index 63ba170685a..ac44536abdb 100644 --- a/seed/python-sdk/exhaustive/pydantic-v1/src/seed/version.py +++ b/seed/python-sdk/exhaustive/pydantic-v1/src/seed/version.py @@ -1,4 +1,3 @@ - from importlib import metadata __version__ = metadata.version("fern_exhaustive") diff --git a/seed/python-sdk/exhaustive/pydantic-v1/tests/conftest.py b/seed/python-sdk/exhaustive/pydantic-v1/tests/conftest.py index b5b50383b94..86cb2b41af8 100644 --- a/seed/python-sdk/exhaustive/pydantic-v1/tests/conftest.py +++ b/seed/python-sdk/exhaustive/pydantic-v1/tests/conftest.py @@ -1,16 +1,22 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive import os - import pytest -from seed import AsyncSeedExhaustive, SeedExhaustive +from seed import AsyncSeedExhaustive @pytest.fixture def client() -> SeedExhaustive: - return SeedExhaustive(token=os.getenv("ENV_TOKEN", "token"), base_url=os.getenv("TESTS_BASE_URL", "base_url")) + return SeedExhaustive( + token=os.getenv("ENV_TOKEN", "token"), + base_url=os.getenv("TESTS_BASE_URL", "base_url"), + ) @pytest.fixture def async_client() -> AsyncSeedExhaustive: - return AsyncSeedExhaustive(token=os.getenv("ENV_TOKEN", "token"), base_url=os.getenv("TESTS_BASE_URL", "base_url")) + return AsyncSeedExhaustive( + token=os.getenv("ENV_TOKEN", "token"), + base_url=os.getenv("TESTS_BASE_URL", "base_url"), + ) diff --git a/seed/python-sdk/exhaustive/pydantic-v1/tests/custom/test_client.py b/seed/python-sdk/exhaustive/pydantic-v1/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/python-sdk/exhaustive/pydantic-v1/tests/custom/test_client.py +++ b/seed/python-sdk/exhaustive/pydantic-v1/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/python-sdk/exhaustive/pydantic-v1/tests/endpoints/test_container.py b/seed/python-sdk/exhaustive/pydantic-v1/tests/endpoints/test_container.py index 17d9d75240d..240f16f2a8c 100644 --- a/seed/python-sdk/exhaustive/pydantic-v1/tests/endpoints/test_container.py +++ b/seed/python-sdk/exhaustive/pydantic-v1/tests/endpoints/test_container.py @@ -1,91 +1,137 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing - -from seed import AsyncSeedExhaustive, SeedExhaustive -from seed.types.object import ObjectWithRequiredField - from ..utilities import validate_response +from seed.types.object import ObjectWithRequiredField -async def test_get_and_return_list_of_primitives(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_list_of_primitives( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = ["string"] expected_types: typing.Tuple[typing.Any, typing.Any] = ("list", {0: None}) - response = client.endpoints.container.get_and_return_list_of_primitives(request=["string"]) + response = client.endpoints.container.get_and_return_list_of_primitives( + request=["string"] + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.container.get_and_return_list_of_primitives(request=["string"]) + async_response = ( + await async_client.endpoints.container.get_and_return_list_of_primitives( + request=["string"] + ) + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_list_of_objects(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_list_of_objects( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = [{"string": "string"}] - expected_types: typing.Tuple[typing.Any, typing.Any] = ("list", {0: {"string": None}}) + expected_types: typing.Tuple[typing.Any, typing.Any] = ( + "list", + {0: {"string": None}}, + ) response = client.endpoints.container.get_and_return_list_of_objects( request=[ObjectWithRequiredField(string="string")] ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.container.get_and_return_list_of_objects( - request=[ObjectWithRequiredField(string="string")] + async_response = ( + await async_client.endpoints.container.get_and_return_list_of_objects( + request=[ObjectWithRequiredField(string="string")] + ) ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_set_of_primitives(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_set_of_primitives( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = ["string"] expected_types: typing.Tuple[typing.Any, typing.Any] = ("set", {0: None}) - response = client.endpoints.container.get_and_return_set_of_primitives(request={"string"}) + response = client.endpoints.container.get_and_return_set_of_primitives( + request={"string"} + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.container.get_and_return_set_of_primitives(request={"string"}) + async_response = ( + await async_client.endpoints.container.get_and_return_set_of_primitives( + request={"string"} + ) + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_set_of_objects(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_set_of_objects( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = [{"string": "string"}] - expected_types: typing.Tuple[typing.Any, typing.Any] = ("set", {0: {"string": None}}) + expected_types: typing.Tuple[typing.Any, typing.Any] = ( + "set", + {0: {"string": None}}, + ) response = client.endpoints.container.get_and_return_set_of_objects( request=[ObjectWithRequiredField(string="string")] ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.container.get_and_return_set_of_objects( - request=[ObjectWithRequiredField(string="string")] + async_response = ( + await async_client.endpoints.container.get_and_return_set_of_objects( + request=[ObjectWithRequiredField(string="string")] + ) ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_map_prim_to_prim(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_map_prim_to_prim( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = {"string": "string"} expected_types: typing.Tuple[typing.Any, typing.Any] = ("dict", {0: (None, None)}) - response = client.endpoints.container.get_and_return_map_prim_to_prim(request={"string": "string"}) + response = client.endpoints.container.get_and_return_map_prim_to_prim( + request={"string": "string"} + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.container.get_and_return_map_prim_to_prim( - request={"string": "string"} + async_response = ( + await async_client.endpoints.container.get_and_return_map_prim_to_prim( + request={"string": "string"} + ) ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_map_of_prim_to_object(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_map_of_prim_to_object( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = {"string": {"string": "string"}} - expected_types: typing.Tuple[typing.Any, typing.Any] = ("dict", {0: (None, {"string": None})}) + expected_types: typing.Tuple[typing.Any, typing.Any] = ( + "dict", + {0: (None, {"string": None})}, + ) response = client.endpoints.container.get_and_return_map_of_prim_to_object( request={"string": ObjectWithRequiredField(string="string")} ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.container.get_and_return_map_of_prim_to_object( - request={"string": ObjectWithRequiredField(string="string")} + async_response = ( + await async_client.endpoints.container.get_and_return_map_of_prim_to_object( + request={"string": ObjectWithRequiredField(string="string")} + ) ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_optional(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_optional( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = {"string": "string"} expected_types: typing.Any = {"string": None} - response = client.endpoints.container.get_and_return_optional(request=ObjectWithRequiredField(string="string")) + response = client.endpoints.container.get_and_return_optional( + request=ObjectWithRequiredField(string="string") + ) validate_response(response, expected_response, expected_types) async_response = await async_client.endpoints.container.get_and_return_optional( diff --git a/seed/python-sdk/exhaustive/pydantic-v1/tests/endpoints/test_enum.py b/seed/python-sdk/exhaustive/pydantic-v1/tests/endpoints/test_enum.py index 890aada5ce4..ca3fca30b5a 100644 --- a/seed/python-sdk/exhaustive/pydantic-v1/tests/endpoints/test_enum.py +++ b/seed/python-sdk/exhaustive/pydantic-v1/tests/endpoints/test_enum.py @@ -1,17 +1,20 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing - -from seed import AsyncSeedExhaustive, SeedExhaustive - from ..utilities import validate_response -async def test_get_and_return_enum(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_enum( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "SUNNY" expected_types: typing.Any = None response = client.endpoints.enum.get_and_return_enum(request="SUNNY") validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.enum.get_and_return_enum(request="SUNNY") + async_response = await async_client.endpoints.enum.get_and_return_enum( + request="SUNNY" + ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/exhaustive/pydantic-v1/tests/endpoints/test_http_methods.py b/seed/python-sdk/exhaustive/pydantic-v1/tests/endpoints/test_http_methods.py index dc01bafcf6f..77131fc6e8b 100644 --- a/seed/python-sdk/exhaustive/pydantic-v1/tests/endpoints/test_http_methods.py +++ b/seed/python-sdk/exhaustive/pydantic-v1/tests/endpoints/test_http_methods.py @@ -1,15 +1,16 @@ # This file was auto-generated by Fern from our API Definition. -import datetime +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing -import uuid - -from seed import AsyncSeedExhaustive, SeedExhaustive - from ..utilities import validate_response +import datetime +import uuid -async def test_test_get(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_test_get( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "string" expected_types: typing.Any = None response = client.endpoints.http_methods.test_get(id="string") @@ -19,7 +20,9 @@ async def test_test_get(client: SeedExhaustive, async_client: AsyncSeedExhaustiv validate_response(async_response, expected_response, expected_types) -async def test_test_post(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_test_post( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = { "string": "string", "integer": 1, @@ -53,11 +56,15 @@ async def test_test_post(client: SeedExhaustive, async_client: AsyncSeedExhausti response = client.endpoints.http_methods.test_post(string="string") validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.http_methods.test_post(string="string") + async_response = await async_client.endpoints.http_methods.test_post( + string="string" + ) validate_response(async_response, expected_response, expected_types) -async def test_test_put(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_test_put( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = { "string": "string", "integer": 1, @@ -91,11 +98,15 @@ async def test_test_put(client: SeedExhaustive, async_client: AsyncSeedExhaustiv response = client.endpoints.http_methods.test_put(id="string", string="string") validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.http_methods.test_put(id="string", string="string") + async_response = await async_client.endpoints.http_methods.test_put( + id="string", string="string" + ) validate_response(async_response, expected_response, expected_types) -async def test_test_patch(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_test_patch( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = { "string": "string", "integer": 1, @@ -163,7 +174,9 @@ async def test_test_patch(client: SeedExhaustive, async_client: AsyncSeedExhaust validate_response(async_response, expected_response, expected_types) -async def test_test_delete(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_test_delete( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = True expected_types: typing.Any = None response = client.endpoints.http_methods.test_delete(id="string") diff --git a/seed/python-sdk/exhaustive/pydantic-v1/tests/endpoints/test_object.py b/seed/python-sdk/exhaustive/pydantic-v1/tests/endpoints/test_object.py index a9098b6e9ef..c48c4332b22 100644 --- a/seed/python-sdk/exhaustive/pydantic-v1/tests/endpoints/test_object.py +++ b/seed/python-sdk/exhaustive/pydantic-v1/tests/endpoints/test_object.py @@ -1,16 +1,18 @@ # This file was auto-generated by Fern from our API Definition. -import datetime +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing +import datetime import uuid - -from seed import AsyncSeedExhaustive, SeedExhaustive -from seed.types.object import NestedObjectWithRequiredField, ObjectWithOptionalField - from ..utilities import validate_response +from seed.types.object import ObjectWithOptionalField +from seed.types.object import NestedObjectWithRequiredField -async def test_get_and_return_with_optional_field(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_with_optional_field( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = { "string": "string", "integer": 1, @@ -58,38 +60,54 @@ async def test_get_and_return_with_optional_field(client: SeedExhaustive, async_ ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.object.get_and_return_with_optional_field( - string="string", - integer=1, - long_=1000000, - double=1.1, - bool_=True, - datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), - date=datetime.date.fromisoformat("2023-01-15"), - uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), - base_64="SGVsbG8gd29ybGQh", - list_=["string"], - set_={"string"}, - map_={1: "string"}, - bigint="123456789123456789", + async_response = ( + await async_client.endpoints.object.get_and_return_with_optional_field( + string="string", + integer=1, + long_=1000000, + double=1.1, + bool_=True, + datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), + date=datetime.date.fromisoformat("2023-01-15"), + uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + base_64="SGVsbG8gd29ybGQh", + list_=["string"], + set_={"string"}, + map_={1: "string"}, + bigint="123456789123456789", + ) ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_with_required_field(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_with_required_field( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = {"string": "string"} expected_types: typing.Any = {"string": None} - response = client.endpoints.object.get_and_return_with_required_field(string="string") + response = client.endpoints.object.get_and_return_with_required_field( + string="string" + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.object.get_and_return_with_required_field(string="string") + async_response = ( + await async_client.endpoints.object.get_and_return_with_required_field( + string="string" + ) + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_with_map_of_map(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_with_map_of_map( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = {"map": {"string": {"string": "string"}}} - expected_types: typing.Any = {"map": ("dict", {0: (None, ("dict", {0: (None, None)}))})} - response = client.endpoints.object.get_and_return_with_map_of_map(map_={"string": {"string": "string"}}) + expected_types: typing.Any = { + "map": ("dict", {0: (None, ("dict", {0: (None, None)}))}) + } + response = client.endpoints.object.get_and_return_with_map_of_map( + map_={"string": {"string": "string"}} + ) validate_response(response, expected_response, expected_types) async_response = await async_client.endpoints.object.get_and_return_with_map_of_map( @@ -157,23 +175,25 @@ async def test_get_and_return_nested_with_optional_field( ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.object.get_and_return_nested_with_optional_field( - string="string", - nested_object=ObjectWithOptionalField( + async_response = ( + await async_client.endpoints.object.get_and_return_nested_with_optional_field( string="string", - integer=1, - long_=1000000, - double=1.1, - bool_=True, - datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), - date=datetime.date.fromisoformat("2023-01-15"), - uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), - base_64="SGVsbG8gd29ybGQh", - list_=["string"], - set_={"string"}, - map_={1: "string"}, - bigint="123456789123456789", - ), + nested_object=ObjectWithOptionalField( + string="string", + integer=1, + long_=1000000, + double=1.1, + bool_=True, + datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), + date=datetime.date.fromisoformat("2023-01-15"), + uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + base_64="SGVsbG8gd29ybGQh", + list_=["string"], + set_={"string"}, + map_={1: "string"}, + bigint="123456789123456789", + ), + ) ) validate_response(async_response, expected_response, expected_types) @@ -238,24 +258,26 @@ async def test_get_and_return_nested_with_required_field( ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.object.get_and_return_nested_with_required_field( - string_="string", - string="string", - nested_object=ObjectWithOptionalField( + async_response = ( + await async_client.endpoints.object.get_and_return_nested_with_required_field( + string_="string", string="string", - integer=1, - long_=1000000, - double=1.1, - bool_=True, - datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), - date=datetime.date.fromisoformat("2023-01-15"), - uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), - base_64="SGVsbG8gd29ybGQh", - list_=["string"], - set_={"string"}, - map_={1: "string"}, - bigint="123456789123456789", - ), + nested_object=ObjectWithOptionalField( + string="string", + integer=1, + long_=1000000, + double=1.1, + bool_=True, + datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), + date=datetime.date.fromisoformat("2023-01-15"), + uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + base_64="SGVsbG8gd29ybGQh", + list_=["string"], + set_={"string"}, + map_={1: "string"}, + bigint="123456789123456789", + ), + ) ) validate_response(async_response, expected_response, expected_types) @@ -299,27 +321,31 @@ async def test_get_and_return_nested_with_required_field_as_list( "bigint": None, }, } - response = client.endpoints.object.get_and_return_nested_with_required_field_as_list( - request=[ - NestedObjectWithRequiredField( - string="string", - nested_object=ObjectWithOptionalField( + response = ( + client.endpoints.object.get_and_return_nested_with_required_field_as_list( + request=[ + NestedObjectWithRequiredField( string="string", - integer=1, - long_=1000000, - double=1.1, - bool_=True, - datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), - date=datetime.date.fromisoformat("2023-01-15"), - uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), - base_64="SGVsbG8gd29ybGQh", - list_=["string"], - set_={"string"}, - map_={1: "string"}, - bigint="123456789123456789", - ), - ) - ] + nested_object=ObjectWithOptionalField( + string="string", + integer=1, + long_=1000000, + double=1.1, + bool_=True, + datetime=datetime.datetime.fromisoformat( + "2024-01-15 09:30:00+00:00" + ), + date=datetime.date.fromisoformat("2023-01-15"), + uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + base_64="SGVsbG8gd29ybGQh", + list_=["string"], + set_={"string"}, + map_={1: "string"}, + bigint="123456789123456789", + ), + ) + ] + ) ) validate_response(response, expected_response, expected_types) @@ -333,7 +359,9 @@ async def test_get_and_return_nested_with_required_field_as_list( long_=1000000, double=1.1, bool_=True, - datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), + datetime=datetime.datetime.fromisoformat( + "2024-01-15 09:30:00+00:00" + ), date=datetime.date.fromisoformat("2023-01-15"), uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), base_64="SGVsbG8gd29ybGQh", diff --git a/seed/python-sdk/exhaustive/pydantic-v1/tests/endpoints/test_params.py b/seed/python-sdk/exhaustive/pydantic-v1/tests/endpoints/test_params.py index 163d7b9161d..d8ffb00c0a0 100644 --- a/seed/python-sdk/exhaustive/pydantic-v1/tests/endpoints/test_params.py +++ b/seed/python-sdk/exhaustive/pydantic-v1/tests/endpoints/test_params.py @@ -1,13 +1,14 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing - -from seed import AsyncSeedExhaustive, SeedExhaustive - from ..utilities import validate_response -async def test_get_with_path(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_with_path( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "string" expected_types: typing.Any = None response = client.endpoints.params.get_with_path(param="string") @@ -17,32 +18,63 @@ async def test_get_with_path(client: SeedExhaustive, async_client: AsyncSeedExha validate_response(async_response, expected_response, expected_types) -async def test_get_with_query(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_with_query( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: # Type ignore to avoid mypy complaining about the function not being meant to return a value assert client.endpoints.params.get_with_query(query="string", number=1) is None # type: ignore[func-returns-value] - assert await async_client.endpoints.params.get_with_query(query="string", number=1) is None # type: ignore[func-returns-value] + assert ( + await async_client.endpoints.params.get_with_query(query="string", number=1) + is None + ) # type: ignore[func-returns-value] -async def test_get_with_allow_multiple_query(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_with_allow_multiple_query( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: # Type ignore to avoid mypy complaining about the function not being meant to return a value - assert client.endpoints.params.get_with_allow_multiple_query(query="string", numer=1) is None # type: ignore[func-returns-value] - - assert await async_client.endpoints.params.get_with_allow_multiple_query(query="string", numer=1) is None # type: ignore[func-returns-value] - - -async def test_get_with_path_and_query(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: + assert ( + client.endpoints.params.get_with_allow_multiple_query(query="string", numer=1) + is None + ) # type: ignore[func-returns-value] + + assert ( + await async_client.endpoints.params.get_with_allow_multiple_query( + query="string", numer=1 + ) + is None + ) # type: ignore[func-returns-value] + + +async def test_get_with_path_and_query( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: # Type ignore to avoid mypy complaining about the function not being meant to return a value - assert client.endpoints.params.get_with_path_and_query(param="string", query="string") is None # type: ignore[func-returns-value] - - assert await async_client.endpoints.params.get_with_path_and_query(param="string", query="string") is None # type: ignore[func-returns-value] - - -async def test_modify_with_path(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: + assert ( + client.endpoints.params.get_with_path_and_query(param="string", query="string") + is None + ) # type: ignore[func-returns-value] + + assert ( + await async_client.endpoints.params.get_with_path_and_query( + param="string", query="string" + ) + is None + ) # type: ignore[func-returns-value] + + +async def test_modify_with_path( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "string" expected_types: typing.Any = None - response = client.endpoints.params.modify_with_path(param="string", request="string") + response = client.endpoints.params.modify_with_path( + param="string", request="string" + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.params.modify_with_path(param="string", request="string") + async_response = await async_client.endpoints.params.modify_with_path( + param="string", request="string" + ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/exhaustive/pydantic-v1/tests/endpoints/test_primitive.py b/seed/python-sdk/exhaustive/pydantic-v1/tests/endpoints/test_primitive.py index ba3bc7e29e5..26cbcf45d2f 100644 --- a/seed/python-sdk/exhaustive/pydantic-v1/tests/endpoints/test_primitive.py +++ b/seed/python-sdk/exhaustive/pydantic-v1/tests/endpoints/test_primitive.py @@ -1,65 +1,86 @@ # This file was auto-generated by Fern from our API Definition. -import datetime +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing -import uuid - -from seed import AsyncSeedExhaustive, SeedExhaustive - from ..utilities import validate_response +import datetime +import uuid -async def test_get_and_return_string(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_string( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "string" expected_types: typing.Any = None response = client.endpoints.primitive.get_and_return_string(request="string") validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.primitive.get_and_return_string(request="string") + async_response = await async_client.endpoints.primitive.get_and_return_string( + request="string" + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_int(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_int( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = 1 expected_types: typing.Any = "integer" response = client.endpoints.primitive.get_and_return_int(request=1) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.primitive.get_and_return_int(request=1) + async_response = await async_client.endpoints.primitive.get_and_return_int( + request=1 + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_long(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_long( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = 1000000 expected_types: typing.Any = None response = client.endpoints.primitive.get_and_return_long(request=1000000) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.primitive.get_and_return_long(request=1000000) + async_response = await async_client.endpoints.primitive.get_and_return_long( + request=1000000 + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_double(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_double( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = 1.1 expected_types: typing.Any = None response = client.endpoints.primitive.get_and_return_double(request=1.1) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.primitive.get_and_return_double(request=1.1) + async_response = await async_client.endpoints.primitive.get_and_return_double( + request=1.1 + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_bool(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_bool( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = True expected_types: typing.Any = None response = client.endpoints.primitive.get_and_return_bool(request=True) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.primitive.get_and_return_bool(request=True) + async_response = await async_client.endpoints.primitive.get_and_return_bool( + request=True + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_datetime(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_datetime( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "2024-01-15T09:30:00Z" expected_types: typing.Any = "datetime" response = client.endpoints.primitive.get_and_return_datetime( @@ -73,10 +94,14 @@ async def test_get_and_return_datetime(client: SeedExhaustive, async_client: Asy validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_date(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_date( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "2023-01-15" expected_types: typing.Any = "date" - response = client.endpoints.primitive.get_and_return_date(request=datetime.date.fromisoformat("2023-01-15")) + response = client.endpoints.primitive.get_and_return_date( + request=datetime.date.fromisoformat("2023-01-15") + ) validate_response(response, expected_response, expected_types) async_response = await async_client.endpoints.primitive.get_and_return_date( @@ -85,10 +110,14 @@ async def test_get_and_return_date(client: SeedExhaustive, async_client: AsyncSe validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_uuid(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_uuid( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32" expected_types: typing.Any = "uuid" - response = client.endpoints.primitive.get_and_return_uuid(request=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32")) + response = client.endpoints.primitive.get_and_return_uuid( + request=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32") + ) validate_response(response, expected_response, expected_types) async_response = await async_client.endpoints.primitive.get_and_return_uuid( @@ -97,11 +126,17 @@ async def test_get_and_return_uuid(client: SeedExhaustive, async_client: AsyncSe validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_base_64(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_base_64( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "SGVsbG8gd29ybGQh" expected_types: typing.Any = None - response = client.endpoints.primitive.get_and_return_base_64(request="SGVsbG8gd29ybGQh") + response = client.endpoints.primitive.get_and_return_base_64( + request="SGVsbG8gd29ybGQh" + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.primitive.get_and_return_base_64(request="SGVsbG8gd29ybGQh") + async_response = await async_client.endpoints.primitive.get_and_return_base_64( + request="SGVsbG8gd29ybGQh" + ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/exhaustive/pydantic-v1/tests/endpoints/test_union.py b/seed/python-sdk/exhaustive/pydantic-v1/tests/endpoints/test_union.py index 14e34c2a6df..ceb84928cd9 100644 --- a/seed/python-sdk/exhaustive/pydantic-v1/tests/endpoints/test_union.py +++ b/seed/python-sdk/exhaustive/pydantic-v1/tests/endpoints/test_union.py @@ -1,17 +1,24 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing - -from seed import AsyncSeedExhaustive, SeedExhaustive from seed.types.union import Animal_Dog - from ..utilities import validate_response -async def test_get_and_return_union(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: - expected_response: typing.Any = {"animal": "dog", "name": "string", "likesToWoof": True} +async def test_get_and_return_union( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: + expected_response: typing.Any = { + "animal": "dog", + "name": "string", + "likesToWoof": True, + } expected_types: typing.Any = "no_validate" - response = client.endpoints.union.get_and_return_union(request=Animal_Dog(name="string", likes_to_woof=True)) + response = client.endpoints.union.get_and_return_union( + request=Animal_Dog(name="string", likes_to_woof=True) + ) validate_response(response, expected_response, expected_types) async_response = await async_client.endpoints.union.get_and_return_union( diff --git a/seed/python-sdk/exhaustive/pydantic-v1/tests/test_inlined_requests.py b/seed/python-sdk/exhaustive/pydantic-v1/tests/test_inlined_requests.py index bb9390d3845..03f46b31cc9 100644 --- a/seed/python-sdk/exhaustive/pydantic-v1/tests/test_inlined_requests.py +++ b/seed/python-sdk/exhaustive/pydantic-v1/tests/test_inlined_requests.py @@ -1,16 +1,17 @@ # This file was auto-generated by Fern from our API Definition. -import datetime +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing -import uuid - -from seed import AsyncSeedExhaustive, SeedExhaustive from seed.types.object import ObjectWithOptionalField - +import datetime +import uuid from .utilities import validate_response -async def test_post_with_object_bodyand_response(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_post_with_object_bodyand_response( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = { "string": "string", "integer": 1, @@ -62,23 +63,25 @@ async def test_post_with_object_bodyand_response(client: SeedExhaustive, async_c ) validate_response(response, expected_response, expected_types) - async_response = await async_client.inlined_requests.post_with_object_bodyand_response( - string="string", - integer=1, - nested_object=ObjectWithOptionalField( + async_response = ( + await async_client.inlined_requests.post_with_object_bodyand_response( string="string", integer=1, - long_=1000000, - double=1.1, - bool_=True, - datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), - date=datetime.date.fromisoformat("2023-01-15"), - uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), - base_64="SGVsbG8gd29ybGQh", - list_=["string"], - set_={"string"}, - map_={1: "string"}, - bigint="123456789123456789", - ), + nested_object=ObjectWithOptionalField( + string="string", + integer=1, + long_=1000000, + double=1.1, + bool_=True, + datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), + date=datetime.date.fromisoformat("2023-01-15"), + uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + base_64="SGVsbG8gd29ybGQh", + list_=["string"], + set_={"string"}, + map_={1: "string"}, + bigint="123456789123456789", + ), + ) ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/exhaustive/pydantic-v1/tests/test_no_auth.py b/seed/python-sdk/exhaustive/pydantic-v1/tests/test_no_auth.py index 3328661bb48..fc475f4b6fb 100644 --- a/seed/python-sdk/exhaustive/pydantic-v1/tests/test_no_auth.py +++ b/seed/python-sdk/exhaustive/pydantic-v1/tests/test_no_auth.py @@ -1,17 +1,20 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing - -from seed import AsyncSeedExhaustive, SeedExhaustive - from .utilities import validate_response -async def test_post_with_no_auth(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_post_with_no_auth( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = True expected_types: typing.Any = None response = client.no_auth.post_with_no_auth(request={"key": "value"}) validate_response(response, expected_response, expected_types) - async_response = await async_client.no_auth.post_with_no_auth(request={"key": "value"}) + async_response = await async_client.no_auth.post_with_no_auth( + request={"key": "value"} + ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/exhaustive/pydantic-v1/tests/test_no_req_body.py b/seed/python-sdk/exhaustive/pydantic-v1/tests/test_no_req_body.py index 73abac9d2d8..07061a0e99e 100644 --- a/seed/python-sdk/exhaustive/pydantic-v1/tests/test_no_req_body.py +++ b/seed/python-sdk/exhaustive/pydantic-v1/tests/test_no_req_body.py @@ -1,13 +1,14 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing - -from seed import AsyncSeedExhaustive, SeedExhaustive - from .utilities import validate_response -async def test_get_with_no_request_body(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_with_no_request_body( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = { "string": "string", "integer": 1, @@ -45,7 +46,9 @@ async def test_get_with_no_request_body(client: SeedExhaustive, async_client: As validate_response(async_response, expected_response, expected_types) -async def test_post_with_no_request_body(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_post_with_no_request_body( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "string" expected_types: typing.Any = None response = client.no_req_body.post_with_no_request_body() diff --git a/seed/python-sdk/exhaustive/pydantic-v1/tests/test_req_with_headers.py b/seed/python-sdk/exhaustive/pydantic-v1/tests/test_req_with_headers.py index bba3b5b5507..75ce9d00c03 100644 --- a/seed/python-sdk/exhaustive/pydantic-v1/tests/test_req_with_headers.py +++ b/seed/python-sdk/exhaustive/pydantic-v1/tests/test_req_with_headers.py @@ -1,10 +1,27 @@ # This file was auto-generated by Fern from our API Definition. -from seed import AsyncSeedExhaustive, SeedExhaustive +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive -async def test_get_with_custom_header(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_with_custom_header( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: # Type ignore to avoid mypy complaining about the function not being meant to return a value - assert client.req_with_headers.get_with_custom_header(x_test_service_header="string", x_test_endpoint_header="string", request="string") is None # type: ignore[func-returns-value] + assert ( + client.req_with_headers.get_with_custom_header( + x_test_service_header="string", + x_test_endpoint_header="string", + request="string", + ) + is None + ) # type: ignore[func-returns-value] - assert await async_client.req_with_headers.get_with_custom_header(x_test_service_header="string", x_test_endpoint_header="string", request="string") is None # type: ignore[func-returns-value] + assert ( + await async_client.req_with_headers.get_with_custom_header( + x_test_service_header="string", + x_test_endpoint_header="string", + request="string", + ) + is None + ) # type: ignore[func-returns-value] diff --git a/seed/python-sdk/exhaustive/pydantic-v1/tests/utilities.py b/seed/python-sdk/exhaustive/pydantic-v1/tests/utilities.py index 13da208eb3a..e8f4472564c 100644 --- a/seed/python-sdk/exhaustive/pydantic-v1/tests/utilities.py +++ b/seed/python-sdk/exhaustive/pydantic-v1/tests/utilities.py @@ -3,11 +3,14 @@ import typing import uuid -import pydantic from dateutil import parser +import pydantic + -def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> typing.Any: +def cast_field( + json_expectation: typing.Any, type_expectation: typing.Any +) -> typing.Any: # Cast these specific types which come through as string and expect our # models to cast to the correct type. if type_expectation == "uuid": @@ -25,7 +28,9 @@ def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> ty return json_expectation -def validate_field(response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any) -> None: +def validate_field( + response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectation == "no_validate": return @@ -44,7 +49,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(entry_expectation, dict): is_container_of_complex_type = True validate_response( - response=response[idx], json_expectation=ex, type_expectations=entry_expectation + response=response[idx], + json_expectation=ex, + type_expectations=entry_expectation, ) else: cast_json_expectation.append(cast_field(ex, entry_expectation)) @@ -56,7 +63,10 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # if any of the values of the set have a type_expectation of a dict, we're assuming it's a pydantic # model and keeping it a list. if container_expectation != "set" or not any( - map(lambda value: isinstance(value, dict), list(contents_expectation.values())) + map( + lambda value: isinstance(value, dict), + list(contents_expectation.values()), + ) ): json_expectation = cast_field(json_expectation, container_expectation) elif isinstance(type_expectation, tuple): @@ -65,9 +75,15 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(contents_expectation, dict): json_expectation = { cast_field( - key, contents_expectation.get(idx)[0] if contents_expectation.get(idx) is not None else None # type: ignore + key, + contents_expectation.get(idx)[0] + if contents_expectation.get(idx) is not None + else None, # type: ignore ): cast_field( - value, contents_expectation.get(idx)[1] if contents_expectation.get(idx) is not None else None # type: ignore + value, + contents_expectation.get(idx)[1] + if contents_expectation.get(idx) is not None + else None, # type: ignore ) for idx, (key, value) in enumerate(json_expectation.items()) } @@ -86,7 +102,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # Arg type_expectations is a deeply nested structure that matches the response, but with the values replaced with the expected types -def validate_response(response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any) -> None: +def validate_response( + response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectations == "no_validate": return @@ -96,11 +114,17 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e and not isinstance(response, dict) and not issubclass(type(response), pydantic.BaseModel) ): - validate_field(response=response, json_expectation=json_expectation, type_expectation=type_expectations) + validate_field( + response=response, + json_expectation=json_expectation, + type_expectation=type_expectations, + ) return if isinstance(response, list): - assert len(response) == len(json_expectation), "Length mismatch, expected: {0}, Actual: {1}".format( + assert len(response) == len( + json_expectation + ), "Length mismatch, expected: {0}, Actual: {1}".format( len(response), len(json_expectation) ) content_expectation = type_expectations @@ -108,7 +132,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e content_expectation = type_expectations[1] for idx, item in enumerate(response): validate_response( - response=item, json_expectation=json_expectation[idx], type_expectations=content_expectation[idx] + response=item, + json_expectation=json_expectation[idx], + type_expectations=content_expectation[idx], ) else: response_json = response @@ -116,7 +142,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e response_json = response.dict(by_alias=True) for key, value in json_expectation.items(): - assert key in response_json, "Field {0} not found within the response object: {1}".format( + assert ( + key in response_json + ), "Field {0} not found within the response object: {1}".format( key, response_json ) @@ -128,11 +156,19 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e # Otherwise, we're just validating a single field that's a pydantic model. if isinstance(value, dict) and not isinstance(type_expectation, tuple): validate_response( - response=response_json[key], json_expectation=value, type_expectations=type_expectation + response=response_json[key], + json_expectation=value, + type_expectations=type_expectation, ) else: - validate_field(response=response_json[key], json_expectation=value, type_expectation=type_expectation) + validate_field( + response=response_json[key], + json_expectation=value, + type_expectation=type_expectation, + ) # Ensure there are no additional fields here either del response_json[key] - assert len(response_json) == 0, "Additional fields found, expected None: {0}".format(response_json) + assert ( + len(response_json) == 0 + ), "Additional fields found, expected None: {0}".format(response_json) diff --git a/seed/python-sdk/exhaustive/pydantic-v1/tests/utils/assets/models/__init__.py b/seed/python-sdk/exhaustive/pydantic-v1/tests/utils/assets/models/__init__.py index 2cf01263529..3a1c852e71e 100644 --- a/seed/python-sdk/exhaustive/pydantic-v1/tests/utils/assets/models/__init__.py +++ b/seed/python-sdk/exhaustive/pydantic-v1/tests/utils/assets/models/__init__.py @@ -5,7 +5,7 @@ from .circle import CircleParams from .object_with_defaults import ObjectWithDefaultsParams from .object_with_optional_field import ObjectWithOptionalFieldParams -from .shape import Shape_CircleParams, Shape_SquareParams, ShapeParams +from .shape import ShapeParams, Shape_CircleParams, Shape_SquareParams from .square import SquareParams from .undiscriminated_shape import UndiscriminatedShapeParams diff --git a/seed/python-sdk/exhaustive/pydantic-v1/tests/utils/assets/models/circle.py b/seed/python-sdk/exhaustive/pydantic-v1/tests/utils/assets/models/circle.py index af7a1bf8a8e..253f12d38b3 100644 --- a/seed/python-sdk/exhaustive/pydantic-v1/tests/utils/assets/models/circle.py +++ b/seed/python-sdk/exhaustive/pydantic-v1/tests/utils/assets/models/circle.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class CircleParams(typing_extensions.TypedDict): - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] diff --git a/seed/python-sdk/exhaustive/pydantic-v1/tests/utils/assets/models/object_with_optional_field.py b/seed/python-sdk/exhaustive/pydantic-v1/tests/utils/assets/models/object_with_optional_field.py index 3ad93d5f305..ebe7dc80547 100644 --- a/seed/python-sdk/exhaustive/pydantic-v1/tests/utils/assets/models/object_with_optional_field.py +++ b/seed/python-sdk/exhaustive/pydantic-v1/tests/utils/assets/models/object_with_optional_field.py @@ -7,8 +7,8 @@ import uuid import typing_extensions -from seed.core.serialization import FieldMetadata +from seed.core.serialization import FieldMetadata from .color import Color from .shape import ShapeParams from .undiscriminated_shape import UndiscriminatedShapeParams @@ -18,16 +18,30 @@ class ObjectWithOptionalFieldParams(typing_extensions.TypedDict): literal: typing.Literal["lit_one"] string: typing_extensions.NotRequired[str] integer: typing_extensions.NotRequired[int] - long_: typing_extensions.NotRequired[typing_extensions.Annotated[int, FieldMetadata(alias="long")]] + long_: typing_extensions.NotRequired[ + typing_extensions.Annotated[int, FieldMetadata(alias="long")] + ] double: typing_extensions.NotRequired[float] - bool_: typing_extensions.NotRequired[typing_extensions.Annotated[bool, FieldMetadata(alias="bool")]] + bool_: typing_extensions.NotRequired[ + typing_extensions.Annotated[bool, FieldMetadata(alias="bool")] + ] datetime: typing_extensions.NotRequired[dt.datetime] date: typing_extensions.NotRequired[dt.date] - uuid_: typing_extensions.NotRequired[typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")]] - base_64: typing_extensions.NotRequired[typing_extensions.Annotated[str, FieldMetadata(alias="base64")]] - list_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")]] - set_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")]] - map_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")]] + uuid_: typing_extensions.NotRequired[ + typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")] + ] + base_64: typing_extensions.NotRequired[ + typing_extensions.Annotated[str, FieldMetadata(alias="base64")] + ] + list_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")] + ] + set_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")] + ] + map_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")] + ] enum: typing_extensions.NotRequired[Color] union: typing_extensions.NotRequired[ShapeParams] second_union: typing_extensions.NotRequired[ShapeParams] diff --git a/seed/python-sdk/exhaustive/pydantic-v1/tests/utils/assets/models/shape.py b/seed/python-sdk/exhaustive/pydantic-v1/tests/utils/assets/models/shape.py index 2c33c877951..816ffc51bdc 100644 --- a/seed/python-sdk/exhaustive/pydantic-v1/tests/utils/assets/models/shape.py +++ b/seed/python-sdk/exhaustive/pydantic-v1/tests/utils/assets/models/shape.py @@ -7,6 +7,7 @@ import typing import typing_extensions + from seed.core.serialization import FieldMetadata @@ -15,13 +16,21 @@ class Base(typing_extensions.TypedDict): class Shape_CircleParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["circle"], FieldMetadata(alias="shapeType")] - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["circle"], FieldMetadata(alias="shapeType") + ] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] class Shape_SquareParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["square"], FieldMetadata(alias="shapeType")] - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["square"], FieldMetadata(alias="shapeType") + ] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] ShapeParams = typing.Union[Shape_CircleParams, Shape_SquareParams] diff --git a/seed/python-sdk/exhaustive/pydantic-v1/tests/utils/assets/models/square.py b/seed/python-sdk/exhaustive/pydantic-v1/tests/utils/assets/models/square.py index b9b7dd319bc..bcf08a723c5 100644 --- a/seed/python-sdk/exhaustive/pydantic-v1/tests/utils/assets/models/square.py +++ b/seed/python-sdk/exhaustive/pydantic-v1/tests/utils/assets/models/square.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class SquareParams(typing_extensions.TypedDict): - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] diff --git a/seed/python-sdk/exhaustive/pydantic-v1/tests/utils/test_http_client.py b/seed/python-sdk/exhaustive/pydantic-v1/tests/utils/test_http_client.py index edd11ca7afb..f5a874a75f3 100644 --- a/seed/python-sdk/exhaustive/pydantic-v1/tests/utils/test_http_client.py +++ b/seed/python-sdk/exhaustive/pydantic-v1/tests/utils/test_http_client.py @@ -9,12 +9,17 @@ def get_request_options() -> RequestOptions: def test_get_json_request_body() -> None: - json_body, data_body = get_request_body(json={"hello": "world"}, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json={"hello": "world"}, data=None, request_options=None, omit=None + ) assert json_body == {"hello": "world"} assert data_body is None json_body_extras, data_body_extras = get_request_body( - json={"goodbye": "world"}, data=None, request_options=get_request_options(), omit=None + json={"goodbye": "world"}, + data=None, + request_options=get_request_options(), + omit=None, ) assert json_body_extras == {"goodbye": "world", "see you": "later"} @@ -22,12 +27,17 @@ def test_get_json_request_body() -> None: def test_get_files_request_body() -> None: - json_body, data_body = get_request_body(json=None, data={"hello": "world"}, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data={"hello": "world"}, request_options=None, omit=None + ) assert data_body == {"hello": "world"} assert json_body is None json_body_extras, data_body_extras = get_request_body( - json=None, data={"goodbye": "world"}, request_options=get_request_options(), omit=None + json=None, + data={"goodbye": "world"}, + request_options=get_request_options(), + omit=None, ) assert data_body_extras == {"goodbye": "world", "see you": "later"} @@ -35,7 +45,9 @@ def test_get_files_request_body() -> None: def test_get_none_request_body() -> None: - json_body, data_body = get_request_body(json=None, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data=None, request_options=None, omit=None + ) assert data_body is None assert json_body is None diff --git a/seed/python-sdk/exhaustive/pydantic-v1/tests/utils/test_query_encoding.py b/seed/python-sdk/exhaustive/pydantic-v1/tests/utils/test_query_encoding.py index 247e1551b46..fbc8f402167 100644 --- a/seed/python-sdk/exhaustive/pydantic-v1/tests/utils/test_query_encoding.py +++ b/seed/python-sdk/exhaustive/pydantic-v1/tests/utils/test_query_encoding.py @@ -4,9 +4,15 @@ def test_query_encoding() -> None: - assert encode_query({"hello world": "hello world"}) == {"hello world": "hello world"} - assert encode_query({"hello_world": {"hello": "world"}}) == {"hello_world[hello]": "world"} - assert encode_query({"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"}) == { + assert encode_query({"hello world": "hello world"}) == { + "hello world": "hello world" + } + assert encode_query({"hello_world": {"hello": "world"}}) == { + "hello_world[hello]": "world" + } + assert encode_query( + {"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"} + ) == { "hello_world[hello][world]": "today", "hello_world[test]": "this", "hi": "there", diff --git a/seed/python-sdk/exhaustive/pydantic-v1/tests/utils/test_serialization.py b/seed/python-sdk/exhaustive/pydantic-v1/tests/utils/test_serialization.py index 58b1ed66e6d..5ca956916dd 100644 --- a/seed/python-sdk/exhaustive/pydantic-v1/tests/utils/test_serialization.py +++ b/seed/python-sdk/exhaustive/pydantic-v1/tests/utils/test_serialization.py @@ -1,10 +1,12 @@ # This file was auto-generated by Fern from our API Definition. -from typing import Any, List +from typing import List, Any -from seed.core.serialization import convert_and_respect_annotation_metadata +from seed.core.serialization import ( + convert_and_respect_annotation_metadata, +) +from .assets.models import ShapeParams, ObjectWithOptionalFieldParams -from .assets.models import ObjectWithOptionalFieldParams, ShapeParams UNION_TEST: ShapeParams = {"radius_measurement": 1.0, "shape_type": "circle", "id": "1"} UNION_TEST_CONVERTED = {"shapeType": "circle", "radiusMeasurement": 1.0, "id": "1"} @@ -18,20 +20,54 @@ def test_convert_and_respect_annotation_metadata() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) - assert converted == {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"} + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) + assert converted == { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + } def test_convert_and_respect_annotation_metadata_in_list() -> None: data: List[ObjectWithOptionalFieldParams] = [ - {"string": "string", "long_": 12345, "bool_": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long_": 67890, "list_": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long_": 12345, + "bool_": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long_": 67890, + "list_": [], + "literal": "lit_one", + "any": "any", + }, ] - converted = convert_and_respect_annotation_metadata(object_=data, annotation=List[ObjectWithOptionalFieldParams]) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=List[ObjectWithOptionalFieldParams] + ) assert converted == [ - {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long": 67890, "list": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long": 67890, + "list": [], + "literal": "lit_one", + "any": "any", + }, ] @@ -43,7 +79,9 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) assert converted == { "string": "string", @@ -55,12 +93,16 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: def test_convert_and_respect_annotation_metadata_in_union() -> None: - converted = convert_and_respect_annotation_metadata(object_=UNION_TEST, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=UNION_TEST, annotation=ShapeParams + ) assert converted == UNION_TEST_CONVERTED def test_convert_and_respect_annotation_metadata_with_empty_object() -> None: data: Any = {} - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ShapeParams + ) assert converted == data diff --git a/seed/python-sdk/exhaustive/skip-pydantic-validation/pyproject.toml b/seed/python-sdk/exhaustive/skip-pydantic-validation/pyproject.toml index c6cd3a2b7b9..fc29a237334 100644 --- a/seed/python-sdk/exhaustive/skip-pydantic-validation/pyproject.toml +++ b/seed/python-sdk/exhaustive/skip-pydantic-validation/pyproject.toml @@ -43,6 +43,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/__init__.py b/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/__init__.py index eb56b0ce275..dc1ef03a650 100644 --- a/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/__init__.py +++ b/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/__init__.py @@ -1,6 +1,14 @@ # This file was auto-generated by Fern from our API Definition. -from . import endpoints, general_errors, inlined_requests, no_auth, no_req_body, req_with_headers, types +from . import ( + endpoints, + general_errors, + inlined_requests, + no_auth, + no_req_body, + req_with_headers, + types, +) from .client import AsyncSeedExhaustive, SeedExhaustive from .general_errors import BadObjectRequestInfo, BadRequestBody from .version import __version__ diff --git a/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/client.py b/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/client.py index b1b9764c7a7..f5ab292af6b 100644 --- a/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/client.py +++ b/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/client.py @@ -1,15 +1,19 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from .endpoints.client import AsyncEndpointsClient, EndpointsClient -from .inlined_requests.client import AsyncInlinedRequestsClient, InlinedRequestsClient -from .no_auth.client import AsyncNoAuthClient, NoAuthClient -from .no_req_body.client import AsyncNoReqBodyClient, NoReqBodyClient -from .req_with_headers.client import AsyncReqWithHeadersClient, ReqWithHeadersClient +from .core.client_wrapper import SyncClientWrapper +from .endpoints.client import EndpointsClient +from .inlined_requests.client import InlinedRequestsClient +from .no_auth.client import NoAuthClient +from .no_req_body.client import NoReqBodyClient +from .req_with_headers.client import ReqWithHeadersClient +from .core.client_wrapper import AsyncClientWrapper +from .endpoints.client import AsyncEndpointsClient +from .inlined_requests.client import AsyncInlinedRequestsClient +from .no_auth.client import AsyncNoAuthClient +from .no_req_body.client import AsyncNoReqBodyClient +from .req_with_headers.client import AsyncReqWithHeadersClient class SeedExhaustive: @@ -48,24 +52,32 @@ def __init__( token: typing.Optional[typing.Union[str, typing.Callable[[], str]]] = None, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.Client] = None + httpx_client: typing.Optional[httpx.Client] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = SyncClientWrapper( base_url=base_url, token=token, httpx_client=httpx_client if httpx_client is not None - else httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.Client( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.Client(timeout=_defaulted_timeout), timeout=_defaulted_timeout, ) self.endpoints = EndpointsClient(client_wrapper=self._client_wrapper) - self.inlined_requests = InlinedRequestsClient(client_wrapper=self._client_wrapper) + self.inlined_requests = InlinedRequestsClient( + client_wrapper=self._client_wrapper + ) self.no_auth = NoAuthClient(client_wrapper=self._client_wrapper) self.no_req_body = NoReqBodyClient(client_wrapper=self._client_wrapper) - self.req_with_headers = ReqWithHeadersClient(client_wrapper=self._client_wrapper) + self.req_with_headers = ReqWithHeadersClient( + client_wrapper=self._client_wrapper + ) class AsyncSeedExhaustive: @@ -104,21 +116,29 @@ def __init__( token: typing.Optional[typing.Union[str, typing.Callable[[], str]]] = None, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.AsyncClient] = None + httpx_client: typing.Optional[httpx.AsyncClient] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = AsyncClientWrapper( base_url=base_url, token=token, httpx_client=httpx_client if httpx_client is not None - else httpx.AsyncClient(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.AsyncClient( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.AsyncClient(timeout=_defaulted_timeout), timeout=_defaulted_timeout, ) self.endpoints = AsyncEndpointsClient(client_wrapper=self._client_wrapper) - self.inlined_requests = AsyncInlinedRequestsClient(client_wrapper=self._client_wrapper) + self.inlined_requests = AsyncInlinedRequestsClient( + client_wrapper=self._client_wrapper + ) self.no_auth = AsyncNoAuthClient(client_wrapper=self._client_wrapper) self.no_req_body = AsyncNoReqBodyClient(client_wrapper=self._client_wrapper) - self.req_with_headers = AsyncReqWithHeadersClient(client_wrapper=self._client_wrapper) + self.req_with_headers = AsyncReqWithHeadersClient( + client_wrapper=self._client_wrapper + ) diff --git a/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/core/api_error.py b/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/core/api_error.py index 2e9fc5431cd..da734b58068 100644 --- a/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/core/api_error.py +++ b/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/core/api_error.py @@ -7,7 +7,9 @@ class ApiError(Exception): status_code: typing.Optional[int] body: typing.Any - def __init__(self, *, status_code: typing.Optional[int] = None, body: typing.Any = None): + def __init__( + self, *, status_code: typing.Optional[int] = None, body: typing.Any = None + ): self.status_code = status_code self.body = body diff --git a/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/core/client_wrapper.py b/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/core/client_wrapper.py index 8d01b584b82..d037184a816 100644 --- a/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/core/client_wrapper.py +++ b/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/core/client_wrapper.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .http_client import AsyncHttpClient, HttpClient +from .http_client import HttpClient +from .http_client import AsyncHttpClient class BaseClientWrapper: diff --git a/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/core/datetime_utils.py b/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/core/datetime_utils.py +++ b/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/core/file.py b/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/core/file.py index cb0d40bbbf3..6e0f92bfcb1 100644 --- a/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/core/file.py +++ b/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/core/file.py @@ -13,12 +13,17 @@ # (filename, file (or bytes), content_type) typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str]], # (filename, file (or bytes), content_type, headers) - typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str], typing.Mapping[str, str]], + typing.Tuple[ + typing.Optional[str], + FileContent, + typing.Optional[str], + typing.Mapping[str, str], + ], ] def convert_file_dict_to_httpx_tuples( - d: typing.Dict[str, typing.Union[File, typing.List[File]]] + d: typing.Dict[str, typing.Union[File, typing.List[File]]], ) -> typing.List[typing.Tuple[str, File]]: """ The format we use is a list of tuples, where the first element is the diff --git a/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/core/http_client.py b/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/core/http_client.py index 9333d8a7f15..091f71bc185 100644 --- a/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/core/http_client.py +++ b/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/core/http_client.py @@ -77,7 +77,9 @@ def _retry_timeout(response: httpx.Response, retries: int) -> float: return retry_after # Apply exponential backoff, capped at MAX_RETRY_DELAY_SECONDS. - retry_delay = min(INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS) + retry_delay = min( + INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS + ) # Add a randomness / jitter to the retry delay to avoid overwhelming the server with retries. timeout = retry_delay * (1 - 0.25 * random()) @@ -90,7 +92,8 @@ def _should_retry(response: httpx.Response) -> bool: def remove_omit_from_dict( - original: typing.Dict[str, typing.Optional[typing.Any]], omit: typing.Optional[typing.Any] + original: typing.Dict[str, typing.Optional[typing.Any]], + omit: typing.Optional[typing.Any], ) -> typing.Dict[str, typing.Any]: if omit is None: return original @@ -108,7 +111,8 @@ def maybe_filter_request_body( ) -> typing.Optional[typing.Any]: if data is None: return ( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else None ) @@ -118,7 +122,8 @@ def maybe_filter_request_body( data_content = { **(jsonable_encoder(remove_omit_from_dict(data, omit))), # type: ignore **( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else {} ), @@ -162,7 +167,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url def request( @@ -174,8 +181,12 @@ def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -184,11 +195,14 @@ def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) response = self.httpx_client.request( method=method, @@ -198,7 +212,11 @@ def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -209,7 +227,10 @@ def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -222,11 +243,15 @@ def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: time.sleep(_retry_timeout(response=response, retries=retries)) @@ -256,8 +281,12 @@ def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -266,11 +295,14 @@ def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) with self.httpx_client.stream( method=method, @@ -280,7 +312,11 @@ def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -291,7 +327,9 @@ def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -304,7 +342,9 @@ def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream @@ -327,7 +367,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url async def request( @@ -339,8 +381,12 @@ async def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -349,11 +395,14 @@ async def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) # Add the input to each of these and do None-safety checks response = await self.httpx_client.request( @@ -364,7 +413,11 @@ async def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -375,7 +428,10 @@ async def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -388,11 +444,15 @@ async def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: await asyncio.sleep(_retry_timeout(response=response, retries=retries)) @@ -421,8 +481,12 @@ async def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -431,11 +495,14 @@ async def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) async with self.httpx_client.stream( method=method, @@ -445,7 +512,11 @@ async def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -456,7 +527,9 @@ async def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -469,7 +542,9 @@ async def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream diff --git a/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/core/jsonable_encoder.py b/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/core/jsonable_encoder.py index d3fd328fd41..12a8b52fc22 100644 --- a/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/core/jsonable_encoder.py +++ b/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/core/jsonable_encoder.py @@ -19,13 +19,19 @@ import pydantic from .datetime_utils import serialize_datetime -from .pydantic_utilities import IS_PYDANTIC_V2, encode_by_type, to_jsonable_with_fallback +from .pydantic_utilities import ( + IS_PYDANTIC_V2, + encode_by_type, + to_jsonable_with_fallback, +) SetIntStr = Set[Union[int, str]] DictIntStrAny = Dict[Union[int, str], Any] -def jsonable_encoder(obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None) -> Any: +def jsonable_encoder( + obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None +) -> Any: custom_encoder = custom_encoder or {} if custom_encoder: if type(obj) in custom_encoder: diff --git a/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/core/pydantic_utilities.py b/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/core/pydantic_utilities.py index 170a563d6eb..c63935c32a2 100644 --- a/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/core/pydantic_utilities.py +++ b/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) # type: ignore # Pydantic v1 diff --git a/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/core/query_encoder.py b/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/core/query_encoder.py index 24076d72ee9..7cb98f52cd7 100644 --- a/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/core/query_encoder.py +++ b/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/core/query_encoder.py @@ -7,7 +7,9 @@ # Flattens dicts to be of the form {"key[subkey][subkey2]": value} where value is not a dict -def traverse_query_dict(dict_flat: Dict[str, Any], key_prefix: Optional[str] = None) -> Dict[str, Any]: +def traverse_query_dict( + dict_flat: Dict[str, Any], key_prefix: Optional[str] = None +) -> Dict[str, Any]: result = {} for k, v in dict_flat.items(): key = f"{key_prefix}[{k}]" if key_prefix is not None else k @@ -30,4 +32,8 @@ def single_query_encoder(query_key: str, query_value: Any) -> Dict[str, Any]: def encode_query(query: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: - return dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) if query is not None else None + return ( + dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) + if query is not None + else None + ) diff --git a/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/core/serialization.py b/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/core/serialization.py +++ b/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/core/unchecked_base_model.py b/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/core/unchecked_base_model.py index 401cc513bd1..c5e3ed36f22 100644 --- a/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/core/unchecked_base_model.py +++ b/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/core/unchecked_base_model.py @@ -5,10 +5,11 @@ import typing import uuid -import pydantic import typing_extensions from pydantic_core import PydanticUndefined +import pydantic + from .pydantic_utilities import ( IS_PYDANTIC_V2, ModelField, @@ -35,7 +36,9 @@ def __init__(self, *, discriminant: str) -> None: class UncheckedBaseModel(UniversalBaseModel): if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -43,7 +46,9 @@ class Config: @classmethod def model_construct( - cls: typing.Type["Model"], _fields_set: typing.Optional[typing.Set[str]] = None, **values: typing.Any + cls: typing.Type["Model"], + _fields_set: typing.Optional[typing.Set[str]] = None, + **values: typing.Any, ) -> "Model": # Fallback construct function to the specified override below. return cls.construct(_fields_set=_fields_set, **values) @@ -52,7 +57,9 @@ def model_construct( # Implementation taken from: https://github.com/pydantic/pydantic/issues/1168#issuecomment-817742836 @classmethod def construct( - cls: typing.Type["Model"], _fields_set: typing.Optional[typing.Set[str]] = None, **values: typing.Any + cls: typing.Type["Model"], + _fields_set: typing.Optional[typing.Set[str]] = None, + **values: typing.Any, ) -> "Model": m = cls.__new__(cls) fields_values = {} @@ -68,7 +75,9 @@ def construct( # you should always use the NAME of the field to for field_values, etc. # because that's how the object is constructed from a pydantic perspective key = field.alias - if key is None or (key not in values and populate_by_name): # Added this to allow population by field name + if key is None or ( + key not in values and populate_by_name + ): # Added this to allow population by field name key = name if key in values: @@ -78,7 +87,9 @@ def construct( type_ = typing.cast(typing.Type, field.outer_type_) # type: ignore # Pydantic < v1.10.15 fields_values[name] = ( - construct_type(object_=values[key], type_=type_) if type_ is not None else values[key] + construct_type(object_=values[key], type_=type_) + if type_ is not None + else values[key] ) _fields_set.add(name) else: @@ -114,14 +125,18 @@ def construct( return m -def _convert_undiscriminated_union_type(union_type: typing.Type[typing.Any], object_: typing.Any) -> typing.Any: +def _convert_undiscriminated_union_type( + union_type: typing.Type[typing.Any], object_: typing.Any +) -> typing.Any: inner_types = get_args(union_type) if typing.Any in inner_types: return object_ for inner_type in inner_types: try: - if inspect.isclass(inner_type) and issubclass(inner_type, pydantic.BaseModel): + if inspect.isclass(inner_type) and issubclass( + inner_type, pydantic.BaseModel + ): # Attempt a validated parse until one works return parse_obj_as(inner_type, object_) except Exception: @@ -135,7 +150,9 @@ def _convert_undiscriminated_union_type(union_type: typing.Type[typing.Any], obj continue -def _convert_union_type(type_: typing.Type[typing.Any], object_: typing.Any) -> typing.Any: +def _convert_union_type( + type_: typing.Type[typing.Any], object_: typing.Any +) -> typing.Any: base_type = get_origin(type_) or type_ union_type = type_ if base_type == typing_extensions.Annotated: @@ -147,10 +164,15 @@ def _convert_union_type(type_: typing.Type[typing.Any], object_: typing.Any) -> # Cast to the correct type, based on the discriminant for inner_type in get_args(union_type): try: - objects_discriminant = getattr(object_, metadata.discriminant) + objects_discriminant = getattr( + object_, metadata.discriminant + ) except: objects_discriminant = object_[metadata.discriminant] - if inner_type.__fields__[metadata.discriminant].default == objects_discriminant: + if ( + inner_type.__fields__[metadata.discriminant].default + == objects_discriminant + ): return construct_type(object_=object_, type_=inner_type) except Exception: # Allow to fall through to our regular union handling @@ -158,7 +180,9 @@ def _convert_union_type(type_: typing.Type[typing.Any], object_: typing.Any) -> return _convert_undiscriminated_union_type(union_type, object_) -def construct_type(*, type_: typing.Type[typing.Any], object_: typing.Any) -> typing.Any: +def construct_type( + *, type_: typing.Type[typing.Any], object_: typing.Any +) -> typing.Any: """ Here we are essentially creating the same `construct` method in spirit as the above, but for all types, not just Pydantic models. @@ -171,7 +195,9 @@ def construct_type(*, type_: typing.Type[typing.Any], object_: typing.Any) -> ty base_type = get_origin(type_) or type_ is_annotated = base_type == typing_extensions.Annotated maybe_annotation_members = get_args(type_) - is_annotated_union = is_annotated and is_union(get_origin(maybe_annotation_members[0])) + is_annotated_union = is_annotated and is_union( + get_origin(maybe_annotation_members[0]) + ) if base_type == typing.Any: return object_ @@ -182,7 +208,9 @@ def construct_type(*, type_: typing.Type[typing.Any], object_: typing.Any) -> ty key_type, items_type = get_args(type_) d = { - construct_type(object_=key, type_=key_type): construct_type(object_=item, type_=items_type) + construct_type(object_=key, type_=key_type): construct_type( + object_=item, type_=items_type + ) for key, item in object_.items() } return d @@ -263,7 +291,9 @@ def _get_is_populate_by_name(model: typing.Type["Model"]) -> bool: # Pydantic V1 swapped the typing of __fields__'s values from ModelField to FieldInfo # And so we try to handle both V1 cases, as well as V2 (FieldInfo from model.model_fields) -def _get_model_fields(model: typing.Type["Model"]) -> typing.Mapping[str, PydanticField]: +def _get_model_fields( + model: typing.Type["Model"], +) -> typing.Mapping[str, PydanticField]: if IS_PYDANTIC_V2: return model.model_fields # type: ignore # Pydantic v2 else: diff --git a/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/endpoints/__init__.py b/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/endpoints/__init__.py index 92307cab7fe..a9496ece178 100644 --- a/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/endpoints/__init__.py +++ b/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/endpoints/__init__.py @@ -2,4 +2,12 @@ from . import container, enum, http_methods, object, params, primitive, union -__all__ = ["container", "enum", "http_methods", "object", "params", "primitive", "union"] +__all__ = [ + "container", + "enum", + "http_methods", + "object", + "params", + "primitive", + "union", +] diff --git a/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/endpoints/client.py b/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/endpoints/client.py index 18dc397fdf1..69930de54d7 100644 --- a/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/endpoints/client.py +++ b/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/endpoints/client.py @@ -1,13 +1,21 @@ # This file was auto-generated by Fern from our API Definition. -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from .container.client import AsyncContainerClient, ContainerClient -from .enum.client import AsyncEnumClient, EnumClient -from .http_methods.client import AsyncHttpMethodsClient, HttpMethodsClient -from .object.client import AsyncObjectClient, ObjectClient -from .params.client import AsyncParamsClient, ParamsClient -from .primitive.client import AsyncPrimitiveClient, PrimitiveClient -from .union.client import AsyncUnionClient, UnionClient +from ..core.client_wrapper import SyncClientWrapper +from .container.client import ContainerClient +from .enum.client import EnumClient +from .http_methods.client import HttpMethodsClient +from .object.client import ObjectClient +from .params.client import ParamsClient +from .primitive.client import PrimitiveClient +from .union.client import UnionClient +from ..core.client_wrapper import AsyncClientWrapper +from .container.client import AsyncContainerClient +from .enum.client import AsyncEnumClient +from .http_methods.client import AsyncHttpMethodsClient +from .object.client import AsyncObjectClient +from .params.client import AsyncParamsClient +from .primitive.client import AsyncPrimitiveClient +from .union.client import AsyncUnionClient class EndpointsClient: diff --git a/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/endpoints/container/client.py b/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/endpoints/container/client.py index 5487de73783..86c216edf71 100644 --- a/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/endpoints/container/client.py +++ b/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/endpoints/container/client.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. import typing -from json.decoder import JSONDecodeError - -from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper +from ...core.client_wrapper import SyncClientWrapper from ...core.request_options import RequestOptions from ...core.unchecked_base_model import construct_type +from json.decoder import JSONDecodeError +from ...core.api_error import ApiError from ...types.object.types.object_with_required_field import ObjectWithRequiredField +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -18,7 +18,10 @@ def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper def get_and_return_list_of_primitives( - self, *, request: typing.Sequence[str], request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Sequence[str], + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[str]: """ Parameters @@ -45,11 +48,18 @@ def get_and_return_list_of_primitives( ) """ _response = self._client_wrapper.httpx_client.request( - "container/list-of-primitives", method="POST", json=request, request_options=request_options, omit=OMIT + "container/list-of-primitives", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.List[str], construct_type(type_=typing.List[str], object_=_response.json())) # type: ignore + return typing.cast( + typing.List[str], + construct_type(type_=typing.List[str], object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -59,7 +69,7 @@ def get_and_return_list_of_objects( self, *, request: typing.Sequence[ObjectWithRequiredField], - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[ObjectWithRequiredField]: """ Parameters @@ -91,18 +101,31 @@ def get_and_return_list_of_objects( ) """ _response = self._client_wrapper.httpx_client.request( - "container/list-of-objects", method="POST", json=request, request_options=request_options, omit=OMIT + "container/list-of-objects", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.List[ObjectWithRequiredField], construct_type(type_=typing.List[ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.List[ObjectWithRequiredField], + construct_type( + type_=typing.List[ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_and_return_set_of_primitives( - self, *, request: typing.Set[str], request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Set[str], + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Set[str]: """ Parameters @@ -129,11 +152,18 @@ def get_and_return_set_of_primitives( ) """ _response = self._client_wrapper.httpx_client.request( - "container/set-of-primitives", method="POST", json=request, request_options=request_options, omit=OMIT + "container/set-of-primitives", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Set[str], construct_type(type_=typing.Set[str], object_=_response.json())) # type: ignore + return typing.cast( + typing.Set[str], + construct_type(type_=typing.Set[str], object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -143,7 +173,7 @@ def get_and_return_set_of_objects( self, *, request: typing.Sequence[ObjectWithRequiredField], - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[ObjectWithRequiredField]: """ Parameters @@ -175,18 +205,31 @@ def get_and_return_set_of_objects( ) """ _response = self._client_wrapper.httpx_client.request( - "container/set-of-objects", method="POST", json=request, request_options=request_options, omit=OMIT + "container/set-of-objects", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.List[ObjectWithRequiredField], construct_type(type_=typing.List[ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.List[ObjectWithRequiredField], + construct_type( + type_=typing.List[ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_and_return_map_prim_to_prim( - self, *, request: typing.Dict[str, str], request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Dict[str, str], + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Dict[str, str]: """ Parameters @@ -213,11 +256,20 @@ def get_and_return_map_prim_to_prim( ) """ _response = self._client_wrapper.httpx_client.request( - "container/map-prim-to-prim", method="POST", json=request, request_options=request_options, omit=OMIT + "container/map-prim-to-prim", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Dict[str, str], construct_type(type_=typing.Dict[str, str], object_=_response.json())) # type: ignore + return typing.cast( + typing.Dict[str, str], + construct_type( + type_=typing.Dict[str, str], object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -227,7 +279,7 @@ def get_and_return_map_of_prim_to_object( self, *, request: typing.Dict[str, ObjectWithRequiredField], - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Dict[str, ObjectWithRequiredField]: """ Parameters @@ -259,11 +311,21 @@ def get_and_return_map_of_prim_to_object( ) """ _response = self._client_wrapper.httpx_client.request( - "container/map-prim-to-object", method="POST", json=request, request_options=request_options, omit=OMIT + "container/map-prim-to-object", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Dict[str, ObjectWithRequiredField], construct_type(type_=typing.Dict[str, ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.Dict[str, ObjectWithRequiredField], + construct_type( + type_=typing.Dict[str, ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -273,7 +335,7 @@ def get_and_return_optional( self, *, request: typing.Optional[ObjectWithRequiredField] = None, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Optional[ObjectWithRequiredField]: """ Parameters @@ -303,11 +365,21 @@ def get_and_return_optional( ) """ _response = self._client_wrapper.httpx_client.request( - "container/opt-objects", method="POST", json=request, request_options=request_options, omit=OMIT + "container/opt-objects", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Optional[ObjectWithRequiredField], construct_type(type_=typing.Optional[ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.Optional[ObjectWithRequiredField], + construct_type( + type_=typing.Optional[ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -319,7 +391,10 @@ def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper async def get_and_return_list_of_primitives( - self, *, request: typing.Sequence[str], request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Sequence[str], + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[str]: """ Parameters @@ -354,11 +429,18 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/list-of-primitives", method="POST", json=request, request_options=request_options, omit=OMIT + "container/list-of-primitives", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.List[str], construct_type(type_=typing.List[str], object_=_response.json())) # type: ignore + return typing.cast( + typing.List[str], + construct_type(type_=typing.List[str], object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -368,7 +450,7 @@ async def get_and_return_list_of_objects( self, *, request: typing.Sequence[ObjectWithRequiredField], - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[ObjectWithRequiredField]: """ Parameters @@ -408,18 +490,31 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/list-of-objects", method="POST", json=request, request_options=request_options, omit=OMIT + "container/list-of-objects", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.List[ObjectWithRequiredField], construct_type(type_=typing.List[ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.List[ObjectWithRequiredField], + construct_type( + type_=typing.List[ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_and_return_set_of_primitives( - self, *, request: typing.Set[str], request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Set[str], + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Set[str]: """ Parameters @@ -454,11 +549,18 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/set-of-primitives", method="POST", json=request, request_options=request_options, omit=OMIT + "container/set-of-primitives", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Set[str], construct_type(type_=typing.Set[str], object_=_response.json())) # type: ignore + return typing.cast( + typing.Set[str], + construct_type(type_=typing.Set[str], object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -468,7 +570,7 @@ async def get_and_return_set_of_objects( self, *, request: typing.Sequence[ObjectWithRequiredField], - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[ObjectWithRequiredField]: """ Parameters @@ -508,18 +610,31 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/set-of-objects", method="POST", json=request, request_options=request_options, omit=OMIT + "container/set-of-objects", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.List[ObjectWithRequiredField], construct_type(type_=typing.List[ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.List[ObjectWithRequiredField], + construct_type( + type_=typing.List[ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_and_return_map_prim_to_prim( - self, *, request: typing.Dict[str, str], request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Dict[str, str], + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Dict[str, str]: """ Parameters @@ -554,11 +669,20 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/map-prim-to-prim", method="POST", json=request, request_options=request_options, omit=OMIT + "container/map-prim-to-prim", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Dict[str, str], construct_type(type_=typing.Dict[str, str], object_=_response.json())) # type: ignore + return typing.cast( + typing.Dict[str, str], + construct_type( + type_=typing.Dict[str, str], object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -568,7 +692,7 @@ async def get_and_return_map_of_prim_to_object( self, *, request: typing.Dict[str, ObjectWithRequiredField], - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Dict[str, ObjectWithRequiredField]: """ Parameters @@ -608,11 +732,21 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/map-prim-to-object", method="POST", json=request, request_options=request_options, omit=OMIT + "container/map-prim-to-object", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Dict[str, ObjectWithRequiredField], construct_type(type_=typing.Dict[str, ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.Dict[str, ObjectWithRequiredField], + construct_type( + type_=typing.Dict[str, ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -622,7 +756,7 @@ async def get_and_return_optional( self, *, request: typing.Optional[ObjectWithRequiredField] = None, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Optional[ObjectWithRequiredField]: """ Parameters @@ -660,11 +794,21 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/opt-objects", method="POST", json=request, request_options=request_options, omit=OMIT + "container/opt-objects", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Optional[ObjectWithRequiredField], construct_type(type_=typing.Optional[ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.Optional[ObjectWithRequiredField], + construct_type( + type_=typing.Optional[ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/endpoints/enum/client.py b/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/endpoints/enum/client.py index 310bf8f7e1c..fa144f63dd4 100644 --- a/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/endpoints/enum/client.py +++ b/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/endpoints/enum/client.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. import typing -from json.decoder import JSONDecodeError - -from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper +from ...core.client_wrapper import SyncClientWrapper +from ...types.enum.types.weather_report import WeatherReport from ...core.request_options import RequestOptions from ...core.unchecked_base_model import construct_type -from ...types.enum.types.weather_report import WeatherReport +from json.decoder import JSONDecodeError +from ...core.api_error import ApiError +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -18,7 +18,10 @@ def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper def get_and_return_enum( - self, *, request: WeatherReport, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: WeatherReport, + request_options: typing.Optional[RequestOptions] = None, ) -> WeatherReport: """ Parameters @@ -45,11 +48,18 @@ def get_and_return_enum( ) """ _response = self._client_wrapper.httpx_client.request( - "enum", method="POST", json=request, request_options=request_options, omit=OMIT + "enum", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(WeatherReport, construct_type(type_=WeatherReport, object_=_response.json())) # type: ignore + return typing.cast( + WeatherReport, + construct_type(type_=WeatherReport, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -61,7 +71,10 @@ def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper async def get_and_return_enum( - self, *, request: WeatherReport, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: WeatherReport, + request_options: typing.Optional[RequestOptions] = None, ) -> WeatherReport: """ Parameters @@ -96,11 +109,18 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "enum", method="POST", json=request, request_options=request_options, omit=OMIT + "enum", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(WeatherReport, construct_type(type_=WeatherReport, object_=_response.json())) # type: ignore + return typing.cast( + WeatherReport, + construct_type(type_=WeatherReport, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/endpoints/http_methods/client.py b/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/endpoints/http_methods/client.py index bd79db12edf..81c0059e1c7 100644 --- a/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/endpoints/http_methods/client.py +++ b/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/endpoints/http_methods/client.py @@ -1,16 +1,16 @@ # This file was auto-generated by Fern from our API Definition. -import datetime as dt import typing -import uuid -from json.decoder import JSONDecodeError - -from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ...core.jsonable_encoder import jsonable_encoder +from ...core.client_wrapper import SyncClientWrapper from ...core.request_options import RequestOptions +from ...core.jsonable_encoder import jsonable_encoder from ...core.unchecked_base_model import construct_type +from json.decoder import JSONDecodeError +from ...core.api_error import ApiError from ...types.object.types.object_with_optional_field import ObjectWithOptionalField +import datetime as dt +import uuid +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -20,7 +20,9 @@ class HttpMethodsClient: def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper - def test_get(self, id: str, *, request_options: typing.Optional[RequestOptions] = None) -> str: + def test_get( + self, id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -46,11 +48,15 @@ def test_get(self, id: str, *, request_options: typing.Optional[RequestOptions] ) """ _response = self._client_wrapper.httpx_client.request( - f"http-methods/{jsonable_encoder(id)}", method="GET", request_options=request_options + f"http-methods/{jsonable_encoder(id)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, construct_type(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, construct_type(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -84,18 +90,33 @@ def test_post( ) """ _response = self._client_wrapper.httpx_client.request( - "http-methods", method="POST", json={"string": string}, request_options=request_options, omit=OMIT + "http-methods", + method="POST", + json={ + "string": string, + }, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, construct_type(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + construct_type( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def test_put( - self, id: str, *, string: str, request_options: typing.Optional[RequestOptions] = None + self, + id: str, + *, + string: str, + request_options: typing.Optional[RequestOptions] = None, ) -> ObjectWithOptionalField: """ Parameters @@ -127,13 +148,20 @@ def test_put( _response = self._client_wrapper.httpx_client.request( f"http-methods/{jsonable_encoder(id)}", method="PUT", - json={"string": string}, + json={ + "string": string, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, construct_type(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + construct_type( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -254,13 +282,20 @@ def test_patch( ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, construct_type(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + construct_type( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def test_delete(self, id: str, *, request_options: typing.Optional[RequestOptions] = None) -> bool: + def test_delete( + self, id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> bool: """ Parameters ---------- @@ -286,11 +321,15 @@ def test_delete(self, id: str, *, request_options: typing.Optional[RequestOption ) """ _response = self._client_wrapper.httpx_client.request( - f"http-methods/{jsonable_encoder(id)}", method="DELETE", request_options=request_options + f"http-methods/{jsonable_encoder(id)}", + method="DELETE", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, construct_type(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, construct_type(type_=bool, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -301,7 +340,9 @@ class AsyncHttpMethodsClient: def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper - async def test_get(self, id: str, *, request_options: typing.Optional[RequestOptions] = None) -> str: + async def test_get( + self, id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -335,11 +376,15 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - f"http-methods/{jsonable_encoder(id)}", method="GET", request_options=request_options + f"http-methods/{jsonable_encoder(id)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, construct_type(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, construct_type(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -381,18 +426,33 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "http-methods", method="POST", json={"string": string}, request_options=request_options, omit=OMIT + "http-methods", + method="POST", + json={ + "string": string, + }, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, construct_type(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + construct_type( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def test_put( - self, id: str, *, string: str, request_options: typing.Optional[RequestOptions] = None + self, + id: str, + *, + string: str, + request_options: typing.Optional[RequestOptions] = None, ) -> ObjectWithOptionalField: """ Parameters @@ -432,13 +492,20 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( f"http-methods/{jsonable_encoder(id)}", method="PUT", - json={"string": string}, + json={ + "string": string, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, construct_type(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + construct_type( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -566,13 +633,20 @@ async def main() -> None: ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, construct_type(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + construct_type( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - async def test_delete(self, id: str, *, request_options: typing.Optional[RequestOptions] = None) -> bool: + async def test_delete( + self, id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> bool: """ Parameters ---------- @@ -606,11 +680,15 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - f"http-methods/{jsonable_encoder(id)}", method="DELETE", request_options=request_options + f"http-methods/{jsonable_encoder(id)}", + method="DELETE", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, construct_type(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, construct_type(type_=bool, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/endpoints/object/client.py b/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/endpoints/object/client.py index e0a1a0b774f..bb48fc80100 100644 --- a/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/endpoints/object/client.py +++ b/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/endpoints/object/client.py @@ -1,20 +1,24 @@ # This file was auto-generated by Fern from our API Definition. -import datetime as dt import typing +from ...core.client_wrapper import SyncClientWrapper +import datetime as dt import uuid -from json.decoder import JSONDecodeError - -from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ...core.jsonable_encoder import jsonable_encoder from ...core.request_options import RequestOptions -from ...core.unchecked_base_model import construct_type -from ...types.object.types.nested_object_with_optional_field import NestedObjectWithOptionalField -from ...types.object.types.nested_object_with_required_field import NestedObjectWithRequiredField -from ...types.object.types.object_with_map_of_map import ObjectWithMapOfMap from ...types.object.types.object_with_optional_field import ObjectWithOptionalField +from ...core.unchecked_base_model import construct_type +from json.decoder import JSONDecodeError +from ...core.api_error import ApiError from ...types.object.types.object_with_required_field import ObjectWithRequiredField +from ...types.object.types.object_with_map_of_map import ObjectWithMapOfMap +from ...types.object.types.nested_object_with_optional_field import ( + NestedObjectWithOptionalField, +) +from ...types.object.types.nested_object_with_required_field import ( + NestedObjectWithRequiredField, +) +from ...core.jsonable_encoder import jsonable_encoder +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -135,7 +139,12 @@ def get_and_return_with_optional_field( ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, construct_type(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + construct_type( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -171,20 +180,30 @@ def get_and_return_with_required_field( _response = self._client_wrapper.httpx_client.request( "object/get-and-return-with-required-field", method="POST", - json={"string": string}, + json={ + "string": string, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithRequiredField, construct_type(type_=ObjectWithRequiredField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithRequiredField, + construct_type( + type_=ObjectWithRequiredField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_and_return_with_map_of_map( - self, *, map_: typing.Dict[str, typing.Dict[str, str]], request_options: typing.Optional[RequestOptions] = None + self, + *, + map_: typing.Dict[str, typing.Dict[str, str]], + request_options: typing.Optional[RequestOptions] = None, ) -> ObjectWithMapOfMap: """ Parameters @@ -213,13 +232,18 @@ def get_and_return_with_map_of_map( _response = self._client_wrapper.httpx_client.request( "object/get-and-return-with-map-of-map", method="POST", - json={"map": map_}, + json={ + "map": map_, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithMapOfMap, construct_type(type_=ObjectWithMapOfMap, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithMapOfMap, + construct_type(type_=ObjectWithMapOfMap, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -286,13 +310,21 @@ def get_and_return_nested_with_optional_field( _response = self._client_wrapper.httpx_client.request( "object/get-and-return-nested-with-optional-field", method="POST", - json={"string": string, "NestedObject": nested_object}, + json={ + "string": string, + "NestedObject": nested_object, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(NestedObjectWithOptionalField, construct_type(type_=NestedObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + NestedObjectWithOptionalField, + construct_type( + type_=NestedObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -363,13 +395,21 @@ def get_and_return_nested_with_required_field( _response = self._client_wrapper.httpx_client.request( f"object/get-and-return-nested-with-required-field/{jsonable_encoder(string_)}", method="POST", - json={"string": string, "NestedObject": nested_object}, + json={ + "string": string, + "NestedObject": nested_object, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(NestedObjectWithRequiredField, construct_type(type_=NestedObjectWithRequiredField, object_=_response.json())) # type: ignore + return typing.cast( + NestedObjectWithRequiredField, + construct_type( + type_=NestedObjectWithRequiredField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -446,7 +486,12 @@ def get_and_return_nested_with_required_field_as_list( ) try: if 200 <= _response.status_code < 300: - return typing.cast(NestedObjectWithRequiredField, construct_type(type_=NestedObjectWithRequiredField, object_=_response.json())) # type: ignore + return typing.cast( + NestedObjectWithRequiredField, + construct_type( + type_=NestedObjectWithRequiredField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -575,7 +620,12 @@ async def main() -> None: ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, construct_type(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + construct_type( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -619,20 +669,30 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( "object/get-and-return-with-required-field", method="POST", - json={"string": string}, + json={ + "string": string, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithRequiredField, construct_type(type_=ObjectWithRequiredField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithRequiredField, + construct_type( + type_=ObjectWithRequiredField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_and_return_with_map_of_map( - self, *, map_: typing.Dict[str, typing.Dict[str, str]], request_options: typing.Optional[RequestOptions] = None + self, + *, + map_: typing.Dict[str, typing.Dict[str, str]], + request_options: typing.Optional[RequestOptions] = None, ) -> ObjectWithMapOfMap: """ Parameters @@ -669,13 +729,18 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( "object/get-and-return-with-map-of-map", method="POST", - json={"map": map_}, + json={ + "map": map_, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithMapOfMap, construct_type(type_=ObjectWithMapOfMap, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithMapOfMap, + construct_type(type_=ObjectWithMapOfMap, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -749,13 +814,21 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( "object/get-and-return-nested-with-optional-field", method="POST", - json={"string": string, "NestedObject": nested_object}, + json={ + "string": string, + "NestedObject": nested_object, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(NestedObjectWithOptionalField, construct_type(type_=NestedObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + NestedObjectWithOptionalField, + construct_type( + type_=NestedObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -833,13 +906,21 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( f"object/get-and-return-nested-with-required-field/{jsonable_encoder(string_)}", method="POST", - json={"string": string, "NestedObject": nested_object}, + json={ + "string": string, + "NestedObject": nested_object, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(NestedObjectWithRequiredField, construct_type(type_=NestedObjectWithRequiredField, object_=_response.json())) # type: ignore + return typing.cast( + NestedObjectWithRequiredField, + construct_type( + type_=NestedObjectWithRequiredField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -923,7 +1004,12 @@ async def main() -> None: ) try: if 200 <= _response.status_code < 300: - return typing.cast(NestedObjectWithRequiredField, construct_type(type_=NestedObjectWithRequiredField, object_=_response.json())) # type: ignore + return typing.cast( + NestedObjectWithRequiredField, + construct_type( + type_=NestedObjectWithRequiredField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/endpoints/params/client.py b/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/endpoints/params/client.py index 8c5977fc691..9008d154a11 100644 --- a/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/endpoints/params/client.py +++ b/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/endpoints/params/client.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. import typing -from json.decoder import JSONDecodeError - -from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ...core.jsonable_encoder import jsonable_encoder +from ...core.client_wrapper import SyncClientWrapper from ...core.request_options import RequestOptions +from ...core.jsonable_encoder import jsonable_encoder from ...core.unchecked_base_model import construct_type +from json.decoder import JSONDecodeError +from ...core.api_error import ApiError +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -17,7 +17,9 @@ class ParamsClient: def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper - def get_with_path(self, param: str, *, request_options: typing.Optional[RequestOptions] = None) -> str: + def get_with_path( + self, param: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ GET with path param @@ -45,18 +47,26 @@ def get_with_path(self, param: str, *, request_options: typing.Optional[RequestO ) """ _response = self._client_wrapper.httpx_client.request( - f"params/path/{jsonable_encoder(param)}", method="GET", request_options=request_options + f"params/path/{jsonable_encoder(param)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, construct_type(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, construct_type(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_with_query( - self, *, query: str, number: int, request_options: typing.Optional[RequestOptions] = None + self, + *, + query: str, + number: int, + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ GET with query param @@ -88,7 +98,13 @@ def get_with_query( ) """ _response = self._client_wrapper.httpx_client.request( - "params", method="GET", params={"query": query, "number": number}, request_options=request_options + "params", + method="GET", + params={ + "query": query, + "number": number, + }, + request_options=request_options, ) try: if 200 <= _response.status_code < 300: @@ -135,7 +151,13 @@ def get_with_allow_multiple_query( ) """ _response = self._client_wrapper.httpx_client.request( - "params", method="GET", params={"query": query, "numer": numer}, request_options=request_options + "params", + method="GET", + params={ + "query": query, + "numer": numer, + }, + request_options=request_options, ) try: if 200 <= _response.status_code < 300: @@ -146,7 +168,11 @@ def get_with_allow_multiple_query( raise ApiError(status_code=_response.status_code, body=_response_json) def get_with_path_and_query( - self, param: str, *, query: str, request_options: typing.Optional[RequestOptions] = None + self, + param: str, + *, + query: str, + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ GET with path and query params @@ -180,7 +206,9 @@ def get_with_path_and_query( _response = self._client_wrapper.httpx_client.request( f"params/path-query/{jsonable_encoder(param)}", method="GET", - params={"query": query}, + params={ + "query": query, + }, request_options=request_options, ) try: @@ -192,7 +220,11 @@ def get_with_path_and_query( raise ApiError(status_code=_response.status_code, body=_response_json) def modify_with_path( - self, param: str, *, request: str, request_options: typing.Optional[RequestOptions] = None + self, + param: str, + *, + request: str, + request_options: typing.Optional[RequestOptions] = None, ) -> str: """ PUT to update with path param @@ -232,7 +264,9 @@ def modify_with_path( ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, construct_type(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, construct_type(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -243,7 +277,9 @@ class AsyncParamsClient: def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper - async def get_with_path(self, param: str, *, request_options: typing.Optional[RequestOptions] = None) -> str: + async def get_with_path( + self, param: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ GET with path param @@ -279,18 +315,26 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - f"params/path/{jsonable_encoder(param)}", method="GET", request_options=request_options + f"params/path/{jsonable_encoder(param)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, construct_type(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, construct_type(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_with_query( - self, *, query: str, number: int, request_options: typing.Optional[RequestOptions] = None + self, + *, + query: str, + number: int, + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ GET with query param @@ -330,7 +374,13 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "params", method="GET", params={"query": query, "number": number}, request_options=request_options + "params", + method="GET", + params={ + "query": query, + "number": number, + }, + request_options=request_options, ) try: if 200 <= _response.status_code < 300: @@ -385,7 +435,13 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "params", method="GET", params={"query": query, "numer": numer}, request_options=request_options + "params", + method="GET", + params={ + "query": query, + "numer": numer, + }, + request_options=request_options, ) try: if 200 <= _response.status_code < 300: @@ -396,7 +452,11 @@ async def main() -> None: raise ApiError(status_code=_response.status_code, body=_response_json) async def get_with_path_and_query( - self, param: str, *, query: str, request_options: typing.Optional[RequestOptions] = None + self, + param: str, + *, + query: str, + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ GET with path and query params @@ -438,7 +498,9 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( f"params/path-query/{jsonable_encoder(param)}", method="GET", - params={"query": query}, + params={ + "query": query, + }, request_options=request_options, ) try: @@ -450,7 +512,11 @@ async def main() -> None: raise ApiError(status_code=_response.status_code, body=_response_json) async def modify_with_path( - self, param: str, *, request: str, request_options: typing.Optional[RequestOptions] = None + self, + param: str, + *, + request: str, + request_options: typing.Optional[RequestOptions] = None, ) -> str: """ PUT to update with path param @@ -498,7 +564,9 @@ async def main() -> None: ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, construct_type(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, construct_type(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/endpoints/primitive/client.py b/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/endpoints/primitive/client.py index 1f294713406..941e9765df7 100644 --- a/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/endpoints/primitive/client.py +++ b/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/endpoints/primitive/client.py @@ -1,14 +1,14 @@ # This file was auto-generated by Fern from our API Definition. -import datetime as dt import typing -import uuid -from json.decoder import JSONDecodeError - -from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper +from ...core.client_wrapper import SyncClientWrapper from ...core.request_options import RequestOptions from ...core.unchecked_base_model import construct_type +from json.decoder import JSONDecodeError +from ...core.api_error import ApiError +import datetime as dt +import uuid +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -18,7 +18,9 @@ class PrimitiveClient: def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper - def get_and_return_string(self, *, request: str, request_options: typing.Optional[RequestOptions] = None) -> str: + def get_and_return_string( + self, *, request: str, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -44,17 +46,25 @@ def get_and_return_string(self, *, request: str, request_options: typing.Optiona ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/string", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/string", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, construct_type(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, construct_type(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def get_and_return_int(self, *, request: int, request_options: typing.Optional[RequestOptions] = None) -> int: + def get_and_return_int( + self, *, request: int, request_options: typing.Optional[RequestOptions] = None + ) -> int: """ Parameters ---------- @@ -80,17 +90,25 @@ def get_and_return_int(self, *, request: int, request_options: typing.Optional[R ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/integer", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/integer", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(int, construct_type(type_=int, object_=_response.json())) # type: ignore + return typing.cast( + int, construct_type(type_=int, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def get_and_return_long(self, *, request: int, request_options: typing.Optional[RequestOptions] = None) -> int: + def get_and_return_long( + self, *, request: int, request_options: typing.Optional[RequestOptions] = None + ) -> int: """ Parameters ---------- @@ -116,11 +134,17 @@ def get_and_return_long(self, *, request: int, request_options: typing.Optional[ ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/long", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/long", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(int, construct_type(type_=int, object_=_response.json())) # type: ignore + return typing.cast( + int, construct_type(type_=int, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -154,17 +178,25 @@ def get_and_return_double( ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/double", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/double", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(float, construct_type(type_=float, object_=_response.json())) # type: ignore + return typing.cast( + float, construct_type(type_=float, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def get_and_return_bool(self, *, request: bool, request_options: typing.Optional[RequestOptions] = None) -> bool: + def get_and_return_bool( + self, *, request: bool, request_options: typing.Optional[RequestOptions] = None + ) -> bool: """ Parameters ---------- @@ -190,18 +222,27 @@ def get_and_return_bool(self, *, request: bool, request_options: typing.Optional ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/boolean", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/boolean", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, construct_type(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, construct_type(type_=bool, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_and_return_datetime( - self, *, request: dt.datetime, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: dt.datetime, + request_options: typing.Optional[RequestOptions] = None, ) -> dt.datetime: """ Parameters @@ -232,18 +273,28 @@ def get_and_return_datetime( ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/datetime", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/datetime", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(dt.datetime, construct_type(type_=dt.datetime, object_=_response.json())) # type: ignore + return typing.cast( + dt.datetime, + construct_type(type_=dt.datetime, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_and_return_date( - self, *, request: dt.date, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: dt.date, + request_options: typing.Optional[RequestOptions] = None, ) -> dt.date: """ Parameters @@ -274,18 +325,27 @@ def get_and_return_date( ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/date", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/date", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(dt.date, construct_type(type_=dt.date, object_=_response.json())) # type: ignore + return typing.cast( + dt.date, construct_type(type_=dt.date, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_and_return_uuid( - self, *, request: uuid.UUID, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: uuid.UUID, + request_options: typing.Optional[RequestOptions] = None, ) -> uuid.UUID: """ Parameters @@ -316,17 +376,25 @@ def get_and_return_uuid( ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/uuid", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/uuid", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(uuid.UUID, construct_type(type_=uuid.UUID, object_=_response.json())) # type: ignore + return typing.cast( + uuid.UUID, construct_type(type_=uuid.UUID, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def get_and_return_base_64(self, *, request: str, request_options: typing.Optional[RequestOptions] = None) -> str: + def get_and_return_base_64( + self, *, request: str, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -352,11 +420,17 @@ def get_and_return_base_64(self, *, request: str, request_options: typing.Option ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/base64", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/base64", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, construct_type(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, construct_type(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -403,17 +477,25 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/string", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/string", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, construct_type(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, construct_type(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - async def get_and_return_int(self, *, request: int, request_options: typing.Optional[RequestOptions] = None) -> int: + async def get_and_return_int( + self, *, request: int, request_options: typing.Optional[RequestOptions] = None + ) -> int: """ Parameters ---------- @@ -447,11 +529,17 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/integer", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/integer", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(int, construct_type(type_=int, object_=_response.json())) # type: ignore + return typing.cast( + int, construct_type(type_=int, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -493,11 +581,17 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/long", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/long", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(int, construct_type(type_=int, object_=_response.json())) # type: ignore + return typing.cast( + int, construct_type(type_=int, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -539,11 +633,17 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/double", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/double", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(float, construct_type(type_=float, object_=_response.json())) # type: ignore + return typing.cast( + float, construct_type(type_=float, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -585,18 +685,27 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/boolean", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/boolean", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, construct_type(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, construct_type(type_=bool, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_and_return_datetime( - self, *, request: dt.datetime, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: dt.datetime, + request_options: typing.Optional[RequestOptions] = None, ) -> dt.datetime: """ Parameters @@ -634,18 +743,28 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/datetime", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/datetime", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(dt.datetime, construct_type(type_=dt.datetime, object_=_response.json())) # type: ignore + return typing.cast( + dt.datetime, + construct_type(type_=dt.datetime, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_and_return_date( - self, *, request: dt.date, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: dt.date, + request_options: typing.Optional[RequestOptions] = None, ) -> dt.date: """ Parameters @@ -683,18 +802,27 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/date", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/date", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(dt.date, construct_type(type_=dt.date, object_=_response.json())) # type: ignore + return typing.cast( + dt.date, construct_type(type_=dt.date, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_and_return_uuid( - self, *, request: uuid.UUID, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: uuid.UUID, + request_options: typing.Optional[RequestOptions] = None, ) -> uuid.UUID: """ Parameters @@ -732,11 +860,17 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/uuid", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/uuid", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(uuid.UUID, construct_type(type_=uuid.UUID, object_=_response.json())) # type: ignore + return typing.cast( + uuid.UUID, construct_type(type_=uuid.UUID, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -778,11 +912,17 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/base64", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/base64", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, construct_type(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, construct_type(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/endpoints/union/client.py b/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/endpoints/union/client.py index a57a26e2da6..0cd6de7df6d 100644 --- a/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/endpoints/union/client.py +++ b/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/endpoints/union/client.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. import typing -from json.decoder import JSONDecodeError - -from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper +from ...core.client_wrapper import SyncClientWrapper +from ...types.union.types.animal import Animal from ...core.request_options import RequestOptions from ...core.unchecked_base_model import construct_type -from ...types.union.types.animal import Animal +from json.decoder import JSONDecodeError +from ...core.api_error import ApiError +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -18,7 +18,10 @@ def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper def get_and_return_union( - self, *, request: Animal, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: Animal, + request_options: typing.Optional[RequestOptions] = None, ) -> Animal: """ Parameters @@ -49,11 +52,17 @@ def get_and_return_union( ) """ _response = self._client_wrapper.httpx_client.request( - "union", method="POST", json=request, request_options=request_options, omit=OMIT + "union", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(Animal, construct_type(type_=Animal, object_=_response.json())) # type: ignore + return typing.cast( + Animal, construct_type(type_=Animal, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -65,7 +74,10 @@ def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper async def get_and_return_union( - self, *, request: Animal, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: Animal, + request_options: typing.Optional[RequestOptions] = None, ) -> Animal: """ Parameters @@ -104,11 +116,17 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "union", method="POST", json=request, request_options=request_options, omit=OMIT + "union", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(Animal, construct_type(type_=Animal, object_=_response.json())) # type: ignore + return typing.cast( + Animal, construct_type(type_=Animal, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/general_errors/types/bad_object_request_info.py b/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/general_errors/types/bad_object_request_info.py index 39b2e7cdbf1..c0468a69189 100644 --- a/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/general_errors/types/bad_object_request_info.py +++ b/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/general_errors/types/bad_object_request_info.py @@ -1,18 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.unchecked_base_model import UncheckedBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2 -from ...core.unchecked_base_model import UncheckedBaseModel - class BadObjectRequestInfo(UncheckedBaseModel): message: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/inlined_requests/client.py b/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/inlined_requests/client.py index e9d3db7ff66..2b993484538 100644 --- a/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/inlined_requests/client.py +++ b/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/inlined_requests/client.py @@ -1,15 +1,15 @@ # This file was auto-generated by Fern from our API Definition. import typing -from json.decoder import JSONDecodeError - -from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper +from ..core.client_wrapper import SyncClientWrapper +from ..types.object.types.object_with_optional_field import ObjectWithOptionalField from ..core.request_options import RequestOptions from ..core.unchecked_base_model import construct_type from ..general_errors.errors.bad_request_body import BadRequestBody from ..general_errors.types.bad_object_request_info import BadObjectRequestInfo -from ..types.object.types.object_with_optional_field import ObjectWithOptionalField +from json.decoder import JSONDecodeError +from ..core.api_error import ApiError +from ..core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -25,7 +25,7 @@ def post_with_object_bodyand_response( string: str, integer: int, nested_object: ObjectWithOptionalField, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> ObjectWithOptionalField: """ POST with custom object in request body, response is an object @@ -86,16 +86,30 @@ def post_with_object_bodyand_response( _response = self._client_wrapper.httpx_client.request( "req-bodies/object", method="POST", - json={"string": string, "integer": integer, "NestedObject": nested_object}, + json={ + "string": string, + "integer": integer, + "NestedObject": nested_object, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, construct_type(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + construct_type( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore if _response.status_code == 400: raise BadRequestBody( - typing.cast(BadObjectRequestInfo, construct_type(type_=BadObjectRequestInfo, object_=_response.json())) # type: ignore + typing.cast( + BadObjectRequestInfo, + construct_type( + type_=BadObjectRequestInfo, object_=_response.json() + ), + ) # type: ignore ) _response_json = _response.json() except JSONDecodeError: @@ -113,7 +127,7 @@ async def post_with_object_bodyand_response( string: str, integer: int, nested_object: ObjectWithOptionalField, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> ObjectWithOptionalField: """ POST with custom object in request body, response is an object @@ -181,16 +195,30 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( "req-bodies/object", method="POST", - json={"string": string, "integer": integer, "NestedObject": nested_object}, + json={ + "string": string, + "integer": integer, + "NestedObject": nested_object, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, construct_type(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + construct_type( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore if _response.status_code == 400: raise BadRequestBody( - typing.cast(BadObjectRequestInfo, construct_type(type_=BadObjectRequestInfo, object_=_response.json())) # type: ignore + typing.cast( + BadObjectRequestInfo, + construct_type( + type_=BadObjectRequestInfo, object_=_response.json() + ), + ) # type: ignore ) _response_json = _response.json() except JSONDecodeError: diff --git a/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/no_auth/client.py b/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/no_auth/client.py index 8119094c7f0..01b56c779ec 100644 --- a/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/no_auth/client.py +++ b/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/no_auth/client.py @@ -1,14 +1,14 @@ # This file was auto-generated by Fern from our API Definition. import typing -from json.decoder import JSONDecodeError - -from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper +from ..core.client_wrapper import SyncClientWrapper from ..core.request_options import RequestOptions from ..core.unchecked_base_model import construct_type from ..general_errors.errors.bad_request_body import BadRequestBody from ..general_errors.types.bad_object_request_info import BadObjectRequestInfo +from json.decoder import JSONDecodeError +from ..core.api_error import ApiError +from ..core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -19,7 +19,10 @@ def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper def post_with_no_auth( - self, *, request: typing.Any, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Any, + request_options: typing.Optional[RequestOptions] = None, ) -> bool: """ POST request with no auth @@ -48,14 +51,25 @@ def post_with_no_auth( ) """ _response = self._client_wrapper.httpx_client.request( - "no-auth", method="POST", json=request, request_options=request_options, omit=OMIT + "no-auth", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, construct_type(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, construct_type(type_=bool, object_=_response.json()) + ) # type: ignore if _response.status_code == 400: raise BadRequestBody( - typing.cast(BadObjectRequestInfo, construct_type(type_=BadObjectRequestInfo, object_=_response.json())) # type: ignore + typing.cast( + BadObjectRequestInfo, + construct_type( + type_=BadObjectRequestInfo, object_=_response.json() + ), + ) # type: ignore ) _response_json = _response.json() except JSONDecodeError: @@ -68,7 +82,10 @@ def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper async def post_with_no_auth( - self, *, request: typing.Any, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Any, + request_options: typing.Optional[RequestOptions] = None, ) -> bool: """ POST request with no auth @@ -105,14 +122,25 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "no-auth", method="POST", json=request, request_options=request_options, omit=OMIT + "no-auth", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, construct_type(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, construct_type(type_=bool, object_=_response.json()) + ) # type: ignore if _response.status_code == 400: raise BadRequestBody( - typing.cast(BadObjectRequestInfo, construct_type(type_=BadObjectRequestInfo, object_=_response.json())) # type: ignore + typing.cast( + BadObjectRequestInfo, + construct_type( + type_=BadObjectRequestInfo, object_=_response.json() + ), + ) # type: ignore ) _response_json = _response.json() except JSONDecodeError: diff --git a/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/no_req_body/client.py b/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/no_req_body/client.py index 891e0f63fb0..ba80233c096 100644 --- a/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/no_req_body/client.py +++ b/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/no_req_body/client.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. +from ..core.client_wrapper import SyncClientWrapper import typing -from json.decoder import JSONDecodeError - -from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper from ..core.request_options import RequestOptions -from ..core.unchecked_base_model import construct_type from ..types.object.types.object_with_optional_field import ObjectWithOptionalField +from ..core.unchecked_base_model import construct_type +from json.decoder import JSONDecodeError +from ..core.api_error import ApiError +from ..core.client_wrapper import AsyncClientWrapper class NoReqBodyClient: @@ -38,17 +38,26 @@ def get_with_no_request_body( client.no_req_body.get_with_no_request_body() """ _response = self._client_wrapper.httpx_client.request( - "no-req-body", method="GET", request_options=request_options + "no-req-body", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, construct_type(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + construct_type( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def post_with_no_request_body(self, *, request_options: typing.Optional[RequestOptions] = None) -> str: + def post_with_no_request_body( + self, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -70,11 +79,15 @@ def post_with_no_request_body(self, *, request_options: typing.Optional[RequestO client.no_req_body.post_with_no_request_body() """ _response = self._client_wrapper.httpx_client.request( - "no-req-body", method="POST", request_options=request_options + "no-req-body", + method="POST", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, construct_type(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, construct_type(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -117,17 +130,26 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "no-req-body", method="GET", request_options=request_options + "no-req-body", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, construct_type(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + construct_type( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - async def post_with_no_request_body(self, *, request_options: typing.Optional[RequestOptions] = None) -> str: + async def post_with_no_request_body( + self, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -157,11 +179,15 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "no-req-body", method="POST", request_options=request_options + "no-req-body", + method="POST", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, construct_type(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, construct_type(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/req_with_headers/client.py b/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/req_with_headers/client.py index 655402249e9..984428516e3 100644 --- a/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/req_with_headers/client.py +++ b/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/req_with_headers/client.py @@ -1,11 +1,11 @@ # This file was auto-generated by Fern from our API Definition. import typing +from ..core.client_wrapper import SyncClientWrapper +from ..core.request_options import RequestOptions from json.decoder import JSONDecodeError - from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.request_options import RequestOptions +from ..core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -21,7 +21,7 @@ def get_with_custom_header( x_test_service_header: str, x_test_endpoint_header: str, request: str, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ Parameters @@ -58,8 +58,12 @@ def get_with_custom_header( method="POST", json=request, headers={ - "X-TEST-SERVICE-HEADER": str(x_test_service_header) if x_test_service_header is not None else None, - "X-TEST-ENDPOINT-HEADER": str(x_test_endpoint_header) if x_test_endpoint_header is not None else None, + "X-TEST-SERVICE-HEADER": str(x_test_service_header) + if x_test_service_header is not None + else None, + "X-TEST-ENDPOINT-HEADER": str(x_test_endpoint_header) + if x_test_endpoint_header is not None + else None, }, request_options=request_options, omit=OMIT, @@ -83,7 +87,7 @@ async def get_with_custom_header( x_test_service_header: str, x_test_endpoint_header: str, request: str, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ Parameters @@ -128,8 +132,12 @@ async def main() -> None: method="POST", json=request, headers={ - "X-TEST-SERVICE-HEADER": str(x_test_service_header) if x_test_service_header is not None else None, - "X-TEST-ENDPOINT-HEADER": str(x_test_endpoint_header) if x_test_endpoint_header is not None else None, + "X-TEST-SERVICE-HEADER": str(x_test_service_header) + if x_test_service_header is not None + else None, + "X-TEST-ENDPOINT-HEADER": str(x_test_endpoint_header) + if x_test_endpoint_header is not None + else None, }, request_options=request_options, omit=OMIT, diff --git a/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/types/enum/types/weather_report.py b/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/types/enum/types/weather_report.py index 2d54965dc22..84017ef161d 100644 --- a/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/types/enum/types/weather_report.py +++ b/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/types/enum/types/weather_report.py @@ -2,4 +2,6 @@ import typing -WeatherReport = typing.Union[typing.Literal["SUNNY", "CLOUDY", "RAINING", "SNOWING"], typing.Any] +WeatherReport = typing.Union[ + typing.Literal["SUNNY", "CLOUDY", "RAINING", "SNOWING"], typing.Any +] diff --git a/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/types/object/types/double_optional.py b/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/types/object/types/double_optional.py index 5e603a0f1d0..03b463d9123 100644 --- a/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/types/object/types/double_optional.py +++ b/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/types/object/types/double_optional.py @@ -1,19 +1,21 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.unchecked_base_model import UncheckedBaseModel import typing - +from .optional_alias import OptionalAlias import pydantic - from ....core.pydantic_utilities import IS_PYDANTIC_V2 -from ....core.unchecked_base_model import UncheckedBaseModel -from .optional_alias import OptionalAlias class DoubleOptional(UncheckedBaseModel): - optional_alias: typing.Optional[OptionalAlias] = pydantic.Field(alias="optionalAlias", default=None) + optional_alias: typing.Optional[OptionalAlias] = pydantic.Field( + alias="optionalAlias", default=None + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/types/object/types/nested_object_with_optional_field.py b/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/types/object/types/nested_object_with_optional_field.py index a1b6ad8a6c0..b3416ed1491 100644 --- a/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/types/object/types/nested_object_with_optional_field.py +++ b/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/types/object/types/nested_object_with_optional_field.py @@ -1,20 +1,22 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.unchecked_base_model import UncheckedBaseModel import typing - +from .object_with_optional_field import ObjectWithOptionalField import pydantic - from ....core.pydantic_utilities import IS_PYDANTIC_V2 -from ....core.unchecked_base_model import UncheckedBaseModel -from .object_with_optional_field import ObjectWithOptionalField class NestedObjectWithOptionalField(UncheckedBaseModel): string: typing.Optional[str] = None - nested_object: typing.Optional[ObjectWithOptionalField] = pydantic.Field(alias="NestedObject", default=None) + nested_object: typing.Optional[ObjectWithOptionalField] = pydantic.Field( + alias="NestedObject", default=None + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/types/object/types/nested_object_with_required_field.py b/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/types/object/types/nested_object_with_required_field.py index 18166bcb872..c32c9051454 100644 --- a/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/types/object/types/nested_object_with_required_field.py +++ b/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/types/object/types/nested_object_with_required_field.py @@ -1,12 +1,10 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2 from ....core.unchecked_base_model import UncheckedBaseModel from .object_with_optional_field import ObjectWithOptionalField +import pydantic +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class NestedObjectWithRequiredField(UncheckedBaseModel): @@ -14,7 +12,9 @@ class NestedObjectWithRequiredField(UncheckedBaseModel): nested_object: ObjectWithOptionalField = pydantic.Field(alias="NestedObject") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/types/object/types/object_with_map_of_map.py b/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/types/object/types/object_with_map_of_map.py index f4b5fc3f810..76f3413cfdb 100644 --- a/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/types/object/types/object_with_map_of_map.py +++ b/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/types/object/types/object_with_map_of_map.py @@ -1,18 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.unchecked_base_model import UncheckedBaseModel import typing - import pydantic - from ....core.pydantic_utilities import IS_PYDANTIC_V2 -from ....core.unchecked_base_model import UncheckedBaseModel class ObjectWithMapOfMap(UncheckedBaseModel): map_: typing.Dict[str, typing.Dict[str, str]] = pydantic.Field(alias="map") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/types/object/types/object_with_optional_field.py b/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/types/object/types/object_with_optional_field.py index fa0f49d6c55..4f4f023a5a1 100644 --- a/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/types/object/types/object_with_optional_field.py +++ b/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/types/object/types/object_with_optional_field.py @@ -1,13 +1,11 @@ # This file was auto-generated by Fern from our API Definition. -import datetime as dt +from ....core.unchecked_base_model import UncheckedBaseModel import typing -import uuid - import pydantic - +import datetime as dt +import uuid from ....core.pydantic_utilities import IS_PYDANTIC_V2 -from ....core.unchecked_base_model import UncheckedBaseModel class ObjectWithOptionalField(UncheckedBaseModel): @@ -24,13 +22,19 @@ class ObjectWithOptionalField(UncheckedBaseModel): date: typing.Optional[dt.date] = None uuid_: typing.Optional[uuid.UUID] = pydantic.Field(alias="uuid", default=None) base_64: typing.Optional[str] = pydantic.Field(alias="base64", default=None) - list_: typing.Optional[typing.List[str]] = pydantic.Field(alias="list", default=None) + list_: typing.Optional[typing.List[str]] = pydantic.Field( + alias="list", default=None + ) set_: typing.Optional[typing.Set[str]] = pydantic.Field(alias="set", default=None) - map_: typing.Optional[typing.Dict[int, str]] = pydantic.Field(alias="map", default=None) + map_: typing.Optional[typing.Dict[int, str]] = pydantic.Field( + alias="map", default=None + ) bigint: typing.Optional[str] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/types/object/types/object_with_required_field.py b/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/types/object/types/object_with_required_field.py index 4f6a1f9e748..bddbca40b21 100644 --- a/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/types/object/types/object_with_required_field.py +++ b/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/types/object/types/object_with_required_field.py @@ -1,18 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.unchecked_base_model import UncheckedBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2 -from ....core.unchecked_base_model import UncheckedBaseModel - class ObjectWithRequiredField(UncheckedBaseModel): string: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/types/union/types/animal.py b/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/types/union/types/animal.py index ea1550db5ec..4f19b7fad15 100644 --- a/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/types/union/types/animal.py +++ b/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/types/union/types/animal.py @@ -1,14 +1,12 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ....core.unchecked_base_model import UncheckedBaseModel import typing - import pydantic -import typing_extensions - from ....core.pydantic_utilities import IS_PYDANTIC_V2 -from ....core.unchecked_base_model import UncheckedBaseModel, UnionMetadata +import typing_extensions +from ....core.unchecked_base_model import UnionMetadata class Animal_Dog(UncheckedBaseModel): @@ -17,7 +15,9 @@ class Animal_Dog(UncheckedBaseModel): likes_to_woof: bool = pydantic.Field(alias="likesToWoof") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: @@ -32,7 +32,9 @@ class Animal_Cat(UncheckedBaseModel): likes_to_meow: bool = pydantic.Field(alias="likesToMeow") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: @@ -41,4 +43,6 @@ class Config: extra = pydantic.Extra.allow -Animal = typing_extensions.Annotated[typing.Union[Animal_Dog, Animal_Cat], UnionMetadata(discriminant="animal")] +Animal = typing_extensions.Annotated[ + typing.Union[Animal_Dog, Animal_Cat], UnionMetadata(discriminant="animal") +] diff --git a/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/types/union/types/cat.py b/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/types/union/types/cat.py index a0d7dcb5bf6..5a75ac35654 100644 --- a/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/types/union/types/cat.py +++ b/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/types/union/types/cat.py @@ -1,11 +1,9 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ....core.unchecked_base_model import UncheckedBaseModel import pydantic - from ....core.pydantic_utilities import IS_PYDANTIC_V2 -from ....core.unchecked_base_model import UncheckedBaseModel +import typing class Cat(UncheckedBaseModel): @@ -13,7 +11,9 @@ class Cat(UncheckedBaseModel): likes_to_meow: bool = pydantic.Field(alias="likesToMeow") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/types/union/types/dog.py b/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/types/union/types/dog.py index 1f5965e2e70..ab6846a8b44 100644 --- a/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/types/union/types/dog.py +++ b/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/types/union/types/dog.py @@ -1,11 +1,9 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ....core.unchecked_base_model import UncheckedBaseModel import pydantic - from ....core.pydantic_utilities import IS_PYDANTIC_V2 -from ....core.unchecked_base_model import UncheckedBaseModel +import typing class Dog(UncheckedBaseModel): @@ -13,7 +11,9 @@ class Dog(UncheckedBaseModel): likes_to_woof: bool = pydantic.Field(alias="likesToWoof") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/version.py b/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/version.py index 63ba170685a..ac44536abdb 100644 --- a/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/version.py +++ b/seed/python-sdk/exhaustive/skip-pydantic-validation/src/seed/version.py @@ -1,4 +1,3 @@ - from importlib import metadata __version__ = metadata.version("fern_exhaustive") diff --git a/seed/python-sdk/exhaustive/skip-pydantic-validation/tests/conftest.py b/seed/python-sdk/exhaustive/skip-pydantic-validation/tests/conftest.py index b5b50383b94..86cb2b41af8 100644 --- a/seed/python-sdk/exhaustive/skip-pydantic-validation/tests/conftest.py +++ b/seed/python-sdk/exhaustive/skip-pydantic-validation/tests/conftest.py @@ -1,16 +1,22 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive import os - import pytest -from seed import AsyncSeedExhaustive, SeedExhaustive +from seed import AsyncSeedExhaustive @pytest.fixture def client() -> SeedExhaustive: - return SeedExhaustive(token=os.getenv("ENV_TOKEN", "token"), base_url=os.getenv("TESTS_BASE_URL", "base_url")) + return SeedExhaustive( + token=os.getenv("ENV_TOKEN", "token"), + base_url=os.getenv("TESTS_BASE_URL", "base_url"), + ) @pytest.fixture def async_client() -> AsyncSeedExhaustive: - return AsyncSeedExhaustive(token=os.getenv("ENV_TOKEN", "token"), base_url=os.getenv("TESTS_BASE_URL", "base_url")) + return AsyncSeedExhaustive( + token=os.getenv("ENV_TOKEN", "token"), + base_url=os.getenv("TESTS_BASE_URL", "base_url"), + ) diff --git a/seed/python-sdk/exhaustive/skip-pydantic-validation/tests/custom/test_client.py b/seed/python-sdk/exhaustive/skip-pydantic-validation/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/python-sdk/exhaustive/skip-pydantic-validation/tests/custom/test_client.py +++ b/seed/python-sdk/exhaustive/skip-pydantic-validation/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/python-sdk/exhaustive/skip-pydantic-validation/tests/endpoints/test_container.py b/seed/python-sdk/exhaustive/skip-pydantic-validation/tests/endpoints/test_container.py index 17d9d75240d..240f16f2a8c 100644 --- a/seed/python-sdk/exhaustive/skip-pydantic-validation/tests/endpoints/test_container.py +++ b/seed/python-sdk/exhaustive/skip-pydantic-validation/tests/endpoints/test_container.py @@ -1,91 +1,137 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing - -from seed import AsyncSeedExhaustive, SeedExhaustive -from seed.types.object import ObjectWithRequiredField - from ..utilities import validate_response +from seed.types.object import ObjectWithRequiredField -async def test_get_and_return_list_of_primitives(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_list_of_primitives( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = ["string"] expected_types: typing.Tuple[typing.Any, typing.Any] = ("list", {0: None}) - response = client.endpoints.container.get_and_return_list_of_primitives(request=["string"]) + response = client.endpoints.container.get_and_return_list_of_primitives( + request=["string"] + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.container.get_and_return_list_of_primitives(request=["string"]) + async_response = ( + await async_client.endpoints.container.get_and_return_list_of_primitives( + request=["string"] + ) + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_list_of_objects(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_list_of_objects( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = [{"string": "string"}] - expected_types: typing.Tuple[typing.Any, typing.Any] = ("list", {0: {"string": None}}) + expected_types: typing.Tuple[typing.Any, typing.Any] = ( + "list", + {0: {"string": None}}, + ) response = client.endpoints.container.get_and_return_list_of_objects( request=[ObjectWithRequiredField(string="string")] ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.container.get_and_return_list_of_objects( - request=[ObjectWithRequiredField(string="string")] + async_response = ( + await async_client.endpoints.container.get_and_return_list_of_objects( + request=[ObjectWithRequiredField(string="string")] + ) ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_set_of_primitives(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_set_of_primitives( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = ["string"] expected_types: typing.Tuple[typing.Any, typing.Any] = ("set", {0: None}) - response = client.endpoints.container.get_and_return_set_of_primitives(request={"string"}) + response = client.endpoints.container.get_and_return_set_of_primitives( + request={"string"} + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.container.get_and_return_set_of_primitives(request={"string"}) + async_response = ( + await async_client.endpoints.container.get_and_return_set_of_primitives( + request={"string"} + ) + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_set_of_objects(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_set_of_objects( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = [{"string": "string"}] - expected_types: typing.Tuple[typing.Any, typing.Any] = ("set", {0: {"string": None}}) + expected_types: typing.Tuple[typing.Any, typing.Any] = ( + "set", + {0: {"string": None}}, + ) response = client.endpoints.container.get_and_return_set_of_objects( request=[ObjectWithRequiredField(string="string")] ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.container.get_and_return_set_of_objects( - request=[ObjectWithRequiredField(string="string")] + async_response = ( + await async_client.endpoints.container.get_and_return_set_of_objects( + request=[ObjectWithRequiredField(string="string")] + ) ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_map_prim_to_prim(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_map_prim_to_prim( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = {"string": "string"} expected_types: typing.Tuple[typing.Any, typing.Any] = ("dict", {0: (None, None)}) - response = client.endpoints.container.get_and_return_map_prim_to_prim(request={"string": "string"}) + response = client.endpoints.container.get_and_return_map_prim_to_prim( + request={"string": "string"} + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.container.get_and_return_map_prim_to_prim( - request={"string": "string"} + async_response = ( + await async_client.endpoints.container.get_and_return_map_prim_to_prim( + request={"string": "string"} + ) ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_map_of_prim_to_object(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_map_of_prim_to_object( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = {"string": {"string": "string"}} - expected_types: typing.Tuple[typing.Any, typing.Any] = ("dict", {0: (None, {"string": None})}) + expected_types: typing.Tuple[typing.Any, typing.Any] = ( + "dict", + {0: (None, {"string": None})}, + ) response = client.endpoints.container.get_and_return_map_of_prim_to_object( request={"string": ObjectWithRequiredField(string="string")} ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.container.get_and_return_map_of_prim_to_object( - request={"string": ObjectWithRequiredField(string="string")} + async_response = ( + await async_client.endpoints.container.get_and_return_map_of_prim_to_object( + request={"string": ObjectWithRequiredField(string="string")} + ) ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_optional(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_optional( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = {"string": "string"} expected_types: typing.Any = {"string": None} - response = client.endpoints.container.get_and_return_optional(request=ObjectWithRequiredField(string="string")) + response = client.endpoints.container.get_and_return_optional( + request=ObjectWithRequiredField(string="string") + ) validate_response(response, expected_response, expected_types) async_response = await async_client.endpoints.container.get_and_return_optional( diff --git a/seed/python-sdk/exhaustive/skip-pydantic-validation/tests/endpoints/test_enum.py b/seed/python-sdk/exhaustive/skip-pydantic-validation/tests/endpoints/test_enum.py index 890aada5ce4..ca3fca30b5a 100644 --- a/seed/python-sdk/exhaustive/skip-pydantic-validation/tests/endpoints/test_enum.py +++ b/seed/python-sdk/exhaustive/skip-pydantic-validation/tests/endpoints/test_enum.py @@ -1,17 +1,20 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing - -from seed import AsyncSeedExhaustive, SeedExhaustive - from ..utilities import validate_response -async def test_get_and_return_enum(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_enum( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "SUNNY" expected_types: typing.Any = None response = client.endpoints.enum.get_and_return_enum(request="SUNNY") validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.enum.get_and_return_enum(request="SUNNY") + async_response = await async_client.endpoints.enum.get_and_return_enum( + request="SUNNY" + ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/exhaustive/skip-pydantic-validation/tests/endpoints/test_http_methods.py b/seed/python-sdk/exhaustive/skip-pydantic-validation/tests/endpoints/test_http_methods.py index dc01bafcf6f..77131fc6e8b 100644 --- a/seed/python-sdk/exhaustive/skip-pydantic-validation/tests/endpoints/test_http_methods.py +++ b/seed/python-sdk/exhaustive/skip-pydantic-validation/tests/endpoints/test_http_methods.py @@ -1,15 +1,16 @@ # This file was auto-generated by Fern from our API Definition. -import datetime +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing -import uuid - -from seed import AsyncSeedExhaustive, SeedExhaustive - from ..utilities import validate_response +import datetime +import uuid -async def test_test_get(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_test_get( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "string" expected_types: typing.Any = None response = client.endpoints.http_methods.test_get(id="string") @@ -19,7 +20,9 @@ async def test_test_get(client: SeedExhaustive, async_client: AsyncSeedExhaustiv validate_response(async_response, expected_response, expected_types) -async def test_test_post(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_test_post( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = { "string": "string", "integer": 1, @@ -53,11 +56,15 @@ async def test_test_post(client: SeedExhaustive, async_client: AsyncSeedExhausti response = client.endpoints.http_methods.test_post(string="string") validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.http_methods.test_post(string="string") + async_response = await async_client.endpoints.http_methods.test_post( + string="string" + ) validate_response(async_response, expected_response, expected_types) -async def test_test_put(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_test_put( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = { "string": "string", "integer": 1, @@ -91,11 +98,15 @@ async def test_test_put(client: SeedExhaustive, async_client: AsyncSeedExhaustiv response = client.endpoints.http_methods.test_put(id="string", string="string") validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.http_methods.test_put(id="string", string="string") + async_response = await async_client.endpoints.http_methods.test_put( + id="string", string="string" + ) validate_response(async_response, expected_response, expected_types) -async def test_test_patch(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_test_patch( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = { "string": "string", "integer": 1, @@ -163,7 +174,9 @@ async def test_test_patch(client: SeedExhaustive, async_client: AsyncSeedExhaust validate_response(async_response, expected_response, expected_types) -async def test_test_delete(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_test_delete( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = True expected_types: typing.Any = None response = client.endpoints.http_methods.test_delete(id="string") diff --git a/seed/python-sdk/exhaustive/skip-pydantic-validation/tests/endpoints/test_object.py b/seed/python-sdk/exhaustive/skip-pydantic-validation/tests/endpoints/test_object.py index a9098b6e9ef..c48c4332b22 100644 --- a/seed/python-sdk/exhaustive/skip-pydantic-validation/tests/endpoints/test_object.py +++ b/seed/python-sdk/exhaustive/skip-pydantic-validation/tests/endpoints/test_object.py @@ -1,16 +1,18 @@ # This file was auto-generated by Fern from our API Definition. -import datetime +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing +import datetime import uuid - -from seed import AsyncSeedExhaustive, SeedExhaustive -from seed.types.object import NestedObjectWithRequiredField, ObjectWithOptionalField - from ..utilities import validate_response +from seed.types.object import ObjectWithOptionalField +from seed.types.object import NestedObjectWithRequiredField -async def test_get_and_return_with_optional_field(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_with_optional_field( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = { "string": "string", "integer": 1, @@ -58,38 +60,54 @@ async def test_get_and_return_with_optional_field(client: SeedExhaustive, async_ ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.object.get_and_return_with_optional_field( - string="string", - integer=1, - long_=1000000, - double=1.1, - bool_=True, - datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), - date=datetime.date.fromisoformat("2023-01-15"), - uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), - base_64="SGVsbG8gd29ybGQh", - list_=["string"], - set_={"string"}, - map_={1: "string"}, - bigint="123456789123456789", + async_response = ( + await async_client.endpoints.object.get_and_return_with_optional_field( + string="string", + integer=1, + long_=1000000, + double=1.1, + bool_=True, + datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), + date=datetime.date.fromisoformat("2023-01-15"), + uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + base_64="SGVsbG8gd29ybGQh", + list_=["string"], + set_={"string"}, + map_={1: "string"}, + bigint="123456789123456789", + ) ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_with_required_field(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_with_required_field( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = {"string": "string"} expected_types: typing.Any = {"string": None} - response = client.endpoints.object.get_and_return_with_required_field(string="string") + response = client.endpoints.object.get_and_return_with_required_field( + string="string" + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.object.get_and_return_with_required_field(string="string") + async_response = ( + await async_client.endpoints.object.get_and_return_with_required_field( + string="string" + ) + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_with_map_of_map(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_with_map_of_map( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = {"map": {"string": {"string": "string"}}} - expected_types: typing.Any = {"map": ("dict", {0: (None, ("dict", {0: (None, None)}))})} - response = client.endpoints.object.get_and_return_with_map_of_map(map_={"string": {"string": "string"}}) + expected_types: typing.Any = { + "map": ("dict", {0: (None, ("dict", {0: (None, None)}))}) + } + response = client.endpoints.object.get_and_return_with_map_of_map( + map_={"string": {"string": "string"}} + ) validate_response(response, expected_response, expected_types) async_response = await async_client.endpoints.object.get_and_return_with_map_of_map( @@ -157,23 +175,25 @@ async def test_get_and_return_nested_with_optional_field( ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.object.get_and_return_nested_with_optional_field( - string="string", - nested_object=ObjectWithOptionalField( + async_response = ( + await async_client.endpoints.object.get_and_return_nested_with_optional_field( string="string", - integer=1, - long_=1000000, - double=1.1, - bool_=True, - datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), - date=datetime.date.fromisoformat("2023-01-15"), - uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), - base_64="SGVsbG8gd29ybGQh", - list_=["string"], - set_={"string"}, - map_={1: "string"}, - bigint="123456789123456789", - ), + nested_object=ObjectWithOptionalField( + string="string", + integer=1, + long_=1000000, + double=1.1, + bool_=True, + datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), + date=datetime.date.fromisoformat("2023-01-15"), + uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + base_64="SGVsbG8gd29ybGQh", + list_=["string"], + set_={"string"}, + map_={1: "string"}, + bigint="123456789123456789", + ), + ) ) validate_response(async_response, expected_response, expected_types) @@ -238,24 +258,26 @@ async def test_get_and_return_nested_with_required_field( ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.object.get_and_return_nested_with_required_field( - string_="string", - string="string", - nested_object=ObjectWithOptionalField( + async_response = ( + await async_client.endpoints.object.get_and_return_nested_with_required_field( + string_="string", string="string", - integer=1, - long_=1000000, - double=1.1, - bool_=True, - datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), - date=datetime.date.fromisoformat("2023-01-15"), - uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), - base_64="SGVsbG8gd29ybGQh", - list_=["string"], - set_={"string"}, - map_={1: "string"}, - bigint="123456789123456789", - ), + nested_object=ObjectWithOptionalField( + string="string", + integer=1, + long_=1000000, + double=1.1, + bool_=True, + datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), + date=datetime.date.fromisoformat("2023-01-15"), + uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + base_64="SGVsbG8gd29ybGQh", + list_=["string"], + set_={"string"}, + map_={1: "string"}, + bigint="123456789123456789", + ), + ) ) validate_response(async_response, expected_response, expected_types) @@ -299,27 +321,31 @@ async def test_get_and_return_nested_with_required_field_as_list( "bigint": None, }, } - response = client.endpoints.object.get_and_return_nested_with_required_field_as_list( - request=[ - NestedObjectWithRequiredField( - string="string", - nested_object=ObjectWithOptionalField( + response = ( + client.endpoints.object.get_and_return_nested_with_required_field_as_list( + request=[ + NestedObjectWithRequiredField( string="string", - integer=1, - long_=1000000, - double=1.1, - bool_=True, - datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), - date=datetime.date.fromisoformat("2023-01-15"), - uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), - base_64="SGVsbG8gd29ybGQh", - list_=["string"], - set_={"string"}, - map_={1: "string"}, - bigint="123456789123456789", - ), - ) - ] + nested_object=ObjectWithOptionalField( + string="string", + integer=1, + long_=1000000, + double=1.1, + bool_=True, + datetime=datetime.datetime.fromisoformat( + "2024-01-15 09:30:00+00:00" + ), + date=datetime.date.fromisoformat("2023-01-15"), + uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + base_64="SGVsbG8gd29ybGQh", + list_=["string"], + set_={"string"}, + map_={1: "string"}, + bigint="123456789123456789", + ), + ) + ] + ) ) validate_response(response, expected_response, expected_types) @@ -333,7 +359,9 @@ async def test_get_and_return_nested_with_required_field_as_list( long_=1000000, double=1.1, bool_=True, - datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), + datetime=datetime.datetime.fromisoformat( + "2024-01-15 09:30:00+00:00" + ), date=datetime.date.fromisoformat("2023-01-15"), uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), base_64="SGVsbG8gd29ybGQh", diff --git a/seed/python-sdk/exhaustive/skip-pydantic-validation/tests/endpoints/test_params.py b/seed/python-sdk/exhaustive/skip-pydantic-validation/tests/endpoints/test_params.py index 163d7b9161d..d8ffb00c0a0 100644 --- a/seed/python-sdk/exhaustive/skip-pydantic-validation/tests/endpoints/test_params.py +++ b/seed/python-sdk/exhaustive/skip-pydantic-validation/tests/endpoints/test_params.py @@ -1,13 +1,14 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing - -from seed import AsyncSeedExhaustive, SeedExhaustive - from ..utilities import validate_response -async def test_get_with_path(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_with_path( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "string" expected_types: typing.Any = None response = client.endpoints.params.get_with_path(param="string") @@ -17,32 +18,63 @@ async def test_get_with_path(client: SeedExhaustive, async_client: AsyncSeedExha validate_response(async_response, expected_response, expected_types) -async def test_get_with_query(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_with_query( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: # Type ignore to avoid mypy complaining about the function not being meant to return a value assert client.endpoints.params.get_with_query(query="string", number=1) is None # type: ignore[func-returns-value] - assert await async_client.endpoints.params.get_with_query(query="string", number=1) is None # type: ignore[func-returns-value] + assert ( + await async_client.endpoints.params.get_with_query(query="string", number=1) + is None + ) # type: ignore[func-returns-value] -async def test_get_with_allow_multiple_query(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_with_allow_multiple_query( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: # Type ignore to avoid mypy complaining about the function not being meant to return a value - assert client.endpoints.params.get_with_allow_multiple_query(query="string", numer=1) is None # type: ignore[func-returns-value] - - assert await async_client.endpoints.params.get_with_allow_multiple_query(query="string", numer=1) is None # type: ignore[func-returns-value] - - -async def test_get_with_path_and_query(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: + assert ( + client.endpoints.params.get_with_allow_multiple_query(query="string", numer=1) + is None + ) # type: ignore[func-returns-value] + + assert ( + await async_client.endpoints.params.get_with_allow_multiple_query( + query="string", numer=1 + ) + is None + ) # type: ignore[func-returns-value] + + +async def test_get_with_path_and_query( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: # Type ignore to avoid mypy complaining about the function not being meant to return a value - assert client.endpoints.params.get_with_path_and_query(param="string", query="string") is None # type: ignore[func-returns-value] - - assert await async_client.endpoints.params.get_with_path_and_query(param="string", query="string") is None # type: ignore[func-returns-value] - - -async def test_modify_with_path(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: + assert ( + client.endpoints.params.get_with_path_and_query(param="string", query="string") + is None + ) # type: ignore[func-returns-value] + + assert ( + await async_client.endpoints.params.get_with_path_and_query( + param="string", query="string" + ) + is None + ) # type: ignore[func-returns-value] + + +async def test_modify_with_path( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "string" expected_types: typing.Any = None - response = client.endpoints.params.modify_with_path(param="string", request="string") + response = client.endpoints.params.modify_with_path( + param="string", request="string" + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.params.modify_with_path(param="string", request="string") + async_response = await async_client.endpoints.params.modify_with_path( + param="string", request="string" + ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/exhaustive/skip-pydantic-validation/tests/endpoints/test_primitive.py b/seed/python-sdk/exhaustive/skip-pydantic-validation/tests/endpoints/test_primitive.py index ba3bc7e29e5..26cbcf45d2f 100644 --- a/seed/python-sdk/exhaustive/skip-pydantic-validation/tests/endpoints/test_primitive.py +++ b/seed/python-sdk/exhaustive/skip-pydantic-validation/tests/endpoints/test_primitive.py @@ -1,65 +1,86 @@ # This file was auto-generated by Fern from our API Definition. -import datetime +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing -import uuid - -from seed import AsyncSeedExhaustive, SeedExhaustive - from ..utilities import validate_response +import datetime +import uuid -async def test_get_and_return_string(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_string( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "string" expected_types: typing.Any = None response = client.endpoints.primitive.get_and_return_string(request="string") validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.primitive.get_and_return_string(request="string") + async_response = await async_client.endpoints.primitive.get_and_return_string( + request="string" + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_int(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_int( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = 1 expected_types: typing.Any = "integer" response = client.endpoints.primitive.get_and_return_int(request=1) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.primitive.get_and_return_int(request=1) + async_response = await async_client.endpoints.primitive.get_and_return_int( + request=1 + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_long(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_long( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = 1000000 expected_types: typing.Any = None response = client.endpoints.primitive.get_and_return_long(request=1000000) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.primitive.get_and_return_long(request=1000000) + async_response = await async_client.endpoints.primitive.get_and_return_long( + request=1000000 + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_double(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_double( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = 1.1 expected_types: typing.Any = None response = client.endpoints.primitive.get_and_return_double(request=1.1) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.primitive.get_and_return_double(request=1.1) + async_response = await async_client.endpoints.primitive.get_and_return_double( + request=1.1 + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_bool(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_bool( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = True expected_types: typing.Any = None response = client.endpoints.primitive.get_and_return_bool(request=True) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.primitive.get_and_return_bool(request=True) + async_response = await async_client.endpoints.primitive.get_and_return_bool( + request=True + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_datetime(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_datetime( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "2024-01-15T09:30:00Z" expected_types: typing.Any = "datetime" response = client.endpoints.primitive.get_and_return_datetime( @@ -73,10 +94,14 @@ async def test_get_and_return_datetime(client: SeedExhaustive, async_client: Asy validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_date(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_date( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "2023-01-15" expected_types: typing.Any = "date" - response = client.endpoints.primitive.get_and_return_date(request=datetime.date.fromisoformat("2023-01-15")) + response = client.endpoints.primitive.get_and_return_date( + request=datetime.date.fromisoformat("2023-01-15") + ) validate_response(response, expected_response, expected_types) async_response = await async_client.endpoints.primitive.get_and_return_date( @@ -85,10 +110,14 @@ async def test_get_and_return_date(client: SeedExhaustive, async_client: AsyncSe validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_uuid(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_uuid( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32" expected_types: typing.Any = "uuid" - response = client.endpoints.primitive.get_and_return_uuid(request=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32")) + response = client.endpoints.primitive.get_and_return_uuid( + request=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32") + ) validate_response(response, expected_response, expected_types) async_response = await async_client.endpoints.primitive.get_and_return_uuid( @@ -97,11 +126,17 @@ async def test_get_and_return_uuid(client: SeedExhaustive, async_client: AsyncSe validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_base_64(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_base_64( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "SGVsbG8gd29ybGQh" expected_types: typing.Any = None - response = client.endpoints.primitive.get_and_return_base_64(request="SGVsbG8gd29ybGQh") + response = client.endpoints.primitive.get_and_return_base_64( + request="SGVsbG8gd29ybGQh" + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.primitive.get_and_return_base_64(request="SGVsbG8gd29ybGQh") + async_response = await async_client.endpoints.primitive.get_and_return_base_64( + request="SGVsbG8gd29ybGQh" + ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/exhaustive/skip-pydantic-validation/tests/endpoints/test_union.py b/seed/python-sdk/exhaustive/skip-pydantic-validation/tests/endpoints/test_union.py index 14e34c2a6df..ceb84928cd9 100644 --- a/seed/python-sdk/exhaustive/skip-pydantic-validation/tests/endpoints/test_union.py +++ b/seed/python-sdk/exhaustive/skip-pydantic-validation/tests/endpoints/test_union.py @@ -1,17 +1,24 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing - -from seed import AsyncSeedExhaustive, SeedExhaustive from seed.types.union import Animal_Dog - from ..utilities import validate_response -async def test_get_and_return_union(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: - expected_response: typing.Any = {"animal": "dog", "name": "string", "likesToWoof": True} +async def test_get_and_return_union( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: + expected_response: typing.Any = { + "animal": "dog", + "name": "string", + "likesToWoof": True, + } expected_types: typing.Any = "no_validate" - response = client.endpoints.union.get_and_return_union(request=Animal_Dog(name="string", likes_to_woof=True)) + response = client.endpoints.union.get_and_return_union( + request=Animal_Dog(name="string", likes_to_woof=True) + ) validate_response(response, expected_response, expected_types) async_response = await async_client.endpoints.union.get_and_return_union( diff --git a/seed/python-sdk/exhaustive/skip-pydantic-validation/tests/test_inlined_requests.py b/seed/python-sdk/exhaustive/skip-pydantic-validation/tests/test_inlined_requests.py index bb9390d3845..03f46b31cc9 100644 --- a/seed/python-sdk/exhaustive/skip-pydantic-validation/tests/test_inlined_requests.py +++ b/seed/python-sdk/exhaustive/skip-pydantic-validation/tests/test_inlined_requests.py @@ -1,16 +1,17 @@ # This file was auto-generated by Fern from our API Definition. -import datetime +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing -import uuid - -from seed import AsyncSeedExhaustive, SeedExhaustive from seed.types.object import ObjectWithOptionalField - +import datetime +import uuid from .utilities import validate_response -async def test_post_with_object_bodyand_response(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_post_with_object_bodyand_response( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = { "string": "string", "integer": 1, @@ -62,23 +63,25 @@ async def test_post_with_object_bodyand_response(client: SeedExhaustive, async_c ) validate_response(response, expected_response, expected_types) - async_response = await async_client.inlined_requests.post_with_object_bodyand_response( - string="string", - integer=1, - nested_object=ObjectWithOptionalField( + async_response = ( + await async_client.inlined_requests.post_with_object_bodyand_response( string="string", integer=1, - long_=1000000, - double=1.1, - bool_=True, - datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), - date=datetime.date.fromisoformat("2023-01-15"), - uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), - base_64="SGVsbG8gd29ybGQh", - list_=["string"], - set_={"string"}, - map_={1: "string"}, - bigint="123456789123456789", - ), + nested_object=ObjectWithOptionalField( + string="string", + integer=1, + long_=1000000, + double=1.1, + bool_=True, + datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), + date=datetime.date.fromisoformat("2023-01-15"), + uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + base_64="SGVsbG8gd29ybGQh", + list_=["string"], + set_={"string"}, + map_={1: "string"}, + bigint="123456789123456789", + ), + ) ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/exhaustive/skip-pydantic-validation/tests/test_no_auth.py b/seed/python-sdk/exhaustive/skip-pydantic-validation/tests/test_no_auth.py index 3328661bb48..fc475f4b6fb 100644 --- a/seed/python-sdk/exhaustive/skip-pydantic-validation/tests/test_no_auth.py +++ b/seed/python-sdk/exhaustive/skip-pydantic-validation/tests/test_no_auth.py @@ -1,17 +1,20 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing - -from seed import AsyncSeedExhaustive, SeedExhaustive - from .utilities import validate_response -async def test_post_with_no_auth(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_post_with_no_auth( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = True expected_types: typing.Any = None response = client.no_auth.post_with_no_auth(request={"key": "value"}) validate_response(response, expected_response, expected_types) - async_response = await async_client.no_auth.post_with_no_auth(request={"key": "value"}) + async_response = await async_client.no_auth.post_with_no_auth( + request={"key": "value"} + ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/exhaustive/skip-pydantic-validation/tests/test_no_req_body.py b/seed/python-sdk/exhaustive/skip-pydantic-validation/tests/test_no_req_body.py index 73abac9d2d8..07061a0e99e 100644 --- a/seed/python-sdk/exhaustive/skip-pydantic-validation/tests/test_no_req_body.py +++ b/seed/python-sdk/exhaustive/skip-pydantic-validation/tests/test_no_req_body.py @@ -1,13 +1,14 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing - -from seed import AsyncSeedExhaustive, SeedExhaustive - from .utilities import validate_response -async def test_get_with_no_request_body(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_with_no_request_body( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = { "string": "string", "integer": 1, @@ -45,7 +46,9 @@ async def test_get_with_no_request_body(client: SeedExhaustive, async_client: As validate_response(async_response, expected_response, expected_types) -async def test_post_with_no_request_body(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_post_with_no_request_body( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "string" expected_types: typing.Any = None response = client.no_req_body.post_with_no_request_body() diff --git a/seed/python-sdk/exhaustive/skip-pydantic-validation/tests/test_req_with_headers.py b/seed/python-sdk/exhaustive/skip-pydantic-validation/tests/test_req_with_headers.py index bba3b5b5507..75ce9d00c03 100644 --- a/seed/python-sdk/exhaustive/skip-pydantic-validation/tests/test_req_with_headers.py +++ b/seed/python-sdk/exhaustive/skip-pydantic-validation/tests/test_req_with_headers.py @@ -1,10 +1,27 @@ # This file was auto-generated by Fern from our API Definition. -from seed import AsyncSeedExhaustive, SeedExhaustive +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive -async def test_get_with_custom_header(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_with_custom_header( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: # Type ignore to avoid mypy complaining about the function not being meant to return a value - assert client.req_with_headers.get_with_custom_header(x_test_service_header="string", x_test_endpoint_header="string", request="string") is None # type: ignore[func-returns-value] + assert ( + client.req_with_headers.get_with_custom_header( + x_test_service_header="string", + x_test_endpoint_header="string", + request="string", + ) + is None + ) # type: ignore[func-returns-value] - assert await async_client.req_with_headers.get_with_custom_header(x_test_service_header="string", x_test_endpoint_header="string", request="string") is None # type: ignore[func-returns-value] + assert ( + await async_client.req_with_headers.get_with_custom_header( + x_test_service_header="string", + x_test_endpoint_header="string", + request="string", + ) + is None + ) # type: ignore[func-returns-value] diff --git a/seed/python-sdk/exhaustive/skip-pydantic-validation/tests/utilities.py b/seed/python-sdk/exhaustive/skip-pydantic-validation/tests/utilities.py index 13da208eb3a..e8f4472564c 100644 --- a/seed/python-sdk/exhaustive/skip-pydantic-validation/tests/utilities.py +++ b/seed/python-sdk/exhaustive/skip-pydantic-validation/tests/utilities.py @@ -3,11 +3,14 @@ import typing import uuid -import pydantic from dateutil import parser +import pydantic + -def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> typing.Any: +def cast_field( + json_expectation: typing.Any, type_expectation: typing.Any +) -> typing.Any: # Cast these specific types which come through as string and expect our # models to cast to the correct type. if type_expectation == "uuid": @@ -25,7 +28,9 @@ def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> ty return json_expectation -def validate_field(response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any) -> None: +def validate_field( + response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectation == "no_validate": return @@ -44,7 +49,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(entry_expectation, dict): is_container_of_complex_type = True validate_response( - response=response[idx], json_expectation=ex, type_expectations=entry_expectation + response=response[idx], + json_expectation=ex, + type_expectations=entry_expectation, ) else: cast_json_expectation.append(cast_field(ex, entry_expectation)) @@ -56,7 +63,10 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # if any of the values of the set have a type_expectation of a dict, we're assuming it's a pydantic # model and keeping it a list. if container_expectation != "set" or not any( - map(lambda value: isinstance(value, dict), list(contents_expectation.values())) + map( + lambda value: isinstance(value, dict), + list(contents_expectation.values()), + ) ): json_expectation = cast_field(json_expectation, container_expectation) elif isinstance(type_expectation, tuple): @@ -65,9 +75,15 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(contents_expectation, dict): json_expectation = { cast_field( - key, contents_expectation.get(idx)[0] if contents_expectation.get(idx) is not None else None # type: ignore + key, + contents_expectation.get(idx)[0] + if contents_expectation.get(idx) is not None + else None, # type: ignore ): cast_field( - value, contents_expectation.get(idx)[1] if contents_expectation.get(idx) is not None else None # type: ignore + value, + contents_expectation.get(idx)[1] + if contents_expectation.get(idx) is not None + else None, # type: ignore ) for idx, (key, value) in enumerate(json_expectation.items()) } @@ -86,7 +102,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # Arg type_expectations is a deeply nested structure that matches the response, but with the values replaced with the expected types -def validate_response(response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any) -> None: +def validate_response( + response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectations == "no_validate": return @@ -96,11 +114,17 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e and not isinstance(response, dict) and not issubclass(type(response), pydantic.BaseModel) ): - validate_field(response=response, json_expectation=json_expectation, type_expectation=type_expectations) + validate_field( + response=response, + json_expectation=json_expectation, + type_expectation=type_expectations, + ) return if isinstance(response, list): - assert len(response) == len(json_expectation), "Length mismatch, expected: {0}, Actual: {1}".format( + assert len(response) == len( + json_expectation + ), "Length mismatch, expected: {0}, Actual: {1}".format( len(response), len(json_expectation) ) content_expectation = type_expectations @@ -108,7 +132,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e content_expectation = type_expectations[1] for idx, item in enumerate(response): validate_response( - response=item, json_expectation=json_expectation[idx], type_expectations=content_expectation[idx] + response=item, + json_expectation=json_expectation[idx], + type_expectations=content_expectation[idx], ) else: response_json = response @@ -116,7 +142,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e response_json = response.dict(by_alias=True) for key, value in json_expectation.items(): - assert key in response_json, "Field {0} not found within the response object: {1}".format( + assert ( + key in response_json + ), "Field {0} not found within the response object: {1}".format( key, response_json ) @@ -128,11 +156,19 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e # Otherwise, we're just validating a single field that's a pydantic model. if isinstance(value, dict) and not isinstance(type_expectation, tuple): validate_response( - response=response_json[key], json_expectation=value, type_expectations=type_expectation + response=response_json[key], + json_expectation=value, + type_expectations=type_expectation, ) else: - validate_field(response=response_json[key], json_expectation=value, type_expectation=type_expectation) + validate_field( + response=response_json[key], + json_expectation=value, + type_expectation=type_expectation, + ) # Ensure there are no additional fields here either del response_json[key] - assert len(response_json) == 0, "Additional fields found, expected None: {0}".format(response_json) + assert ( + len(response_json) == 0 + ), "Additional fields found, expected None: {0}".format(response_json) diff --git a/seed/python-sdk/exhaustive/skip-pydantic-validation/tests/utils/assets/models/__init__.py b/seed/python-sdk/exhaustive/skip-pydantic-validation/tests/utils/assets/models/__init__.py index 2cf01263529..3a1c852e71e 100644 --- a/seed/python-sdk/exhaustive/skip-pydantic-validation/tests/utils/assets/models/__init__.py +++ b/seed/python-sdk/exhaustive/skip-pydantic-validation/tests/utils/assets/models/__init__.py @@ -5,7 +5,7 @@ from .circle import CircleParams from .object_with_defaults import ObjectWithDefaultsParams from .object_with_optional_field import ObjectWithOptionalFieldParams -from .shape import Shape_CircleParams, Shape_SquareParams, ShapeParams +from .shape import ShapeParams, Shape_CircleParams, Shape_SquareParams from .square import SquareParams from .undiscriminated_shape import UndiscriminatedShapeParams diff --git a/seed/python-sdk/exhaustive/skip-pydantic-validation/tests/utils/assets/models/circle.py b/seed/python-sdk/exhaustive/skip-pydantic-validation/tests/utils/assets/models/circle.py index af7a1bf8a8e..253f12d38b3 100644 --- a/seed/python-sdk/exhaustive/skip-pydantic-validation/tests/utils/assets/models/circle.py +++ b/seed/python-sdk/exhaustive/skip-pydantic-validation/tests/utils/assets/models/circle.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class CircleParams(typing_extensions.TypedDict): - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] diff --git a/seed/python-sdk/exhaustive/skip-pydantic-validation/tests/utils/assets/models/object_with_optional_field.py b/seed/python-sdk/exhaustive/skip-pydantic-validation/tests/utils/assets/models/object_with_optional_field.py index 3ad93d5f305..ebe7dc80547 100644 --- a/seed/python-sdk/exhaustive/skip-pydantic-validation/tests/utils/assets/models/object_with_optional_field.py +++ b/seed/python-sdk/exhaustive/skip-pydantic-validation/tests/utils/assets/models/object_with_optional_field.py @@ -7,8 +7,8 @@ import uuid import typing_extensions -from seed.core.serialization import FieldMetadata +from seed.core.serialization import FieldMetadata from .color import Color from .shape import ShapeParams from .undiscriminated_shape import UndiscriminatedShapeParams @@ -18,16 +18,30 @@ class ObjectWithOptionalFieldParams(typing_extensions.TypedDict): literal: typing.Literal["lit_one"] string: typing_extensions.NotRequired[str] integer: typing_extensions.NotRequired[int] - long_: typing_extensions.NotRequired[typing_extensions.Annotated[int, FieldMetadata(alias="long")]] + long_: typing_extensions.NotRequired[ + typing_extensions.Annotated[int, FieldMetadata(alias="long")] + ] double: typing_extensions.NotRequired[float] - bool_: typing_extensions.NotRequired[typing_extensions.Annotated[bool, FieldMetadata(alias="bool")]] + bool_: typing_extensions.NotRequired[ + typing_extensions.Annotated[bool, FieldMetadata(alias="bool")] + ] datetime: typing_extensions.NotRequired[dt.datetime] date: typing_extensions.NotRequired[dt.date] - uuid_: typing_extensions.NotRequired[typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")]] - base_64: typing_extensions.NotRequired[typing_extensions.Annotated[str, FieldMetadata(alias="base64")]] - list_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")]] - set_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")]] - map_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")]] + uuid_: typing_extensions.NotRequired[ + typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")] + ] + base_64: typing_extensions.NotRequired[ + typing_extensions.Annotated[str, FieldMetadata(alias="base64")] + ] + list_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")] + ] + set_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")] + ] + map_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")] + ] enum: typing_extensions.NotRequired[Color] union: typing_extensions.NotRequired[ShapeParams] second_union: typing_extensions.NotRequired[ShapeParams] diff --git a/seed/python-sdk/exhaustive/skip-pydantic-validation/tests/utils/assets/models/shape.py b/seed/python-sdk/exhaustive/skip-pydantic-validation/tests/utils/assets/models/shape.py index 2c33c877951..816ffc51bdc 100644 --- a/seed/python-sdk/exhaustive/skip-pydantic-validation/tests/utils/assets/models/shape.py +++ b/seed/python-sdk/exhaustive/skip-pydantic-validation/tests/utils/assets/models/shape.py @@ -7,6 +7,7 @@ import typing import typing_extensions + from seed.core.serialization import FieldMetadata @@ -15,13 +16,21 @@ class Base(typing_extensions.TypedDict): class Shape_CircleParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["circle"], FieldMetadata(alias="shapeType")] - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["circle"], FieldMetadata(alias="shapeType") + ] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] class Shape_SquareParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["square"], FieldMetadata(alias="shapeType")] - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["square"], FieldMetadata(alias="shapeType") + ] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] ShapeParams = typing.Union[Shape_CircleParams, Shape_SquareParams] diff --git a/seed/python-sdk/exhaustive/skip-pydantic-validation/tests/utils/assets/models/square.py b/seed/python-sdk/exhaustive/skip-pydantic-validation/tests/utils/assets/models/square.py index b9b7dd319bc..bcf08a723c5 100644 --- a/seed/python-sdk/exhaustive/skip-pydantic-validation/tests/utils/assets/models/square.py +++ b/seed/python-sdk/exhaustive/skip-pydantic-validation/tests/utils/assets/models/square.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class SquareParams(typing_extensions.TypedDict): - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] diff --git a/seed/python-sdk/exhaustive/skip-pydantic-validation/tests/utils/test_http_client.py b/seed/python-sdk/exhaustive/skip-pydantic-validation/tests/utils/test_http_client.py index edd11ca7afb..f5a874a75f3 100644 --- a/seed/python-sdk/exhaustive/skip-pydantic-validation/tests/utils/test_http_client.py +++ b/seed/python-sdk/exhaustive/skip-pydantic-validation/tests/utils/test_http_client.py @@ -9,12 +9,17 @@ def get_request_options() -> RequestOptions: def test_get_json_request_body() -> None: - json_body, data_body = get_request_body(json={"hello": "world"}, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json={"hello": "world"}, data=None, request_options=None, omit=None + ) assert json_body == {"hello": "world"} assert data_body is None json_body_extras, data_body_extras = get_request_body( - json={"goodbye": "world"}, data=None, request_options=get_request_options(), omit=None + json={"goodbye": "world"}, + data=None, + request_options=get_request_options(), + omit=None, ) assert json_body_extras == {"goodbye": "world", "see you": "later"} @@ -22,12 +27,17 @@ def test_get_json_request_body() -> None: def test_get_files_request_body() -> None: - json_body, data_body = get_request_body(json=None, data={"hello": "world"}, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data={"hello": "world"}, request_options=None, omit=None + ) assert data_body == {"hello": "world"} assert json_body is None json_body_extras, data_body_extras = get_request_body( - json=None, data={"goodbye": "world"}, request_options=get_request_options(), omit=None + json=None, + data={"goodbye": "world"}, + request_options=get_request_options(), + omit=None, ) assert data_body_extras == {"goodbye": "world", "see you": "later"} @@ -35,7 +45,9 @@ def test_get_files_request_body() -> None: def test_get_none_request_body() -> None: - json_body, data_body = get_request_body(json=None, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data=None, request_options=None, omit=None + ) assert data_body is None assert json_body is None diff --git a/seed/python-sdk/exhaustive/skip-pydantic-validation/tests/utils/test_query_encoding.py b/seed/python-sdk/exhaustive/skip-pydantic-validation/tests/utils/test_query_encoding.py index 247e1551b46..fbc8f402167 100644 --- a/seed/python-sdk/exhaustive/skip-pydantic-validation/tests/utils/test_query_encoding.py +++ b/seed/python-sdk/exhaustive/skip-pydantic-validation/tests/utils/test_query_encoding.py @@ -4,9 +4,15 @@ def test_query_encoding() -> None: - assert encode_query({"hello world": "hello world"}) == {"hello world": "hello world"} - assert encode_query({"hello_world": {"hello": "world"}}) == {"hello_world[hello]": "world"} - assert encode_query({"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"}) == { + assert encode_query({"hello world": "hello world"}) == { + "hello world": "hello world" + } + assert encode_query({"hello_world": {"hello": "world"}}) == { + "hello_world[hello]": "world" + } + assert encode_query( + {"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"} + ) == { "hello_world[hello][world]": "today", "hello_world[test]": "this", "hi": "there", diff --git a/seed/python-sdk/exhaustive/skip-pydantic-validation/tests/utils/test_serialization.py b/seed/python-sdk/exhaustive/skip-pydantic-validation/tests/utils/test_serialization.py index 58b1ed66e6d..5ca956916dd 100644 --- a/seed/python-sdk/exhaustive/skip-pydantic-validation/tests/utils/test_serialization.py +++ b/seed/python-sdk/exhaustive/skip-pydantic-validation/tests/utils/test_serialization.py @@ -1,10 +1,12 @@ # This file was auto-generated by Fern from our API Definition. -from typing import Any, List +from typing import List, Any -from seed.core.serialization import convert_and_respect_annotation_metadata +from seed.core.serialization import ( + convert_and_respect_annotation_metadata, +) +from .assets.models import ShapeParams, ObjectWithOptionalFieldParams -from .assets.models import ObjectWithOptionalFieldParams, ShapeParams UNION_TEST: ShapeParams = {"radius_measurement": 1.0, "shape_type": "circle", "id": "1"} UNION_TEST_CONVERTED = {"shapeType": "circle", "radiusMeasurement": 1.0, "id": "1"} @@ -18,20 +20,54 @@ def test_convert_and_respect_annotation_metadata() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) - assert converted == {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"} + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) + assert converted == { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + } def test_convert_and_respect_annotation_metadata_in_list() -> None: data: List[ObjectWithOptionalFieldParams] = [ - {"string": "string", "long_": 12345, "bool_": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long_": 67890, "list_": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long_": 12345, + "bool_": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long_": 67890, + "list_": [], + "literal": "lit_one", + "any": "any", + }, ] - converted = convert_and_respect_annotation_metadata(object_=data, annotation=List[ObjectWithOptionalFieldParams]) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=List[ObjectWithOptionalFieldParams] + ) assert converted == [ - {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long": 67890, "list": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long": 67890, + "list": [], + "literal": "lit_one", + "any": "any", + }, ] @@ -43,7 +79,9 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) assert converted == { "string": "string", @@ -55,12 +93,16 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: def test_convert_and_respect_annotation_metadata_in_union() -> None: - converted = convert_and_respect_annotation_metadata(object_=UNION_TEST, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=UNION_TEST, annotation=ShapeParams + ) assert converted == UNION_TEST_CONVERTED def test_convert_and_respect_annotation_metadata_with_empty_object() -> None: data: Any = {} - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ShapeParams + ) assert converted == data diff --git a/seed/python-sdk/exhaustive/typeddict_requests/src/seed/__init__.py b/seed/python-sdk/exhaustive/typeddict_requests/src/seed/__init__.py index 3d4da41a50e..f091a61f1ba 100644 --- a/seed/python-sdk/exhaustive/typeddict_requests/src/seed/__init__.py +++ b/seed/python-sdk/exhaustive/typeddict_requests/src/seed/__init__.py @@ -1,8 +1,20 @@ # This file was auto-generated by Fern from our API Definition. -from . import endpoints, general_errors, inlined_requests, no_auth, no_req_body, req_with_headers, types +from . import ( + endpoints, + general_errors, + inlined_requests, + no_auth, + no_req_body, + req_with_headers, + types, +) from .client import AsyncSeedExhaustive, SeedExhaustive -from .general_errors import BadObjectRequestInfo, BadObjectRequestInfoParams, BadRequestBody +from .general_errors import ( + BadObjectRequestInfo, + BadObjectRequestInfoParams, + BadRequestBody, +) from .version import __version__ __all__ = [ diff --git a/seed/python-sdk/exhaustive/typeddict_requests/src/seed/client.py b/seed/python-sdk/exhaustive/typeddict_requests/src/seed/client.py index b1b9764c7a7..c9e8b72f422 100644 --- a/seed/python-sdk/exhaustive/typeddict_requests/src/seed/client.py +++ b/seed/python-sdk/exhaustive/typeddict_requests/src/seed/client.py @@ -48,24 +48,32 @@ def __init__( token: typing.Optional[typing.Union[str, typing.Callable[[], str]]] = None, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.Client] = None + httpx_client: typing.Optional[httpx.Client] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = SyncClientWrapper( base_url=base_url, token=token, httpx_client=httpx_client if httpx_client is not None - else httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.Client( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.Client(timeout=_defaulted_timeout), timeout=_defaulted_timeout, ) self.endpoints = EndpointsClient(client_wrapper=self._client_wrapper) - self.inlined_requests = InlinedRequestsClient(client_wrapper=self._client_wrapper) + self.inlined_requests = InlinedRequestsClient( + client_wrapper=self._client_wrapper + ) self.no_auth = NoAuthClient(client_wrapper=self._client_wrapper) self.no_req_body = NoReqBodyClient(client_wrapper=self._client_wrapper) - self.req_with_headers = ReqWithHeadersClient(client_wrapper=self._client_wrapper) + self.req_with_headers = ReqWithHeadersClient( + client_wrapper=self._client_wrapper + ) class AsyncSeedExhaustive: @@ -104,21 +112,29 @@ def __init__( token: typing.Optional[typing.Union[str, typing.Callable[[], str]]] = None, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.AsyncClient] = None + httpx_client: typing.Optional[httpx.AsyncClient] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = AsyncClientWrapper( base_url=base_url, token=token, httpx_client=httpx_client if httpx_client is not None - else httpx.AsyncClient(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.AsyncClient( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.AsyncClient(timeout=_defaulted_timeout), timeout=_defaulted_timeout, ) self.endpoints = AsyncEndpointsClient(client_wrapper=self._client_wrapper) - self.inlined_requests = AsyncInlinedRequestsClient(client_wrapper=self._client_wrapper) + self.inlined_requests = AsyncInlinedRequestsClient( + client_wrapper=self._client_wrapper + ) self.no_auth = AsyncNoAuthClient(client_wrapper=self._client_wrapper) self.no_req_body = AsyncNoReqBodyClient(client_wrapper=self._client_wrapper) - self.req_with_headers = AsyncReqWithHeadersClient(client_wrapper=self._client_wrapper) + self.req_with_headers = AsyncReqWithHeadersClient( + client_wrapper=self._client_wrapper + ) diff --git a/seed/python-sdk/exhaustive/typeddict_requests/src/seed/core/api_error.py b/seed/python-sdk/exhaustive/typeddict_requests/src/seed/core/api_error.py index 2e9fc5431cd..da734b58068 100644 --- a/seed/python-sdk/exhaustive/typeddict_requests/src/seed/core/api_error.py +++ b/seed/python-sdk/exhaustive/typeddict_requests/src/seed/core/api_error.py @@ -7,7 +7,9 @@ class ApiError(Exception): status_code: typing.Optional[int] body: typing.Any - def __init__(self, *, status_code: typing.Optional[int] = None, body: typing.Any = None): + def __init__( + self, *, status_code: typing.Optional[int] = None, body: typing.Any = None + ): self.status_code = status_code self.body = body diff --git a/seed/python-sdk/exhaustive/typeddict_requests/src/seed/core/datetime_utils.py b/seed/python-sdk/exhaustive/typeddict_requests/src/seed/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/python-sdk/exhaustive/typeddict_requests/src/seed/core/datetime_utils.py +++ b/seed/python-sdk/exhaustive/typeddict_requests/src/seed/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/python-sdk/exhaustive/typeddict_requests/src/seed/core/file.py b/seed/python-sdk/exhaustive/typeddict_requests/src/seed/core/file.py index cb0d40bbbf3..6e0f92bfcb1 100644 --- a/seed/python-sdk/exhaustive/typeddict_requests/src/seed/core/file.py +++ b/seed/python-sdk/exhaustive/typeddict_requests/src/seed/core/file.py @@ -13,12 +13,17 @@ # (filename, file (or bytes), content_type) typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str]], # (filename, file (or bytes), content_type, headers) - typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str], typing.Mapping[str, str]], + typing.Tuple[ + typing.Optional[str], + FileContent, + typing.Optional[str], + typing.Mapping[str, str], + ], ] def convert_file_dict_to_httpx_tuples( - d: typing.Dict[str, typing.Union[File, typing.List[File]]] + d: typing.Dict[str, typing.Union[File, typing.List[File]]], ) -> typing.List[typing.Tuple[str, File]]: """ The format we use is a list of tuples, where the first element is the diff --git a/seed/python-sdk/exhaustive/typeddict_requests/src/seed/core/http_client.py b/seed/python-sdk/exhaustive/typeddict_requests/src/seed/core/http_client.py index 9333d8a7f15..091f71bc185 100644 --- a/seed/python-sdk/exhaustive/typeddict_requests/src/seed/core/http_client.py +++ b/seed/python-sdk/exhaustive/typeddict_requests/src/seed/core/http_client.py @@ -77,7 +77,9 @@ def _retry_timeout(response: httpx.Response, retries: int) -> float: return retry_after # Apply exponential backoff, capped at MAX_RETRY_DELAY_SECONDS. - retry_delay = min(INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS) + retry_delay = min( + INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS + ) # Add a randomness / jitter to the retry delay to avoid overwhelming the server with retries. timeout = retry_delay * (1 - 0.25 * random()) @@ -90,7 +92,8 @@ def _should_retry(response: httpx.Response) -> bool: def remove_omit_from_dict( - original: typing.Dict[str, typing.Optional[typing.Any]], omit: typing.Optional[typing.Any] + original: typing.Dict[str, typing.Optional[typing.Any]], + omit: typing.Optional[typing.Any], ) -> typing.Dict[str, typing.Any]: if omit is None: return original @@ -108,7 +111,8 @@ def maybe_filter_request_body( ) -> typing.Optional[typing.Any]: if data is None: return ( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else None ) @@ -118,7 +122,8 @@ def maybe_filter_request_body( data_content = { **(jsonable_encoder(remove_omit_from_dict(data, omit))), # type: ignore **( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else {} ), @@ -162,7 +167,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url def request( @@ -174,8 +181,12 @@ def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -184,11 +195,14 @@ def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) response = self.httpx_client.request( method=method, @@ -198,7 +212,11 @@ def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -209,7 +227,10 @@ def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -222,11 +243,15 @@ def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: time.sleep(_retry_timeout(response=response, retries=retries)) @@ -256,8 +281,12 @@ def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -266,11 +295,14 @@ def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) with self.httpx_client.stream( method=method, @@ -280,7 +312,11 @@ def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -291,7 +327,9 @@ def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -304,7 +342,9 @@ def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream @@ -327,7 +367,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url async def request( @@ -339,8 +381,12 @@ async def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -349,11 +395,14 @@ async def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) # Add the input to each of these and do None-safety checks response = await self.httpx_client.request( @@ -364,7 +413,11 @@ async def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -375,7 +428,10 @@ async def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -388,11 +444,15 @@ async def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: await asyncio.sleep(_retry_timeout(response=response, retries=retries)) @@ -421,8 +481,12 @@ async def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -431,11 +495,14 @@ async def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) async with self.httpx_client.stream( method=method, @@ -445,7 +512,11 @@ async def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -456,7 +527,9 @@ async def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -469,7 +542,9 @@ async def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream diff --git a/seed/python-sdk/exhaustive/typeddict_requests/src/seed/core/jsonable_encoder.py b/seed/python-sdk/exhaustive/typeddict_requests/src/seed/core/jsonable_encoder.py index 9251cd589d6..71f3b620049 100644 --- a/seed/python-sdk/exhaustive/typeddict_requests/src/seed/core/jsonable_encoder.py +++ b/seed/python-sdk/exhaustive/typeddict_requests/src/seed/core/jsonable_encoder.py @@ -19,13 +19,19 @@ import pydantic from .datetime_utils import serialize_datetime -from .pydantic_utilities import IS_PYDANTIC_V2, encode_by_type, to_jsonable_with_fallback +from .pydantic_utilities import ( + IS_PYDANTIC_V2, + encode_by_type, + to_jsonable_with_fallback, +) SetIntStr = Set[Union[int, str]] DictIntStrAny = Dict[Union[int, str], Any] -def jsonable_encoder(obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None) -> Any: +def jsonable_encoder( + obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None +) -> Any: custom_encoder = custom_encoder or {} if custom_encoder: if type(obj) in custom_encoder: diff --git a/seed/python-sdk/exhaustive/typeddict_requests/src/seed/core/pydantic_utilities.py b/seed/python-sdk/exhaustive/typeddict_requests/src/seed/core/pydantic_utilities.py index 7c5418b5cf7..8afd6468713 100644 --- a/seed/python-sdk/exhaustive/typeddict_requests/src/seed/core/pydantic_utilities.py +++ b/seed/python-sdk/exhaustive/typeddict_requests/src/seed/core/pydantic_utilities.py @@ -90,15 +90,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +119,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +160,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +180,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) diff --git a/seed/python-sdk/exhaustive/typeddict_requests/src/seed/core/query_encoder.py b/seed/python-sdk/exhaustive/typeddict_requests/src/seed/core/query_encoder.py index 24076d72ee9..7cb98f52cd7 100644 --- a/seed/python-sdk/exhaustive/typeddict_requests/src/seed/core/query_encoder.py +++ b/seed/python-sdk/exhaustive/typeddict_requests/src/seed/core/query_encoder.py @@ -7,7 +7,9 @@ # Flattens dicts to be of the form {"key[subkey][subkey2]": value} where value is not a dict -def traverse_query_dict(dict_flat: Dict[str, Any], key_prefix: Optional[str] = None) -> Dict[str, Any]: +def traverse_query_dict( + dict_flat: Dict[str, Any], key_prefix: Optional[str] = None +) -> Dict[str, Any]: result = {} for k, v in dict_flat.items(): key = f"{key_prefix}[{k}]" if key_prefix is not None else k @@ -30,4 +32,8 @@ def single_query_encoder(query_key: str, query_value: Any) -> Dict[str, Any]: def encode_query(query: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: - return dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) if query is not None else None + return ( + dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) + if query is not None + else None + ) diff --git a/seed/python-sdk/exhaustive/typeddict_requests/src/seed/core/serialization.py b/seed/python-sdk/exhaustive/typeddict_requests/src/seed/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/python-sdk/exhaustive/typeddict_requests/src/seed/core/serialization.py +++ b/seed/python-sdk/exhaustive/typeddict_requests/src/seed/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/python-sdk/exhaustive/typeddict_requests/src/seed/endpoints/__init__.py b/seed/python-sdk/exhaustive/typeddict_requests/src/seed/endpoints/__init__.py index 92307cab7fe..a9496ece178 100644 --- a/seed/python-sdk/exhaustive/typeddict_requests/src/seed/endpoints/__init__.py +++ b/seed/python-sdk/exhaustive/typeddict_requests/src/seed/endpoints/__init__.py @@ -2,4 +2,12 @@ from . import container, enum, http_methods, object, params, primitive, union -__all__ = ["container", "enum", "http_methods", "object", "params", "primitive", "union"] +__all__ = [ + "container", + "enum", + "http_methods", + "object", + "params", + "primitive", + "union", +] diff --git a/seed/python-sdk/exhaustive/typeddict_requests/src/seed/endpoints/container/client.py b/seed/python-sdk/exhaustive/typeddict_requests/src/seed/endpoints/container/client.py index 4470368a74e..2994c05a248 100644 --- a/seed/python-sdk/exhaustive/typeddict_requests/src/seed/endpoints/container/client.py +++ b/seed/python-sdk/exhaustive/typeddict_requests/src/seed/endpoints/container/client.py @@ -8,7 +8,9 @@ from ...core.pydantic_utilities import parse_obj_as from ...core.request_options import RequestOptions from ...core.serialization import convert_and_respect_annotation_metadata -from ...types.object.requests.object_with_required_field import ObjectWithRequiredFieldParams +from ...types.object.requests.object_with_required_field import ( + ObjectWithRequiredFieldParams, +) from ...types.object.types.object_with_required_field import ObjectWithRequiredField # this is used as the default value for optional parameters @@ -20,7 +22,10 @@ def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper def get_and_return_list_of_primitives( - self, *, request: typing.Sequence[str], request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Sequence[str], + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[str]: """ Parameters @@ -47,11 +52,18 @@ def get_and_return_list_of_primitives( ) """ _response = self._client_wrapper.httpx_client.request( - "container/list-of-primitives", method="POST", json=request, request_options=request_options, omit=OMIT + "container/list-of-primitives", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.List[str], parse_obj_as(type_=typing.List[str], object_=_response.json())) # type: ignore + return typing.cast( + typing.List[str], + parse_obj_as(type_=typing.List[str], object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -61,7 +73,7 @@ def get_and_return_list_of_objects( self, *, request: typing.Sequence[ObjectWithRequiredFieldParams], - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[ObjectWithRequiredField]: """ Parameters @@ -91,21 +103,31 @@ def get_and_return_list_of_objects( "container/list-of-objects", method="POST", json=convert_and_respect_annotation_metadata( - object_=request, annotation=typing.Sequence[ObjectWithRequiredFieldParams] + object_=request, + annotation=typing.Sequence[ObjectWithRequiredFieldParams], ), request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.List[ObjectWithRequiredField], parse_obj_as(type_=typing.List[ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.List[ObjectWithRequiredField], + parse_obj_as( + type_=typing.List[ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_and_return_set_of_primitives( - self, *, request: typing.Set[str], request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Set[str], + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Set[str]: """ Parameters @@ -132,11 +154,18 @@ def get_and_return_set_of_primitives( ) """ _response = self._client_wrapper.httpx_client.request( - "container/set-of-primitives", method="POST", json=request, request_options=request_options, omit=OMIT + "container/set-of-primitives", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Set[str], parse_obj_as(type_=typing.Set[str], object_=_response.json())) # type: ignore + return typing.cast( + typing.Set[str], + parse_obj_as(type_=typing.Set[str], object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -146,7 +175,7 @@ def get_and_return_set_of_objects( self, *, request: typing.Sequence[ObjectWithRequiredFieldParams], - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[ObjectWithRequiredField]: """ Parameters @@ -176,21 +205,31 @@ def get_and_return_set_of_objects( "container/set-of-objects", method="POST", json=convert_and_respect_annotation_metadata( - object_=request, annotation=typing.Sequence[ObjectWithRequiredFieldParams] + object_=request, + annotation=typing.Sequence[ObjectWithRequiredFieldParams], ), request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.List[ObjectWithRequiredField], parse_obj_as(type_=typing.List[ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.List[ObjectWithRequiredField], + parse_obj_as( + type_=typing.List[ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_and_return_map_prim_to_prim( - self, *, request: typing.Dict[str, str], request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Dict[str, str], + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Dict[str, str]: """ Parameters @@ -217,11 +256,18 @@ def get_and_return_map_prim_to_prim( ) """ _response = self._client_wrapper.httpx_client.request( - "container/map-prim-to-prim", method="POST", json=request, request_options=request_options, omit=OMIT + "container/map-prim-to-prim", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Dict[str, str], parse_obj_as(type_=typing.Dict[str, str], object_=_response.json())) # type: ignore + return typing.cast( + typing.Dict[str, str], + parse_obj_as(type_=typing.Dict[str, str], object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -231,7 +277,7 @@ def get_and_return_map_of_prim_to_object( self, *, request: typing.Dict[str, ObjectWithRequiredFieldParams], - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Dict[str, ObjectWithRequiredField]: """ Parameters @@ -261,14 +307,21 @@ def get_and_return_map_of_prim_to_object( "container/map-prim-to-object", method="POST", json=convert_and_respect_annotation_metadata( - object_=request, annotation=typing.Dict[str, ObjectWithRequiredFieldParams] + object_=request, + annotation=typing.Dict[str, ObjectWithRequiredFieldParams], ), request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Dict[str, ObjectWithRequiredField], parse_obj_as(type_=typing.Dict[str, ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.Dict[str, ObjectWithRequiredField], + parse_obj_as( + type_=typing.Dict[str, ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -278,7 +331,7 @@ def get_and_return_optional( self, *, request: typing.Optional[ObjectWithRequiredFieldParams] = None, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Optional[ObjectWithRequiredField]: """ Parameters @@ -307,13 +360,21 @@ def get_and_return_optional( _response = self._client_wrapper.httpx_client.request( "container/opt-objects", method="POST", - json=convert_and_respect_annotation_metadata(object_=request, annotation=ObjectWithRequiredFieldParams), + json=convert_and_respect_annotation_metadata( + object_=request, annotation=ObjectWithRequiredFieldParams + ), request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Optional[ObjectWithRequiredField], parse_obj_as(type_=typing.Optional[ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.Optional[ObjectWithRequiredField], + parse_obj_as( + type_=typing.Optional[ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -325,7 +386,10 @@ def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper async def get_and_return_list_of_primitives( - self, *, request: typing.Sequence[str], request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Sequence[str], + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[str]: """ Parameters @@ -360,11 +424,18 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/list-of-primitives", method="POST", json=request, request_options=request_options, omit=OMIT + "container/list-of-primitives", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.List[str], parse_obj_as(type_=typing.List[str], object_=_response.json())) # type: ignore + return typing.cast( + typing.List[str], + parse_obj_as(type_=typing.List[str], object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -374,7 +445,7 @@ async def get_and_return_list_of_objects( self, *, request: typing.Sequence[ObjectWithRequiredFieldParams], - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[ObjectWithRequiredField]: """ Parameters @@ -412,21 +483,31 @@ async def main() -> None: "container/list-of-objects", method="POST", json=convert_and_respect_annotation_metadata( - object_=request, annotation=typing.Sequence[ObjectWithRequiredFieldParams] + object_=request, + annotation=typing.Sequence[ObjectWithRequiredFieldParams], ), request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.List[ObjectWithRequiredField], parse_obj_as(type_=typing.List[ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.List[ObjectWithRequiredField], + parse_obj_as( + type_=typing.List[ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_and_return_set_of_primitives( - self, *, request: typing.Set[str], request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Set[str], + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Set[str]: """ Parameters @@ -461,11 +542,18 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/set-of-primitives", method="POST", json=request, request_options=request_options, omit=OMIT + "container/set-of-primitives", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Set[str], parse_obj_as(type_=typing.Set[str], object_=_response.json())) # type: ignore + return typing.cast( + typing.Set[str], + parse_obj_as(type_=typing.Set[str], object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -475,7 +563,7 @@ async def get_and_return_set_of_objects( self, *, request: typing.Sequence[ObjectWithRequiredFieldParams], - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[ObjectWithRequiredField]: """ Parameters @@ -513,21 +601,31 @@ async def main() -> None: "container/set-of-objects", method="POST", json=convert_and_respect_annotation_metadata( - object_=request, annotation=typing.Sequence[ObjectWithRequiredFieldParams] + object_=request, + annotation=typing.Sequence[ObjectWithRequiredFieldParams], ), request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.List[ObjectWithRequiredField], parse_obj_as(type_=typing.List[ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.List[ObjectWithRequiredField], + parse_obj_as( + type_=typing.List[ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_and_return_map_prim_to_prim( - self, *, request: typing.Dict[str, str], request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Dict[str, str], + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Dict[str, str]: """ Parameters @@ -562,11 +660,18 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/map-prim-to-prim", method="POST", json=request, request_options=request_options, omit=OMIT + "container/map-prim-to-prim", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Dict[str, str], parse_obj_as(type_=typing.Dict[str, str], object_=_response.json())) # type: ignore + return typing.cast( + typing.Dict[str, str], + parse_obj_as(type_=typing.Dict[str, str], object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -576,7 +681,7 @@ async def get_and_return_map_of_prim_to_object( self, *, request: typing.Dict[str, ObjectWithRequiredFieldParams], - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Dict[str, ObjectWithRequiredField]: """ Parameters @@ -614,14 +719,21 @@ async def main() -> None: "container/map-prim-to-object", method="POST", json=convert_and_respect_annotation_metadata( - object_=request, annotation=typing.Dict[str, ObjectWithRequiredFieldParams] + object_=request, + annotation=typing.Dict[str, ObjectWithRequiredFieldParams], ), request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Dict[str, ObjectWithRequiredField], parse_obj_as(type_=typing.Dict[str, ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.Dict[str, ObjectWithRequiredField], + parse_obj_as( + type_=typing.Dict[str, ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -631,7 +743,7 @@ async def get_and_return_optional( self, *, request: typing.Optional[ObjectWithRequiredFieldParams] = None, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Optional[ObjectWithRequiredField]: """ Parameters @@ -668,13 +780,21 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( "container/opt-objects", method="POST", - json=convert_and_respect_annotation_metadata(object_=request, annotation=ObjectWithRequiredFieldParams), + json=convert_and_respect_annotation_metadata( + object_=request, annotation=ObjectWithRequiredFieldParams + ), request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Optional[ObjectWithRequiredField], parse_obj_as(type_=typing.Optional[ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.Optional[ObjectWithRequiredField], + parse_obj_as( + type_=typing.Optional[ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/typeddict_requests/src/seed/endpoints/enum/client.py b/seed/python-sdk/exhaustive/typeddict_requests/src/seed/endpoints/enum/client.py index 44e2690ff6c..6fe17b03c8b 100644 --- a/seed/python-sdk/exhaustive/typeddict_requests/src/seed/endpoints/enum/client.py +++ b/seed/python-sdk/exhaustive/typeddict_requests/src/seed/endpoints/enum/client.py @@ -18,7 +18,10 @@ def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper def get_and_return_enum( - self, *, request: WeatherReport, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: WeatherReport, + request_options: typing.Optional[RequestOptions] = None, ) -> WeatherReport: """ Parameters @@ -45,11 +48,18 @@ def get_and_return_enum( ) """ _response = self._client_wrapper.httpx_client.request( - "enum", method="POST", json=request, request_options=request_options, omit=OMIT + "enum", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(WeatherReport, parse_obj_as(type_=WeatherReport, object_=_response.json())) # type: ignore + return typing.cast( + WeatherReport, + parse_obj_as(type_=WeatherReport, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -61,7 +71,10 @@ def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper async def get_and_return_enum( - self, *, request: WeatherReport, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: WeatherReport, + request_options: typing.Optional[RequestOptions] = None, ) -> WeatherReport: """ Parameters @@ -96,11 +109,18 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "enum", method="POST", json=request, request_options=request_options, omit=OMIT + "enum", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(WeatherReport, parse_obj_as(type_=WeatherReport, object_=_response.json())) # type: ignore + return typing.cast( + WeatherReport, + parse_obj_as(type_=WeatherReport, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/typeddict_requests/src/seed/endpoints/http_methods/client.py b/seed/python-sdk/exhaustive/typeddict_requests/src/seed/endpoints/http_methods/client.py index a2549280a1b..5488eb1abb7 100644 --- a/seed/python-sdk/exhaustive/typeddict_requests/src/seed/endpoints/http_methods/client.py +++ b/seed/python-sdk/exhaustive/typeddict_requests/src/seed/endpoints/http_methods/client.py @@ -20,7 +20,9 @@ class HttpMethodsClient: def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper - def test_get(self, id: str, *, request_options: typing.Optional[RequestOptions] = None) -> str: + def test_get( + self, id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -46,11 +48,15 @@ def test_get(self, id: str, *, request_options: typing.Optional[RequestOptions] ) """ _response = self._client_wrapper.httpx_client.request( - f"http-methods/{jsonable_encoder(id)}", method="GET", request_options=request_options + f"http-methods/{jsonable_encoder(id)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -84,18 +90,31 @@ def test_post( ) """ _response = self._client_wrapper.httpx_client.request( - "http-methods", method="POST", json={"string": string}, request_options=request_options, omit=OMIT + "http-methods", + method="POST", + json={"string": string}, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def test_put( - self, id: str, *, string: str, request_options: typing.Optional[RequestOptions] = None + self, + id: str, + *, + string: str, + request_options: typing.Optional[RequestOptions] = None, ) -> ObjectWithOptionalField: """ Parameters @@ -133,7 +152,12 @@ def test_put( ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -254,13 +278,20 @@ def test_patch( ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def test_delete(self, id: str, *, request_options: typing.Optional[RequestOptions] = None) -> bool: + def test_delete( + self, id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> bool: """ Parameters ---------- @@ -286,11 +317,15 @@ def test_delete(self, id: str, *, request_options: typing.Optional[RequestOption ) """ _response = self._client_wrapper.httpx_client.request( - f"http-methods/{jsonable_encoder(id)}", method="DELETE", request_options=request_options + f"http-methods/{jsonable_encoder(id)}", + method="DELETE", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -301,7 +336,9 @@ class AsyncHttpMethodsClient: def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper - async def test_get(self, id: str, *, request_options: typing.Optional[RequestOptions] = None) -> str: + async def test_get( + self, id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -335,11 +372,15 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - f"http-methods/{jsonable_encoder(id)}", method="GET", request_options=request_options + f"http-methods/{jsonable_encoder(id)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -381,18 +422,31 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "http-methods", method="POST", json={"string": string}, request_options=request_options, omit=OMIT + "http-methods", + method="POST", + json={"string": string}, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def test_put( - self, id: str, *, string: str, request_options: typing.Optional[RequestOptions] = None + self, + id: str, + *, + string: str, + request_options: typing.Optional[RequestOptions] = None, ) -> ObjectWithOptionalField: """ Parameters @@ -438,7 +492,12 @@ async def main() -> None: ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -566,13 +625,20 @@ async def main() -> None: ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - async def test_delete(self, id: str, *, request_options: typing.Optional[RequestOptions] = None) -> bool: + async def test_delete( + self, id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> bool: """ Parameters ---------- @@ -606,11 +672,15 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - f"http-methods/{jsonable_encoder(id)}", method="DELETE", request_options=request_options + f"http-methods/{jsonable_encoder(id)}", + method="DELETE", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/typeddict_requests/src/seed/endpoints/object/client.py b/seed/python-sdk/exhaustive/typeddict_requests/src/seed/endpoints/object/client.py index 33886ce01ef..c36befb213d 100644 --- a/seed/python-sdk/exhaustive/typeddict_requests/src/seed/endpoints/object/client.py +++ b/seed/python-sdk/exhaustive/typeddict_requests/src/seed/endpoints/object/client.py @@ -11,10 +11,18 @@ from ...core.pydantic_utilities import parse_obj_as from ...core.request_options import RequestOptions from ...core.serialization import convert_and_respect_annotation_metadata -from ...types.object.requests.nested_object_with_required_field import NestedObjectWithRequiredFieldParams -from ...types.object.requests.object_with_optional_field import ObjectWithOptionalFieldParams -from ...types.object.types.nested_object_with_optional_field import NestedObjectWithOptionalField -from ...types.object.types.nested_object_with_required_field import NestedObjectWithRequiredField +from ...types.object.requests.nested_object_with_required_field import ( + NestedObjectWithRequiredFieldParams, +) +from ...types.object.requests.object_with_optional_field import ( + ObjectWithOptionalFieldParams, +) +from ...types.object.types.nested_object_with_optional_field import ( + NestedObjectWithOptionalField, +) +from ...types.object.types.nested_object_with_required_field import ( + NestedObjectWithRequiredField, +) from ...types.object.types.object_with_map_of_map import ObjectWithMapOfMap from ...types.object.types.object_with_optional_field import ObjectWithOptionalField from ...types.object.types.object_with_required_field import ObjectWithRequiredField @@ -138,7 +146,12 @@ def get_and_return_with_optional_field( ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -180,14 +193,22 @@ def get_and_return_with_required_field( ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithRequiredField, parse_obj_as(type_=ObjectWithRequiredField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithRequiredField, + parse_obj_as( + type_=ObjectWithRequiredField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_and_return_with_map_of_map( - self, *, map_: typing.Dict[str, typing.Dict[str, str]], request_options: typing.Optional[RequestOptions] = None + self, + *, + map_: typing.Dict[str, typing.Dict[str, str]], + request_options: typing.Optional[RequestOptions] = None, ) -> ObjectWithMapOfMap: """ Parameters @@ -222,7 +243,10 @@ def get_and_return_with_map_of_map( ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithMapOfMap, parse_obj_as(type_=ObjectWithMapOfMap, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithMapOfMap, + parse_obj_as(type_=ObjectWithMapOfMap, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -299,7 +323,12 @@ def get_and_return_nested_with_optional_field( ) try: if 200 <= _response.status_code < 300: - return typing.cast(NestedObjectWithOptionalField, parse_obj_as(type_=NestedObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + NestedObjectWithOptionalField, + parse_obj_as( + type_=NestedObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -380,7 +409,12 @@ def get_and_return_nested_with_required_field( ) try: if 200 <= _response.status_code < 300: - return typing.cast(NestedObjectWithRequiredField, parse_obj_as(type_=NestedObjectWithRequiredField, object_=_response.json())) # type: ignore + return typing.cast( + NestedObjectWithRequiredField, + parse_obj_as( + type_=NestedObjectWithRequiredField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -448,14 +482,20 @@ def get_and_return_nested_with_required_field_as_list( "object/get-and-return-nested-with-required-field-list", method="POST", json=convert_and_respect_annotation_metadata( - object_=request, annotation=typing.Sequence[NestedObjectWithRequiredFieldParams] + object_=request, + annotation=typing.Sequence[NestedObjectWithRequiredFieldParams], ), request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(NestedObjectWithRequiredField, parse_obj_as(type_=NestedObjectWithRequiredField, object_=_response.json())) # type: ignore + return typing.cast( + NestedObjectWithRequiredField, + parse_obj_as( + type_=NestedObjectWithRequiredField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -584,7 +624,12 @@ async def main() -> None: ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -634,14 +679,22 @@ async def main() -> None: ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithRequiredField, parse_obj_as(type_=ObjectWithRequiredField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithRequiredField, + parse_obj_as( + type_=ObjectWithRequiredField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_and_return_with_map_of_map( - self, *, map_: typing.Dict[str, typing.Dict[str, str]], request_options: typing.Optional[RequestOptions] = None + self, + *, + map_: typing.Dict[str, typing.Dict[str, str]], + request_options: typing.Optional[RequestOptions] = None, ) -> ObjectWithMapOfMap: """ Parameters @@ -684,7 +737,10 @@ async def main() -> None: ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithMapOfMap, parse_obj_as(type_=ObjectWithMapOfMap, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithMapOfMap, + parse_obj_as(type_=ObjectWithMapOfMap, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -768,7 +824,12 @@ async def main() -> None: ) try: if 200 <= _response.status_code < 300: - return typing.cast(NestedObjectWithOptionalField, parse_obj_as(type_=NestedObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + NestedObjectWithOptionalField, + parse_obj_as( + type_=NestedObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -856,7 +917,12 @@ async def main() -> None: ) try: if 200 <= _response.status_code < 300: - return typing.cast(NestedObjectWithRequiredField, parse_obj_as(type_=NestedObjectWithRequiredField, object_=_response.json())) # type: ignore + return typing.cast( + NestedObjectWithRequiredField, + parse_obj_as( + type_=NestedObjectWithRequiredField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -931,14 +997,20 @@ async def main() -> None: "object/get-and-return-nested-with-required-field-list", method="POST", json=convert_and_respect_annotation_metadata( - object_=request, annotation=typing.Sequence[NestedObjectWithRequiredFieldParams] + object_=request, + annotation=typing.Sequence[NestedObjectWithRequiredFieldParams], ), request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(NestedObjectWithRequiredField, parse_obj_as(type_=NestedObjectWithRequiredField, object_=_response.json())) # type: ignore + return typing.cast( + NestedObjectWithRequiredField, + parse_obj_as( + type_=NestedObjectWithRequiredField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/typeddict_requests/src/seed/endpoints/params/client.py b/seed/python-sdk/exhaustive/typeddict_requests/src/seed/endpoints/params/client.py index 5cd7ceef42a..947bf256501 100644 --- a/seed/python-sdk/exhaustive/typeddict_requests/src/seed/endpoints/params/client.py +++ b/seed/python-sdk/exhaustive/typeddict_requests/src/seed/endpoints/params/client.py @@ -17,7 +17,9 @@ class ParamsClient: def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper - def get_with_path(self, param: str, *, request_options: typing.Optional[RequestOptions] = None) -> str: + def get_with_path( + self, param: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ GET with path param @@ -45,18 +47,26 @@ def get_with_path(self, param: str, *, request_options: typing.Optional[RequestO ) """ _response = self._client_wrapper.httpx_client.request( - f"params/path/{jsonable_encoder(param)}", method="GET", request_options=request_options + f"params/path/{jsonable_encoder(param)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_with_query( - self, *, query: str, number: int, request_options: typing.Optional[RequestOptions] = None + self, + *, + query: str, + number: int, + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ GET with query param @@ -88,7 +98,10 @@ def get_with_query( ) """ _response = self._client_wrapper.httpx_client.request( - "params", method="GET", params={"query": query, "number": number}, request_options=request_options + "params", + method="GET", + params={"query": query, "number": number}, + request_options=request_options, ) try: if 200 <= _response.status_code < 300: @@ -135,7 +148,10 @@ def get_with_allow_multiple_query( ) """ _response = self._client_wrapper.httpx_client.request( - "params", method="GET", params={"query": query, "numer": numer}, request_options=request_options + "params", + method="GET", + params={"query": query, "numer": numer}, + request_options=request_options, ) try: if 200 <= _response.status_code < 300: @@ -146,7 +162,11 @@ def get_with_allow_multiple_query( raise ApiError(status_code=_response.status_code, body=_response_json) def get_with_path_and_query( - self, param: str, *, query: str, request_options: typing.Optional[RequestOptions] = None + self, + param: str, + *, + query: str, + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ GET with path and query params @@ -192,7 +212,11 @@ def get_with_path_and_query( raise ApiError(status_code=_response.status_code, body=_response_json) def modify_with_path( - self, param: str, *, request: str, request_options: typing.Optional[RequestOptions] = None + self, + param: str, + *, + request: str, + request_options: typing.Optional[RequestOptions] = None, ) -> str: """ PUT to update with path param @@ -232,7 +256,9 @@ def modify_with_path( ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -243,7 +269,9 @@ class AsyncParamsClient: def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper - async def get_with_path(self, param: str, *, request_options: typing.Optional[RequestOptions] = None) -> str: + async def get_with_path( + self, param: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ GET with path param @@ -279,18 +307,26 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - f"params/path/{jsonable_encoder(param)}", method="GET", request_options=request_options + f"params/path/{jsonable_encoder(param)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_with_query( - self, *, query: str, number: int, request_options: typing.Optional[RequestOptions] = None + self, + *, + query: str, + number: int, + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ GET with query param @@ -330,7 +366,10 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "params", method="GET", params={"query": query, "number": number}, request_options=request_options + "params", + method="GET", + params={"query": query, "number": number}, + request_options=request_options, ) try: if 200 <= _response.status_code < 300: @@ -385,7 +424,10 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "params", method="GET", params={"query": query, "numer": numer}, request_options=request_options + "params", + method="GET", + params={"query": query, "numer": numer}, + request_options=request_options, ) try: if 200 <= _response.status_code < 300: @@ -396,7 +438,11 @@ async def main() -> None: raise ApiError(status_code=_response.status_code, body=_response_json) async def get_with_path_and_query( - self, param: str, *, query: str, request_options: typing.Optional[RequestOptions] = None + self, + param: str, + *, + query: str, + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ GET with path and query params @@ -450,7 +496,11 @@ async def main() -> None: raise ApiError(status_code=_response.status_code, body=_response_json) async def modify_with_path( - self, param: str, *, request: str, request_options: typing.Optional[RequestOptions] = None + self, + param: str, + *, + request: str, + request_options: typing.Optional[RequestOptions] = None, ) -> str: """ PUT to update with path param @@ -498,7 +548,9 @@ async def main() -> None: ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/typeddict_requests/src/seed/endpoints/primitive/client.py b/seed/python-sdk/exhaustive/typeddict_requests/src/seed/endpoints/primitive/client.py index 844b6a782f0..9cf5ddaad12 100644 --- a/seed/python-sdk/exhaustive/typeddict_requests/src/seed/endpoints/primitive/client.py +++ b/seed/python-sdk/exhaustive/typeddict_requests/src/seed/endpoints/primitive/client.py @@ -18,7 +18,9 @@ class PrimitiveClient: def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper - def get_and_return_string(self, *, request: str, request_options: typing.Optional[RequestOptions] = None) -> str: + def get_and_return_string( + self, *, request: str, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -44,17 +46,25 @@ def get_and_return_string(self, *, request: str, request_options: typing.Optiona ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/string", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/string", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def get_and_return_int(self, *, request: int, request_options: typing.Optional[RequestOptions] = None) -> int: + def get_and_return_int( + self, *, request: int, request_options: typing.Optional[RequestOptions] = None + ) -> int: """ Parameters ---------- @@ -80,17 +90,25 @@ def get_and_return_int(self, *, request: int, request_options: typing.Optional[R ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/integer", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/integer", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(int, parse_obj_as(type_=int, object_=_response.json())) # type: ignore + return typing.cast( + int, parse_obj_as(type_=int, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def get_and_return_long(self, *, request: int, request_options: typing.Optional[RequestOptions] = None) -> int: + def get_and_return_long( + self, *, request: int, request_options: typing.Optional[RequestOptions] = None + ) -> int: """ Parameters ---------- @@ -116,11 +134,17 @@ def get_and_return_long(self, *, request: int, request_options: typing.Optional[ ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/long", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/long", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(int, parse_obj_as(type_=int, object_=_response.json())) # type: ignore + return typing.cast( + int, parse_obj_as(type_=int, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -154,17 +178,25 @@ def get_and_return_double( ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/double", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/double", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(float, parse_obj_as(type_=float, object_=_response.json())) # type: ignore + return typing.cast( + float, parse_obj_as(type_=float, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def get_and_return_bool(self, *, request: bool, request_options: typing.Optional[RequestOptions] = None) -> bool: + def get_and_return_bool( + self, *, request: bool, request_options: typing.Optional[RequestOptions] = None + ) -> bool: """ Parameters ---------- @@ -190,18 +222,27 @@ def get_and_return_bool(self, *, request: bool, request_options: typing.Optional ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/boolean", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/boolean", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_and_return_datetime( - self, *, request: dt.datetime, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: dt.datetime, + request_options: typing.Optional[RequestOptions] = None, ) -> dt.datetime: """ Parameters @@ -232,18 +273,28 @@ def get_and_return_datetime( ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/datetime", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/datetime", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(dt.datetime, parse_obj_as(type_=dt.datetime, object_=_response.json())) # type: ignore + return typing.cast( + dt.datetime, + parse_obj_as(type_=dt.datetime, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_and_return_date( - self, *, request: dt.date, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: dt.date, + request_options: typing.Optional[RequestOptions] = None, ) -> dt.date: """ Parameters @@ -274,18 +325,27 @@ def get_and_return_date( ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/date", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/date", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(dt.date, parse_obj_as(type_=dt.date, object_=_response.json())) # type: ignore + return typing.cast( + dt.date, parse_obj_as(type_=dt.date, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_and_return_uuid( - self, *, request: uuid.UUID, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: uuid.UUID, + request_options: typing.Optional[RequestOptions] = None, ) -> uuid.UUID: """ Parameters @@ -316,17 +376,25 @@ def get_and_return_uuid( ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/uuid", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/uuid", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(uuid.UUID, parse_obj_as(type_=uuid.UUID, object_=_response.json())) # type: ignore + return typing.cast( + uuid.UUID, parse_obj_as(type_=uuid.UUID, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def get_and_return_base_64(self, *, request: str, request_options: typing.Optional[RequestOptions] = None) -> str: + def get_and_return_base_64( + self, *, request: str, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -352,11 +420,17 @@ def get_and_return_base_64(self, *, request: str, request_options: typing.Option ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/base64", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/base64", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -403,17 +477,25 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/string", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/string", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - async def get_and_return_int(self, *, request: int, request_options: typing.Optional[RequestOptions] = None) -> int: + async def get_and_return_int( + self, *, request: int, request_options: typing.Optional[RequestOptions] = None + ) -> int: """ Parameters ---------- @@ -447,11 +529,17 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/integer", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/integer", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(int, parse_obj_as(type_=int, object_=_response.json())) # type: ignore + return typing.cast( + int, parse_obj_as(type_=int, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -493,11 +581,17 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/long", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/long", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(int, parse_obj_as(type_=int, object_=_response.json())) # type: ignore + return typing.cast( + int, parse_obj_as(type_=int, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -539,11 +633,17 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/double", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/double", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(float, parse_obj_as(type_=float, object_=_response.json())) # type: ignore + return typing.cast( + float, parse_obj_as(type_=float, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -585,18 +685,27 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/boolean", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/boolean", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_and_return_datetime( - self, *, request: dt.datetime, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: dt.datetime, + request_options: typing.Optional[RequestOptions] = None, ) -> dt.datetime: """ Parameters @@ -634,18 +743,28 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/datetime", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/datetime", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(dt.datetime, parse_obj_as(type_=dt.datetime, object_=_response.json())) # type: ignore + return typing.cast( + dt.datetime, + parse_obj_as(type_=dt.datetime, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_and_return_date( - self, *, request: dt.date, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: dt.date, + request_options: typing.Optional[RequestOptions] = None, ) -> dt.date: """ Parameters @@ -683,18 +802,27 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/date", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/date", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(dt.date, parse_obj_as(type_=dt.date, object_=_response.json())) # type: ignore + return typing.cast( + dt.date, parse_obj_as(type_=dt.date, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_and_return_uuid( - self, *, request: uuid.UUID, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: uuid.UUID, + request_options: typing.Optional[RequestOptions] = None, ) -> uuid.UUID: """ Parameters @@ -732,11 +860,17 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/uuid", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/uuid", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(uuid.UUID, parse_obj_as(type_=uuid.UUID, object_=_response.json())) # type: ignore + return typing.cast( + uuid.UUID, parse_obj_as(type_=uuid.UUID, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -778,11 +912,17 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/base64", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/base64", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/typeddict_requests/src/seed/endpoints/union/client.py b/seed/python-sdk/exhaustive/typeddict_requests/src/seed/endpoints/union/client.py index fa396e6dbf2..4688751bd33 100644 --- a/seed/python-sdk/exhaustive/typeddict_requests/src/seed/endpoints/union/client.py +++ b/seed/python-sdk/exhaustive/typeddict_requests/src/seed/endpoints/union/client.py @@ -20,7 +20,10 @@ def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper def get_and_return_union( - self, *, request: AnimalParams, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: AnimalParams, + request_options: typing.Optional[RequestOptions] = None, ) -> Animal: """ Parameters @@ -49,13 +52,17 @@ def get_and_return_union( _response = self._client_wrapper.httpx_client.request( "union", method="POST", - json=convert_and_respect_annotation_metadata(object_=request, annotation=AnimalParams), + json=convert_and_respect_annotation_metadata( + object_=request, annotation=AnimalParams + ), request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(Animal, parse_obj_as(type_=Animal, object_=_response.json())) # type: ignore + return typing.cast( + Animal, parse_obj_as(type_=Animal, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -67,7 +74,10 @@ def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper async def get_and_return_union( - self, *, request: AnimalParams, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: AnimalParams, + request_options: typing.Optional[RequestOptions] = None, ) -> Animal: """ Parameters @@ -104,13 +114,17 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( "union", method="POST", - json=convert_and_respect_annotation_metadata(object_=request, annotation=AnimalParams), + json=convert_and_respect_annotation_metadata( + object_=request, annotation=AnimalParams + ), request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(Animal, parse_obj_as(type_=Animal, object_=_response.json())) # type: ignore + return typing.cast( + Animal, parse_obj_as(type_=Animal, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/typeddict_requests/src/seed/general_errors/types/bad_object_request_info.py b/seed/python-sdk/exhaustive/typeddict_requests/src/seed/general_errors/types/bad_object_request_info.py index 7f03429e922..9166d97754a 100644 --- a/seed/python-sdk/exhaustive/typeddict_requests/src/seed/general_errors/types/bad_object_request_info.py +++ b/seed/python-sdk/exhaustive/typeddict_requests/src/seed/general_errors/types/bad_object_request_info.py @@ -11,7 +11,9 @@ class BadObjectRequestInfo(UniversalBaseModel): message: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/typeddict_requests/src/seed/inlined_requests/client.py b/seed/python-sdk/exhaustive/typeddict_requests/src/seed/inlined_requests/client.py index c8632a7a7e3..a03f3e69a88 100644 --- a/seed/python-sdk/exhaustive/typeddict_requests/src/seed/inlined_requests/client.py +++ b/seed/python-sdk/exhaustive/typeddict_requests/src/seed/inlined_requests/client.py @@ -10,7 +10,9 @@ from ..core.serialization import convert_and_respect_annotation_metadata from ..general_errors.errors.bad_request_body import BadRequestBody from ..general_errors.types.bad_object_request_info import BadObjectRequestInfo -from ..types.object.requests.object_with_optional_field import ObjectWithOptionalFieldParams +from ..types.object.requests.object_with_optional_field import ( + ObjectWithOptionalFieldParams, +) from ..types.object.types.object_with_optional_field import ObjectWithOptionalField # this is used as the default value for optional parameters @@ -27,7 +29,7 @@ def post_with_object_bodyand_response( string: str, integer: int, nested_object: ObjectWithOptionalFieldParams, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> ObjectWithOptionalField: """ POST with custom object in request body, response is an object @@ -99,10 +101,20 @@ def post_with_object_bodyand_response( ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore if _response.status_code == 400: raise BadRequestBody( - typing.cast(BadObjectRequestInfo, parse_obj_as(type_=BadObjectRequestInfo, object_=_response.json())) # type: ignore + typing.cast( + BadObjectRequestInfo, + parse_obj_as( + type_=BadObjectRequestInfo, object_=_response.json() + ), + ) # type: ignore ) _response_json = _response.json() except JSONDecodeError: @@ -120,7 +132,7 @@ async def post_with_object_bodyand_response( string: str, integer: int, nested_object: ObjectWithOptionalFieldParams, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> ObjectWithOptionalField: """ POST with custom object in request body, response is an object @@ -199,10 +211,20 @@ async def main() -> None: ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore if _response.status_code == 400: raise BadRequestBody( - typing.cast(BadObjectRequestInfo, parse_obj_as(type_=BadObjectRequestInfo, object_=_response.json())) # type: ignore + typing.cast( + BadObjectRequestInfo, + parse_obj_as( + type_=BadObjectRequestInfo, object_=_response.json() + ), + ) # type: ignore ) _response_json = _response.json() except JSONDecodeError: diff --git a/seed/python-sdk/exhaustive/typeddict_requests/src/seed/no_auth/client.py b/seed/python-sdk/exhaustive/typeddict_requests/src/seed/no_auth/client.py index 3d203bcea34..35a419d9a4b 100644 --- a/seed/python-sdk/exhaustive/typeddict_requests/src/seed/no_auth/client.py +++ b/seed/python-sdk/exhaustive/typeddict_requests/src/seed/no_auth/client.py @@ -19,7 +19,10 @@ def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper def post_with_no_auth( - self, *, request: typing.Any, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Any, + request_options: typing.Optional[RequestOptions] = None, ) -> bool: """ POST request with no auth @@ -48,14 +51,25 @@ def post_with_no_auth( ) """ _response = self._client_wrapper.httpx_client.request( - "no-auth", method="POST", json=request, request_options=request_options, omit=OMIT + "no-auth", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore if _response.status_code == 400: raise BadRequestBody( - typing.cast(BadObjectRequestInfo, parse_obj_as(type_=BadObjectRequestInfo, object_=_response.json())) # type: ignore + typing.cast( + BadObjectRequestInfo, + parse_obj_as( + type_=BadObjectRequestInfo, object_=_response.json() + ), + ) # type: ignore ) _response_json = _response.json() except JSONDecodeError: @@ -68,7 +82,10 @@ def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper async def post_with_no_auth( - self, *, request: typing.Any, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Any, + request_options: typing.Optional[RequestOptions] = None, ) -> bool: """ POST request with no auth @@ -105,14 +122,25 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "no-auth", method="POST", json=request, request_options=request_options, omit=OMIT + "no-auth", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore if _response.status_code == 400: raise BadRequestBody( - typing.cast(BadObjectRequestInfo, parse_obj_as(type_=BadObjectRequestInfo, object_=_response.json())) # type: ignore + typing.cast( + BadObjectRequestInfo, + parse_obj_as( + type_=BadObjectRequestInfo, object_=_response.json() + ), + ) # type: ignore ) _response_json = _response.json() except JSONDecodeError: diff --git a/seed/python-sdk/exhaustive/typeddict_requests/src/seed/no_req_body/client.py b/seed/python-sdk/exhaustive/typeddict_requests/src/seed/no_req_body/client.py index 33fa0c77d27..7ab2d58a7fb 100644 --- a/seed/python-sdk/exhaustive/typeddict_requests/src/seed/no_req_body/client.py +++ b/seed/python-sdk/exhaustive/typeddict_requests/src/seed/no_req_body/client.py @@ -42,13 +42,20 @@ def get_with_no_request_body( ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def post_with_no_request_body(self, *, request_options: typing.Optional[RequestOptions] = None) -> str: + def post_with_no_request_body( + self, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -74,7 +81,9 @@ def post_with_no_request_body(self, *, request_options: typing.Optional[RequestO ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -121,13 +130,20 @@ async def main() -> None: ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - async def post_with_no_request_body(self, *, request_options: typing.Optional[RequestOptions] = None) -> str: + async def post_with_no_request_body( + self, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -161,7 +177,9 @@ async def main() -> None: ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/typeddict_requests/src/seed/req_with_headers/client.py b/seed/python-sdk/exhaustive/typeddict_requests/src/seed/req_with_headers/client.py index 655402249e9..ed0630a16d5 100644 --- a/seed/python-sdk/exhaustive/typeddict_requests/src/seed/req_with_headers/client.py +++ b/seed/python-sdk/exhaustive/typeddict_requests/src/seed/req_with_headers/client.py @@ -21,7 +21,7 @@ def get_with_custom_header( x_test_service_header: str, x_test_endpoint_header: str, request: str, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ Parameters @@ -58,8 +58,12 @@ def get_with_custom_header( method="POST", json=request, headers={ - "X-TEST-SERVICE-HEADER": str(x_test_service_header) if x_test_service_header is not None else None, - "X-TEST-ENDPOINT-HEADER": str(x_test_endpoint_header) if x_test_endpoint_header is not None else None, + "X-TEST-SERVICE-HEADER": str(x_test_service_header) + if x_test_service_header is not None + else None, + "X-TEST-ENDPOINT-HEADER": str(x_test_endpoint_header) + if x_test_endpoint_header is not None + else None, }, request_options=request_options, omit=OMIT, @@ -83,7 +87,7 @@ async def get_with_custom_header( x_test_service_header: str, x_test_endpoint_header: str, request: str, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ Parameters @@ -128,8 +132,12 @@ async def main() -> None: method="POST", json=request, headers={ - "X-TEST-SERVICE-HEADER": str(x_test_service_header) if x_test_service_header is not None else None, - "X-TEST-ENDPOINT-HEADER": str(x_test_endpoint_header) if x_test_endpoint_header is not None else None, + "X-TEST-SERVICE-HEADER": str(x_test_service_header) + if x_test_service_header is not None + else None, + "X-TEST-ENDPOINT-HEADER": str(x_test_endpoint_header) + if x_test_endpoint_header is not None + else None, }, request_options=request_options, omit=OMIT, diff --git a/seed/python-sdk/exhaustive/typeddict_requests/src/seed/types/enum/types/weather_report.py b/seed/python-sdk/exhaustive/typeddict_requests/src/seed/types/enum/types/weather_report.py index 2d54965dc22..84017ef161d 100644 --- a/seed/python-sdk/exhaustive/typeddict_requests/src/seed/types/enum/types/weather_report.py +++ b/seed/python-sdk/exhaustive/typeddict_requests/src/seed/types/enum/types/weather_report.py @@ -2,4 +2,6 @@ import typing -WeatherReport = typing.Union[typing.Literal["SUNNY", "CLOUDY", "RAINING", "SNOWING"], typing.Any] +WeatherReport = typing.Union[ + typing.Literal["SUNNY", "CLOUDY", "RAINING", "SNOWING"], typing.Any +] diff --git a/seed/python-sdk/exhaustive/typeddict_requests/src/seed/types/object/requests/nested_object_with_optional_field.py b/seed/python-sdk/exhaustive/typeddict_requests/src/seed/types/object/requests/nested_object_with_optional_field.py index 403336ee465..9c8bf2fa386 100644 --- a/seed/python-sdk/exhaustive/typeddict_requests/src/seed/types/object/requests/nested_object_with_optional_field.py +++ b/seed/python-sdk/exhaustive/typeddict_requests/src/seed/types/object/requests/nested_object_with_optional_field.py @@ -9,5 +9,7 @@ class NestedObjectWithOptionalFieldParams(typing_extensions.TypedDict): string: typing_extensions.NotRequired[str] nested_object: typing_extensions.NotRequired[ - typing_extensions.Annotated[ObjectWithOptionalFieldParams, FieldMetadata(alias="NestedObject")] + typing_extensions.Annotated[ + ObjectWithOptionalFieldParams, FieldMetadata(alias="NestedObject") + ] ] diff --git a/seed/python-sdk/exhaustive/typeddict_requests/src/seed/types/object/requests/nested_object_with_required_field.py b/seed/python-sdk/exhaustive/typeddict_requests/src/seed/types/object/requests/nested_object_with_required_field.py index 42e2c0c1462..df61852aecf 100644 --- a/seed/python-sdk/exhaustive/typeddict_requests/src/seed/types/object/requests/nested_object_with_required_field.py +++ b/seed/python-sdk/exhaustive/typeddict_requests/src/seed/types/object/requests/nested_object_with_required_field.py @@ -8,4 +8,6 @@ class NestedObjectWithRequiredFieldParams(typing_extensions.TypedDict): string: str - nested_object: typing_extensions.Annotated[ObjectWithOptionalFieldParams, FieldMetadata(alias="NestedObject")] + nested_object: typing_extensions.Annotated[ + ObjectWithOptionalFieldParams, FieldMetadata(alias="NestedObject") + ] diff --git a/seed/python-sdk/exhaustive/typeddict_requests/src/seed/types/object/requests/object_with_map_of_map.py b/seed/python-sdk/exhaustive/typeddict_requests/src/seed/types/object/requests/object_with_map_of_map.py index ee7c6cdddb6..f8887c5c131 100644 --- a/seed/python-sdk/exhaustive/typeddict_requests/src/seed/types/object/requests/object_with_map_of_map.py +++ b/seed/python-sdk/exhaustive/typeddict_requests/src/seed/types/object/requests/object_with_map_of_map.py @@ -8,4 +8,6 @@ class ObjectWithMapOfMapParams(typing_extensions.TypedDict): - map_: typing_extensions.Annotated[typing.Dict[str, typing.Dict[str, str]], FieldMetadata(alias="map")] + map_: typing_extensions.Annotated[ + typing.Dict[str, typing.Dict[str, str]], FieldMetadata(alias="map") + ] diff --git a/seed/python-sdk/exhaustive/typeddict_requests/src/seed/types/object/requests/object_with_optional_field.py b/seed/python-sdk/exhaustive/typeddict_requests/src/seed/types/object/requests/object_with_optional_field.py index 1eabaeab732..bd1292b2529 100644 --- a/seed/python-sdk/exhaustive/typeddict_requests/src/seed/types/object/requests/object_with_optional_field.py +++ b/seed/python-sdk/exhaustive/typeddict_requests/src/seed/types/object/requests/object_with_optional_field.py @@ -16,14 +16,28 @@ class ObjectWithOptionalFieldParams(typing_extensions.TypedDict): """ integer: typing_extensions.NotRequired[int] - long_: typing_extensions.NotRequired[typing_extensions.Annotated[int, FieldMetadata(alias="long")]] + long_: typing_extensions.NotRequired[ + typing_extensions.Annotated[int, FieldMetadata(alias="long")] + ] double: typing_extensions.NotRequired[float] - bool_: typing_extensions.NotRequired[typing_extensions.Annotated[bool, FieldMetadata(alias="bool")]] + bool_: typing_extensions.NotRequired[ + typing_extensions.Annotated[bool, FieldMetadata(alias="bool")] + ] datetime: typing_extensions.NotRequired[dt.datetime] date: typing_extensions.NotRequired[dt.date] - uuid_: typing_extensions.NotRequired[typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")]] - base_64: typing_extensions.NotRequired[typing_extensions.Annotated[str, FieldMetadata(alias="base64")]] - list_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")]] - set_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")]] - map_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")]] + uuid_: typing_extensions.NotRequired[ + typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")] + ] + base_64: typing_extensions.NotRequired[ + typing_extensions.Annotated[str, FieldMetadata(alias="base64")] + ] + list_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")] + ] + set_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")] + ] + map_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")] + ] bigint: typing_extensions.NotRequired[str] diff --git a/seed/python-sdk/exhaustive/typeddict_requests/src/seed/types/object/types/double_optional.py b/seed/python-sdk/exhaustive/typeddict_requests/src/seed/types/object/types/double_optional.py index ddf165b13bd..3b36d9b1b08 100644 --- a/seed/python-sdk/exhaustive/typeddict_requests/src/seed/types/object/types/double_optional.py +++ b/seed/python-sdk/exhaustive/typeddict_requests/src/seed/types/object/types/double_optional.py @@ -9,10 +9,14 @@ class DoubleOptional(UniversalBaseModel): - optional_alias: typing.Optional[OptionalAlias] = pydantic.Field(alias="optionalAlias", default=None) + optional_alias: typing.Optional[OptionalAlias] = pydantic.Field( + alias="optionalAlias", default=None + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/typeddict_requests/src/seed/types/object/types/nested_object_with_optional_field.py b/seed/python-sdk/exhaustive/typeddict_requests/src/seed/types/object/types/nested_object_with_optional_field.py index 81669c0dd39..e6a5c7a3ce5 100644 --- a/seed/python-sdk/exhaustive/typeddict_requests/src/seed/types/object/types/nested_object_with_optional_field.py +++ b/seed/python-sdk/exhaustive/typeddict_requests/src/seed/types/object/types/nested_object_with_optional_field.py @@ -10,10 +10,14 @@ class NestedObjectWithOptionalField(UniversalBaseModel): string: typing.Optional[str] = None - nested_object: typing.Optional[ObjectWithOptionalField] = pydantic.Field(alias="NestedObject", default=None) + nested_object: typing.Optional[ObjectWithOptionalField] = pydantic.Field( + alias="NestedObject", default=None + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/typeddict_requests/src/seed/types/object/types/nested_object_with_required_field.py b/seed/python-sdk/exhaustive/typeddict_requests/src/seed/types/object/types/nested_object_with_required_field.py index 1a621942c6c..c3ccf1010eb 100644 --- a/seed/python-sdk/exhaustive/typeddict_requests/src/seed/types/object/types/nested_object_with_required_field.py +++ b/seed/python-sdk/exhaustive/typeddict_requests/src/seed/types/object/types/nested_object_with_required_field.py @@ -13,7 +13,9 @@ class NestedObjectWithRequiredField(UniversalBaseModel): nested_object: ObjectWithOptionalField = pydantic.Field(alias="NestedObject") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/typeddict_requests/src/seed/types/object/types/object_with_map_of_map.py b/seed/python-sdk/exhaustive/typeddict_requests/src/seed/types/object/types/object_with_map_of_map.py index 8883cc1d498..f1a12c19b49 100644 --- a/seed/python-sdk/exhaustive/typeddict_requests/src/seed/types/object/types/object_with_map_of_map.py +++ b/seed/python-sdk/exhaustive/typeddict_requests/src/seed/types/object/types/object_with_map_of_map.py @@ -11,7 +11,9 @@ class ObjectWithMapOfMap(UniversalBaseModel): map_: typing.Dict[str, typing.Dict[str, str]] = pydantic.Field(alias="map") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/typeddict_requests/src/seed/types/object/types/object_with_optional_field.py b/seed/python-sdk/exhaustive/typeddict_requests/src/seed/types/object/types/object_with_optional_field.py index 6aab170be0c..189c387cc61 100644 --- a/seed/python-sdk/exhaustive/typeddict_requests/src/seed/types/object/types/object_with_optional_field.py +++ b/seed/python-sdk/exhaustive/typeddict_requests/src/seed/types/object/types/object_with_optional_field.py @@ -23,13 +23,19 @@ class ObjectWithOptionalField(UniversalBaseModel): date: typing.Optional[dt.date] = None uuid_: typing.Optional[uuid.UUID] = pydantic.Field(alias="uuid", default=None) base_64: typing.Optional[str] = pydantic.Field(alias="base64", default=None) - list_: typing.Optional[typing.List[str]] = pydantic.Field(alias="list", default=None) + list_: typing.Optional[typing.List[str]] = pydantic.Field( + alias="list", default=None + ) set_: typing.Optional[typing.Set[str]] = pydantic.Field(alias="set", default=None) - map_: typing.Optional[typing.Dict[int, str]] = pydantic.Field(alias="map", default=None) + map_: typing.Optional[typing.Dict[int, str]] = pydantic.Field( + alias="map", default=None + ) bigint: typing.Optional[str] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/typeddict_requests/src/seed/types/object/types/object_with_required_field.py b/seed/python-sdk/exhaustive/typeddict_requests/src/seed/types/object/types/object_with_required_field.py index 61b98867984..27fb3177a9e 100644 --- a/seed/python-sdk/exhaustive/typeddict_requests/src/seed/types/object/types/object_with_required_field.py +++ b/seed/python-sdk/exhaustive/typeddict_requests/src/seed/types/object/types/object_with_required_field.py @@ -11,7 +11,9 @@ class ObjectWithRequiredField(UniversalBaseModel): string: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/typeddict_requests/src/seed/types/union/__init__.py b/seed/python-sdk/exhaustive/typeddict_requests/src/seed/types/union/__init__.py index 193bd362726..7da0b9bb721 100644 --- a/seed/python-sdk/exhaustive/typeddict_requests/src/seed/types/union/__init__.py +++ b/seed/python-sdk/exhaustive/typeddict_requests/src/seed/types/union/__init__.py @@ -2,7 +2,13 @@ from .types import Animal, Animal_Cat, Animal_Dog, Cat, Dog from .errors import ErrorWithUnionBody -from .requests import AnimalParams, Animal_CatParams, Animal_DogParams, CatParams, DogParams +from .requests import ( + AnimalParams, + Animal_CatParams, + Animal_DogParams, + CatParams, + DogParams, +) __all__ = [ "Animal", diff --git a/seed/python-sdk/exhaustive/typeddict_requests/src/seed/types/union/requests/__init__.py b/seed/python-sdk/exhaustive/typeddict_requests/src/seed/types/union/requests/__init__.py index 3a3d70795f8..dc4dd442a76 100644 --- a/seed/python-sdk/exhaustive/typeddict_requests/src/seed/types/union/requests/__init__.py +++ b/seed/python-sdk/exhaustive/typeddict_requests/src/seed/types/union/requests/__init__.py @@ -4,4 +4,10 @@ from .cat import CatParams from .dog import DogParams -__all__ = ["AnimalParams", "Animal_CatParams", "Animal_DogParams", "CatParams", "DogParams"] +__all__ = [ + "AnimalParams", + "Animal_CatParams", + "Animal_DogParams", + "CatParams", + "DogParams", +] diff --git a/seed/python-sdk/exhaustive/typeddict_requests/src/seed/types/union/types/animal.py b/seed/python-sdk/exhaustive/typeddict_requests/src/seed/types/union/types/animal.py index 1ae43d1663e..31369a87ed1 100644 --- a/seed/python-sdk/exhaustive/typeddict_requests/src/seed/types/union/types/animal.py +++ b/seed/python-sdk/exhaustive/typeddict_requests/src/seed/types/union/types/animal.py @@ -15,7 +15,9 @@ class Animal_Dog(UniversalBaseModel): likes_to_woof: bool = pydantic.Field(alias="likesToWoof") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: @@ -30,7 +32,9 @@ class Animal_Cat(UniversalBaseModel): likes_to_meow: bool = pydantic.Field(alias="likesToMeow") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/typeddict_requests/src/seed/types/union/types/cat.py b/seed/python-sdk/exhaustive/typeddict_requests/src/seed/types/union/types/cat.py index 61fc5527b1f..036a0a81166 100644 --- a/seed/python-sdk/exhaustive/typeddict_requests/src/seed/types/union/types/cat.py +++ b/seed/python-sdk/exhaustive/typeddict_requests/src/seed/types/union/types/cat.py @@ -12,7 +12,9 @@ class Cat(UniversalBaseModel): likes_to_meow: bool = pydantic.Field(alias="likesToMeow") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/typeddict_requests/src/seed/types/union/types/dog.py b/seed/python-sdk/exhaustive/typeddict_requests/src/seed/types/union/types/dog.py index c1ff5339dfe..f7e4ab636dc 100644 --- a/seed/python-sdk/exhaustive/typeddict_requests/src/seed/types/union/types/dog.py +++ b/seed/python-sdk/exhaustive/typeddict_requests/src/seed/types/union/types/dog.py @@ -12,7 +12,9 @@ class Dog(UniversalBaseModel): likes_to_woof: bool = pydantic.Field(alias="likesToWoof") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/typeddict_requests/src/seed/version.py b/seed/python-sdk/exhaustive/typeddict_requests/src/seed/version.py index 63ba170685a..ac44536abdb 100644 --- a/seed/python-sdk/exhaustive/typeddict_requests/src/seed/version.py +++ b/seed/python-sdk/exhaustive/typeddict_requests/src/seed/version.py @@ -1,4 +1,3 @@ - from importlib import metadata __version__ = metadata.version("fern_exhaustive") diff --git a/seed/python-sdk/exhaustive/typeddict_requests/tests/conftest.py b/seed/python-sdk/exhaustive/typeddict_requests/tests/conftest.py index b5b50383b94..70e3626c3ab 100644 --- a/seed/python-sdk/exhaustive/typeddict_requests/tests/conftest.py +++ b/seed/python-sdk/exhaustive/typeddict_requests/tests/conftest.py @@ -8,9 +8,15 @@ @pytest.fixture def client() -> SeedExhaustive: - return SeedExhaustive(token=os.getenv("ENV_TOKEN", "token"), base_url=os.getenv("TESTS_BASE_URL", "base_url")) + return SeedExhaustive( + token=os.getenv("ENV_TOKEN", "token"), + base_url=os.getenv("TESTS_BASE_URL", "base_url"), + ) @pytest.fixture def async_client() -> AsyncSeedExhaustive: - return AsyncSeedExhaustive(token=os.getenv("ENV_TOKEN", "token"), base_url=os.getenv("TESTS_BASE_URL", "base_url")) + return AsyncSeedExhaustive( + token=os.getenv("ENV_TOKEN", "token"), + base_url=os.getenv("TESTS_BASE_URL", "base_url"), + ) diff --git a/seed/python-sdk/exhaustive/typeddict_requests/tests/custom/test_client.py b/seed/python-sdk/exhaustive/typeddict_requests/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/python-sdk/exhaustive/typeddict_requests/tests/custom/test_client.py +++ b/seed/python-sdk/exhaustive/typeddict_requests/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/python-sdk/exhaustive/typeddict_requests/tests/endpoints/test_container.py b/seed/python-sdk/exhaustive/typeddict_requests/tests/endpoints/test_container.py index 13be2ac9f70..1d9fc59c94e 100644 --- a/seed/python-sdk/exhaustive/typeddict_requests/tests/endpoints/test_container.py +++ b/seed/python-sdk/exhaustive/typeddict_requests/tests/endpoints/test_container.py @@ -7,79 +7,134 @@ from ..utilities import validate_response -async def test_get_and_return_list_of_primitives(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_list_of_primitives( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = ["string"] expected_types: typing.Tuple[typing.Any, typing.Any] = ("list", {0: None}) - response = client.endpoints.container.get_and_return_list_of_primitives(request=["string"]) + response = client.endpoints.container.get_and_return_list_of_primitives( + request=["string"] + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.container.get_and_return_list_of_primitives(request=["string"]) + async_response = ( + await async_client.endpoints.container.get_and_return_list_of_primitives( + request=["string"] + ) + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_list_of_objects(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_list_of_objects( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = [{"string": "string"}] - expected_types: typing.Tuple[typing.Any, typing.Any] = ("list", {0: {"string": None}}) - response = client.endpoints.container.get_and_return_list_of_objects(request=[{"string": "string"}]) + expected_types: typing.Tuple[typing.Any, typing.Any] = ( + "list", + {0: {"string": None}}, + ) + response = client.endpoints.container.get_and_return_list_of_objects( + request=[{"string": "string"}] + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.container.get_and_return_list_of_objects( - request=[{"string": "string"}] + async_response = ( + await async_client.endpoints.container.get_and_return_list_of_objects( + request=[{"string": "string"}] + ) ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_set_of_primitives(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_set_of_primitives( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = ["string"] expected_types: typing.Tuple[typing.Any, typing.Any] = ("set", {0: None}) - response = client.endpoints.container.get_and_return_set_of_primitives(request={"string"}) + response = client.endpoints.container.get_and_return_set_of_primitives( + request={"string"} + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.container.get_and_return_set_of_primitives(request={"string"}) + async_response = ( + await async_client.endpoints.container.get_and_return_set_of_primitives( + request={"string"} + ) + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_set_of_objects(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_set_of_objects( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = [{"string": "string"}] - expected_types: typing.Tuple[typing.Any, typing.Any] = ("set", {0: {"string": None}}) - response = client.endpoints.container.get_and_return_set_of_objects(request=[{"string": "string"}]) + expected_types: typing.Tuple[typing.Any, typing.Any] = ( + "set", + {0: {"string": None}}, + ) + response = client.endpoints.container.get_and_return_set_of_objects( + request=[{"string": "string"}] + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.container.get_and_return_set_of_objects( - request=[{"string": "string"}] + async_response = ( + await async_client.endpoints.container.get_and_return_set_of_objects( + request=[{"string": "string"}] + ) ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_map_prim_to_prim(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_map_prim_to_prim( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = {"string": "string"} expected_types: typing.Tuple[typing.Any, typing.Any] = ("dict", {0: (None, None)}) - response = client.endpoints.container.get_and_return_map_prim_to_prim(request={"string": "string"}) + response = client.endpoints.container.get_and_return_map_prim_to_prim( + request={"string": "string"} + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.container.get_and_return_map_prim_to_prim( - request={"string": "string"} + async_response = ( + await async_client.endpoints.container.get_and_return_map_prim_to_prim( + request={"string": "string"} + ) ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_map_of_prim_to_object(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_map_of_prim_to_object( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = {"string": {"string": "string"}} - expected_types: typing.Tuple[typing.Any, typing.Any] = ("dict", {0: (None, {"string": None})}) - response = client.endpoints.container.get_and_return_map_of_prim_to_object(request={"string": {"string": "string"}}) + expected_types: typing.Tuple[typing.Any, typing.Any] = ( + "dict", + {0: (None, {"string": None})}, + ) + response = client.endpoints.container.get_and_return_map_of_prim_to_object( + request={"string": {"string": "string"}} + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.container.get_and_return_map_of_prim_to_object( - request={"string": {"string": "string"}} + async_response = ( + await async_client.endpoints.container.get_and_return_map_of_prim_to_object( + request={"string": {"string": "string"}} + ) ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_optional(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_optional( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = {"string": "string"} expected_types: typing.Any = {"string": None} - response = client.endpoints.container.get_and_return_optional(request={"string": "string"}) + response = client.endpoints.container.get_and_return_optional( + request={"string": "string"} + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.container.get_and_return_optional(request={"string": "string"}) + async_response = await async_client.endpoints.container.get_and_return_optional( + request={"string": "string"} + ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/exhaustive/typeddict_requests/tests/endpoints/test_enum.py b/seed/python-sdk/exhaustive/typeddict_requests/tests/endpoints/test_enum.py index 890aada5ce4..4fb50fbba6e 100644 --- a/seed/python-sdk/exhaustive/typeddict_requests/tests/endpoints/test_enum.py +++ b/seed/python-sdk/exhaustive/typeddict_requests/tests/endpoints/test_enum.py @@ -7,11 +7,15 @@ from ..utilities import validate_response -async def test_get_and_return_enum(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_enum( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "SUNNY" expected_types: typing.Any = None response = client.endpoints.enum.get_and_return_enum(request="SUNNY") validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.enum.get_and_return_enum(request="SUNNY") + async_response = await async_client.endpoints.enum.get_and_return_enum( + request="SUNNY" + ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/exhaustive/typeddict_requests/tests/endpoints/test_http_methods.py b/seed/python-sdk/exhaustive/typeddict_requests/tests/endpoints/test_http_methods.py index dc01bafcf6f..705a2fc8978 100644 --- a/seed/python-sdk/exhaustive/typeddict_requests/tests/endpoints/test_http_methods.py +++ b/seed/python-sdk/exhaustive/typeddict_requests/tests/endpoints/test_http_methods.py @@ -9,7 +9,9 @@ from ..utilities import validate_response -async def test_test_get(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_test_get( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "string" expected_types: typing.Any = None response = client.endpoints.http_methods.test_get(id="string") @@ -19,7 +21,9 @@ async def test_test_get(client: SeedExhaustive, async_client: AsyncSeedExhaustiv validate_response(async_response, expected_response, expected_types) -async def test_test_post(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_test_post( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = { "string": "string", "integer": 1, @@ -53,11 +57,15 @@ async def test_test_post(client: SeedExhaustive, async_client: AsyncSeedExhausti response = client.endpoints.http_methods.test_post(string="string") validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.http_methods.test_post(string="string") + async_response = await async_client.endpoints.http_methods.test_post( + string="string" + ) validate_response(async_response, expected_response, expected_types) -async def test_test_put(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_test_put( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = { "string": "string", "integer": 1, @@ -91,11 +99,15 @@ async def test_test_put(client: SeedExhaustive, async_client: AsyncSeedExhaustiv response = client.endpoints.http_methods.test_put(id="string", string="string") validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.http_methods.test_put(id="string", string="string") + async_response = await async_client.endpoints.http_methods.test_put( + id="string", string="string" + ) validate_response(async_response, expected_response, expected_types) -async def test_test_patch(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_test_patch( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = { "string": "string", "integer": 1, @@ -163,7 +175,9 @@ async def test_test_patch(client: SeedExhaustive, async_client: AsyncSeedExhaust validate_response(async_response, expected_response, expected_types) -async def test_test_delete(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_test_delete( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = True expected_types: typing.Any = None response = client.endpoints.http_methods.test_delete(id="string") diff --git a/seed/python-sdk/exhaustive/typeddict_requests/tests/endpoints/test_object.py b/seed/python-sdk/exhaustive/typeddict_requests/tests/endpoints/test_object.py index cc0e59589b0..ec11358a02f 100644 --- a/seed/python-sdk/exhaustive/typeddict_requests/tests/endpoints/test_object.py +++ b/seed/python-sdk/exhaustive/typeddict_requests/tests/endpoints/test_object.py @@ -9,7 +9,9 @@ from ..utilities import validate_response -async def test_get_and_return_with_optional_field(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_with_optional_field( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = { "string": "string", "integer": 1, @@ -57,38 +59,54 @@ async def test_get_and_return_with_optional_field(client: SeedExhaustive, async_ ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.object.get_and_return_with_optional_field( - string="string", - integer=1, - long_=1000000, - double=1.1, - bool_=True, - datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), - date=datetime.date.fromisoformat("2023-01-15"), - uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), - base_64="SGVsbG8gd29ybGQh", - list_=["string"], - set_={"string"}, - map_={1: "string"}, - bigint="123456789123456789", + async_response = ( + await async_client.endpoints.object.get_and_return_with_optional_field( + string="string", + integer=1, + long_=1000000, + double=1.1, + bool_=True, + datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), + date=datetime.date.fromisoformat("2023-01-15"), + uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + base_64="SGVsbG8gd29ybGQh", + list_=["string"], + set_={"string"}, + map_={1: "string"}, + bigint="123456789123456789", + ) ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_with_required_field(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_with_required_field( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = {"string": "string"} expected_types: typing.Any = {"string": None} - response = client.endpoints.object.get_and_return_with_required_field(string="string") + response = client.endpoints.object.get_and_return_with_required_field( + string="string" + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.object.get_and_return_with_required_field(string="string") + async_response = ( + await async_client.endpoints.object.get_and_return_with_required_field( + string="string" + ) + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_with_map_of_map(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_with_map_of_map( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = {"map": {"string": {"string": "string"}}} - expected_types: typing.Any = {"map": ("dict", {0: (None, ("dict", {0: (None, None)}))})} - response = client.endpoints.object.get_and_return_with_map_of_map(map_={"string": {"string": "string"}}) + expected_types: typing.Any = { + "map": ("dict", {0: (None, ("dict", {0: (None, None)}))}) + } + response = client.endpoints.object.get_and_return_with_map_of_map( + map_={"string": {"string": "string"}} + ) validate_response(response, expected_response, expected_types) async_response = await async_client.endpoints.object.get_and_return_with_map_of_map( @@ -156,23 +174,27 @@ async def test_get_and_return_nested_with_optional_field( ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.object.get_and_return_nested_with_optional_field( - string="string", - nested_object={ - "string": "string", - "integer": 1, - "long_": 1000000, - "double": 1.1, - "bool_": True, - "datetime": datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), - "date": datetime.date.fromisoformat("2023-01-15"), - "uuid_": uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), - "base_64": "SGVsbG8gd29ybGQh", - "list_": ["string"], - "set_": {"string"}, - "map_": {1: "string"}, - "bigint": "123456789123456789", - }, + async_response = ( + await async_client.endpoints.object.get_and_return_nested_with_optional_field( + string="string", + nested_object={ + "string": "string", + "integer": 1, + "long_": 1000000, + "double": 1.1, + "bool_": True, + "datetime": datetime.datetime.fromisoformat( + "2024-01-15 09:30:00+00:00" + ), + "date": datetime.date.fromisoformat("2023-01-15"), + "uuid_": uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + "base_64": "SGVsbG8gd29ybGQh", + "list_": ["string"], + "set_": {"string"}, + "map_": {1: "string"}, + "bigint": "123456789123456789", + }, + ) ) validate_response(async_response, expected_response, expected_types) @@ -237,24 +259,28 @@ async def test_get_and_return_nested_with_required_field( ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.object.get_and_return_nested_with_required_field( - string_="string", - string="string", - nested_object={ - "string": "string", - "integer": 1, - "long_": 1000000, - "double": 1.1, - "bool_": True, - "datetime": datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), - "date": datetime.date.fromisoformat("2023-01-15"), - "uuid_": uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), - "base_64": "SGVsbG8gd29ybGQh", - "list_": ["string"], - "set_": {"string"}, - "map_": {1: "string"}, - "bigint": "123456789123456789", - }, + async_response = ( + await async_client.endpoints.object.get_and_return_nested_with_required_field( + string_="string", + string="string", + nested_object={ + "string": "string", + "integer": 1, + "long_": 1000000, + "double": 1.1, + "bool_": True, + "datetime": datetime.datetime.fromisoformat( + "2024-01-15 09:30:00+00:00" + ), + "date": datetime.date.fromisoformat("2023-01-15"), + "uuid_": uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + "base_64": "SGVsbG8gd29ybGQh", + "list_": ["string"], + "set_": {"string"}, + "map_": {1: "string"}, + "bigint": "123456789123456789", + }, + ) ) validate_response(async_response, expected_response, expected_types) @@ -298,27 +324,31 @@ async def test_get_and_return_nested_with_required_field_as_list( "bigint": None, }, } - response = client.endpoints.object.get_and_return_nested_with_required_field_as_list( - request=[ - { - "string": "string", - "nested_object": { + response = ( + client.endpoints.object.get_and_return_nested_with_required_field_as_list( + request=[ + { "string": "string", - "integer": 1, - "long_": 1000000, - "double": 1.1, - "bool_": True, - "datetime": datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), - "date": datetime.date.fromisoformat("2023-01-15"), - "uuid_": uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), - "base_64": "SGVsbG8gd29ybGQh", - "list_": ["string"], - "set_": {"string"}, - "map_": {1: "string"}, - "bigint": "123456789123456789", - }, - } - ] + "nested_object": { + "string": "string", + "integer": 1, + "long_": 1000000, + "double": 1.1, + "bool_": True, + "datetime": datetime.datetime.fromisoformat( + "2024-01-15 09:30:00+00:00" + ), + "date": datetime.date.fromisoformat("2023-01-15"), + "uuid_": uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + "base_64": "SGVsbG8gd29ybGQh", + "list_": ["string"], + "set_": {"string"}, + "map_": {1: "string"}, + "bigint": "123456789123456789", + }, + } + ] + ) ) validate_response(response, expected_response, expected_types) @@ -332,7 +362,9 @@ async def test_get_and_return_nested_with_required_field_as_list( "long_": 1000000, "double": 1.1, "bool_": True, - "datetime": datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), + "datetime": datetime.datetime.fromisoformat( + "2024-01-15 09:30:00+00:00" + ), "date": datetime.date.fromisoformat("2023-01-15"), "uuid_": uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), "base_64": "SGVsbG8gd29ybGQh", diff --git a/seed/python-sdk/exhaustive/typeddict_requests/tests/endpoints/test_params.py b/seed/python-sdk/exhaustive/typeddict_requests/tests/endpoints/test_params.py index 163d7b9161d..b3512aac63d 100644 --- a/seed/python-sdk/exhaustive/typeddict_requests/tests/endpoints/test_params.py +++ b/seed/python-sdk/exhaustive/typeddict_requests/tests/endpoints/test_params.py @@ -7,7 +7,9 @@ from ..utilities import validate_response -async def test_get_with_path(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_with_path( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "string" expected_types: typing.Any = None response = client.endpoints.params.get_with_path(param="string") @@ -17,32 +19,63 @@ async def test_get_with_path(client: SeedExhaustive, async_client: AsyncSeedExha validate_response(async_response, expected_response, expected_types) -async def test_get_with_query(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_with_query( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: # Type ignore to avoid mypy complaining about the function not being meant to return a value assert client.endpoints.params.get_with_query(query="string", number=1) is None # type: ignore[func-returns-value] - assert await async_client.endpoints.params.get_with_query(query="string", number=1) is None # type: ignore[func-returns-value] + assert ( + await async_client.endpoints.params.get_with_query(query="string", number=1) + is None + ) # type: ignore[func-returns-value] -async def test_get_with_allow_multiple_query(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_with_allow_multiple_query( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: # Type ignore to avoid mypy complaining about the function not being meant to return a value - assert client.endpoints.params.get_with_allow_multiple_query(query="string", numer=1) is None # type: ignore[func-returns-value] - - assert await async_client.endpoints.params.get_with_allow_multiple_query(query="string", numer=1) is None # type: ignore[func-returns-value] - - -async def test_get_with_path_and_query(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: + assert ( + client.endpoints.params.get_with_allow_multiple_query(query="string", numer=1) + is None + ) # type: ignore[func-returns-value] + + assert ( + await async_client.endpoints.params.get_with_allow_multiple_query( + query="string", numer=1 + ) + is None + ) # type: ignore[func-returns-value] + + +async def test_get_with_path_and_query( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: # Type ignore to avoid mypy complaining about the function not being meant to return a value - assert client.endpoints.params.get_with_path_and_query(param="string", query="string") is None # type: ignore[func-returns-value] - - assert await async_client.endpoints.params.get_with_path_and_query(param="string", query="string") is None # type: ignore[func-returns-value] - - -async def test_modify_with_path(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: + assert ( + client.endpoints.params.get_with_path_and_query(param="string", query="string") + is None + ) # type: ignore[func-returns-value] + + assert ( + await async_client.endpoints.params.get_with_path_and_query( + param="string", query="string" + ) + is None + ) # type: ignore[func-returns-value] + + +async def test_modify_with_path( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "string" expected_types: typing.Any = None - response = client.endpoints.params.modify_with_path(param="string", request="string") + response = client.endpoints.params.modify_with_path( + param="string", request="string" + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.params.modify_with_path(param="string", request="string") + async_response = await async_client.endpoints.params.modify_with_path( + param="string", request="string" + ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/exhaustive/typeddict_requests/tests/endpoints/test_primitive.py b/seed/python-sdk/exhaustive/typeddict_requests/tests/endpoints/test_primitive.py index ba3bc7e29e5..88269f80663 100644 --- a/seed/python-sdk/exhaustive/typeddict_requests/tests/endpoints/test_primitive.py +++ b/seed/python-sdk/exhaustive/typeddict_requests/tests/endpoints/test_primitive.py @@ -9,57 +9,79 @@ from ..utilities import validate_response -async def test_get_and_return_string(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_string( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "string" expected_types: typing.Any = None response = client.endpoints.primitive.get_and_return_string(request="string") validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.primitive.get_and_return_string(request="string") + async_response = await async_client.endpoints.primitive.get_and_return_string( + request="string" + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_int(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_int( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = 1 expected_types: typing.Any = "integer" response = client.endpoints.primitive.get_and_return_int(request=1) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.primitive.get_and_return_int(request=1) + async_response = await async_client.endpoints.primitive.get_and_return_int( + request=1 + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_long(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_long( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = 1000000 expected_types: typing.Any = None response = client.endpoints.primitive.get_and_return_long(request=1000000) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.primitive.get_and_return_long(request=1000000) + async_response = await async_client.endpoints.primitive.get_and_return_long( + request=1000000 + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_double(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_double( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = 1.1 expected_types: typing.Any = None response = client.endpoints.primitive.get_and_return_double(request=1.1) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.primitive.get_and_return_double(request=1.1) + async_response = await async_client.endpoints.primitive.get_and_return_double( + request=1.1 + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_bool(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_bool( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = True expected_types: typing.Any = None response = client.endpoints.primitive.get_and_return_bool(request=True) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.primitive.get_and_return_bool(request=True) + async_response = await async_client.endpoints.primitive.get_and_return_bool( + request=True + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_datetime(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_datetime( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "2024-01-15T09:30:00Z" expected_types: typing.Any = "datetime" response = client.endpoints.primitive.get_and_return_datetime( @@ -73,10 +95,14 @@ async def test_get_and_return_datetime(client: SeedExhaustive, async_client: Asy validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_date(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_date( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "2023-01-15" expected_types: typing.Any = "date" - response = client.endpoints.primitive.get_and_return_date(request=datetime.date.fromisoformat("2023-01-15")) + response = client.endpoints.primitive.get_and_return_date( + request=datetime.date.fromisoformat("2023-01-15") + ) validate_response(response, expected_response, expected_types) async_response = await async_client.endpoints.primitive.get_and_return_date( @@ -85,10 +111,14 @@ async def test_get_and_return_date(client: SeedExhaustive, async_client: AsyncSe validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_uuid(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_uuid( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32" expected_types: typing.Any = "uuid" - response = client.endpoints.primitive.get_and_return_uuid(request=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32")) + response = client.endpoints.primitive.get_and_return_uuid( + request=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32") + ) validate_response(response, expected_response, expected_types) async_response = await async_client.endpoints.primitive.get_and_return_uuid( @@ -97,11 +127,17 @@ async def test_get_and_return_uuid(client: SeedExhaustive, async_client: AsyncSe validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_base_64(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_base_64( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "SGVsbG8gd29ybGQh" expected_types: typing.Any = None - response = client.endpoints.primitive.get_and_return_base_64(request="SGVsbG8gd29ybGQh") + response = client.endpoints.primitive.get_and_return_base_64( + request="SGVsbG8gd29ybGQh" + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.primitive.get_and_return_base_64(request="SGVsbG8gd29ybGQh") + async_response = await async_client.endpoints.primitive.get_and_return_base_64( + request="SGVsbG8gd29ybGQh" + ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/exhaustive/typeddict_requests/tests/endpoints/test_union.py b/seed/python-sdk/exhaustive/typeddict_requests/tests/endpoints/test_union.py index f7988fac5d7..8a77aed6a3a 100644 --- a/seed/python-sdk/exhaustive/typeddict_requests/tests/endpoints/test_union.py +++ b/seed/python-sdk/exhaustive/typeddict_requests/tests/endpoints/test_union.py @@ -7,8 +7,14 @@ from ..utilities import validate_response -async def test_get_and_return_union(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: - expected_response: typing.Any = {"animal": "dog", "name": "string", "likesToWoof": True} +async def test_get_and_return_union( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: + expected_response: typing.Any = { + "animal": "dog", + "name": "string", + "likesToWoof": True, + } expected_types: typing.Any = "no_validate" response = client.endpoints.union.get_and_return_union( request={"name": "string", "likes_to_woof": True, "animal": "dog"} diff --git a/seed/python-sdk/exhaustive/typeddict_requests/tests/test_inlined_requests.py b/seed/python-sdk/exhaustive/typeddict_requests/tests/test_inlined_requests.py index 635184eebf8..620139ed615 100644 --- a/seed/python-sdk/exhaustive/typeddict_requests/tests/test_inlined_requests.py +++ b/seed/python-sdk/exhaustive/typeddict_requests/tests/test_inlined_requests.py @@ -9,7 +9,9 @@ from .utilities import validate_response -async def test_post_with_object_bodyand_response(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_post_with_object_bodyand_response( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = { "string": "string", "integer": 1, @@ -61,23 +63,27 @@ async def test_post_with_object_bodyand_response(client: SeedExhaustive, async_c ) validate_response(response, expected_response, expected_types) - async_response = await async_client.inlined_requests.post_with_object_bodyand_response( - string="string", - integer=1, - nested_object={ - "string": "string", - "integer": 1, - "long_": 1000000, - "double": 1.1, - "bool_": True, - "datetime": datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), - "date": datetime.date.fromisoformat("2023-01-15"), - "uuid_": uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), - "base_64": "SGVsbG8gd29ybGQh", - "list_": ["string"], - "set_": {"string"}, - "map_": {1: "string"}, - "bigint": "123456789123456789", - }, + async_response = ( + await async_client.inlined_requests.post_with_object_bodyand_response( + string="string", + integer=1, + nested_object={ + "string": "string", + "integer": 1, + "long_": 1000000, + "double": 1.1, + "bool_": True, + "datetime": datetime.datetime.fromisoformat( + "2024-01-15 09:30:00+00:00" + ), + "date": datetime.date.fromisoformat("2023-01-15"), + "uuid_": uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + "base_64": "SGVsbG8gd29ybGQh", + "list_": ["string"], + "set_": {"string"}, + "map_": {1: "string"}, + "bigint": "123456789123456789", + }, + ) ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/exhaustive/typeddict_requests/tests/test_no_auth.py b/seed/python-sdk/exhaustive/typeddict_requests/tests/test_no_auth.py index 3328661bb48..7e6e66a5fb2 100644 --- a/seed/python-sdk/exhaustive/typeddict_requests/tests/test_no_auth.py +++ b/seed/python-sdk/exhaustive/typeddict_requests/tests/test_no_auth.py @@ -7,11 +7,15 @@ from .utilities import validate_response -async def test_post_with_no_auth(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_post_with_no_auth( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = True expected_types: typing.Any = None response = client.no_auth.post_with_no_auth(request={"key": "value"}) validate_response(response, expected_response, expected_types) - async_response = await async_client.no_auth.post_with_no_auth(request={"key": "value"}) + async_response = await async_client.no_auth.post_with_no_auth( + request={"key": "value"} + ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/exhaustive/typeddict_requests/tests/test_no_req_body.py b/seed/python-sdk/exhaustive/typeddict_requests/tests/test_no_req_body.py index 73abac9d2d8..5b6bc175eb9 100644 --- a/seed/python-sdk/exhaustive/typeddict_requests/tests/test_no_req_body.py +++ b/seed/python-sdk/exhaustive/typeddict_requests/tests/test_no_req_body.py @@ -7,7 +7,9 @@ from .utilities import validate_response -async def test_get_with_no_request_body(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_with_no_request_body( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = { "string": "string", "integer": 1, @@ -45,7 +47,9 @@ async def test_get_with_no_request_body(client: SeedExhaustive, async_client: As validate_response(async_response, expected_response, expected_types) -async def test_post_with_no_request_body(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_post_with_no_request_body( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "string" expected_types: typing.Any = None response = client.no_req_body.post_with_no_request_body() diff --git a/seed/python-sdk/exhaustive/typeddict_requests/tests/test_req_with_headers.py b/seed/python-sdk/exhaustive/typeddict_requests/tests/test_req_with_headers.py index bba3b5b5507..49888dfea93 100644 --- a/seed/python-sdk/exhaustive/typeddict_requests/tests/test_req_with_headers.py +++ b/seed/python-sdk/exhaustive/typeddict_requests/tests/test_req_with_headers.py @@ -3,8 +3,24 @@ from seed import AsyncSeedExhaustive, SeedExhaustive -async def test_get_with_custom_header(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_with_custom_header( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: # Type ignore to avoid mypy complaining about the function not being meant to return a value - assert client.req_with_headers.get_with_custom_header(x_test_service_header="string", x_test_endpoint_header="string", request="string") is None # type: ignore[func-returns-value] + assert ( + client.req_with_headers.get_with_custom_header( + x_test_service_header="string", + x_test_endpoint_header="string", + request="string", + ) + is None + ) # type: ignore[func-returns-value] - assert await async_client.req_with_headers.get_with_custom_header(x_test_service_header="string", x_test_endpoint_header="string", request="string") is None # type: ignore[func-returns-value] + assert ( + await async_client.req_with_headers.get_with_custom_header( + x_test_service_header="string", + x_test_endpoint_header="string", + request="string", + ) + is None + ) # type: ignore[func-returns-value] diff --git a/seed/python-sdk/exhaustive/typeddict_requests/tests/utilities.py b/seed/python-sdk/exhaustive/typeddict_requests/tests/utilities.py index 846741f9a0a..e8e706672c6 100644 --- a/seed/python-sdk/exhaustive/typeddict_requests/tests/utilities.py +++ b/seed/python-sdk/exhaustive/typeddict_requests/tests/utilities.py @@ -7,7 +7,9 @@ from dateutil import parser -def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> typing.Any: +def cast_field( + json_expectation: typing.Any, type_expectation: typing.Any +) -> typing.Any: # Cast these specific types which come through as string and expect our # models to cast to the correct type. if type_expectation == "uuid": @@ -25,7 +27,9 @@ def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> ty return json_expectation -def validate_field(response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any) -> None: +def validate_field( + response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectation == "no_validate": return @@ -44,7 +48,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(entry_expectation, dict): is_container_of_complex_type = True validate_response( - response=response[idx], json_expectation=ex, type_expectations=entry_expectation + response=response[idx], + json_expectation=ex, + type_expectations=entry_expectation, ) else: cast_json_expectation.append(cast_field(ex, entry_expectation)) @@ -56,7 +62,10 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # if any of the values of the set have a type_expectation of a dict, we're assuming it's a pydantic # model and keeping it a list. if container_expectation != "set" or not any( - map(lambda value: isinstance(value, dict), list(contents_expectation.values())) + map( + lambda value: isinstance(value, dict), + list(contents_expectation.values()), + ) ): json_expectation = cast_field(json_expectation, container_expectation) elif isinstance(type_expectation, tuple): @@ -65,9 +74,15 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(contents_expectation, dict): json_expectation = { cast_field( - key, contents_expectation.get(idx)[0] if contents_expectation.get(idx) is not None else None # type: ignore + key, + contents_expectation.get(idx)[0] + if contents_expectation.get(idx) is not None + else None, # type: ignore ): cast_field( - value, contents_expectation.get(idx)[1] if contents_expectation.get(idx) is not None else None # type: ignore + value, + contents_expectation.get(idx)[1] + if contents_expectation.get(idx) is not None + else None, # type: ignore ) for idx, (key, value) in enumerate(json_expectation.items()) } @@ -78,13 +93,17 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # When dealing with containers of models, etc. we're validating them implicitly, so no need to check the resultant list if not is_container_of_complex_type: - assert json_expectation == response, "Primitives found, expected: {0}, Actual: {1}".format( + assert ( + json_expectation == response + ), "Primitives found, expected: {0}, Actual: {1}".format( json_expectation, response ) # Arg type_expectations is a deeply nested structure that matches the response, but with the values replaced with the expected types -def validate_response(response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any) -> None: +def validate_response( + response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectations == "no_validate": return @@ -94,16 +113,24 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e and not isinstance(response, dict) and not issubclass(type(response), pydantic.BaseModel) ): - validate_field(response=response, json_expectation=json_expectation, type_expectation=type_expectations) + validate_field( + response=response, + json_expectation=json_expectation, + type_expectation=type_expectations, + ) return if isinstance(response, list): - assert len(response) == len(json_expectation), "Length mismatch, expected: {0}, Actual: {1}".format( + assert len(response) == len( + json_expectation + ), "Length mismatch, expected: {0}, Actual: {1}".format( len(response), len(json_expectation) ) for idx, item in enumerate(response): validate_response( - response=item, json_expectation=json_expectation[idx], type_expectations=type_expectations[idx] + response=item, + json_expectation=json_expectation[idx], + type_expectations=type_expectations[idx], ) else: response_json = response @@ -111,7 +138,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e response_json = response.dict(by_alias=True) for key, value in json_expectation.items(): - assert key in response_json, "Field {0} not found within the response object: {1}".format( + assert ( + key in response_json + ), "Field {0} not found within the response object: {1}".format( key, response_json ) @@ -123,11 +152,19 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e # Otherwise, we're just validating a single field that's a pydantic model. if isinstance(value, dict) and not isinstance(type_expectation, tuple): validate_response( - response=response_json[key], json_expectation=value, type_expectations=type_expectation + response=response_json[key], + json_expectation=value, + type_expectations=type_expectation, ) else: - validate_field(response=response_json[key], json_expectation=value, type_expectation=type_expectation) + validate_field( + response=response_json[key], + json_expectation=value, + type_expectation=type_expectation, + ) # Ensure there are no additional fields here either del response_json[key] - assert len(response_json) == 0, "Additional fields found, expected None: {0}".format(response_json) + assert ( + len(response_json) == 0 + ), "Additional fields found, expected None: {0}".format(response_json) diff --git a/seed/python-sdk/exhaustive/typeddict_requests/tests/utils/assets/models/circle.py b/seed/python-sdk/exhaustive/typeddict_requests/tests/utils/assets/models/circle.py index af7a1bf8a8e..6f8ad608aa7 100644 --- a/seed/python-sdk/exhaustive/typeddict_requests/tests/utils/assets/models/circle.py +++ b/seed/python-sdk/exhaustive/typeddict_requests/tests/utils/assets/models/circle.py @@ -7,4 +7,6 @@ class CircleParams(typing_extensions.TypedDict): - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] diff --git a/seed/python-sdk/exhaustive/typeddict_requests/tests/utils/assets/models/object_with_optional_field.py b/seed/python-sdk/exhaustive/typeddict_requests/tests/utils/assets/models/object_with_optional_field.py index 3ad93d5f305..96e216f1e5d 100644 --- a/seed/python-sdk/exhaustive/typeddict_requests/tests/utils/assets/models/object_with_optional_field.py +++ b/seed/python-sdk/exhaustive/typeddict_requests/tests/utils/assets/models/object_with_optional_field.py @@ -18,16 +18,30 @@ class ObjectWithOptionalFieldParams(typing_extensions.TypedDict): literal: typing.Literal["lit_one"] string: typing_extensions.NotRequired[str] integer: typing_extensions.NotRequired[int] - long_: typing_extensions.NotRequired[typing_extensions.Annotated[int, FieldMetadata(alias="long")]] + long_: typing_extensions.NotRequired[ + typing_extensions.Annotated[int, FieldMetadata(alias="long")] + ] double: typing_extensions.NotRequired[float] - bool_: typing_extensions.NotRequired[typing_extensions.Annotated[bool, FieldMetadata(alias="bool")]] + bool_: typing_extensions.NotRequired[ + typing_extensions.Annotated[bool, FieldMetadata(alias="bool")] + ] datetime: typing_extensions.NotRequired[dt.datetime] date: typing_extensions.NotRequired[dt.date] - uuid_: typing_extensions.NotRequired[typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")]] - base_64: typing_extensions.NotRequired[typing_extensions.Annotated[str, FieldMetadata(alias="base64")]] - list_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")]] - set_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")]] - map_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")]] + uuid_: typing_extensions.NotRequired[ + typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")] + ] + base_64: typing_extensions.NotRequired[ + typing_extensions.Annotated[str, FieldMetadata(alias="base64")] + ] + list_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")] + ] + set_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")] + ] + map_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")] + ] enum: typing_extensions.NotRequired[Color] union: typing_extensions.NotRequired[ShapeParams] second_union: typing_extensions.NotRequired[ShapeParams] diff --git a/seed/python-sdk/exhaustive/typeddict_requests/tests/utils/assets/models/shape.py b/seed/python-sdk/exhaustive/typeddict_requests/tests/utils/assets/models/shape.py index 2c33c877951..36a4dc88c37 100644 --- a/seed/python-sdk/exhaustive/typeddict_requests/tests/utils/assets/models/shape.py +++ b/seed/python-sdk/exhaustive/typeddict_requests/tests/utils/assets/models/shape.py @@ -15,13 +15,21 @@ class Base(typing_extensions.TypedDict): class Shape_CircleParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["circle"], FieldMetadata(alias="shapeType")] - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["circle"], FieldMetadata(alias="shapeType") + ] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] class Shape_SquareParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["square"], FieldMetadata(alias="shapeType")] - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["square"], FieldMetadata(alias="shapeType") + ] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] ShapeParams = typing.Union[Shape_CircleParams, Shape_SquareParams] diff --git a/seed/python-sdk/exhaustive/typeddict_requests/tests/utils/assets/models/square.py b/seed/python-sdk/exhaustive/typeddict_requests/tests/utils/assets/models/square.py index b9b7dd319bc..1fe4f0951dc 100644 --- a/seed/python-sdk/exhaustive/typeddict_requests/tests/utils/assets/models/square.py +++ b/seed/python-sdk/exhaustive/typeddict_requests/tests/utils/assets/models/square.py @@ -7,4 +7,6 @@ class SquareParams(typing_extensions.TypedDict): - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] diff --git a/seed/python-sdk/exhaustive/typeddict_requests/tests/utils/test_http_client.py b/seed/python-sdk/exhaustive/typeddict_requests/tests/utils/test_http_client.py index edd11ca7afb..f5a874a75f3 100644 --- a/seed/python-sdk/exhaustive/typeddict_requests/tests/utils/test_http_client.py +++ b/seed/python-sdk/exhaustive/typeddict_requests/tests/utils/test_http_client.py @@ -9,12 +9,17 @@ def get_request_options() -> RequestOptions: def test_get_json_request_body() -> None: - json_body, data_body = get_request_body(json={"hello": "world"}, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json={"hello": "world"}, data=None, request_options=None, omit=None + ) assert json_body == {"hello": "world"} assert data_body is None json_body_extras, data_body_extras = get_request_body( - json={"goodbye": "world"}, data=None, request_options=get_request_options(), omit=None + json={"goodbye": "world"}, + data=None, + request_options=get_request_options(), + omit=None, ) assert json_body_extras == {"goodbye": "world", "see you": "later"} @@ -22,12 +27,17 @@ def test_get_json_request_body() -> None: def test_get_files_request_body() -> None: - json_body, data_body = get_request_body(json=None, data={"hello": "world"}, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data={"hello": "world"}, request_options=None, omit=None + ) assert data_body == {"hello": "world"} assert json_body is None json_body_extras, data_body_extras = get_request_body( - json=None, data={"goodbye": "world"}, request_options=get_request_options(), omit=None + json=None, + data={"goodbye": "world"}, + request_options=get_request_options(), + omit=None, ) assert data_body_extras == {"goodbye": "world", "see you": "later"} @@ -35,7 +45,9 @@ def test_get_files_request_body() -> None: def test_get_none_request_body() -> None: - json_body, data_body = get_request_body(json=None, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data=None, request_options=None, omit=None + ) assert data_body is None assert json_body is None diff --git a/seed/python-sdk/exhaustive/typeddict_requests/tests/utils/test_query_encoding.py b/seed/python-sdk/exhaustive/typeddict_requests/tests/utils/test_query_encoding.py index 247e1551b46..fbc8f402167 100644 --- a/seed/python-sdk/exhaustive/typeddict_requests/tests/utils/test_query_encoding.py +++ b/seed/python-sdk/exhaustive/typeddict_requests/tests/utils/test_query_encoding.py @@ -4,9 +4,15 @@ def test_query_encoding() -> None: - assert encode_query({"hello world": "hello world"}) == {"hello world": "hello world"} - assert encode_query({"hello_world": {"hello": "world"}}) == {"hello_world[hello]": "world"} - assert encode_query({"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"}) == { + assert encode_query({"hello world": "hello world"}) == { + "hello world": "hello world" + } + assert encode_query({"hello_world": {"hello": "world"}}) == { + "hello_world[hello]": "world" + } + assert encode_query( + {"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"} + ) == { "hello_world[hello][world]": "today", "hello_world[test]": "this", "hi": "there", diff --git a/seed/python-sdk/exhaustive/typeddict_requests/tests/utils/test_serialization.py b/seed/python-sdk/exhaustive/typeddict_requests/tests/utils/test_serialization.py index 58b1ed66e6d..b5af3e550fe 100644 --- a/seed/python-sdk/exhaustive/typeddict_requests/tests/utils/test_serialization.py +++ b/seed/python-sdk/exhaustive/typeddict_requests/tests/utils/test_serialization.py @@ -18,20 +18,54 @@ def test_convert_and_respect_annotation_metadata() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) - assert converted == {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"} + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) + assert converted == { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + } def test_convert_and_respect_annotation_metadata_in_list() -> None: data: List[ObjectWithOptionalFieldParams] = [ - {"string": "string", "long_": 12345, "bool_": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long_": 67890, "list_": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long_": 12345, + "bool_": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long_": 67890, + "list_": [], + "literal": "lit_one", + "any": "any", + }, ] - converted = convert_and_respect_annotation_metadata(object_=data, annotation=List[ObjectWithOptionalFieldParams]) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=List[ObjectWithOptionalFieldParams] + ) assert converted == [ - {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long": 67890, "list": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long": 67890, + "list": [], + "literal": "lit_one", + "any": "any", + }, ] @@ -43,7 +77,9 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) assert converted == { "string": "string", @@ -55,12 +91,16 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: def test_convert_and_respect_annotation_metadata_in_union() -> None: - converted = convert_and_respect_annotation_metadata(object_=UNION_TEST, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=UNION_TEST, annotation=ShapeParams + ) assert converted == UNION_TEST_CONVERTED def test_convert_and_respect_annotation_metadata_with_empty_object() -> None: data: Any = {} - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ShapeParams + ) assert converted == data diff --git a/seed/python-sdk/exhaustive/union-utils/pyproject.toml b/seed/python-sdk/exhaustive/union-utils/pyproject.toml index c6cd3a2b7b9..fc29a237334 100644 --- a/seed/python-sdk/exhaustive/union-utils/pyproject.toml +++ b/seed/python-sdk/exhaustive/union-utils/pyproject.toml @@ -43,6 +43,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/python-sdk/exhaustive/union-utils/src/seed/__init__.py b/seed/python-sdk/exhaustive/union-utils/src/seed/__init__.py index eb56b0ce275..dc1ef03a650 100644 --- a/seed/python-sdk/exhaustive/union-utils/src/seed/__init__.py +++ b/seed/python-sdk/exhaustive/union-utils/src/seed/__init__.py @@ -1,6 +1,14 @@ # This file was auto-generated by Fern from our API Definition. -from . import endpoints, general_errors, inlined_requests, no_auth, no_req_body, req_with_headers, types +from . import ( + endpoints, + general_errors, + inlined_requests, + no_auth, + no_req_body, + req_with_headers, + types, +) from .client import AsyncSeedExhaustive, SeedExhaustive from .general_errors import BadObjectRequestInfo, BadRequestBody from .version import __version__ diff --git a/seed/python-sdk/exhaustive/union-utils/src/seed/client.py b/seed/python-sdk/exhaustive/union-utils/src/seed/client.py index b1b9764c7a7..f5ab292af6b 100644 --- a/seed/python-sdk/exhaustive/union-utils/src/seed/client.py +++ b/seed/python-sdk/exhaustive/union-utils/src/seed/client.py @@ -1,15 +1,19 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from .endpoints.client import AsyncEndpointsClient, EndpointsClient -from .inlined_requests.client import AsyncInlinedRequestsClient, InlinedRequestsClient -from .no_auth.client import AsyncNoAuthClient, NoAuthClient -from .no_req_body.client import AsyncNoReqBodyClient, NoReqBodyClient -from .req_with_headers.client import AsyncReqWithHeadersClient, ReqWithHeadersClient +from .core.client_wrapper import SyncClientWrapper +from .endpoints.client import EndpointsClient +from .inlined_requests.client import InlinedRequestsClient +from .no_auth.client import NoAuthClient +from .no_req_body.client import NoReqBodyClient +from .req_with_headers.client import ReqWithHeadersClient +from .core.client_wrapper import AsyncClientWrapper +from .endpoints.client import AsyncEndpointsClient +from .inlined_requests.client import AsyncInlinedRequestsClient +from .no_auth.client import AsyncNoAuthClient +from .no_req_body.client import AsyncNoReqBodyClient +from .req_with_headers.client import AsyncReqWithHeadersClient class SeedExhaustive: @@ -48,24 +52,32 @@ def __init__( token: typing.Optional[typing.Union[str, typing.Callable[[], str]]] = None, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.Client] = None + httpx_client: typing.Optional[httpx.Client] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = SyncClientWrapper( base_url=base_url, token=token, httpx_client=httpx_client if httpx_client is not None - else httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.Client( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.Client(timeout=_defaulted_timeout), timeout=_defaulted_timeout, ) self.endpoints = EndpointsClient(client_wrapper=self._client_wrapper) - self.inlined_requests = InlinedRequestsClient(client_wrapper=self._client_wrapper) + self.inlined_requests = InlinedRequestsClient( + client_wrapper=self._client_wrapper + ) self.no_auth = NoAuthClient(client_wrapper=self._client_wrapper) self.no_req_body = NoReqBodyClient(client_wrapper=self._client_wrapper) - self.req_with_headers = ReqWithHeadersClient(client_wrapper=self._client_wrapper) + self.req_with_headers = ReqWithHeadersClient( + client_wrapper=self._client_wrapper + ) class AsyncSeedExhaustive: @@ -104,21 +116,29 @@ def __init__( token: typing.Optional[typing.Union[str, typing.Callable[[], str]]] = None, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.AsyncClient] = None + httpx_client: typing.Optional[httpx.AsyncClient] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = AsyncClientWrapper( base_url=base_url, token=token, httpx_client=httpx_client if httpx_client is not None - else httpx.AsyncClient(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.AsyncClient( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.AsyncClient(timeout=_defaulted_timeout), timeout=_defaulted_timeout, ) self.endpoints = AsyncEndpointsClient(client_wrapper=self._client_wrapper) - self.inlined_requests = AsyncInlinedRequestsClient(client_wrapper=self._client_wrapper) + self.inlined_requests = AsyncInlinedRequestsClient( + client_wrapper=self._client_wrapper + ) self.no_auth = AsyncNoAuthClient(client_wrapper=self._client_wrapper) self.no_req_body = AsyncNoReqBodyClient(client_wrapper=self._client_wrapper) - self.req_with_headers = AsyncReqWithHeadersClient(client_wrapper=self._client_wrapper) + self.req_with_headers = AsyncReqWithHeadersClient( + client_wrapper=self._client_wrapper + ) diff --git a/seed/python-sdk/exhaustive/union-utils/src/seed/core/api_error.py b/seed/python-sdk/exhaustive/union-utils/src/seed/core/api_error.py index 2e9fc5431cd..da734b58068 100644 --- a/seed/python-sdk/exhaustive/union-utils/src/seed/core/api_error.py +++ b/seed/python-sdk/exhaustive/union-utils/src/seed/core/api_error.py @@ -7,7 +7,9 @@ class ApiError(Exception): status_code: typing.Optional[int] body: typing.Any - def __init__(self, *, status_code: typing.Optional[int] = None, body: typing.Any = None): + def __init__( + self, *, status_code: typing.Optional[int] = None, body: typing.Any = None + ): self.status_code = status_code self.body = body diff --git a/seed/python-sdk/exhaustive/union-utils/src/seed/core/client_wrapper.py b/seed/python-sdk/exhaustive/union-utils/src/seed/core/client_wrapper.py index 8d01b584b82..d037184a816 100644 --- a/seed/python-sdk/exhaustive/union-utils/src/seed/core/client_wrapper.py +++ b/seed/python-sdk/exhaustive/union-utils/src/seed/core/client_wrapper.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .http_client import AsyncHttpClient, HttpClient +from .http_client import HttpClient +from .http_client import AsyncHttpClient class BaseClientWrapper: diff --git a/seed/python-sdk/exhaustive/union-utils/src/seed/core/datetime_utils.py b/seed/python-sdk/exhaustive/union-utils/src/seed/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/python-sdk/exhaustive/union-utils/src/seed/core/datetime_utils.py +++ b/seed/python-sdk/exhaustive/union-utils/src/seed/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/python-sdk/exhaustive/union-utils/src/seed/core/file.py b/seed/python-sdk/exhaustive/union-utils/src/seed/core/file.py index cb0d40bbbf3..6e0f92bfcb1 100644 --- a/seed/python-sdk/exhaustive/union-utils/src/seed/core/file.py +++ b/seed/python-sdk/exhaustive/union-utils/src/seed/core/file.py @@ -13,12 +13,17 @@ # (filename, file (or bytes), content_type) typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str]], # (filename, file (or bytes), content_type, headers) - typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str], typing.Mapping[str, str]], + typing.Tuple[ + typing.Optional[str], + FileContent, + typing.Optional[str], + typing.Mapping[str, str], + ], ] def convert_file_dict_to_httpx_tuples( - d: typing.Dict[str, typing.Union[File, typing.List[File]]] + d: typing.Dict[str, typing.Union[File, typing.List[File]]], ) -> typing.List[typing.Tuple[str, File]]: """ The format we use is a list of tuples, where the first element is the diff --git a/seed/python-sdk/exhaustive/union-utils/src/seed/core/http_client.py b/seed/python-sdk/exhaustive/union-utils/src/seed/core/http_client.py index 9333d8a7f15..091f71bc185 100644 --- a/seed/python-sdk/exhaustive/union-utils/src/seed/core/http_client.py +++ b/seed/python-sdk/exhaustive/union-utils/src/seed/core/http_client.py @@ -77,7 +77,9 @@ def _retry_timeout(response: httpx.Response, retries: int) -> float: return retry_after # Apply exponential backoff, capped at MAX_RETRY_DELAY_SECONDS. - retry_delay = min(INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS) + retry_delay = min( + INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS + ) # Add a randomness / jitter to the retry delay to avoid overwhelming the server with retries. timeout = retry_delay * (1 - 0.25 * random()) @@ -90,7 +92,8 @@ def _should_retry(response: httpx.Response) -> bool: def remove_omit_from_dict( - original: typing.Dict[str, typing.Optional[typing.Any]], omit: typing.Optional[typing.Any] + original: typing.Dict[str, typing.Optional[typing.Any]], + omit: typing.Optional[typing.Any], ) -> typing.Dict[str, typing.Any]: if omit is None: return original @@ -108,7 +111,8 @@ def maybe_filter_request_body( ) -> typing.Optional[typing.Any]: if data is None: return ( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else None ) @@ -118,7 +122,8 @@ def maybe_filter_request_body( data_content = { **(jsonable_encoder(remove_omit_from_dict(data, omit))), # type: ignore **( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else {} ), @@ -162,7 +167,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url def request( @@ -174,8 +181,12 @@ def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -184,11 +195,14 @@ def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) response = self.httpx_client.request( method=method, @@ -198,7 +212,11 @@ def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -209,7 +227,10 @@ def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -222,11 +243,15 @@ def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: time.sleep(_retry_timeout(response=response, retries=retries)) @@ -256,8 +281,12 @@ def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -266,11 +295,14 @@ def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) with self.httpx_client.stream( method=method, @@ -280,7 +312,11 @@ def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -291,7 +327,9 @@ def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -304,7 +342,9 @@ def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream @@ -327,7 +367,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url async def request( @@ -339,8 +381,12 @@ async def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -349,11 +395,14 @@ async def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) # Add the input to each of these and do None-safety checks response = await self.httpx_client.request( @@ -364,7 +413,11 @@ async def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -375,7 +428,10 @@ async def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -388,11 +444,15 @@ async def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: await asyncio.sleep(_retry_timeout(response=response, retries=retries)) @@ -421,8 +481,12 @@ async def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -431,11 +495,14 @@ async def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) async with self.httpx_client.stream( method=method, @@ -445,7 +512,11 @@ async def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -456,7 +527,9 @@ async def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -469,7 +542,9 @@ async def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream diff --git a/seed/python-sdk/exhaustive/union-utils/src/seed/core/jsonable_encoder.py b/seed/python-sdk/exhaustive/union-utils/src/seed/core/jsonable_encoder.py index d3fd328fd41..12a8b52fc22 100644 --- a/seed/python-sdk/exhaustive/union-utils/src/seed/core/jsonable_encoder.py +++ b/seed/python-sdk/exhaustive/union-utils/src/seed/core/jsonable_encoder.py @@ -19,13 +19,19 @@ import pydantic from .datetime_utils import serialize_datetime -from .pydantic_utilities import IS_PYDANTIC_V2, encode_by_type, to_jsonable_with_fallback +from .pydantic_utilities import ( + IS_PYDANTIC_V2, + encode_by_type, + to_jsonable_with_fallback, +) SetIntStr = Set[Union[int, str]] DictIntStrAny = Dict[Union[int, str], Any] -def jsonable_encoder(obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None) -> Any: +def jsonable_encoder( + obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None +) -> Any: custom_encoder = custom_encoder or {} if custom_encoder: if type(obj) in custom_encoder: diff --git a/seed/python-sdk/exhaustive/union-utils/src/seed/core/pydantic_utilities.py b/seed/python-sdk/exhaustive/union-utils/src/seed/core/pydantic_utilities.py index 170a563d6eb..c63935c32a2 100644 --- a/seed/python-sdk/exhaustive/union-utils/src/seed/core/pydantic_utilities.py +++ b/seed/python-sdk/exhaustive/union-utils/src/seed/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) # type: ignore # Pydantic v1 diff --git a/seed/python-sdk/exhaustive/union-utils/src/seed/core/query_encoder.py b/seed/python-sdk/exhaustive/union-utils/src/seed/core/query_encoder.py index 24076d72ee9..7cb98f52cd7 100644 --- a/seed/python-sdk/exhaustive/union-utils/src/seed/core/query_encoder.py +++ b/seed/python-sdk/exhaustive/union-utils/src/seed/core/query_encoder.py @@ -7,7 +7,9 @@ # Flattens dicts to be of the form {"key[subkey][subkey2]": value} where value is not a dict -def traverse_query_dict(dict_flat: Dict[str, Any], key_prefix: Optional[str] = None) -> Dict[str, Any]: +def traverse_query_dict( + dict_flat: Dict[str, Any], key_prefix: Optional[str] = None +) -> Dict[str, Any]: result = {} for k, v in dict_flat.items(): key = f"{key_prefix}[{k}]" if key_prefix is not None else k @@ -30,4 +32,8 @@ def single_query_encoder(query_key: str, query_value: Any) -> Dict[str, Any]: def encode_query(query: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: - return dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) if query is not None else None + return ( + dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) + if query is not None + else None + ) diff --git a/seed/python-sdk/exhaustive/union-utils/src/seed/core/serialization.py b/seed/python-sdk/exhaustive/union-utils/src/seed/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/python-sdk/exhaustive/union-utils/src/seed/core/serialization.py +++ b/seed/python-sdk/exhaustive/union-utils/src/seed/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/python-sdk/exhaustive/union-utils/src/seed/endpoints/__init__.py b/seed/python-sdk/exhaustive/union-utils/src/seed/endpoints/__init__.py index 92307cab7fe..a9496ece178 100644 --- a/seed/python-sdk/exhaustive/union-utils/src/seed/endpoints/__init__.py +++ b/seed/python-sdk/exhaustive/union-utils/src/seed/endpoints/__init__.py @@ -2,4 +2,12 @@ from . import container, enum, http_methods, object, params, primitive, union -__all__ = ["container", "enum", "http_methods", "object", "params", "primitive", "union"] +__all__ = [ + "container", + "enum", + "http_methods", + "object", + "params", + "primitive", + "union", +] diff --git a/seed/python-sdk/exhaustive/union-utils/src/seed/endpoints/client.py b/seed/python-sdk/exhaustive/union-utils/src/seed/endpoints/client.py index 18dc397fdf1..69930de54d7 100644 --- a/seed/python-sdk/exhaustive/union-utils/src/seed/endpoints/client.py +++ b/seed/python-sdk/exhaustive/union-utils/src/seed/endpoints/client.py @@ -1,13 +1,21 @@ # This file was auto-generated by Fern from our API Definition. -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from .container.client import AsyncContainerClient, ContainerClient -from .enum.client import AsyncEnumClient, EnumClient -from .http_methods.client import AsyncHttpMethodsClient, HttpMethodsClient -from .object.client import AsyncObjectClient, ObjectClient -from .params.client import AsyncParamsClient, ParamsClient -from .primitive.client import AsyncPrimitiveClient, PrimitiveClient -from .union.client import AsyncUnionClient, UnionClient +from ..core.client_wrapper import SyncClientWrapper +from .container.client import ContainerClient +from .enum.client import EnumClient +from .http_methods.client import HttpMethodsClient +from .object.client import ObjectClient +from .params.client import ParamsClient +from .primitive.client import PrimitiveClient +from .union.client import UnionClient +from ..core.client_wrapper import AsyncClientWrapper +from .container.client import AsyncContainerClient +from .enum.client import AsyncEnumClient +from .http_methods.client import AsyncHttpMethodsClient +from .object.client import AsyncObjectClient +from .params.client import AsyncParamsClient +from .primitive.client import AsyncPrimitiveClient +from .union.client import AsyncUnionClient class EndpointsClient: diff --git a/seed/python-sdk/exhaustive/union-utils/src/seed/endpoints/container/client.py b/seed/python-sdk/exhaustive/union-utils/src/seed/endpoints/container/client.py index c6cf14f63ac..4af9c12d534 100644 --- a/seed/python-sdk/exhaustive/union-utils/src/seed/endpoints/container/client.py +++ b/seed/python-sdk/exhaustive/union-utils/src/seed/endpoints/container/client.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. import typing +from ...core.client_wrapper import SyncClientWrapper +from ...core.request_options import RequestOptions +from ...core.pydantic_utilities import parse_obj_as from json.decoder import JSONDecodeError - from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ...core.pydantic_utilities import parse_obj_as -from ...core.request_options import RequestOptions from ...types.object.types.object_with_required_field import ObjectWithRequiredField +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -18,7 +18,10 @@ def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper def get_and_return_list_of_primitives( - self, *, request: typing.Sequence[str], request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Sequence[str], + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[str]: """ Parameters @@ -45,11 +48,18 @@ def get_and_return_list_of_primitives( ) """ _response = self._client_wrapper.httpx_client.request( - "container/list-of-primitives", method="POST", json=request, request_options=request_options, omit=OMIT + "container/list-of-primitives", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.List[str], parse_obj_as(type_=typing.List[str], object_=_response.json())) # type: ignore + return typing.cast( + typing.List[str], + parse_obj_as(type_=typing.List[str], object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -59,7 +69,7 @@ def get_and_return_list_of_objects( self, *, request: typing.Sequence[ObjectWithRequiredField], - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[ObjectWithRequiredField]: """ Parameters @@ -91,18 +101,31 @@ def get_and_return_list_of_objects( ) """ _response = self._client_wrapper.httpx_client.request( - "container/list-of-objects", method="POST", json=request, request_options=request_options, omit=OMIT + "container/list-of-objects", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.List[ObjectWithRequiredField], parse_obj_as(type_=typing.List[ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.List[ObjectWithRequiredField], + parse_obj_as( + type_=typing.List[ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_and_return_set_of_primitives( - self, *, request: typing.Set[str], request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Set[str], + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Set[str]: """ Parameters @@ -129,11 +152,18 @@ def get_and_return_set_of_primitives( ) """ _response = self._client_wrapper.httpx_client.request( - "container/set-of-primitives", method="POST", json=request, request_options=request_options, omit=OMIT + "container/set-of-primitives", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Set[str], parse_obj_as(type_=typing.Set[str], object_=_response.json())) # type: ignore + return typing.cast( + typing.Set[str], + parse_obj_as(type_=typing.Set[str], object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -143,7 +173,7 @@ def get_and_return_set_of_objects( self, *, request: typing.Sequence[ObjectWithRequiredField], - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[ObjectWithRequiredField]: """ Parameters @@ -175,18 +205,31 @@ def get_and_return_set_of_objects( ) """ _response = self._client_wrapper.httpx_client.request( - "container/set-of-objects", method="POST", json=request, request_options=request_options, omit=OMIT + "container/set-of-objects", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.List[ObjectWithRequiredField], parse_obj_as(type_=typing.List[ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.List[ObjectWithRequiredField], + parse_obj_as( + type_=typing.List[ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_and_return_map_prim_to_prim( - self, *, request: typing.Dict[str, str], request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Dict[str, str], + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Dict[str, str]: """ Parameters @@ -213,11 +256,18 @@ def get_and_return_map_prim_to_prim( ) """ _response = self._client_wrapper.httpx_client.request( - "container/map-prim-to-prim", method="POST", json=request, request_options=request_options, omit=OMIT + "container/map-prim-to-prim", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Dict[str, str], parse_obj_as(type_=typing.Dict[str, str], object_=_response.json())) # type: ignore + return typing.cast( + typing.Dict[str, str], + parse_obj_as(type_=typing.Dict[str, str], object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -227,7 +277,7 @@ def get_and_return_map_of_prim_to_object( self, *, request: typing.Dict[str, ObjectWithRequiredField], - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Dict[str, ObjectWithRequiredField]: """ Parameters @@ -259,11 +309,21 @@ def get_and_return_map_of_prim_to_object( ) """ _response = self._client_wrapper.httpx_client.request( - "container/map-prim-to-object", method="POST", json=request, request_options=request_options, omit=OMIT + "container/map-prim-to-object", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Dict[str, ObjectWithRequiredField], parse_obj_as(type_=typing.Dict[str, ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.Dict[str, ObjectWithRequiredField], + parse_obj_as( + type_=typing.Dict[str, ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -273,7 +333,7 @@ def get_and_return_optional( self, *, request: typing.Optional[ObjectWithRequiredField] = None, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Optional[ObjectWithRequiredField]: """ Parameters @@ -303,11 +363,21 @@ def get_and_return_optional( ) """ _response = self._client_wrapper.httpx_client.request( - "container/opt-objects", method="POST", json=request, request_options=request_options, omit=OMIT + "container/opt-objects", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Optional[ObjectWithRequiredField], parse_obj_as(type_=typing.Optional[ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.Optional[ObjectWithRequiredField], + parse_obj_as( + type_=typing.Optional[ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -319,7 +389,10 @@ def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper async def get_and_return_list_of_primitives( - self, *, request: typing.Sequence[str], request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Sequence[str], + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[str]: """ Parameters @@ -354,11 +427,18 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/list-of-primitives", method="POST", json=request, request_options=request_options, omit=OMIT + "container/list-of-primitives", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.List[str], parse_obj_as(type_=typing.List[str], object_=_response.json())) # type: ignore + return typing.cast( + typing.List[str], + parse_obj_as(type_=typing.List[str], object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -368,7 +448,7 @@ async def get_and_return_list_of_objects( self, *, request: typing.Sequence[ObjectWithRequiredField], - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[ObjectWithRequiredField]: """ Parameters @@ -408,18 +488,31 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/list-of-objects", method="POST", json=request, request_options=request_options, omit=OMIT + "container/list-of-objects", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.List[ObjectWithRequiredField], parse_obj_as(type_=typing.List[ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.List[ObjectWithRequiredField], + parse_obj_as( + type_=typing.List[ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_and_return_set_of_primitives( - self, *, request: typing.Set[str], request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Set[str], + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Set[str]: """ Parameters @@ -454,11 +547,18 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/set-of-primitives", method="POST", json=request, request_options=request_options, omit=OMIT + "container/set-of-primitives", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Set[str], parse_obj_as(type_=typing.Set[str], object_=_response.json())) # type: ignore + return typing.cast( + typing.Set[str], + parse_obj_as(type_=typing.Set[str], object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -468,7 +568,7 @@ async def get_and_return_set_of_objects( self, *, request: typing.Sequence[ObjectWithRequiredField], - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[ObjectWithRequiredField]: """ Parameters @@ -508,18 +608,31 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/set-of-objects", method="POST", json=request, request_options=request_options, omit=OMIT + "container/set-of-objects", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.List[ObjectWithRequiredField], parse_obj_as(type_=typing.List[ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.List[ObjectWithRequiredField], + parse_obj_as( + type_=typing.List[ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_and_return_map_prim_to_prim( - self, *, request: typing.Dict[str, str], request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Dict[str, str], + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Dict[str, str]: """ Parameters @@ -554,11 +667,18 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/map-prim-to-prim", method="POST", json=request, request_options=request_options, omit=OMIT + "container/map-prim-to-prim", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Dict[str, str], parse_obj_as(type_=typing.Dict[str, str], object_=_response.json())) # type: ignore + return typing.cast( + typing.Dict[str, str], + parse_obj_as(type_=typing.Dict[str, str], object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -568,7 +688,7 @@ async def get_and_return_map_of_prim_to_object( self, *, request: typing.Dict[str, ObjectWithRequiredField], - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Dict[str, ObjectWithRequiredField]: """ Parameters @@ -608,11 +728,21 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/map-prim-to-object", method="POST", json=request, request_options=request_options, omit=OMIT + "container/map-prim-to-object", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Dict[str, ObjectWithRequiredField], parse_obj_as(type_=typing.Dict[str, ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.Dict[str, ObjectWithRequiredField], + parse_obj_as( + type_=typing.Dict[str, ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -622,7 +752,7 @@ async def get_and_return_optional( self, *, request: typing.Optional[ObjectWithRequiredField] = None, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Optional[ObjectWithRequiredField]: """ Parameters @@ -660,11 +790,21 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "container/opt-objects", method="POST", json=request, request_options=request_options, omit=OMIT + "container/opt-objects", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.Optional[ObjectWithRequiredField], parse_obj_as(type_=typing.Optional[ObjectWithRequiredField], object_=_response.json())) # type: ignore + return typing.cast( + typing.Optional[ObjectWithRequiredField], + parse_obj_as( + type_=typing.Optional[ObjectWithRequiredField], + object_=_response.json(), + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/union-utils/src/seed/endpoints/enum/client.py b/seed/python-sdk/exhaustive/union-utils/src/seed/endpoints/enum/client.py index 44e2690ff6c..3e3208e3bcf 100644 --- a/seed/python-sdk/exhaustive/union-utils/src/seed/endpoints/enum/client.py +++ b/seed/python-sdk/exhaustive/union-utils/src/seed/endpoints/enum/client.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. import typing +from ...core.client_wrapper import SyncClientWrapper +from ...types.enum.types.weather_report import WeatherReport +from ...core.request_options import RequestOptions +from ...core.pydantic_utilities import parse_obj_as from json.decoder import JSONDecodeError - from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ...core.pydantic_utilities import parse_obj_as -from ...core.request_options import RequestOptions -from ...types.enum.types.weather_report import WeatherReport +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -18,7 +18,10 @@ def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper def get_and_return_enum( - self, *, request: WeatherReport, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: WeatherReport, + request_options: typing.Optional[RequestOptions] = None, ) -> WeatherReport: """ Parameters @@ -45,11 +48,18 @@ def get_and_return_enum( ) """ _response = self._client_wrapper.httpx_client.request( - "enum", method="POST", json=request, request_options=request_options, omit=OMIT + "enum", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(WeatherReport, parse_obj_as(type_=WeatherReport, object_=_response.json())) # type: ignore + return typing.cast( + WeatherReport, + parse_obj_as(type_=WeatherReport, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -61,7 +71,10 @@ def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper async def get_and_return_enum( - self, *, request: WeatherReport, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: WeatherReport, + request_options: typing.Optional[RequestOptions] = None, ) -> WeatherReport: """ Parameters @@ -96,11 +109,18 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "enum", method="POST", json=request, request_options=request_options, omit=OMIT + "enum", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(WeatherReport, parse_obj_as(type_=WeatherReport, object_=_response.json())) # type: ignore + return typing.cast( + WeatherReport, + parse_obj_as(type_=WeatherReport, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/union-utils/src/seed/endpoints/http_methods/client.py b/seed/python-sdk/exhaustive/union-utils/src/seed/endpoints/http_methods/client.py index a2549280a1b..570a227844f 100644 --- a/seed/python-sdk/exhaustive/union-utils/src/seed/endpoints/http_methods/client.py +++ b/seed/python-sdk/exhaustive/union-utils/src/seed/endpoints/http_methods/client.py @@ -1,16 +1,16 @@ # This file was auto-generated by Fern from our API Definition. -import datetime as dt import typing -import uuid -from json.decoder import JSONDecodeError - -from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper +from ...core.client_wrapper import SyncClientWrapper +from ...core.request_options import RequestOptions from ...core.jsonable_encoder import jsonable_encoder from ...core.pydantic_utilities import parse_obj_as -from ...core.request_options import RequestOptions +from json.decoder import JSONDecodeError +from ...core.api_error import ApiError from ...types.object.types.object_with_optional_field import ObjectWithOptionalField +import datetime as dt +import uuid +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -20,7 +20,9 @@ class HttpMethodsClient: def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper - def test_get(self, id: str, *, request_options: typing.Optional[RequestOptions] = None) -> str: + def test_get( + self, id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -46,11 +48,15 @@ def test_get(self, id: str, *, request_options: typing.Optional[RequestOptions] ) """ _response = self._client_wrapper.httpx_client.request( - f"http-methods/{jsonable_encoder(id)}", method="GET", request_options=request_options + f"http-methods/{jsonable_encoder(id)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -84,18 +90,33 @@ def test_post( ) """ _response = self._client_wrapper.httpx_client.request( - "http-methods", method="POST", json={"string": string}, request_options=request_options, omit=OMIT + "http-methods", + method="POST", + json={ + "string": string, + }, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def test_put( - self, id: str, *, string: str, request_options: typing.Optional[RequestOptions] = None + self, + id: str, + *, + string: str, + request_options: typing.Optional[RequestOptions] = None, ) -> ObjectWithOptionalField: """ Parameters @@ -127,13 +148,20 @@ def test_put( _response = self._client_wrapper.httpx_client.request( f"http-methods/{jsonable_encoder(id)}", method="PUT", - json={"string": string}, + json={ + "string": string, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -254,13 +282,20 @@ def test_patch( ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def test_delete(self, id: str, *, request_options: typing.Optional[RequestOptions] = None) -> bool: + def test_delete( + self, id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> bool: """ Parameters ---------- @@ -286,11 +321,15 @@ def test_delete(self, id: str, *, request_options: typing.Optional[RequestOption ) """ _response = self._client_wrapper.httpx_client.request( - f"http-methods/{jsonable_encoder(id)}", method="DELETE", request_options=request_options + f"http-methods/{jsonable_encoder(id)}", + method="DELETE", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -301,7 +340,9 @@ class AsyncHttpMethodsClient: def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper - async def test_get(self, id: str, *, request_options: typing.Optional[RequestOptions] = None) -> str: + async def test_get( + self, id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -335,11 +376,15 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - f"http-methods/{jsonable_encoder(id)}", method="GET", request_options=request_options + f"http-methods/{jsonable_encoder(id)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -381,18 +426,33 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "http-methods", method="POST", json={"string": string}, request_options=request_options, omit=OMIT + "http-methods", + method="POST", + json={ + "string": string, + }, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def test_put( - self, id: str, *, string: str, request_options: typing.Optional[RequestOptions] = None + self, + id: str, + *, + string: str, + request_options: typing.Optional[RequestOptions] = None, ) -> ObjectWithOptionalField: """ Parameters @@ -432,13 +492,20 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( f"http-methods/{jsonable_encoder(id)}", method="PUT", - json={"string": string}, + json={ + "string": string, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -566,13 +633,20 @@ async def main() -> None: ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - async def test_delete(self, id: str, *, request_options: typing.Optional[RequestOptions] = None) -> bool: + async def test_delete( + self, id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> bool: """ Parameters ---------- @@ -606,11 +680,15 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - f"http-methods/{jsonable_encoder(id)}", method="DELETE", request_options=request_options + f"http-methods/{jsonable_encoder(id)}", + method="DELETE", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/union-utils/src/seed/endpoints/object/client.py b/seed/python-sdk/exhaustive/union-utils/src/seed/endpoints/object/client.py index a724f959193..dcb1324b74b 100644 --- a/seed/python-sdk/exhaustive/union-utils/src/seed/endpoints/object/client.py +++ b/seed/python-sdk/exhaustive/union-utils/src/seed/endpoints/object/client.py @@ -1,20 +1,24 @@ # This file was auto-generated by Fern from our API Definition. -import datetime as dt import typing +from ...core.client_wrapper import SyncClientWrapper +import datetime as dt import uuid -from json.decoder import JSONDecodeError - -from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ...core.jsonable_encoder import jsonable_encoder -from ...core.pydantic_utilities import parse_obj_as from ...core.request_options import RequestOptions -from ...types.object.types.nested_object_with_optional_field import NestedObjectWithOptionalField -from ...types.object.types.nested_object_with_required_field import NestedObjectWithRequiredField -from ...types.object.types.object_with_map_of_map import ObjectWithMapOfMap from ...types.object.types.object_with_optional_field import ObjectWithOptionalField +from ...core.pydantic_utilities import parse_obj_as +from json.decoder import JSONDecodeError +from ...core.api_error import ApiError from ...types.object.types.object_with_required_field import ObjectWithRequiredField +from ...types.object.types.object_with_map_of_map import ObjectWithMapOfMap +from ...types.object.types.nested_object_with_optional_field import ( + NestedObjectWithOptionalField, +) +from ...types.object.types.nested_object_with_required_field import ( + NestedObjectWithRequiredField, +) +from ...core.jsonable_encoder import jsonable_encoder +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -135,7 +139,12 @@ def get_and_return_with_optional_field( ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -171,20 +180,30 @@ def get_and_return_with_required_field( _response = self._client_wrapper.httpx_client.request( "object/get-and-return-with-required-field", method="POST", - json={"string": string}, + json={ + "string": string, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithRequiredField, parse_obj_as(type_=ObjectWithRequiredField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithRequiredField, + parse_obj_as( + type_=ObjectWithRequiredField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_and_return_with_map_of_map( - self, *, map_: typing.Dict[str, typing.Dict[str, str]], request_options: typing.Optional[RequestOptions] = None + self, + *, + map_: typing.Dict[str, typing.Dict[str, str]], + request_options: typing.Optional[RequestOptions] = None, ) -> ObjectWithMapOfMap: """ Parameters @@ -213,13 +232,18 @@ def get_and_return_with_map_of_map( _response = self._client_wrapper.httpx_client.request( "object/get-and-return-with-map-of-map", method="POST", - json={"map": map_}, + json={ + "map": map_, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithMapOfMap, parse_obj_as(type_=ObjectWithMapOfMap, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithMapOfMap, + parse_obj_as(type_=ObjectWithMapOfMap, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -286,13 +310,21 @@ def get_and_return_nested_with_optional_field( _response = self._client_wrapper.httpx_client.request( "object/get-and-return-nested-with-optional-field", method="POST", - json={"string": string, "NestedObject": nested_object}, + json={ + "string": string, + "NestedObject": nested_object, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(NestedObjectWithOptionalField, parse_obj_as(type_=NestedObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + NestedObjectWithOptionalField, + parse_obj_as( + type_=NestedObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -363,13 +395,21 @@ def get_and_return_nested_with_required_field( _response = self._client_wrapper.httpx_client.request( f"object/get-and-return-nested-with-required-field/{jsonable_encoder(string_)}", method="POST", - json={"string": string, "NestedObject": nested_object}, + json={ + "string": string, + "NestedObject": nested_object, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(NestedObjectWithRequiredField, parse_obj_as(type_=NestedObjectWithRequiredField, object_=_response.json())) # type: ignore + return typing.cast( + NestedObjectWithRequiredField, + parse_obj_as( + type_=NestedObjectWithRequiredField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -446,7 +486,12 @@ def get_and_return_nested_with_required_field_as_list( ) try: if 200 <= _response.status_code < 300: - return typing.cast(NestedObjectWithRequiredField, parse_obj_as(type_=NestedObjectWithRequiredField, object_=_response.json())) # type: ignore + return typing.cast( + NestedObjectWithRequiredField, + parse_obj_as( + type_=NestedObjectWithRequiredField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -575,7 +620,12 @@ async def main() -> None: ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -619,20 +669,30 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( "object/get-and-return-with-required-field", method="POST", - json={"string": string}, + json={ + "string": string, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithRequiredField, parse_obj_as(type_=ObjectWithRequiredField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithRequiredField, + parse_obj_as( + type_=ObjectWithRequiredField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_and_return_with_map_of_map( - self, *, map_: typing.Dict[str, typing.Dict[str, str]], request_options: typing.Optional[RequestOptions] = None + self, + *, + map_: typing.Dict[str, typing.Dict[str, str]], + request_options: typing.Optional[RequestOptions] = None, ) -> ObjectWithMapOfMap: """ Parameters @@ -669,13 +729,18 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( "object/get-and-return-with-map-of-map", method="POST", - json={"map": map_}, + json={ + "map": map_, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithMapOfMap, parse_obj_as(type_=ObjectWithMapOfMap, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithMapOfMap, + parse_obj_as(type_=ObjectWithMapOfMap, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -749,13 +814,21 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( "object/get-and-return-nested-with-optional-field", method="POST", - json={"string": string, "NestedObject": nested_object}, + json={ + "string": string, + "NestedObject": nested_object, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(NestedObjectWithOptionalField, parse_obj_as(type_=NestedObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + NestedObjectWithOptionalField, + parse_obj_as( + type_=NestedObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -833,13 +906,21 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( f"object/get-and-return-nested-with-required-field/{jsonable_encoder(string_)}", method="POST", - json={"string": string, "NestedObject": nested_object}, + json={ + "string": string, + "NestedObject": nested_object, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(NestedObjectWithRequiredField, parse_obj_as(type_=NestedObjectWithRequiredField, object_=_response.json())) # type: ignore + return typing.cast( + NestedObjectWithRequiredField, + parse_obj_as( + type_=NestedObjectWithRequiredField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -923,7 +1004,12 @@ async def main() -> None: ) try: if 200 <= _response.status_code < 300: - return typing.cast(NestedObjectWithRequiredField, parse_obj_as(type_=NestedObjectWithRequiredField, object_=_response.json())) # type: ignore + return typing.cast( + NestedObjectWithRequiredField, + parse_obj_as( + type_=NestedObjectWithRequiredField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/union-utils/src/seed/endpoints/params/client.py b/seed/python-sdk/exhaustive/union-utils/src/seed/endpoints/params/client.py index 5cd7ceef42a..a9187ac94b8 100644 --- a/seed/python-sdk/exhaustive/union-utils/src/seed/endpoints/params/client.py +++ b/seed/python-sdk/exhaustive/union-utils/src/seed/endpoints/params/client.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. import typing -from json.decoder import JSONDecodeError - -from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper +from ...core.client_wrapper import SyncClientWrapper +from ...core.request_options import RequestOptions from ...core.jsonable_encoder import jsonable_encoder from ...core.pydantic_utilities import parse_obj_as -from ...core.request_options import RequestOptions +from json.decoder import JSONDecodeError +from ...core.api_error import ApiError +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -17,7 +17,9 @@ class ParamsClient: def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper - def get_with_path(self, param: str, *, request_options: typing.Optional[RequestOptions] = None) -> str: + def get_with_path( + self, param: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ GET with path param @@ -45,18 +47,26 @@ def get_with_path(self, param: str, *, request_options: typing.Optional[RequestO ) """ _response = self._client_wrapper.httpx_client.request( - f"params/path/{jsonable_encoder(param)}", method="GET", request_options=request_options + f"params/path/{jsonable_encoder(param)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_with_query( - self, *, query: str, number: int, request_options: typing.Optional[RequestOptions] = None + self, + *, + query: str, + number: int, + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ GET with query param @@ -88,7 +98,13 @@ def get_with_query( ) """ _response = self._client_wrapper.httpx_client.request( - "params", method="GET", params={"query": query, "number": number}, request_options=request_options + "params", + method="GET", + params={ + "query": query, + "number": number, + }, + request_options=request_options, ) try: if 200 <= _response.status_code < 300: @@ -135,7 +151,13 @@ def get_with_allow_multiple_query( ) """ _response = self._client_wrapper.httpx_client.request( - "params", method="GET", params={"query": query, "numer": numer}, request_options=request_options + "params", + method="GET", + params={ + "query": query, + "numer": numer, + }, + request_options=request_options, ) try: if 200 <= _response.status_code < 300: @@ -146,7 +168,11 @@ def get_with_allow_multiple_query( raise ApiError(status_code=_response.status_code, body=_response_json) def get_with_path_and_query( - self, param: str, *, query: str, request_options: typing.Optional[RequestOptions] = None + self, + param: str, + *, + query: str, + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ GET with path and query params @@ -180,7 +206,9 @@ def get_with_path_and_query( _response = self._client_wrapper.httpx_client.request( f"params/path-query/{jsonable_encoder(param)}", method="GET", - params={"query": query}, + params={ + "query": query, + }, request_options=request_options, ) try: @@ -192,7 +220,11 @@ def get_with_path_and_query( raise ApiError(status_code=_response.status_code, body=_response_json) def modify_with_path( - self, param: str, *, request: str, request_options: typing.Optional[RequestOptions] = None + self, + param: str, + *, + request: str, + request_options: typing.Optional[RequestOptions] = None, ) -> str: """ PUT to update with path param @@ -232,7 +264,9 @@ def modify_with_path( ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -243,7 +277,9 @@ class AsyncParamsClient: def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper - async def get_with_path(self, param: str, *, request_options: typing.Optional[RequestOptions] = None) -> str: + async def get_with_path( + self, param: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ GET with path param @@ -279,18 +315,26 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - f"params/path/{jsonable_encoder(param)}", method="GET", request_options=request_options + f"params/path/{jsonable_encoder(param)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_with_query( - self, *, query: str, number: int, request_options: typing.Optional[RequestOptions] = None + self, + *, + query: str, + number: int, + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ GET with query param @@ -330,7 +374,13 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "params", method="GET", params={"query": query, "number": number}, request_options=request_options + "params", + method="GET", + params={ + "query": query, + "number": number, + }, + request_options=request_options, ) try: if 200 <= _response.status_code < 300: @@ -385,7 +435,13 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "params", method="GET", params={"query": query, "numer": numer}, request_options=request_options + "params", + method="GET", + params={ + "query": query, + "numer": numer, + }, + request_options=request_options, ) try: if 200 <= _response.status_code < 300: @@ -396,7 +452,11 @@ async def main() -> None: raise ApiError(status_code=_response.status_code, body=_response_json) async def get_with_path_and_query( - self, param: str, *, query: str, request_options: typing.Optional[RequestOptions] = None + self, + param: str, + *, + query: str, + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ GET with path and query params @@ -438,7 +498,9 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( f"params/path-query/{jsonable_encoder(param)}", method="GET", - params={"query": query}, + params={ + "query": query, + }, request_options=request_options, ) try: @@ -450,7 +512,11 @@ async def main() -> None: raise ApiError(status_code=_response.status_code, body=_response_json) async def modify_with_path( - self, param: str, *, request: str, request_options: typing.Optional[RequestOptions] = None + self, + param: str, + *, + request: str, + request_options: typing.Optional[RequestOptions] = None, ) -> str: """ PUT to update with path param @@ -498,7 +564,9 @@ async def main() -> None: ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/union-utils/src/seed/endpoints/primitive/client.py b/seed/python-sdk/exhaustive/union-utils/src/seed/endpoints/primitive/client.py index 844b6a782f0..20a66f049b4 100644 --- a/seed/python-sdk/exhaustive/union-utils/src/seed/endpoints/primitive/client.py +++ b/seed/python-sdk/exhaustive/union-utils/src/seed/endpoints/primitive/client.py @@ -1,14 +1,14 @@ # This file was auto-generated by Fern from our API Definition. -import datetime as dt import typing -import uuid +from ...core.client_wrapper import SyncClientWrapper +from ...core.request_options import RequestOptions +from ...core.pydantic_utilities import parse_obj_as from json.decoder import JSONDecodeError - from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ...core.pydantic_utilities import parse_obj_as -from ...core.request_options import RequestOptions +import datetime as dt +import uuid +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -18,7 +18,9 @@ class PrimitiveClient: def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper - def get_and_return_string(self, *, request: str, request_options: typing.Optional[RequestOptions] = None) -> str: + def get_and_return_string( + self, *, request: str, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -44,17 +46,25 @@ def get_and_return_string(self, *, request: str, request_options: typing.Optiona ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/string", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/string", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def get_and_return_int(self, *, request: int, request_options: typing.Optional[RequestOptions] = None) -> int: + def get_and_return_int( + self, *, request: int, request_options: typing.Optional[RequestOptions] = None + ) -> int: """ Parameters ---------- @@ -80,17 +90,25 @@ def get_and_return_int(self, *, request: int, request_options: typing.Optional[R ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/integer", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/integer", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(int, parse_obj_as(type_=int, object_=_response.json())) # type: ignore + return typing.cast( + int, parse_obj_as(type_=int, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def get_and_return_long(self, *, request: int, request_options: typing.Optional[RequestOptions] = None) -> int: + def get_and_return_long( + self, *, request: int, request_options: typing.Optional[RequestOptions] = None + ) -> int: """ Parameters ---------- @@ -116,11 +134,17 @@ def get_and_return_long(self, *, request: int, request_options: typing.Optional[ ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/long", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/long", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(int, parse_obj_as(type_=int, object_=_response.json())) # type: ignore + return typing.cast( + int, parse_obj_as(type_=int, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -154,17 +178,25 @@ def get_and_return_double( ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/double", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/double", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(float, parse_obj_as(type_=float, object_=_response.json())) # type: ignore + return typing.cast( + float, parse_obj_as(type_=float, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def get_and_return_bool(self, *, request: bool, request_options: typing.Optional[RequestOptions] = None) -> bool: + def get_and_return_bool( + self, *, request: bool, request_options: typing.Optional[RequestOptions] = None + ) -> bool: """ Parameters ---------- @@ -190,18 +222,27 @@ def get_and_return_bool(self, *, request: bool, request_options: typing.Optional ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/boolean", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/boolean", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_and_return_datetime( - self, *, request: dt.datetime, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: dt.datetime, + request_options: typing.Optional[RequestOptions] = None, ) -> dt.datetime: """ Parameters @@ -232,18 +273,28 @@ def get_and_return_datetime( ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/datetime", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/datetime", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(dt.datetime, parse_obj_as(type_=dt.datetime, object_=_response.json())) # type: ignore + return typing.cast( + dt.datetime, + parse_obj_as(type_=dt.datetime, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_and_return_date( - self, *, request: dt.date, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: dt.date, + request_options: typing.Optional[RequestOptions] = None, ) -> dt.date: """ Parameters @@ -274,18 +325,27 @@ def get_and_return_date( ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/date", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/date", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(dt.date, parse_obj_as(type_=dt.date, object_=_response.json())) # type: ignore + return typing.cast( + dt.date, parse_obj_as(type_=dt.date, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get_and_return_uuid( - self, *, request: uuid.UUID, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: uuid.UUID, + request_options: typing.Optional[RequestOptions] = None, ) -> uuid.UUID: """ Parameters @@ -316,17 +376,25 @@ def get_and_return_uuid( ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/uuid", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/uuid", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(uuid.UUID, parse_obj_as(type_=uuid.UUID, object_=_response.json())) # type: ignore + return typing.cast( + uuid.UUID, parse_obj_as(type_=uuid.UUID, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def get_and_return_base_64(self, *, request: str, request_options: typing.Optional[RequestOptions] = None) -> str: + def get_and_return_base_64( + self, *, request: str, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -352,11 +420,17 @@ def get_and_return_base_64(self, *, request: str, request_options: typing.Option ) """ _response = self._client_wrapper.httpx_client.request( - "primitive/base64", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/base64", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -403,17 +477,25 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/string", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/string", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - async def get_and_return_int(self, *, request: int, request_options: typing.Optional[RequestOptions] = None) -> int: + async def get_and_return_int( + self, *, request: int, request_options: typing.Optional[RequestOptions] = None + ) -> int: """ Parameters ---------- @@ -447,11 +529,17 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/integer", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/integer", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(int, parse_obj_as(type_=int, object_=_response.json())) # type: ignore + return typing.cast( + int, parse_obj_as(type_=int, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -493,11 +581,17 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/long", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/long", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(int, parse_obj_as(type_=int, object_=_response.json())) # type: ignore + return typing.cast( + int, parse_obj_as(type_=int, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -539,11 +633,17 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/double", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/double", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(float, parse_obj_as(type_=float, object_=_response.json())) # type: ignore + return typing.cast( + float, parse_obj_as(type_=float, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -585,18 +685,27 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/boolean", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/boolean", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_and_return_datetime( - self, *, request: dt.datetime, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: dt.datetime, + request_options: typing.Optional[RequestOptions] = None, ) -> dt.datetime: """ Parameters @@ -634,18 +743,28 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/datetime", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/datetime", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(dt.datetime, parse_obj_as(type_=dt.datetime, object_=_response.json())) # type: ignore + return typing.cast( + dt.datetime, + parse_obj_as(type_=dt.datetime, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_and_return_date( - self, *, request: dt.date, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: dt.date, + request_options: typing.Optional[RequestOptions] = None, ) -> dt.date: """ Parameters @@ -683,18 +802,27 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/date", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/date", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(dt.date, parse_obj_as(type_=dt.date, object_=_response.json())) # type: ignore + return typing.cast( + dt.date, parse_obj_as(type_=dt.date, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get_and_return_uuid( - self, *, request: uuid.UUID, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: uuid.UUID, + request_options: typing.Optional[RequestOptions] = None, ) -> uuid.UUID: """ Parameters @@ -732,11 +860,17 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/uuid", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/uuid", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(uuid.UUID, parse_obj_as(type_=uuid.UUID, object_=_response.json())) # type: ignore + return typing.cast( + uuid.UUID, parse_obj_as(type_=uuid.UUID, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -778,11 +912,17 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "primitive/base64", method="POST", json=request, request_options=request_options, omit=OMIT + "primitive/base64", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/union-utils/src/seed/endpoints/union/client.py b/seed/python-sdk/exhaustive/union-utils/src/seed/endpoints/union/client.py index 77153587a27..f4c3d9312de 100644 --- a/seed/python-sdk/exhaustive/union-utils/src/seed/endpoints/union/client.py +++ b/seed/python-sdk/exhaustive/union-utils/src/seed/endpoints/union/client.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. import typing +from ...core.client_wrapper import SyncClientWrapper +from ...types.union.types.animal import Animal +from ...core.request_options import RequestOptions +from ...core.pydantic_utilities import parse_obj_as from json.decoder import JSONDecodeError - from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ...core.pydantic_utilities import parse_obj_as -from ...core.request_options import RequestOptions -from ...types.union.types.animal import Animal +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -18,7 +18,10 @@ def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper def get_and_return_union( - self, *, request: Animal, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: Animal, + request_options: typing.Optional[RequestOptions] = None, ) -> Animal: """ Parameters @@ -49,11 +52,17 @@ def get_and_return_union( ) """ _response = self._client_wrapper.httpx_client.request( - "union", method="POST", json=request, request_options=request_options, omit=OMIT + "union", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(Animal, parse_obj_as(type_=Animal, object_=_response.json())) # type: ignore + return typing.cast( + Animal, parse_obj_as(type_=Animal, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -65,7 +74,10 @@ def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper async def get_and_return_union( - self, *, request: Animal, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: Animal, + request_options: typing.Optional[RequestOptions] = None, ) -> Animal: """ Parameters @@ -104,11 +116,17 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "union", method="POST", json=request, request_options=request_options, omit=OMIT + "union", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(Animal, parse_obj_as(type_=Animal, object_=_response.json())) # type: ignore + return typing.cast( + Animal, parse_obj_as(type_=Animal, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/union-utils/src/seed/general_errors/types/bad_object_request_info.py b/seed/python-sdk/exhaustive/union-utils/src/seed/general_errors/types/bad_object_request_info.py index 7f03429e922..73c44b89531 100644 --- a/seed/python-sdk/exhaustive/union-utils/src/seed/general_errors/types/bad_object_request_info.py +++ b/seed/python-sdk/exhaustive/union-utils/src/seed/general_errors/types/bad_object_request_info.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class BadObjectRequestInfo(UniversalBaseModel): message: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/union-utils/src/seed/inlined_requests/client.py b/seed/python-sdk/exhaustive/union-utils/src/seed/inlined_requests/client.py index f7c46698eb9..39e0c8fe637 100644 --- a/seed/python-sdk/exhaustive/union-utils/src/seed/inlined_requests/client.py +++ b/seed/python-sdk/exhaustive/union-utils/src/seed/inlined_requests/client.py @@ -1,15 +1,15 @@ # This file was auto-generated by Fern from our API Definition. import typing -from json.decoder import JSONDecodeError - -from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.pydantic_utilities import parse_obj_as +from ..core.client_wrapper import SyncClientWrapper +from ..types.object.types.object_with_optional_field import ObjectWithOptionalField from ..core.request_options import RequestOptions +from ..core.pydantic_utilities import parse_obj_as from ..general_errors.errors.bad_request_body import BadRequestBody from ..general_errors.types.bad_object_request_info import BadObjectRequestInfo -from ..types.object.types.object_with_optional_field import ObjectWithOptionalField +from json.decoder import JSONDecodeError +from ..core.api_error import ApiError +from ..core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -25,7 +25,7 @@ def post_with_object_bodyand_response( string: str, integer: int, nested_object: ObjectWithOptionalField, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> ObjectWithOptionalField: """ POST with custom object in request body, response is an object @@ -86,16 +86,30 @@ def post_with_object_bodyand_response( _response = self._client_wrapper.httpx_client.request( "req-bodies/object", method="POST", - json={"string": string, "integer": integer, "NestedObject": nested_object}, + json={ + "string": string, + "integer": integer, + "NestedObject": nested_object, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore if _response.status_code == 400: raise BadRequestBody( - typing.cast(BadObjectRequestInfo, parse_obj_as(type_=BadObjectRequestInfo, object_=_response.json())) # type: ignore + typing.cast( + BadObjectRequestInfo, + parse_obj_as( + type_=BadObjectRequestInfo, object_=_response.json() + ), + ) # type: ignore ) _response_json = _response.json() except JSONDecodeError: @@ -113,7 +127,7 @@ async def post_with_object_bodyand_response( string: str, integer: int, nested_object: ObjectWithOptionalField, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> ObjectWithOptionalField: """ POST with custom object in request body, response is an object @@ -181,16 +195,30 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( "req-bodies/object", method="POST", - json={"string": string, "integer": integer, "NestedObject": nested_object}, + json={ + "string": string, + "integer": integer, + "NestedObject": nested_object, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore if _response.status_code == 400: raise BadRequestBody( - typing.cast(BadObjectRequestInfo, parse_obj_as(type_=BadObjectRequestInfo, object_=_response.json())) # type: ignore + typing.cast( + BadObjectRequestInfo, + parse_obj_as( + type_=BadObjectRequestInfo, object_=_response.json() + ), + ) # type: ignore ) _response_json = _response.json() except JSONDecodeError: diff --git a/seed/python-sdk/exhaustive/union-utils/src/seed/no_auth/client.py b/seed/python-sdk/exhaustive/union-utils/src/seed/no_auth/client.py index 3d203bcea34..e5590cde0df 100644 --- a/seed/python-sdk/exhaustive/union-utils/src/seed/no_auth/client.py +++ b/seed/python-sdk/exhaustive/union-utils/src/seed/no_auth/client.py @@ -1,14 +1,14 @@ # This file was auto-generated by Fern from our API Definition. import typing -from json.decoder import JSONDecodeError - -from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.pydantic_utilities import parse_obj_as +from ..core.client_wrapper import SyncClientWrapper from ..core.request_options import RequestOptions +from ..core.pydantic_utilities import parse_obj_as from ..general_errors.errors.bad_request_body import BadRequestBody from ..general_errors.types.bad_object_request_info import BadObjectRequestInfo +from json.decoder import JSONDecodeError +from ..core.api_error import ApiError +from ..core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -19,7 +19,10 @@ def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper def post_with_no_auth( - self, *, request: typing.Any, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Any, + request_options: typing.Optional[RequestOptions] = None, ) -> bool: """ POST request with no auth @@ -48,14 +51,25 @@ def post_with_no_auth( ) """ _response = self._client_wrapper.httpx_client.request( - "no-auth", method="POST", json=request, request_options=request_options, omit=OMIT + "no-auth", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore if _response.status_code == 400: raise BadRequestBody( - typing.cast(BadObjectRequestInfo, parse_obj_as(type_=BadObjectRequestInfo, object_=_response.json())) # type: ignore + typing.cast( + BadObjectRequestInfo, + parse_obj_as( + type_=BadObjectRequestInfo, object_=_response.json() + ), + ) # type: ignore ) _response_json = _response.json() except JSONDecodeError: @@ -68,7 +82,10 @@ def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper async def post_with_no_auth( - self, *, request: typing.Any, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Any, + request_options: typing.Optional[RequestOptions] = None, ) -> bool: """ POST request with no auth @@ -105,14 +122,25 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "no-auth", method="POST", json=request, request_options=request_options, omit=OMIT + "no-auth", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore if _response.status_code == 400: raise BadRequestBody( - typing.cast(BadObjectRequestInfo, parse_obj_as(type_=BadObjectRequestInfo, object_=_response.json())) # type: ignore + typing.cast( + BadObjectRequestInfo, + parse_obj_as( + type_=BadObjectRequestInfo, object_=_response.json() + ), + ) # type: ignore ) _response_json = _response.json() except JSONDecodeError: diff --git a/seed/python-sdk/exhaustive/union-utils/src/seed/no_req_body/client.py b/seed/python-sdk/exhaustive/union-utils/src/seed/no_req_body/client.py index 33fa0c77d27..5afdd703fdc 100644 --- a/seed/python-sdk/exhaustive/union-utils/src/seed/no_req_body/client.py +++ b/seed/python-sdk/exhaustive/union-utils/src/seed/no_req_body/client.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. +from ..core.client_wrapper import SyncClientWrapper import typing -from json.decoder import JSONDecodeError - -from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.pydantic_utilities import parse_obj_as from ..core.request_options import RequestOptions from ..types.object.types.object_with_optional_field import ObjectWithOptionalField +from ..core.pydantic_utilities import parse_obj_as +from json.decoder import JSONDecodeError +from ..core.api_error import ApiError +from ..core.client_wrapper import AsyncClientWrapper class NoReqBodyClient: @@ -38,17 +38,26 @@ def get_with_no_request_body( client.no_req_body.get_with_no_request_body() """ _response = self._client_wrapper.httpx_client.request( - "no-req-body", method="GET", request_options=request_options + "no-req-body", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def post_with_no_request_body(self, *, request_options: typing.Optional[RequestOptions] = None) -> str: + def post_with_no_request_body( + self, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -70,11 +79,15 @@ def post_with_no_request_body(self, *, request_options: typing.Optional[RequestO client.no_req_body.post_with_no_request_body() """ _response = self._client_wrapper.httpx_client.request( - "no-req-body", method="POST", request_options=request_options + "no-req-body", + method="POST", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -117,17 +130,26 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "no-req-body", method="GET", request_options=request_options + "no-req-body", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(ObjectWithOptionalField, parse_obj_as(type_=ObjectWithOptionalField, object_=_response.json())) # type: ignore + return typing.cast( + ObjectWithOptionalField, + parse_obj_as( + type_=ObjectWithOptionalField, object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - async def post_with_no_request_body(self, *, request_options: typing.Optional[RequestOptions] = None) -> str: + async def post_with_no_request_body( + self, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -157,11 +179,15 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "no-req-body", method="POST", request_options=request_options + "no-req-body", + method="POST", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/exhaustive/union-utils/src/seed/req_with_headers/client.py b/seed/python-sdk/exhaustive/union-utils/src/seed/req_with_headers/client.py index 655402249e9..984428516e3 100644 --- a/seed/python-sdk/exhaustive/union-utils/src/seed/req_with_headers/client.py +++ b/seed/python-sdk/exhaustive/union-utils/src/seed/req_with_headers/client.py @@ -1,11 +1,11 @@ # This file was auto-generated by Fern from our API Definition. import typing +from ..core.client_wrapper import SyncClientWrapper +from ..core.request_options import RequestOptions from json.decoder import JSONDecodeError - from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.request_options import RequestOptions +from ..core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -21,7 +21,7 @@ def get_with_custom_header( x_test_service_header: str, x_test_endpoint_header: str, request: str, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ Parameters @@ -58,8 +58,12 @@ def get_with_custom_header( method="POST", json=request, headers={ - "X-TEST-SERVICE-HEADER": str(x_test_service_header) if x_test_service_header is not None else None, - "X-TEST-ENDPOINT-HEADER": str(x_test_endpoint_header) if x_test_endpoint_header is not None else None, + "X-TEST-SERVICE-HEADER": str(x_test_service_header) + if x_test_service_header is not None + else None, + "X-TEST-ENDPOINT-HEADER": str(x_test_endpoint_header) + if x_test_endpoint_header is not None + else None, }, request_options=request_options, omit=OMIT, @@ -83,7 +87,7 @@ async def get_with_custom_header( x_test_service_header: str, x_test_endpoint_header: str, request: str, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ Parameters @@ -128,8 +132,12 @@ async def main() -> None: method="POST", json=request, headers={ - "X-TEST-SERVICE-HEADER": str(x_test_service_header) if x_test_service_header is not None else None, - "X-TEST-ENDPOINT-HEADER": str(x_test_endpoint_header) if x_test_endpoint_header is not None else None, + "X-TEST-SERVICE-HEADER": str(x_test_service_header) + if x_test_service_header is not None + else None, + "X-TEST-ENDPOINT-HEADER": str(x_test_endpoint_header) + if x_test_endpoint_header is not None + else None, }, request_options=request_options, omit=OMIT, diff --git a/seed/python-sdk/exhaustive/union-utils/src/seed/types/enum/types/weather_report.py b/seed/python-sdk/exhaustive/union-utils/src/seed/types/enum/types/weather_report.py index 2d54965dc22..84017ef161d 100644 --- a/seed/python-sdk/exhaustive/union-utils/src/seed/types/enum/types/weather_report.py +++ b/seed/python-sdk/exhaustive/union-utils/src/seed/types/enum/types/weather_report.py @@ -2,4 +2,6 @@ import typing -WeatherReport = typing.Union[typing.Literal["SUNNY", "CLOUDY", "RAINING", "SNOWING"], typing.Any] +WeatherReport = typing.Union[ + typing.Literal["SUNNY", "CLOUDY", "RAINING", "SNOWING"], typing.Any +] diff --git a/seed/python-sdk/exhaustive/union-utils/src/seed/types/object/types/double_optional.py b/seed/python-sdk/exhaustive/union-utils/src/seed/types/object/types/double_optional.py index ddf165b13bd..ed236347357 100644 --- a/seed/python-sdk/exhaustive/union-utils/src/seed/types/object/types/double_optional.py +++ b/seed/python-sdk/exhaustive/union-utils/src/seed/types/object/types/double_optional.py @@ -1,18 +1,21 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .optional_alias import OptionalAlias +import pydantic +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class DoubleOptional(UniversalBaseModel): - optional_alias: typing.Optional[OptionalAlias] = pydantic.Field(alias="optionalAlias", default=None) + optional_alias: typing.Optional[OptionalAlias] = pydantic.Field( + alias="optionalAlias", default=None + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/union-utils/src/seed/types/object/types/nested_object_with_optional_field.py b/seed/python-sdk/exhaustive/union-utils/src/seed/types/object/types/nested_object_with_optional_field.py index 81669c0dd39..20a4d40a714 100644 --- a/seed/python-sdk/exhaustive/union-utils/src/seed/types/object/types/nested_object_with_optional_field.py +++ b/seed/python-sdk/exhaustive/union-utils/src/seed/types/object/types/nested_object_with_optional_field.py @@ -1,19 +1,22 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .object_with_optional_field import ObjectWithOptionalField +import pydantic +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class NestedObjectWithOptionalField(UniversalBaseModel): string: typing.Optional[str] = None - nested_object: typing.Optional[ObjectWithOptionalField] = pydantic.Field(alias="NestedObject", default=None) + nested_object: typing.Optional[ObjectWithOptionalField] = pydantic.Field( + alias="NestedObject", default=None + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/union-utils/src/seed/types/object/types/nested_object_with_required_field.py b/seed/python-sdk/exhaustive/union-utils/src/seed/types/object/types/nested_object_with_required_field.py index 1a621942c6c..a6ca8781190 100644 --- a/seed/python-sdk/exhaustive/union-utils/src/seed/types/object/types/nested_object_with_required_field.py +++ b/seed/python-sdk/exhaustive/union-utils/src/seed/types/object/types/nested_object_with_required_field.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import UniversalBaseModel from .object_with_optional_field import ObjectWithOptionalField +import pydantic +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class NestedObjectWithRequiredField(UniversalBaseModel): @@ -13,7 +12,9 @@ class NestedObjectWithRequiredField(UniversalBaseModel): nested_object: ObjectWithOptionalField = pydantic.Field(alias="NestedObject") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/union-utils/src/seed/types/object/types/object_with_map_of_map.py b/seed/python-sdk/exhaustive/union-utils/src/seed/types/object/types/object_with_map_of_map.py index 8883cc1d498..313cd25ceb8 100644 --- a/seed/python-sdk/exhaustive/union-utils/src/seed/types/object/types/object_with_map_of_map.py +++ b/seed/python-sdk/exhaustive/union-utils/src/seed/types/object/types/object_with_map_of_map.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class ObjectWithMapOfMap(UniversalBaseModel): map_: typing.Dict[str, typing.Dict[str, str]] = pydantic.Field(alias="map") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/union-utils/src/seed/types/object/types/object_with_optional_field.py b/seed/python-sdk/exhaustive/union-utils/src/seed/types/object/types/object_with_optional_field.py index 6aab170be0c..9131f0e91d7 100644 --- a/seed/python-sdk/exhaustive/union-utils/src/seed/types/object/types/object_with_optional_field.py +++ b/seed/python-sdk/exhaustive/union-utils/src/seed/types/object/types/object_with_optional_field.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. -import datetime as dt +from ....core.pydantic_utilities import UniversalBaseModel import typing -import uuid - import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +import datetime as dt +import uuid +from ....core.pydantic_utilities import IS_PYDANTIC_V2 class ObjectWithOptionalField(UniversalBaseModel): @@ -23,13 +22,19 @@ class ObjectWithOptionalField(UniversalBaseModel): date: typing.Optional[dt.date] = None uuid_: typing.Optional[uuid.UUID] = pydantic.Field(alias="uuid", default=None) base_64: typing.Optional[str] = pydantic.Field(alias="base64", default=None) - list_: typing.Optional[typing.List[str]] = pydantic.Field(alias="list", default=None) + list_: typing.Optional[typing.List[str]] = pydantic.Field( + alias="list", default=None + ) set_: typing.Optional[typing.Set[str]] = pydantic.Field(alias="set", default=None) - map_: typing.Optional[typing.Dict[int, str]] = pydantic.Field(alias="map", default=None) + map_: typing.Optional[typing.Dict[int, str]] = pydantic.Field( + alias="map", default=None + ) bigint: typing.Optional[str] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/union-utils/src/seed/types/object/types/object_with_required_field.py b/seed/python-sdk/exhaustive/union-utils/src/seed/types/object/types/object_with_required_field.py index 61b98867984..24db26a3cf8 100644 --- a/seed/python-sdk/exhaustive/union-utils/src/seed/types/object/types/object_with_required_field.py +++ b/seed/python-sdk/exhaustive/union-utils/src/seed/types/object/types/object_with_required_field.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class ObjectWithRequiredField(UniversalBaseModel): string: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/union-utils/src/seed/types/union/types/animal.py b/seed/python-sdk/exhaustive/union-utils/src/seed/types/union/types/animal.py index 04ffb20e050..554cf8c103b 100644 --- a/seed/python-sdk/exhaustive/union-utils/src/seed/types/union/types/animal.py +++ b/seed/python-sdk/exhaustive/union-utils/src/seed/types/union/types/animal.py @@ -1,15 +1,14 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from .dog import Dog as types_union_types_dog_Dog +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +from .cat import Cat as types_union_types_cat_Cat +from ....core.pydantic_utilities import UniversalRootModel import typing - -import pydantic import typing_extensions - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalRootModel, update_forward_refs -from .cat import Cat as types_union_types_cat_Cat -from .dog import Dog as types_union_types_dog_Dog +import pydantic +from ....core.pydantic_utilities import update_forward_refs T_Result = typing.TypeVar("T_Result") @@ -17,15 +16,23 @@ class _Factory: def dog(self, value: types_union_types_dog_Dog) -> Animal: if IS_PYDANTIC_V2: - return Animal(root=_Animal.Dog(**value.dict(exclude_unset=True), animal="dog")) + return Animal( + root=_Animal.Dog(**value.dict(exclude_unset=True), animal="dog") + ) else: - return Animal(__root__=_Animal.Dog(**value.dict(exclude_unset=True), animal="dog")) + return Animal( + __root__=_Animal.Dog(**value.dict(exclude_unset=True), animal="dog") + ) def cat(self, value: types_union_types_cat_Cat) -> Animal: if IS_PYDANTIC_V2: - return Animal(root=_Animal.Cat(**value.dict(exclude_unset=True), animal="cat")) + return Animal( + root=_Animal.Cat(**value.dict(exclude_unset=True), animal="cat") + ) else: - return Animal(__root__=_Animal.Cat(**value.dict(exclude_unset=True), animal="cat")) + return Animal( + __root__=_Animal.Cat(**value.dict(exclude_unset=True), animal="cat") + ) class Animal(UniversalRootModel): @@ -33,15 +40,16 @@ class Animal(UniversalRootModel): if IS_PYDANTIC_V2: root: typing_extensions.Annotated[ - typing.Union[_Animal.Dog, _Animal.Cat], pydantic.Field(discriminator="animal") + typing.Union[_Animal.Dog, _Animal.Cat], + pydantic.Field(discriminator="animal"), ] def get_as_union(self) -> typing.Union[_Animal.Dog, _Animal.Cat]: return self.root - else: __root__: typing_extensions.Annotated[ - typing.Union[_Animal.Dog, _Animal.Cat], pydantic.Field(discriminator="animal") + typing.Union[_Animal.Dog, _Animal.Cat], + pydantic.Field(discriminator="animal"), ] def get_as_union(self) -> typing.Union[_Animal.Dog, _Animal.Cat]: @@ -54,9 +62,17 @@ def visit( ) -> T_Result: unioned_value = self.get_as_union() if unioned_value.animal == "dog": - return dog(types_union_types_dog_Dog(**unioned_value.dict(exclude_unset=True, exclude={"animal"}))) + return dog( + types_union_types_dog_Dog( + **unioned_value.dict(exclude_unset=True, exclude={"animal"}) + ) + ) if unioned_value.animal == "cat": - return cat(types_union_types_cat_Cat(**unioned_value.dict(exclude_unset=True, exclude={"animal"}))) + return cat( + types_union_types_cat_Cat( + **unioned_value.dict(exclude_unset=True, exclude={"animal"}) + ) + ) class _Animal: @@ -64,7 +80,9 @@ class Dog(types_union_types_dog_Dog): animal: typing.Literal["dog"] = "dog" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + frozen=True + ) # type: ignore # Pydantic v2 else: class Config: @@ -75,7 +93,9 @@ class Cat(types_union_types_cat_Cat): animal: typing.Literal["cat"] = "cat" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/union-utils/src/seed/types/union/types/cat.py b/seed/python-sdk/exhaustive/union-utils/src/seed/types/union/types/cat.py index 61fc5527b1f..c59b78523c9 100644 --- a/seed/python-sdk/exhaustive/union-utils/src/seed/types/union/types/cat.py +++ b/seed/python-sdk/exhaustive/union-utils/src/seed/types/union/types/cat.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ....core.pydantic_utilities import UniversalBaseModel import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class Cat(UniversalBaseModel): @@ -12,7 +11,9 @@ class Cat(UniversalBaseModel): likes_to_meow: bool = pydantic.Field(alias="likesToMeow") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/union-utils/src/seed/types/union/types/dog.py b/seed/python-sdk/exhaustive/union-utils/src/seed/types/union/types/dog.py index c1ff5339dfe..e250c72edef 100644 --- a/seed/python-sdk/exhaustive/union-utils/src/seed/types/union/types/dog.py +++ b/seed/python-sdk/exhaustive/union-utils/src/seed/types/union/types/dog.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ....core.pydantic_utilities import UniversalBaseModel import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class Dog(UniversalBaseModel): @@ -12,7 +11,9 @@ class Dog(UniversalBaseModel): likes_to_woof: bool = pydantic.Field(alias="likesToWoof") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/exhaustive/union-utils/src/seed/version.py b/seed/python-sdk/exhaustive/union-utils/src/seed/version.py index 63ba170685a..ac44536abdb 100644 --- a/seed/python-sdk/exhaustive/union-utils/src/seed/version.py +++ b/seed/python-sdk/exhaustive/union-utils/src/seed/version.py @@ -1,4 +1,3 @@ - from importlib import metadata __version__ = metadata.version("fern_exhaustive") diff --git a/seed/python-sdk/exhaustive/union-utils/tests/conftest.py b/seed/python-sdk/exhaustive/union-utils/tests/conftest.py index b5b50383b94..86cb2b41af8 100644 --- a/seed/python-sdk/exhaustive/union-utils/tests/conftest.py +++ b/seed/python-sdk/exhaustive/union-utils/tests/conftest.py @@ -1,16 +1,22 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive import os - import pytest -from seed import AsyncSeedExhaustive, SeedExhaustive +from seed import AsyncSeedExhaustive @pytest.fixture def client() -> SeedExhaustive: - return SeedExhaustive(token=os.getenv("ENV_TOKEN", "token"), base_url=os.getenv("TESTS_BASE_URL", "base_url")) + return SeedExhaustive( + token=os.getenv("ENV_TOKEN", "token"), + base_url=os.getenv("TESTS_BASE_URL", "base_url"), + ) @pytest.fixture def async_client() -> AsyncSeedExhaustive: - return AsyncSeedExhaustive(token=os.getenv("ENV_TOKEN", "token"), base_url=os.getenv("TESTS_BASE_URL", "base_url")) + return AsyncSeedExhaustive( + token=os.getenv("ENV_TOKEN", "token"), + base_url=os.getenv("TESTS_BASE_URL", "base_url"), + ) diff --git a/seed/python-sdk/exhaustive/union-utils/tests/custom/test_client.py b/seed/python-sdk/exhaustive/union-utils/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/python-sdk/exhaustive/union-utils/tests/custom/test_client.py +++ b/seed/python-sdk/exhaustive/union-utils/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/python-sdk/exhaustive/union-utils/tests/endpoints/test_container.py b/seed/python-sdk/exhaustive/union-utils/tests/endpoints/test_container.py index 17d9d75240d..240f16f2a8c 100644 --- a/seed/python-sdk/exhaustive/union-utils/tests/endpoints/test_container.py +++ b/seed/python-sdk/exhaustive/union-utils/tests/endpoints/test_container.py @@ -1,91 +1,137 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing - -from seed import AsyncSeedExhaustive, SeedExhaustive -from seed.types.object import ObjectWithRequiredField - from ..utilities import validate_response +from seed.types.object import ObjectWithRequiredField -async def test_get_and_return_list_of_primitives(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_list_of_primitives( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = ["string"] expected_types: typing.Tuple[typing.Any, typing.Any] = ("list", {0: None}) - response = client.endpoints.container.get_and_return_list_of_primitives(request=["string"]) + response = client.endpoints.container.get_and_return_list_of_primitives( + request=["string"] + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.container.get_and_return_list_of_primitives(request=["string"]) + async_response = ( + await async_client.endpoints.container.get_and_return_list_of_primitives( + request=["string"] + ) + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_list_of_objects(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_list_of_objects( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = [{"string": "string"}] - expected_types: typing.Tuple[typing.Any, typing.Any] = ("list", {0: {"string": None}}) + expected_types: typing.Tuple[typing.Any, typing.Any] = ( + "list", + {0: {"string": None}}, + ) response = client.endpoints.container.get_and_return_list_of_objects( request=[ObjectWithRequiredField(string="string")] ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.container.get_and_return_list_of_objects( - request=[ObjectWithRequiredField(string="string")] + async_response = ( + await async_client.endpoints.container.get_and_return_list_of_objects( + request=[ObjectWithRequiredField(string="string")] + ) ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_set_of_primitives(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_set_of_primitives( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = ["string"] expected_types: typing.Tuple[typing.Any, typing.Any] = ("set", {0: None}) - response = client.endpoints.container.get_and_return_set_of_primitives(request={"string"}) + response = client.endpoints.container.get_and_return_set_of_primitives( + request={"string"} + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.container.get_and_return_set_of_primitives(request={"string"}) + async_response = ( + await async_client.endpoints.container.get_and_return_set_of_primitives( + request={"string"} + ) + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_set_of_objects(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_set_of_objects( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = [{"string": "string"}] - expected_types: typing.Tuple[typing.Any, typing.Any] = ("set", {0: {"string": None}}) + expected_types: typing.Tuple[typing.Any, typing.Any] = ( + "set", + {0: {"string": None}}, + ) response = client.endpoints.container.get_and_return_set_of_objects( request=[ObjectWithRequiredField(string="string")] ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.container.get_and_return_set_of_objects( - request=[ObjectWithRequiredField(string="string")] + async_response = ( + await async_client.endpoints.container.get_and_return_set_of_objects( + request=[ObjectWithRequiredField(string="string")] + ) ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_map_prim_to_prim(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_map_prim_to_prim( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = {"string": "string"} expected_types: typing.Tuple[typing.Any, typing.Any] = ("dict", {0: (None, None)}) - response = client.endpoints.container.get_and_return_map_prim_to_prim(request={"string": "string"}) + response = client.endpoints.container.get_and_return_map_prim_to_prim( + request={"string": "string"} + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.container.get_and_return_map_prim_to_prim( - request={"string": "string"} + async_response = ( + await async_client.endpoints.container.get_and_return_map_prim_to_prim( + request={"string": "string"} + ) ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_map_of_prim_to_object(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_map_of_prim_to_object( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = {"string": {"string": "string"}} - expected_types: typing.Tuple[typing.Any, typing.Any] = ("dict", {0: (None, {"string": None})}) + expected_types: typing.Tuple[typing.Any, typing.Any] = ( + "dict", + {0: (None, {"string": None})}, + ) response = client.endpoints.container.get_and_return_map_of_prim_to_object( request={"string": ObjectWithRequiredField(string="string")} ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.container.get_and_return_map_of_prim_to_object( - request={"string": ObjectWithRequiredField(string="string")} + async_response = ( + await async_client.endpoints.container.get_and_return_map_of_prim_to_object( + request={"string": ObjectWithRequiredField(string="string")} + ) ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_optional(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_optional( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = {"string": "string"} expected_types: typing.Any = {"string": None} - response = client.endpoints.container.get_and_return_optional(request=ObjectWithRequiredField(string="string")) + response = client.endpoints.container.get_and_return_optional( + request=ObjectWithRequiredField(string="string") + ) validate_response(response, expected_response, expected_types) async_response = await async_client.endpoints.container.get_and_return_optional( diff --git a/seed/python-sdk/exhaustive/union-utils/tests/endpoints/test_enum.py b/seed/python-sdk/exhaustive/union-utils/tests/endpoints/test_enum.py index 890aada5ce4..ca3fca30b5a 100644 --- a/seed/python-sdk/exhaustive/union-utils/tests/endpoints/test_enum.py +++ b/seed/python-sdk/exhaustive/union-utils/tests/endpoints/test_enum.py @@ -1,17 +1,20 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing - -from seed import AsyncSeedExhaustive, SeedExhaustive - from ..utilities import validate_response -async def test_get_and_return_enum(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_enum( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "SUNNY" expected_types: typing.Any = None response = client.endpoints.enum.get_and_return_enum(request="SUNNY") validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.enum.get_and_return_enum(request="SUNNY") + async_response = await async_client.endpoints.enum.get_and_return_enum( + request="SUNNY" + ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/exhaustive/union-utils/tests/endpoints/test_http_methods.py b/seed/python-sdk/exhaustive/union-utils/tests/endpoints/test_http_methods.py index dc01bafcf6f..77131fc6e8b 100644 --- a/seed/python-sdk/exhaustive/union-utils/tests/endpoints/test_http_methods.py +++ b/seed/python-sdk/exhaustive/union-utils/tests/endpoints/test_http_methods.py @@ -1,15 +1,16 @@ # This file was auto-generated by Fern from our API Definition. -import datetime +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing -import uuid - -from seed import AsyncSeedExhaustive, SeedExhaustive - from ..utilities import validate_response +import datetime +import uuid -async def test_test_get(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_test_get( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "string" expected_types: typing.Any = None response = client.endpoints.http_methods.test_get(id="string") @@ -19,7 +20,9 @@ async def test_test_get(client: SeedExhaustive, async_client: AsyncSeedExhaustiv validate_response(async_response, expected_response, expected_types) -async def test_test_post(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_test_post( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = { "string": "string", "integer": 1, @@ -53,11 +56,15 @@ async def test_test_post(client: SeedExhaustive, async_client: AsyncSeedExhausti response = client.endpoints.http_methods.test_post(string="string") validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.http_methods.test_post(string="string") + async_response = await async_client.endpoints.http_methods.test_post( + string="string" + ) validate_response(async_response, expected_response, expected_types) -async def test_test_put(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_test_put( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = { "string": "string", "integer": 1, @@ -91,11 +98,15 @@ async def test_test_put(client: SeedExhaustive, async_client: AsyncSeedExhaustiv response = client.endpoints.http_methods.test_put(id="string", string="string") validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.http_methods.test_put(id="string", string="string") + async_response = await async_client.endpoints.http_methods.test_put( + id="string", string="string" + ) validate_response(async_response, expected_response, expected_types) -async def test_test_patch(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_test_patch( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = { "string": "string", "integer": 1, @@ -163,7 +174,9 @@ async def test_test_patch(client: SeedExhaustive, async_client: AsyncSeedExhaust validate_response(async_response, expected_response, expected_types) -async def test_test_delete(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_test_delete( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = True expected_types: typing.Any = None response = client.endpoints.http_methods.test_delete(id="string") diff --git a/seed/python-sdk/exhaustive/union-utils/tests/endpoints/test_object.py b/seed/python-sdk/exhaustive/union-utils/tests/endpoints/test_object.py index a9098b6e9ef..c48c4332b22 100644 --- a/seed/python-sdk/exhaustive/union-utils/tests/endpoints/test_object.py +++ b/seed/python-sdk/exhaustive/union-utils/tests/endpoints/test_object.py @@ -1,16 +1,18 @@ # This file was auto-generated by Fern from our API Definition. -import datetime +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing +import datetime import uuid - -from seed import AsyncSeedExhaustive, SeedExhaustive -from seed.types.object import NestedObjectWithRequiredField, ObjectWithOptionalField - from ..utilities import validate_response +from seed.types.object import ObjectWithOptionalField +from seed.types.object import NestedObjectWithRequiredField -async def test_get_and_return_with_optional_field(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_with_optional_field( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = { "string": "string", "integer": 1, @@ -58,38 +60,54 @@ async def test_get_and_return_with_optional_field(client: SeedExhaustive, async_ ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.object.get_and_return_with_optional_field( - string="string", - integer=1, - long_=1000000, - double=1.1, - bool_=True, - datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), - date=datetime.date.fromisoformat("2023-01-15"), - uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), - base_64="SGVsbG8gd29ybGQh", - list_=["string"], - set_={"string"}, - map_={1: "string"}, - bigint="123456789123456789", + async_response = ( + await async_client.endpoints.object.get_and_return_with_optional_field( + string="string", + integer=1, + long_=1000000, + double=1.1, + bool_=True, + datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), + date=datetime.date.fromisoformat("2023-01-15"), + uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + base_64="SGVsbG8gd29ybGQh", + list_=["string"], + set_={"string"}, + map_={1: "string"}, + bigint="123456789123456789", + ) ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_with_required_field(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_with_required_field( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = {"string": "string"} expected_types: typing.Any = {"string": None} - response = client.endpoints.object.get_and_return_with_required_field(string="string") + response = client.endpoints.object.get_and_return_with_required_field( + string="string" + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.object.get_and_return_with_required_field(string="string") + async_response = ( + await async_client.endpoints.object.get_and_return_with_required_field( + string="string" + ) + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_with_map_of_map(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_with_map_of_map( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = {"map": {"string": {"string": "string"}}} - expected_types: typing.Any = {"map": ("dict", {0: (None, ("dict", {0: (None, None)}))})} - response = client.endpoints.object.get_and_return_with_map_of_map(map_={"string": {"string": "string"}}) + expected_types: typing.Any = { + "map": ("dict", {0: (None, ("dict", {0: (None, None)}))}) + } + response = client.endpoints.object.get_and_return_with_map_of_map( + map_={"string": {"string": "string"}} + ) validate_response(response, expected_response, expected_types) async_response = await async_client.endpoints.object.get_and_return_with_map_of_map( @@ -157,23 +175,25 @@ async def test_get_and_return_nested_with_optional_field( ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.object.get_and_return_nested_with_optional_field( - string="string", - nested_object=ObjectWithOptionalField( + async_response = ( + await async_client.endpoints.object.get_and_return_nested_with_optional_field( string="string", - integer=1, - long_=1000000, - double=1.1, - bool_=True, - datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), - date=datetime.date.fromisoformat("2023-01-15"), - uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), - base_64="SGVsbG8gd29ybGQh", - list_=["string"], - set_={"string"}, - map_={1: "string"}, - bigint="123456789123456789", - ), + nested_object=ObjectWithOptionalField( + string="string", + integer=1, + long_=1000000, + double=1.1, + bool_=True, + datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), + date=datetime.date.fromisoformat("2023-01-15"), + uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + base_64="SGVsbG8gd29ybGQh", + list_=["string"], + set_={"string"}, + map_={1: "string"}, + bigint="123456789123456789", + ), + ) ) validate_response(async_response, expected_response, expected_types) @@ -238,24 +258,26 @@ async def test_get_and_return_nested_with_required_field( ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.object.get_and_return_nested_with_required_field( - string_="string", - string="string", - nested_object=ObjectWithOptionalField( + async_response = ( + await async_client.endpoints.object.get_and_return_nested_with_required_field( + string_="string", string="string", - integer=1, - long_=1000000, - double=1.1, - bool_=True, - datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), - date=datetime.date.fromisoformat("2023-01-15"), - uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), - base_64="SGVsbG8gd29ybGQh", - list_=["string"], - set_={"string"}, - map_={1: "string"}, - bigint="123456789123456789", - ), + nested_object=ObjectWithOptionalField( + string="string", + integer=1, + long_=1000000, + double=1.1, + bool_=True, + datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), + date=datetime.date.fromisoformat("2023-01-15"), + uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + base_64="SGVsbG8gd29ybGQh", + list_=["string"], + set_={"string"}, + map_={1: "string"}, + bigint="123456789123456789", + ), + ) ) validate_response(async_response, expected_response, expected_types) @@ -299,27 +321,31 @@ async def test_get_and_return_nested_with_required_field_as_list( "bigint": None, }, } - response = client.endpoints.object.get_and_return_nested_with_required_field_as_list( - request=[ - NestedObjectWithRequiredField( - string="string", - nested_object=ObjectWithOptionalField( + response = ( + client.endpoints.object.get_and_return_nested_with_required_field_as_list( + request=[ + NestedObjectWithRequiredField( string="string", - integer=1, - long_=1000000, - double=1.1, - bool_=True, - datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), - date=datetime.date.fromisoformat("2023-01-15"), - uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), - base_64="SGVsbG8gd29ybGQh", - list_=["string"], - set_={"string"}, - map_={1: "string"}, - bigint="123456789123456789", - ), - ) - ] + nested_object=ObjectWithOptionalField( + string="string", + integer=1, + long_=1000000, + double=1.1, + bool_=True, + datetime=datetime.datetime.fromisoformat( + "2024-01-15 09:30:00+00:00" + ), + date=datetime.date.fromisoformat("2023-01-15"), + uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + base_64="SGVsbG8gd29ybGQh", + list_=["string"], + set_={"string"}, + map_={1: "string"}, + bigint="123456789123456789", + ), + ) + ] + ) ) validate_response(response, expected_response, expected_types) @@ -333,7 +359,9 @@ async def test_get_and_return_nested_with_required_field_as_list( long_=1000000, double=1.1, bool_=True, - datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), + datetime=datetime.datetime.fromisoformat( + "2024-01-15 09:30:00+00:00" + ), date=datetime.date.fromisoformat("2023-01-15"), uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), base_64="SGVsbG8gd29ybGQh", diff --git a/seed/python-sdk/exhaustive/union-utils/tests/endpoints/test_params.py b/seed/python-sdk/exhaustive/union-utils/tests/endpoints/test_params.py index 163d7b9161d..d8ffb00c0a0 100644 --- a/seed/python-sdk/exhaustive/union-utils/tests/endpoints/test_params.py +++ b/seed/python-sdk/exhaustive/union-utils/tests/endpoints/test_params.py @@ -1,13 +1,14 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing - -from seed import AsyncSeedExhaustive, SeedExhaustive - from ..utilities import validate_response -async def test_get_with_path(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_with_path( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "string" expected_types: typing.Any = None response = client.endpoints.params.get_with_path(param="string") @@ -17,32 +18,63 @@ async def test_get_with_path(client: SeedExhaustive, async_client: AsyncSeedExha validate_response(async_response, expected_response, expected_types) -async def test_get_with_query(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_with_query( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: # Type ignore to avoid mypy complaining about the function not being meant to return a value assert client.endpoints.params.get_with_query(query="string", number=1) is None # type: ignore[func-returns-value] - assert await async_client.endpoints.params.get_with_query(query="string", number=1) is None # type: ignore[func-returns-value] + assert ( + await async_client.endpoints.params.get_with_query(query="string", number=1) + is None + ) # type: ignore[func-returns-value] -async def test_get_with_allow_multiple_query(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_with_allow_multiple_query( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: # Type ignore to avoid mypy complaining about the function not being meant to return a value - assert client.endpoints.params.get_with_allow_multiple_query(query="string", numer=1) is None # type: ignore[func-returns-value] - - assert await async_client.endpoints.params.get_with_allow_multiple_query(query="string", numer=1) is None # type: ignore[func-returns-value] - - -async def test_get_with_path_and_query(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: + assert ( + client.endpoints.params.get_with_allow_multiple_query(query="string", numer=1) + is None + ) # type: ignore[func-returns-value] + + assert ( + await async_client.endpoints.params.get_with_allow_multiple_query( + query="string", numer=1 + ) + is None + ) # type: ignore[func-returns-value] + + +async def test_get_with_path_and_query( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: # Type ignore to avoid mypy complaining about the function not being meant to return a value - assert client.endpoints.params.get_with_path_and_query(param="string", query="string") is None # type: ignore[func-returns-value] - - assert await async_client.endpoints.params.get_with_path_and_query(param="string", query="string") is None # type: ignore[func-returns-value] - - -async def test_modify_with_path(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: + assert ( + client.endpoints.params.get_with_path_and_query(param="string", query="string") + is None + ) # type: ignore[func-returns-value] + + assert ( + await async_client.endpoints.params.get_with_path_and_query( + param="string", query="string" + ) + is None + ) # type: ignore[func-returns-value] + + +async def test_modify_with_path( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "string" expected_types: typing.Any = None - response = client.endpoints.params.modify_with_path(param="string", request="string") + response = client.endpoints.params.modify_with_path( + param="string", request="string" + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.params.modify_with_path(param="string", request="string") + async_response = await async_client.endpoints.params.modify_with_path( + param="string", request="string" + ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/exhaustive/union-utils/tests/endpoints/test_primitive.py b/seed/python-sdk/exhaustive/union-utils/tests/endpoints/test_primitive.py index ba3bc7e29e5..26cbcf45d2f 100644 --- a/seed/python-sdk/exhaustive/union-utils/tests/endpoints/test_primitive.py +++ b/seed/python-sdk/exhaustive/union-utils/tests/endpoints/test_primitive.py @@ -1,65 +1,86 @@ # This file was auto-generated by Fern from our API Definition. -import datetime +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing -import uuid - -from seed import AsyncSeedExhaustive, SeedExhaustive - from ..utilities import validate_response +import datetime +import uuid -async def test_get_and_return_string(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_string( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "string" expected_types: typing.Any = None response = client.endpoints.primitive.get_and_return_string(request="string") validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.primitive.get_and_return_string(request="string") + async_response = await async_client.endpoints.primitive.get_and_return_string( + request="string" + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_int(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_int( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = 1 expected_types: typing.Any = "integer" response = client.endpoints.primitive.get_and_return_int(request=1) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.primitive.get_and_return_int(request=1) + async_response = await async_client.endpoints.primitive.get_and_return_int( + request=1 + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_long(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_long( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = 1000000 expected_types: typing.Any = None response = client.endpoints.primitive.get_and_return_long(request=1000000) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.primitive.get_and_return_long(request=1000000) + async_response = await async_client.endpoints.primitive.get_and_return_long( + request=1000000 + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_double(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_double( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = 1.1 expected_types: typing.Any = None response = client.endpoints.primitive.get_and_return_double(request=1.1) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.primitive.get_and_return_double(request=1.1) + async_response = await async_client.endpoints.primitive.get_and_return_double( + request=1.1 + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_bool(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_bool( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = True expected_types: typing.Any = None response = client.endpoints.primitive.get_and_return_bool(request=True) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.primitive.get_and_return_bool(request=True) + async_response = await async_client.endpoints.primitive.get_and_return_bool( + request=True + ) validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_datetime(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_datetime( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "2024-01-15T09:30:00Z" expected_types: typing.Any = "datetime" response = client.endpoints.primitive.get_and_return_datetime( @@ -73,10 +94,14 @@ async def test_get_and_return_datetime(client: SeedExhaustive, async_client: Asy validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_date(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_date( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "2023-01-15" expected_types: typing.Any = "date" - response = client.endpoints.primitive.get_and_return_date(request=datetime.date.fromisoformat("2023-01-15")) + response = client.endpoints.primitive.get_and_return_date( + request=datetime.date.fromisoformat("2023-01-15") + ) validate_response(response, expected_response, expected_types) async_response = await async_client.endpoints.primitive.get_and_return_date( @@ -85,10 +110,14 @@ async def test_get_and_return_date(client: SeedExhaustive, async_client: AsyncSe validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_uuid(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_uuid( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32" expected_types: typing.Any = "uuid" - response = client.endpoints.primitive.get_and_return_uuid(request=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32")) + response = client.endpoints.primitive.get_and_return_uuid( + request=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32") + ) validate_response(response, expected_response, expected_types) async_response = await async_client.endpoints.primitive.get_and_return_uuid( @@ -97,11 +126,17 @@ async def test_get_and_return_uuid(client: SeedExhaustive, async_client: AsyncSe validate_response(async_response, expected_response, expected_types) -async def test_get_and_return_base_64(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_and_return_base_64( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "SGVsbG8gd29ybGQh" expected_types: typing.Any = None - response = client.endpoints.primitive.get_and_return_base_64(request="SGVsbG8gd29ybGQh") + response = client.endpoints.primitive.get_and_return_base_64( + request="SGVsbG8gd29ybGQh" + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.endpoints.primitive.get_and_return_base_64(request="SGVsbG8gd29ybGQh") + async_response = await async_client.endpoints.primitive.get_and_return_base_64( + request="SGVsbG8gd29ybGQh" + ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/exhaustive/union-utils/tests/endpoints/test_union.py b/seed/python-sdk/exhaustive/union-utils/tests/endpoints/test_union.py index 14e34c2a6df..ceb84928cd9 100644 --- a/seed/python-sdk/exhaustive/union-utils/tests/endpoints/test_union.py +++ b/seed/python-sdk/exhaustive/union-utils/tests/endpoints/test_union.py @@ -1,17 +1,24 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing - -from seed import AsyncSeedExhaustive, SeedExhaustive from seed.types.union import Animal_Dog - from ..utilities import validate_response -async def test_get_and_return_union(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: - expected_response: typing.Any = {"animal": "dog", "name": "string", "likesToWoof": True} +async def test_get_and_return_union( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: + expected_response: typing.Any = { + "animal": "dog", + "name": "string", + "likesToWoof": True, + } expected_types: typing.Any = "no_validate" - response = client.endpoints.union.get_and_return_union(request=Animal_Dog(name="string", likes_to_woof=True)) + response = client.endpoints.union.get_and_return_union( + request=Animal_Dog(name="string", likes_to_woof=True) + ) validate_response(response, expected_response, expected_types) async_response = await async_client.endpoints.union.get_and_return_union( diff --git a/seed/python-sdk/exhaustive/union-utils/tests/test_inlined_requests.py b/seed/python-sdk/exhaustive/union-utils/tests/test_inlined_requests.py index bb9390d3845..03f46b31cc9 100644 --- a/seed/python-sdk/exhaustive/union-utils/tests/test_inlined_requests.py +++ b/seed/python-sdk/exhaustive/union-utils/tests/test_inlined_requests.py @@ -1,16 +1,17 @@ # This file was auto-generated by Fern from our API Definition. -import datetime +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing -import uuid - -from seed import AsyncSeedExhaustive, SeedExhaustive from seed.types.object import ObjectWithOptionalField - +import datetime +import uuid from .utilities import validate_response -async def test_post_with_object_bodyand_response(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_post_with_object_bodyand_response( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = { "string": "string", "integer": 1, @@ -62,23 +63,25 @@ async def test_post_with_object_bodyand_response(client: SeedExhaustive, async_c ) validate_response(response, expected_response, expected_types) - async_response = await async_client.inlined_requests.post_with_object_bodyand_response( - string="string", - integer=1, - nested_object=ObjectWithOptionalField( + async_response = ( + await async_client.inlined_requests.post_with_object_bodyand_response( string="string", integer=1, - long_=1000000, - double=1.1, - bool_=True, - datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), - date=datetime.date.fromisoformat("2023-01-15"), - uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), - base_64="SGVsbG8gd29ybGQh", - list_=["string"], - set_={"string"}, - map_={1: "string"}, - bigint="123456789123456789", - ), + nested_object=ObjectWithOptionalField( + string="string", + integer=1, + long_=1000000, + double=1.1, + bool_=True, + datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), + date=datetime.date.fromisoformat("2023-01-15"), + uuid_=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + base_64="SGVsbG8gd29ybGQh", + list_=["string"], + set_={"string"}, + map_={1: "string"}, + bigint="123456789123456789", + ), + ) ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/exhaustive/union-utils/tests/test_no_auth.py b/seed/python-sdk/exhaustive/union-utils/tests/test_no_auth.py index 3328661bb48..fc475f4b6fb 100644 --- a/seed/python-sdk/exhaustive/union-utils/tests/test_no_auth.py +++ b/seed/python-sdk/exhaustive/union-utils/tests/test_no_auth.py @@ -1,17 +1,20 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing - -from seed import AsyncSeedExhaustive, SeedExhaustive - from .utilities import validate_response -async def test_post_with_no_auth(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_post_with_no_auth( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = True expected_types: typing.Any = None response = client.no_auth.post_with_no_auth(request={"key": "value"}) validate_response(response, expected_response, expected_types) - async_response = await async_client.no_auth.post_with_no_auth(request={"key": "value"}) + async_response = await async_client.no_auth.post_with_no_auth( + request={"key": "value"} + ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/exhaustive/union-utils/tests/test_no_req_body.py b/seed/python-sdk/exhaustive/union-utils/tests/test_no_req_body.py index 73abac9d2d8..07061a0e99e 100644 --- a/seed/python-sdk/exhaustive/union-utils/tests/test_no_req_body.py +++ b/seed/python-sdk/exhaustive/union-utils/tests/test_no_req_body.py @@ -1,13 +1,14 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive import typing - -from seed import AsyncSeedExhaustive, SeedExhaustive - from .utilities import validate_response -async def test_get_with_no_request_body(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_with_no_request_body( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = { "string": "string", "integer": 1, @@ -45,7 +46,9 @@ async def test_get_with_no_request_body(client: SeedExhaustive, async_client: As validate_response(async_response, expected_response, expected_types) -async def test_post_with_no_request_body(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_post_with_no_request_body( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: expected_response: typing.Any = "string" expected_types: typing.Any = None response = client.no_req_body.post_with_no_request_body() diff --git a/seed/python-sdk/exhaustive/union-utils/tests/test_req_with_headers.py b/seed/python-sdk/exhaustive/union-utils/tests/test_req_with_headers.py index bba3b5b5507..75ce9d00c03 100644 --- a/seed/python-sdk/exhaustive/union-utils/tests/test_req_with_headers.py +++ b/seed/python-sdk/exhaustive/union-utils/tests/test_req_with_headers.py @@ -1,10 +1,27 @@ # This file was auto-generated by Fern from our API Definition. -from seed import AsyncSeedExhaustive, SeedExhaustive +from seed import SeedExhaustive +from seed import AsyncSeedExhaustive -async def test_get_with_custom_header(client: SeedExhaustive, async_client: AsyncSeedExhaustive) -> None: +async def test_get_with_custom_header( + client: SeedExhaustive, async_client: AsyncSeedExhaustive +) -> None: # Type ignore to avoid mypy complaining about the function not being meant to return a value - assert client.req_with_headers.get_with_custom_header(x_test_service_header="string", x_test_endpoint_header="string", request="string") is None # type: ignore[func-returns-value] + assert ( + client.req_with_headers.get_with_custom_header( + x_test_service_header="string", + x_test_endpoint_header="string", + request="string", + ) + is None + ) # type: ignore[func-returns-value] - assert await async_client.req_with_headers.get_with_custom_header(x_test_service_header="string", x_test_endpoint_header="string", request="string") is None # type: ignore[func-returns-value] + assert ( + await async_client.req_with_headers.get_with_custom_header( + x_test_service_header="string", + x_test_endpoint_header="string", + request="string", + ) + is None + ) # type: ignore[func-returns-value] diff --git a/seed/python-sdk/exhaustive/union-utils/tests/utilities.py b/seed/python-sdk/exhaustive/union-utils/tests/utilities.py index 13da208eb3a..e8f4472564c 100644 --- a/seed/python-sdk/exhaustive/union-utils/tests/utilities.py +++ b/seed/python-sdk/exhaustive/union-utils/tests/utilities.py @@ -3,11 +3,14 @@ import typing import uuid -import pydantic from dateutil import parser +import pydantic + -def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> typing.Any: +def cast_field( + json_expectation: typing.Any, type_expectation: typing.Any +) -> typing.Any: # Cast these specific types which come through as string and expect our # models to cast to the correct type. if type_expectation == "uuid": @@ -25,7 +28,9 @@ def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> ty return json_expectation -def validate_field(response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any) -> None: +def validate_field( + response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectation == "no_validate": return @@ -44,7 +49,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(entry_expectation, dict): is_container_of_complex_type = True validate_response( - response=response[idx], json_expectation=ex, type_expectations=entry_expectation + response=response[idx], + json_expectation=ex, + type_expectations=entry_expectation, ) else: cast_json_expectation.append(cast_field(ex, entry_expectation)) @@ -56,7 +63,10 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # if any of the values of the set have a type_expectation of a dict, we're assuming it's a pydantic # model and keeping it a list. if container_expectation != "set" or not any( - map(lambda value: isinstance(value, dict), list(contents_expectation.values())) + map( + lambda value: isinstance(value, dict), + list(contents_expectation.values()), + ) ): json_expectation = cast_field(json_expectation, container_expectation) elif isinstance(type_expectation, tuple): @@ -65,9 +75,15 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(contents_expectation, dict): json_expectation = { cast_field( - key, contents_expectation.get(idx)[0] if contents_expectation.get(idx) is not None else None # type: ignore + key, + contents_expectation.get(idx)[0] + if contents_expectation.get(idx) is not None + else None, # type: ignore ): cast_field( - value, contents_expectation.get(idx)[1] if contents_expectation.get(idx) is not None else None # type: ignore + value, + contents_expectation.get(idx)[1] + if contents_expectation.get(idx) is not None + else None, # type: ignore ) for idx, (key, value) in enumerate(json_expectation.items()) } @@ -86,7 +102,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # Arg type_expectations is a deeply nested structure that matches the response, but with the values replaced with the expected types -def validate_response(response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any) -> None: +def validate_response( + response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectations == "no_validate": return @@ -96,11 +114,17 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e and not isinstance(response, dict) and not issubclass(type(response), pydantic.BaseModel) ): - validate_field(response=response, json_expectation=json_expectation, type_expectation=type_expectations) + validate_field( + response=response, + json_expectation=json_expectation, + type_expectation=type_expectations, + ) return if isinstance(response, list): - assert len(response) == len(json_expectation), "Length mismatch, expected: {0}, Actual: {1}".format( + assert len(response) == len( + json_expectation + ), "Length mismatch, expected: {0}, Actual: {1}".format( len(response), len(json_expectation) ) content_expectation = type_expectations @@ -108,7 +132,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e content_expectation = type_expectations[1] for idx, item in enumerate(response): validate_response( - response=item, json_expectation=json_expectation[idx], type_expectations=content_expectation[idx] + response=item, + json_expectation=json_expectation[idx], + type_expectations=content_expectation[idx], ) else: response_json = response @@ -116,7 +142,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e response_json = response.dict(by_alias=True) for key, value in json_expectation.items(): - assert key in response_json, "Field {0} not found within the response object: {1}".format( + assert ( + key in response_json + ), "Field {0} not found within the response object: {1}".format( key, response_json ) @@ -128,11 +156,19 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e # Otherwise, we're just validating a single field that's a pydantic model. if isinstance(value, dict) and not isinstance(type_expectation, tuple): validate_response( - response=response_json[key], json_expectation=value, type_expectations=type_expectation + response=response_json[key], + json_expectation=value, + type_expectations=type_expectation, ) else: - validate_field(response=response_json[key], json_expectation=value, type_expectation=type_expectation) + validate_field( + response=response_json[key], + json_expectation=value, + type_expectation=type_expectation, + ) # Ensure there are no additional fields here either del response_json[key] - assert len(response_json) == 0, "Additional fields found, expected None: {0}".format(response_json) + assert ( + len(response_json) == 0 + ), "Additional fields found, expected None: {0}".format(response_json) diff --git a/seed/python-sdk/exhaustive/union-utils/tests/utils/assets/models/__init__.py b/seed/python-sdk/exhaustive/union-utils/tests/utils/assets/models/__init__.py index 2cf01263529..3a1c852e71e 100644 --- a/seed/python-sdk/exhaustive/union-utils/tests/utils/assets/models/__init__.py +++ b/seed/python-sdk/exhaustive/union-utils/tests/utils/assets/models/__init__.py @@ -5,7 +5,7 @@ from .circle import CircleParams from .object_with_defaults import ObjectWithDefaultsParams from .object_with_optional_field import ObjectWithOptionalFieldParams -from .shape import Shape_CircleParams, Shape_SquareParams, ShapeParams +from .shape import ShapeParams, Shape_CircleParams, Shape_SquareParams from .square import SquareParams from .undiscriminated_shape import UndiscriminatedShapeParams diff --git a/seed/python-sdk/exhaustive/union-utils/tests/utils/assets/models/circle.py b/seed/python-sdk/exhaustive/union-utils/tests/utils/assets/models/circle.py index af7a1bf8a8e..253f12d38b3 100644 --- a/seed/python-sdk/exhaustive/union-utils/tests/utils/assets/models/circle.py +++ b/seed/python-sdk/exhaustive/union-utils/tests/utils/assets/models/circle.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class CircleParams(typing_extensions.TypedDict): - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] diff --git a/seed/python-sdk/exhaustive/union-utils/tests/utils/assets/models/object_with_optional_field.py b/seed/python-sdk/exhaustive/union-utils/tests/utils/assets/models/object_with_optional_field.py index 3ad93d5f305..ebe7dc80547 100644 --- a/seed/python-sdk/exhaustive/union-utils/tests/utils/assets/models/object_with_optional_field.py +++ b/seed/python-sdk/exhaustive/union-utils/tests/utils/assets/models/object_with_optional_field.py @@ -7,8 +7,8 @@ import uuid import typing_extensions -from seed.core.serialization import FieldMetadata +from seed.core.serialization import FieldMetadata from .color import Color from .shape import ShapeParams from .undiscriminated_shape import UndiscriminatedShapeParams @@ -18,16 +18,30 @@ class ObjectWithOptionalFieldParams(typing_extensions.TypedDict): literal: typing.Literal["lit_one"] string: typing_extensions.NotRequired[str] integer: typing_extensions.NotRequired[int] - long_: typing_extensions.NotRequired[typing_extensions.Annotated[int, FieldMetadata(alias="long")]] + long_: typing_extensions.NotRequired[ + typing_extensions.Annotated[int, FieldMetadata(alias="long")] + ] double: typing_extensions.NotRequired[float] - bool_: typing_extensions.NotRequired[typing_extensions.Annotated[bool, FieldMetadata(alias="bool")]] + bool_: typing_extensions.NotRequired[ + typing_extensions.Annotated[bool, FieldMetadata(alias="bool")] + ] datetime: typing_extensions.NotRequired[dt.datetime] date: typing_extensions.NotRequired[dt.date] - uuid_: typing_extensions.NotRequired[typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")]] - base_64: typing_extensions.NotRequired[typing_extensions.Annotated[str, FieldMetadata(alias="base64")]] - list_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")]] - set_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")]] - map_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")]] + uuid_: typing_extensions.NotRequired[ + typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")] + ] + base_64: typing_extensions.NotRequired[ + typing_extensions.Annotated[str, FieldMetadata(alias="base64")] + ] + list_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")] + ] + set_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")] + ] + map_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")] + ] enum: typing_extensions.NotRequired[Color] union: typing_extensions.NotRequired[ShapeParams] second_union: typing_extensions.NotRequired[ShapeParams] diff --git a/seed/python-sdk/exhaustive/union-utils/tests/utils/assets/models/shape.py b/seed/python-sdk/exhaustive/union-utils/tests/utils/assets/models/shape.py index 2c33c877951..816ffc51bdc 100644 --- a/seed/python-sdk/exhaustive/union-utils/tests/utils/assets/models/shape.py +++ b/seed/python-sdk/exhaustive/union-utils/tests/utils/assets/models/shape.py @@ -7,6 +7,7 @@ import typing import typing_extensions + from seed.core.serialization import FieldMetadata @@ -15,13 +16,21 @@ class Base(typing_extensions.TypedDict): class Shape_CircleParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["circle"], FieldMetadata(alias="shapeType")] - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["circle"], FieldMetadata(alias="shapeType") + ] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] class Shape_SquareParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["square"], FieldMetadata(alias="shapeType")] - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["square"], FieldMetadata(alias="shapeType") + ] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] ShapeParams = typing.Union[Shape_CircleParams, Shape_SquareParams] diff --git a/seed/python-sdk/exhaustive/union-utils/tests/utils/assets/models/square.py b/seed/python-sdk/exhaustive/union-utils/tests/utils/assets/models/square.py index b9b7dd319bc..bcf08a723c5 100644 --- a/seed/python-sdk/exhaustive/union-utils/tests/utils/assets/models/square.py +++ b/seed/python-sdk/exhaustive/union-utils/tests/utils/assets/models/square.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class SquareParams(typing_extensions.TypedDict): - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] diff --git a/seed/python-sdk/exhaustive/union-utils/tests/utils/test_http_client.py b/seed/python-sdk/exhaustive/union-utils/tests/utils/test_http_client.py index edd11ca7afb..f5a874a75f3 100644 --- a/seed/python-sdk/exhaustive/union-utils/tests/utils/test_http_client.py +++ b/seed/python-sdk/exhaustive/union-utils/tests/utils/test_http_client.py @@ -9,12 +9,17 @@ def get_request_options() -> RequestOptions: def test_get_json_request_body() -> None: - json_body, data_body = get_request_body(json={"hello": "world"}, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json={"hello": "world"}, data=None, request_options=None, omit=None + ) assert json_body == {"hello": "world"} assert data_body is None json_body_extras, data_body_extras = get_request_body( - json={"goodbye": "world"}, data=None, request_options=get_request_options(), omit=None + json={"goodbye": "world"}, + data=None, + request_options=get_request_options(), + omit=None, ) assert json_body_extras == {"goodbye": "world", "see you": "later"} @@ -22,12 +27,17 @@ def test_get_json_request_body() -> None: def test_get_files_request_body() -> None: - json_body, data_body = get_request_body(json=None, data={"hello": "world"}, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data={"hello": "world"}, request_options=None, omit=None + ) assert data_body == {"hello": "world"} assert json_body is None json_body_extras, data_body_extras = get_request_body( - json=None, data={"goodbye": "world"}, request_options=get_request_options(), omit=None + json=None, + data={"goodbye": "world"}, + request_options=get_request_options(), + omit=None, ) assert data_body_extras == {"goodbye": "world", "see you": "later"} @@ -35,7 +45,9 @@ def test_get_files_request_body() -> None: def test_get_none_request_body() -> None: - json_body, data_body = get_request_body(json=None, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data=None, request_options=None, omit=None + ) assert data_body is None assert json_body is None diff --git a/seed/python-sdk/exhaustive/union-utils/tests/utils/test_query_encoding.py b/seed/python-sdk/exhaustive/union-utils/tests/utils/test_query_encoding.py index 247e1551b46..fbc8f402167 100644 --- a/seed/python-sdk/exhaustive/union-utils/tests/utils/test_query_encoding.py +++ b/seed/python-sdk/exhaustive/union-utils/tests/utils/test_query_encoding.py @@ -4,9 +4,15 @@ def test_query_encoding() -> None: - assert encode_query({"hello world": "hello world"}) == {"hello world": "hello world"} - assert encode_query({"hello_world": {"hello": "world"}}) == {"hello_world[hello]": "world"} - assert encode_query({"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"}) == { + assert encode_query({"hello world": "hello world"}) == { + "hello world": "hello world" + } + assert encode_query({"hello_world": {"hello": "world"}}) == { + "hello_world[hello]": "world" + } + assert encode_query( + {"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"} + ) == { "hello_world[hello][world]": "today", "hello_world[test]": "this", "hi": "there", diff --git a/seed/python-sdk/exhaustive/union-utils/tests/utils/test_serialization.py b/seed/python-sdk/exhaustive/union-utils/tests/utils/test_serialization.py index 58b1ed66e6d..5ca956916dd 100644 --- a/seed/python-sdk/exhaustive/union-utils/tests/utils/test_serialization.py +++ b/seed/python-sdk/exhaustive/union-utils/tests/utils/test_serialization.py @@ -1,10 +1,12 @@ # This file was auto-generated by Fern from our API Definition. -from typing import Any, List +from typing import List, Any -from seed.core.serialization import convert_and_respect_annotation_metadata +from seed.core.serialization import ( + convert_and_respect_annotation_metadata, +) +from .assets.models import ShapeParams, ObjectWithOptionalFieldParams -from .assets.models import ObjectWithOptionalFieldParams, ShapeParams UNION_TEST: ShapeParams = {"radius_measurement": 1.0, "shape_type": "circle", "id": "1"} UNION_TEST_CONVERTED = {"shapeType": "circle", "radiusMeasurement": 1.0, "id": "1"} @@ -18,20 +20,54 @@ def test_convert_and_respect_annotation_metadata() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) - assert converted == {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"} + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) + assert converted == { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + } def test_convert_and_respect_annotation_metadata_in_list() -> None: data: List[ObjectWithOptionalFieldParams] = [ - {"string": "string", "long_": 12345, "bool_": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long_": 67890, "list_": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long_": 12345, + "bool_": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long_": 67890, + "list_": [], + "literal": "lit_one", + "any": "any", + }, ] - converted = convert_and_respect_annotation_metadata(object_=data, annotation=List[ObjectWithOptionalFieldParams]) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=List[ObjectWithOptionalFieldParams] + ) assert converted == [ - {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long": 67890, "list": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long": 67890, + "list": [], + "literal": "lit_one", + "any": "any", + }, ] @@ -43,7 +79,9 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) assert converted == { "string": "string", @@ -55,12 +93,16 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: def test_convert_and_respect_annotation_metadata_in_union() -> None: - converted = convert_and_respect_annotation_metadata(object_=UNION_TEST, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=UNION_TEST, annotation=ShapeParams + ) assert converted == UNION_TEST_CONVERTED def test_convert_and_respect_annotation_metadata_with_empty_object() -> None: data: Any = {} - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ShapeParams + ) assert converted == data diff --git a/seed/python-sdk/extends/pyproject.toml b/seed/python-sdk/extends/pyproject.toml index cacf0fa93dd..7a9ad9831aa 100644 --- a/seed/python-sdk/extends/pyproject.toml +++ b/seed/python-sdk/extends/pyproject.toml @@ -43,6 +43,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/python-sdk/extends/src/seed/__init__.py b/seed/python-sdk/extends/src/seed/__init__.py index bc234ba6139..120ad631f4d 100644 --- a/seed/python-sdk/extends/src/seed/__init__.py +++ b/seed/python-sdk/extends/src/seed/__init__.py @@ -4,4 +4,12 @@ from .client import AsyncSeedExtends, SeedExtends from .version import __version__ -__all__ = ["AsyncSeedExtends", "Docs", "ExampleType", "Json", "NestedType", "SeedExtends", "__version__"] +__all__ = [ + "AsyncSeedExtends", + "Docs", + "ExampleType", + "Json", + "NestedType", + "SeedExtends", + "__version__", +] diff --git a/seed/python-sdk/extends/src/seed/client.py b/seed/python-sdk/extends/src/seed/client.py index 43ab54650a9..f333581858b 100644 --- a/seed/python-sdk/extends/src/seed/client.py +++ b/seed/python-sdk/extends/src/seed/client.py @@ -1,13 +1,12 @@ # This file was auto-generated by Fern from our API Definition. import typing -from json.decoder import JSONDecodeError - import httpx - -from .core.api_error import ApiError -from .core.client_wrapper import AsyncClientWrapper, SyncClientWrapper +from .core.client_wrapper import SyncClientWrapper from .core.request_options import RequestOptions +from json.decoder import JSONDecodeError +from .core.api_error import ApiError +from .core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -46,21 +45,30 @@ def __init__( base_url: str, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.Client] = None + httpx_client: typing.Optional[httpx.Client] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = SyncClientWrapper( base_url=base_url, httpx_client=httpx_client if httpx_client is not None - else httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.Client( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.Client(timeout=_defaulted_timeout), timeout=_defaulted_timeout, ) def extended_inline_request_body( - self, *, unique: str, name: str, docs: str, request_options: typing.Optional[RequestOptions] = None + self, + *, + unique: str, + name: str, + docs: str, + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ Parameters @@ -94,7 +102,11 @@ def extended_inline_request_body( _response = self._client_wrapper.httpx_client.request( "extends/extended-inline-request-body", method="POST", - json={"unique": unique, "name": name, "docs": docs}, + json={ + "unique": unique, + "name": name, + "docs": docs, + }, request_options=request_options, omit=OMIT, ) @@ -140,21 +152,30 @@ def __init__( base_url: str, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.AsyncClient] = None + httpx_client: typing.Optional[httpx.AsyncClient] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = AsyncClientWrapper( base_url=base_url, httpx_client=httpx_client if httpx_client is not None - else httpx.AsyncClient(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.AsyncClient( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.AsyncClient(timeout=_defaulted_timeout), timeout=_defaulted_timeout, ) async def extended_inline_request_body( - self, *, unique: str, name: str, docs: str, request_options: typing.Optional[RequestOptions] = None + self, + *, + unique: str, + name: str, + docs: str, + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ Parameters @@ -196,7 +217,11 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( "extends/extended-inline-request-body", method="POST", - json={"unique": unique, "name": name, "docs": docs}, + json={ + "unique": unique, + "name": name, + "docs": docs, + }, request_options=request_options, omit=OMIT, ) diff --git a/seed/python-sdk/extends/src/seed/core/api_error.py b/seed/python-sdk/extends/src/seed/core/api_error.py index 2e9fc5431cd..da734b58068 100644 --- a/seed/python-sdk/extends/src/seed/core/api_error.py +++ b/seed/python-sdk/extends/src/seed/core/api_error.py @@ -7,7 +7,9 @@ class ApiError(Exception): status_code: typing.Optional[int] body: typing.Any - def __init__(self, *, status_code: typing.Optional[int] = None, body: typing.Any = None): + def __init__( + self, *, status_code: typing.Optional[int] = None, body: typing.Any = None + ): self.status_code = status_code self.body = body diff --git a/seed/python-sdk/extends/src/seed/core/client_wrapper.py b/seed/python-sdk/extends/src/seed/core/client_wrapper.py index 38194bdd05a..c6e9a739829 100644 --- a/seed/python-sdk/extends/src/seed/core/client_wrapper.py +++ b/seed/python-sdk/extends/src/seed/core/client_wrapper.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .http_client import AsyncHttpClient, HttpClient +from .http_client import HttpClient +from .http_client import AsyncHttpClient class BaseClientWrapper: @@ -28,7 +27,13 @@ def get_timeout(self) -> typing.Optional[float]: class SyncClientWrapper(BaseClientWrapper): - def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, httpx_client: httpx.Client): + def __init__( + self, + *, + base_url: str, + timeout: typing.Optional[float] = None, + httpx_client: httpx.Client, + ): super().__init__(base_url=base_url, timeout=timeout) self.httpx_client = HttpClient( httpx_client=httpx_client, @@ -39,7 +44,13 @@ def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, htt class AsyncClientWrapper(BaseClientWrapper): - def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, httpx_client: httpx.AsyncClient): + def __init__( + self, + *, + base_url: str, + timeout: typing.Optional[float] = None, + httpx_client: httpx.AsyncClient, + ): super().__init__(base_url=base_url, timeout=timeout) self.httpx_client = AsyncHttpClient( httpx_client=httpx_client, diff --git a/seed/python-sdk/extends/src/seed/core/datetime_utils.py b/seed/python-sdk/extends/src/seed/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/python-sdk/extends/src/seed/core/datetime_utils.py +++ b/seed/python-sdk/extends/src/seed/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/python-sdk/extends/src/seed/core/file.py b/seed/python-sdk/extends/src/seed/core/file.py index cb0d40bbbf3..6e0f92bfcb1 100644 --- a/seed/python-sdk/extends/src/seed/core/file.py +++ b/seed/python-sdk/extends/src/seed/core/file.py @@ -13,12 +13,17 @@ # (filename, file (or bytes), content_type) typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str]], # (filename, file (or bytes), content_type, headers) - typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str], typing.Mapping[str, str]], + typing.Tuple[ + typing.Optional[str], + FileContent, + typing.Optional[str], + typing.Mapping[str, str], + ], ] def convert_file_dict_to_httpx_tuples( - d: typing.Dict[str, typing.Union[File, typing.List[File]]] + d: typing.Dict[str, typing.Union[File, typing.List[File]]], ) -> typing.List[typing.Tuple[str, File]]: """ The format we use is a list of tuples, where the first element is the diff --git a/seed/python-sdk/extends/src/seed/core/http_client.py b/seed/python-sdk/extends/src/seed/core/http_client.py index 9333d8a7f15..091f71bc185 100644 --- a/seed/python-sdk/extends/src/seed/core/http_client.py +++ b/seed/python-sdk/extends/src/seed/core/http_client.py @@ -77,7 +77,9 @@ def _retry_timeout(response: httpx.Response, retries: int) -> float: return retry_after # Apply exponential backoff, capped at MAX_RETRY_DELAY_SECONDS. - retry_delay = min(INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS) + retry_delay = min( + INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS + ) # Add a randomness / jitter to the retry delay to avoid overwhelming the server with retries. timeout = retry_delay * (1 - 0.25 * random()) @@ -90,7 +92,8 @@ def _should_retry(response: httpx.Response) -> bool: def remove_omit_from_dict( - original: typing.Dict[str, typing.Optional[typing.Any]], omit: typing.Optional[typing.Any] + original: typing.Dict[str, typing.Optional[typing.Any]], + omit: typing.Optional[typing.Any], ) -> typing.Dict[str, typing.Any]: if omit is None: return original @@ -108,7 +111,8 @@ def maybe_filter_request_body( ) -> typing.Optional[typing.Any]: if data is None: return ( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else None ) @@ -118,7 +122,8 @@ def maybe_filter_request_body( data_content = { **(jsonable_encoder(remove_omit_from_dict(data, omit))), # type: ignore **( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else {} ), @@ -162,7 +167,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url def request( @@ -174,8 +181,12 @@ def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -184,11 +195,14 @@ def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) response = self.httpx_client.request( method=method, @@ -198,7 +212,11 @@ def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -209,7 +227,10 @@ def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -222,11 +243,15 @@ def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: time.sleep(_retry_timeout(response=response, retries=retries)) @@ -256,8 +281,12 @@ def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -266,11 +295,14 @@ def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) with self.httpx_client.stream( method=method, @@ -280,7 +312,11 @@ def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -291,7 +327,9 @@ def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -304,7 +342,9 @@ def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream @@ -327,7 +367,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url async def request( @@ -339,8 +381,12 @@ async def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -349,11 +395,14 @@ async def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) # Add the input to each of these and do None-safety checks response = await self.httpx_client.request( @@ -364,7 +413,11 @@ async def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -375,7 +428,10 @@ async def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -388,11 +444,15 @@ async def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: await asyncio.sleep(_retry_timeout(response=response, retries=retries)) @@ -421,8 +481,12 @@ async def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -431,11 +495,14 @@ async def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) async with self.httpx_client.stream( method=method, @@ -445,7 +512,11 @@ async def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -456,7 +527,9 @@ async def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -469,7 +542,9 @@ async def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream diff --git a/seed/python-sdk/extends/src/seed/core/jsonable_encoder.py b/seed/python-sdk/extends/src/seed/core/jsonable_encoder.py index d3fd328fd41..12a8b52fc22 100644 --- a/seed/python-sdk/extends/src/seed/core/jsonable_encoder.py +++ b/seed/python-sdk/extends/src/seed/core/jsonable_encoder.py @@ -19,13 +19,19 @@ import pydantic from .datetime_utils import serialize_datetime -from .pydantic_utilities import IS_PYDANTIC_V2, encode_by_type, to_jsonable_with_fallback +from .pydantic_utilities import ( + IS_PYDANTIC_V2, + encode_by_type, + to_jsonable_with_fallback, +) SetIntStr = Set[Union[int, str]] DictIntStrAny = Dict[Union[int, str], Any] -def jsonable_encoder(obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None) -> Any: +def jsonable_encoder( + obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None +) -> Any: custom_encoder = custom_encoder or {} if custom_encoder: if type(obj) in custom_encoder: diff --git a/seed/python-sdk/extends/src/seed/core/pydantic_utilities.py b/seed/python-sdk/extends/src/seed/core/pydantic_utilities.py index 170a563d6eb..c63935c32a2 100644 --- a/seed/python-sdk/extends/src/seed/core/pydantic_utilities.py +++ b/seed/python-sdk/extends/src/seed/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) # type: ignore # Pydantic v1 diff --git a/seed/python-sdk/extends/src/seed/core/query_encoder.py b/seed/python-sdk/extends/src/seed/core/query_encoder.py index 24076d72ee9..7cb98f52cd7 100644 --- a/seed/python-sdk/extends/src/seed/core/query_encoder.py +++ b/seed/python-sdk/extends/src/seed/core/query_encoder.py @@ -7,7 +7,9 @@ # Flattens dicts to be of the form {"key[subkey][subkey2]": value} where value is not a dict -def traverse_query_dict(dict_flat: Dict[str, Any], key_prefix: Optional[str] = None) -> Dict[str, Any]: +def traverse_query_dict( + dict_flat: Dict[str, Any], key_prefix: Optional[str] = None +) -> Dict[str, Any]: result = {} for k, v in dict_flat.items(): key = f"{key_prefix}[{k}]" if key_prefix is not None else k @@ -30,4 +32,8 @@ def single_query_encoder(query_key: str, query_value: Any) -> Dict[str, Any]: def encode_query(query: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: - return dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) if query is not None else None + return ( + dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) + if query is not None + else None + ) diff --git a/seed/python-sdk/extends/src/seed/core/serialization.py b/seed/python-sdk/extends/src/seed/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/python-sdk/extends/src/seed/core/serialization.py +++ b/seed/python-sdk/extends/src/seed/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/python-sdk/extends/src/seed/types/docs.py b/seed/python-sdk/extends/src/seed/types/docs.py index dc940583549..04d1fd25c2d 100644 --- a/seed/python-sdk/extends/src/seed/types/docs.py +++ b/seed/python-sdk/extends/src/seed/types/docs.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from ..core.pydantic_utilities import UniversalBaseModel +from ..core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class Docs(UniversalBaseModel): """ @@ -21,7 +20,9 @@ class Docs(UniversalBaseModel): docs: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/extends/src/seed/types/example_type.py b/seed/python-sdk/extends/src/seed/types/example_type.py index ae3313342e4..f62eed7cd15 100644 --- a/seed/python-sdk/extends/src/seed/types/example_type.py +++ b/seed/python-sdk/extends/src/seed/types/example_type.py @@ -1,12 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from .docs import Docs +from ..core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ..core.pydantic_utilities import IS_PYDANTIC_V2 -from .docs import Docs - class ExampleType(Docs): """ @@ -23,7 +21,9 @@ class ExampleType(Docs): name: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/extends/src/seed/types/json.py b/seed/python-sdk/extends/src/seed/types/json.py index 931a8fb92a9..51e4db14a62 100644 --- a/seed/python-sdk/extends/src/seed/types/json.py +++ b/seed/python-sdk/extends/src/seed/types/json.py @@ -1,12 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from .docs import Docs +from ..core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ..core.pydantic_utilities import IS_PYDANTIC_V2 -from .docs import Docs - class Json(Docs): """ @@ -23,7 +21,9 @@ class Json(Docs): raw: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/extends/src/seed/types/nested_type.py b/seed/python-sdk/extends/src/seed/types/nested_type.py index ba1b804e13c..7b5ced3bd31 100644 --- a/seed/python-sdk/extends/src/seed/types/nested_type.py +++ b/seed/python-sdk/extends/src/seed/types/nested_type.py @@ -1,12 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from .json import Json +from ..core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ..core.pydantic_utilities import IS_PYDANTIC_V2 -from .json import Json - class NestedType(Json): """ @@ -24,7 +22,9 @@ class NestedType(Json): name: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/extends/src/seed/version.py b/seed/python-sdk/extends/src/seed/version.py index e1b9fb2ebae..0135cd3c55c 100644 --- a/seed/python-sdk/extends/src/seed/version.py +++ b/seed/python-sdk/extends/src/seed/version.py @@ -1,4 +1,3 @@ - from importlib import metadata __version__ = metadata.version("fern_extends") diff --git a/seed/python-sdk/extends/tests/conftest.py b/seed/python-sdk/extends/tests/conftest.py index a2ccabbece2..b76538eebcb 100644 --- a/seed/python-sdk/extends/tests/conftest.py +++ b/seed/python-sdk/extends/tests/conftest.py @@ -1,9 +1,9 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExtends import os - import pytest -from seed import AsyncSeedExtends, SeedExtends +from seed import AsyncSeedExtends @pytest.fixture diff --git a/seed/python-sdk/extends/tests/custom/test_client.py b/seed/python-sdk/extends/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/python-sdk/extends/tests/custom/test_client.py +++ b/seed/python-sdk/extends/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/python-sdk/extends/tests/test_root.py b/seed/python-sdk/extends/tests/test_root.py index 0fe433f6fe1..008e0ae435a 100644 --- a/seed/python-sdk/extends/tests/test_root.py +++ b/seed/python-sdk/extends/tests/test_root.py @@ -1,10 +1,23 @@ # This file was auto-generated by Fern from our API Definition. -from seed import AsyncSeedExtends, SeedExtends +from seed import SeedExtends +from seed import AsyncSeedExtends -async def test_extended_inline_request_body(client: SeedExtends, async_client: AsyncSeedExtends) -> None: +async def test_extended_inline_request_body( + client: SeedExtends, async_client: AsyncSeedExtends +) -> None: # Type ignore to avoid mypy complaining about the function not being meant to return a value - assert client.extended_inline_request_body(unique="string", name="string", docs="string") is None # type: ignore[func-returns-value] + assert ( + client.extended_inline_request_body( + unique="string", name="string", docs="string" + ) + is None + ) # type: ignore[func-returns-value] - assert await async_client.extended_inline_request_body(unique="string", name="string", docs="string") is None # type: ignore[func-returns-value] + assert ( + await async_client.extended_inline_request_body( + unique="string", name="string", docs="string" + ) + is None + ) # type: ignore[func-returns-value] diff --git a/seed/python-sdk/extends/tests/utilities.py b/seed/python-sdk/extends/tests/utilities.py index 13da208eb3a..e8f4472564c 100644 --- a/seed/python-sdk/extends/tests/utilities.py +++ b/seed/python-sdk/extends/tests/utilities.py @@ -3,11 +3,14 @@ import typing import uuid -import pydantic from dateutil import parser +import pydantic + -def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> typing.Any: +def cast_field( + json_expectation: typing.Any, type_expectation: typing.Any +) -> typing.Any: # Cast these specific types which come through as string and expect our # models to cast to the correct type. if type_expectation == "uuid": @@ -25,7 +28,9 @@ def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> ty return json_expectation -def validate_field(response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any) -> None: +def validate_field( + response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectation == "no_validate": return @@ -44,7 +49,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(entry_expectation, dict): is_container_of_complex_type = True validate_response( - response=response[idx], json_expectation=ex, type_expectations=entry_expectation + response=response[idx], + json_expectation=ex, + type_expectations=entry_expectation, ) else: cast_json_expectation.append(cast_field(ex, entry_expectation)) @@ -56,7 +63,10 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # if any of the values of the set have a type_expectation of a dict, we're assuming it's a pydantic # model and keeping it a list. if container_expectation != "set" or not any( - map(lambda value: isinstance(value, dict), list(contents_expectation.values())) + map( + lambda value: isinstance(value, dict), + list(contents_expectation.values()), + ) ): json_expectation = cast_field(json_expectation, container_expectation) elif isinstance(type_expectation, tuple): @@ -65,9 +75,15 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(contents_expectation, dict): json_expectation = { cast_field( - key, contents_expectation.get(idx)[0] if contents_expectation.get(idx) is not None else None # type: ignore + key, + contents_expectation.get(idx)[0] + if contents_expectation.get(idx) is not None + else None, # type: ignore ): cast_field( - value, contents_expectation.get(idx)[1] if contents_expectation.get(idx) is not None else None # type: ignore + value, + contents_expectation.get(idx)[1] + if contents_expectation.get(idx) is not None + else None, # type: ignore ) for idx, (key, value) in enumerate(json_expectation.items()) } @@ -86,7 +102,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # Arg type_expectations is a deeply nested structure that matches the response, but with the values replaced with the expected types -def validate_response(response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any) -> None: +def validate_response( + response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectations == "no_validate": return @@ -96,11 +114,17 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e and not isinstance(response, dict) and not issubclass(type(response), pydantic.BaseModel) ): - validate_field(response=response, json_expectation=json_expectation, type_expectation=type_expectations) + validate_field( + response=response, + json_expectation=json_expectation, + type_expectation=type_expectations, + ) return if isinstance(response, list): - assert len(response) == len(json_expectation), "Length mismatch, expected: {0}, Actual: {1}".format( + assert len(response) == len( + json_expectation + ), "Length mismatch, expected: {0}, Actual: {1}".format( len(response), len(json_expectation) ) content_expectation = type_expectations @@ -108,7 +132,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e content_expectation = type_expectations[1] for idx, item in enumerate(response): validate_response( - response=item, json_expectation=json_expectation[idx], type_expectations=content_expectation[idx] + response=item, + json_expectation=json_expectation[idx], + type_expectations=content_expectation[idx], ) else: response_json = response @@ -116,7 +142,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e response_json = response.dict(by_alias=True) for key, value in json_expectation.items(): - assert key in response_json, "Field {0} not found within the response object: {1}".format( + assert ( + key in response_json + ), "Field {0} not found within the response object: {1}".format( key, response_json ) @@ -128,11 +156,19 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e # Otherwise, we're just validating a single field that's a pydantic model. if isinstance(value, dict) and not isinstance(type_expectation, tuple): validate_response( - response=response_json[key], json_expectation=value, type_expectations=type_expectation + response=response_json[key], + json_expectation=value, + type_expectations=type_expectation, ) else: - validate_field(response=response_json[key], json_expectation=value, type_expectation=type_expectation) + validate_field( + response=response_json[key], + json_expectation=value, + type_expectation=type_expectation, + ) # Ensure there are no additional fields here either del response_json[key] - assert len(response_json) == 0, "Additional fields found, expected None: {0}".format(response_json) + assert ( + len(response_json) == 0 + ), "Additional fields found, expected None: {0}".format(response_json) diff --git a/seed/python-sdk/extends/tests/utils/assets/models/__init__.py b/seed/python-sdk/extends/tests/utils/assets/models/__init__.py index 2cf01263529..3a1c852e71e 100644 --- a/seed/python-sdk/extends/tests/utils/assets/models/__init__.py +++ b/seed/python-sdk/extends/tests/utils/assets/models/__init__.py @@ -5,7 +5,7 @@ from .circle import CircleParams from .object_with_defaults import ObjectWithDefaultsParams from .object_with_optional_field import ObjectWithOptionalFieldParams -from .shape import Shape_CircleParams, Shape_SquareParams, ShapeParams +from .shape import ShapeParams, Shape_CircleParams, Shape_SquareParams from .square import SquareParams from .undiscriminated_shape import UndiscriminatedShapeParams diff --git a/seed/python-sdk/extends/tests/utils/assets/models/circle.py b/seed/python-sdk/extends/tests/utils/assets/models/circle.py index af7a1bf8a8e..253f12d38b3 100644 --- a/seed/python-sdk/extends/tests/utils/assets/models/circle.py +++ b/seed/python-sdk/extends/tests/utils/assets/models/circle.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class CircleParams(typing_extensions.TypedDict): - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] diff --git a/seed/python-sdk/extends/tests/utils/assets/models/object_with_optional_field.py b/seed/python-sdk/extends/tests/utils/assets/models/object_with_optional_field.py index 3ad93d5f305..ebe7dc80547 100644 --- a/seed/python-sdk/extends/tests/utils/assets/models/object_with_optional_field.py +++ b/seed/python-sdk/extends/tests/utils/assets/models/object_with_optional_field.py @@ -7,8 +7,8 @@ import uuid import typing_extensions -from seed.core.serialization import FieldMetadata +from seed.core.serialization import FieldMetadata from .color import Color from .shape import ShapeParams from .undiscriminated_shape import UndiscriminatedShapeParams @@ -18,16 +18,30 @@ class ObjectWithOptionalFieldParams(typing_extensions.TypedDict): literal: typing.Literal["lit_one"] string: typing_extensions.NotRequired[str] integer: typing_extensions.NotRequired[int] - long_: typing_extensions.NotRequired[typing_extensions.Annotated[int, FieldMetadata(alias="long")]] + long_: typing_extensions.NotRequired[ + typing_extensions.Annotated[int, FieldMetadata(alias="long")] + ] double: typing_extensions.NotRequired[float] - bool_: typing_extensions.NotRequired[typing_extensions.Annotated[bool, FieldMetadata(alias="bool")]] + bool_: typing_extensions.NotRequired[ + typing_extensions.Annotated[bool, FieldMetadata(alias="bool")] + ] datetime: typing_extensions.NotRequired[dt.datetime] date: typing_extensions.NotRequired[dt.date] - uuid_: typing_extensions.NotRequired[typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")]] - base_64: typing_extensions.NotRequired[typing_extensions.Annotated[str, FieldMetadata(alias="base64")]] - list_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")]] - set_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")]] - map_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")]] + uuid_: typing_extensions.NotRequired[ + typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")] + ] + base_64: typing_extensions.NotRequired[ + typing_extensions.Annotated[str, FieldMetadata(alias="base64")] + ] + list_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")] + ] + set_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")] + ] + map_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")] + ] enum: typing_extensions.NotRequired[Color] union: typing_extensions.NotRequired[ShapeParams] second_union: typing_extensions.NotRequired[ShapeParams] diff --git a/seed/python-sdk/extends/tests/utils/assets/models/shape.py b/seed/python-sdk/extends/tests/utils/assets/models/shape.py index 2c33c877951..816ffc51bdc 100644 --- a/seed/python-sdk/extends/tests/utils/assets/models/shape.py +++ b/seed/python-sdk/extends/tests/utils/assets/models/shape.py @@ -7,6 +7,7 @@ import typing import typing_extensions + from seed.core.serialization import FieldMetadata @@ -15,13 +16,21 @@ class Base(typing_extensions.TypedDict): class Shape_CircleParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["circle"], FieldMetadata(alias="shapeType")] - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["circle"], FieldMetadata(alias="shapeType") + ] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] class Shape_SquareParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["square"], FieldMetadata(alias="shapeType")] - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["square"], FieldMetadata(alias="shapeType") + ] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] ShapeParams = typing.Union[Shape_CircleParams, Shape_SquareParams] diff --git a/seed/python-sdk/extends/tests/utils/assets/models/square.py b/seed/python-sdk/extends/tests/utils/assets/models/square.py index b9b7dd319bc..bcf08a723c5 100644 --- a/seed/python-sdk/extends/tests/utils/assets/models/square.py +++ b/seed/python-sdk/extends/tests/utils/assets/models/square.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class SquareParams(typing_extensions.TypedDict): - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] diff --git a/seed/python-sdk/extends/tests/utils/test_http_client.py b/seed/python-sdk/extends/tests/utils/test_http_client.py index edd11ca7afb..f5a874a75f3 100644 --- a/seed/python-sdk/extends/tests/utils/test_http_client.py +++ b/seed/python-sdk/extends/tests/utils/test_http_client.py @@ -9,12 +9,17 @@ def get_request_options() -> RequestOptions: def test_get_json_request_body() -> None: - json_body, data_body = get_request_body(json={"hello": "world"}, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json={"hello": "world"}, data=None, request_options=None, omit=None + ) assert json_body == {"hello": "world"} assert data_body is None json_body_extras, data_body_extras = get_request_body( - json={"goodbye": "world"}, data=None, request_options=get_request_options(), omit=None + json={"goodbye": "world"}, + data=None, + request_options=get_request_options(), + omit=None, ) assert json_body_extras == {"goodbye": "world", "see you": "later"} @@ -22,12 +27,17 @@ def test_get_json_request_body() -> None: def test_get_files_request_body() -> None: - json_body, data_body = get_request_body(json=None, data={"hello": "world"}, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data={"hello": "world"}, request_options=None, omit=None + ) assert data_body == {"hello": "world"} assert json_body is None json_body_extras, data_body_extras = get_request_body( - json=None, data={"goodbye": "world"}, request_options=get_request_options(), omit=None + json=None, + data={"goodbye": "world"}, + request_options=get_request_options(), + omit=None, ) assert data_body_extras == {"goodbye": "world", "see you": "later"} @@ -35,7 +45,9 @@ def test_get_files_request_body() -> None: def test_get_none_request_body() -> None: - json_body, data_body = get_request_body(json=None, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data=None, request_options=None, omit=None + ) assert data_body is None assert json_body is None diff --git a/seed/python-sdk/extends/tests/utils/test_query_encoding.py b/seed/python-sdk/extends/tests/utils/test_query_encoding.py index 247e1551b46..fbc8f402167 100644 --- a/seed/python-sdk/extends/tests/utils/test_query_encoding.py +++ b/seed/python-sdk/extends/tests/utils/test_query_encoding.py @@ -4,9 +4,15 @@ def test_query_encoding() -> None: - assert encode_query({"hello world": "hello world"}) == {"hello world": "hello world"} - assert encode_query({"hello_world": {"hello": "world"}}) == {"hello_world[hello]": "world"} - assert encode_query({"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"}) == { + assert encode_query({"hello world": "hello world"}) == { + "hello world": "hello world" + } + assert encode_query({"hello_world": {"hello": "world"}}) == { + "hello_world[hello]": "world" + } + assert encode_query( + {"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"} + ) == { "hello_world[hello][world]": "today", "hello_world[test]": "this", "hi": "there", diff --git a/seed/python-sdk/extends/tests/utils/test_serialization.py b/seed/python-sdk/extends/tests/utils/test_serialization.py index 58b1ed66e6d..5ca956916dd 100644 --- a/seed/python-sdk/extends/tests/utils/test_serialization.py +++ b/seed/python-sdk/extends/tests/utils/test_serialization.py @@ -1,10 +1,12 @@ # This file was auto-generated by Fern from our API Definition. -from typing import Any, List +from typing import List, Any -from seed.core.serialization import convert_and_respect_annotation_metadata +from seed.core.serialization import ( + convert_and_respect_annotation_metadata, +) +from .assets.models import ShapeParams, ObjectWithOptionalFieldParams -from .assets.models import ObjectWithOptionalFieldParams, ShapeParams UNION_TEST: ShapeParams = {"radius_measurement": 1.0, "shape_type": "circle", "id": "1"} UNION_TEST_CONVERTED = {"shapeType": "circle", "radiusMeasurement": 1.0, "id": "1"} @@ -18,20 +20,54 @@ def test_convert_and_respect_annotation_metadata() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) - assert converted == {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"} + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) + assert converted == { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + } def test_convert_and_respect_annotation_metadata_in_list() -> None: data: List[ObjectWithOptionalFieldParams] = [ - {"string": "string", "long_": 12345, "bool_": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long_": 67890, "list_": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long_": 12345, + "bool_": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long_": 67890, + "list_": [], + "literal": "lit_one", + "any": "any", + }, ] - converted = convert_and_respect_annotation_metadata(object_=data, annotation=List[ObjectWithOptionalFieldParams]) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=List[ObjectWithOptionalFieldParams] + ) assert converted == [ - {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long": 67890, "list": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long": 67890, + "list": [], + "literal": "lit_one", + "any": "any", + }, ] @@ -43,7 +79,9 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) assert converted == { "string": "string", @@ -55,12 +93,16 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: def test_convert_and_respect_annotation_metadata_in_union() -> None: - converted = convert_and_respect_annotation_metadata(object_=UNION_TEST, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=UNION_TEST, annotation=ShapeParams + ) assert converted == UNION_TEST_CONVERTED def test_convert_and_respect_annotation_metadata_with_empty_object() -> None: data: Any = {} - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ShapeParams + ) assert converted == data diff --git a/seed/python-sdk/extra-properties/pyproject.toml b/seed/python-sdk/extra-properties/pyproject.toml index 1228a33e634..9946e1ba9b5 100644 --- a/seed/python-sdk/extra-properties/pyproject.toml +++ b/seed/python-sdk/extra-properties/pyproject.toml @@ -43,6 +43,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/python-sdk/extra-properties/src/seed/__init__.py b/seed/python-sdk/extra-properties/src/seed/__init__.py index faa5ebc1e07..47ab6c06e5d 100644 --- a/seed/python-sdk/extra-properties/src/seed/__init__.py +++ b/seed/python-sdk/extra-properties/src/seed/__init__.py @@ -6,4 +6,11 @@ from .user import User from .version import __version__ -__all__ = ["AsyncSeedExtraProperties", "Failure", "SeedExtraProperties", "User", "__version__", "user"] +__all__ = [ + "AsyncSeedExtraProperties", + "Failure", + "SeedExtraProperties", + "User", + "__version__", + "user", +] diff --git a/seed/python-sdk/extra-properties/src/seed/client.py b/seed/python-sdk/extra-properties/src/seed/client.py index c66a7fb69b0..dfadaff3f01 100644 --- a/seed/python-sdk/extra-properties/src/seed/client.py +++ b/seed/python-sdk/extra-properties/src/seed/client.py @@ -1,11 +1,11 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from .user.client import AsyncUserClient, UserClient +from .core.client_wrapper import SyncClientWrapper +from .user.client import UserClient +from .core.client_wrapper import AsyncClientWrapper +from .user.client import AsyncUserClient class SeedExtraProperties: @@ -41,14 +41,18 @@ def __init__( base_url: str, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.Client] = None + httpx_client: typing.Optional[httpx.Client] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = SyncClientWrapper( base_url=base_url, httpx_client=httpx_client if httpx_client is not None - else httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.Client( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.Client(timeout=_defaulted_timeout), timeout=_defaulted_timeout, @@ -89,14 +93,18 @@ def __init__( base_url: str, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.AsyncClient] = None + httpx_client: typing.Optional[httpx.AsyncClient] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = AsyncClientWrapper( base_url=base_url, httpx_client=httpx_client if httpx_client is not None - else httpx.AsyncClient(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.AsyncClient( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.AsyncClient(timeout=_defaulted_timeout), timeout=_defaulted_timeout, diff --git a/seed/python-sdk/extra-properties/src/seed/core/api_error.py b/seed/python-sdk/extra-properties/src/seed/core/api_error.py index 2e9fc5431cd..da734b58068 100644 --- a/seed/python-sdk/extra-properties/src/seed/core/api_error.py +++ b/seed/python-sdk/extra-properties/src/seed/core/api_error.py @@ -7,7 +7,9 @@ class ApiError(Exception): status_code: typing.Optional[int] body: typing.Any - def __init__(self, *, status_code: typing.Optional[int] = None, body: typing.Any = None): + def __init__( + self, *, status_code: typing.Optional[int] = None, body: typing.Any = None + ): self.status_code = status_code self.body = body diff --git a/seed/python-sdk/extra-properties/src/seed/core/client_wrapper.py b/seed/python-sdk/extra-properties/src/seed/core/client_wrapper.py index c47c9897194..9262627b860 100644 --- a/seed/python-sdk/extra-properties/src/seed/core/client_wrapper.py +++ b/seed/python-sdk/extra-properties/src/seed/core/client_wrapper.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .http_client import AsyncHttpClient, HttpClient +from .http_client import HttpClient +from .http_client import AsyncHttpClient class BaseClientWrapper: @@ -28,7 +27,13 @@ def get_timeout(self) -> typing.Optional[float]: class SyncClientWrapper(BaseClientWrapper): - def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, httpx_client: httpx.Client): + def __init__( + self, + *, + base_url: str, + timeout: typing.Optional[float] = None, + httpx_client: httpx.Client, + ): super().__init__(base_url=base_url, timeout=timeout) self.httpx_client = HttpClient( httpx_client=httpx_client, @@ -39,7 +44,13 @@ def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, htt class AsyncClientWrapper(BaseClientWrapper): - def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, httpx_client: httpx.AsyncClient): + def __init__( + self, + *, + base_url: str, + timeout: typing.Optional[float] = None, + httpx_client: httpx.AsyncClient, + ): super().__init__(base_url=base_url, timeout=timeout) self.httpx_client = AsyncHttpClient( httpx_client=httpx_client, diff --git a/seed/python-sdk/extra-properties/src/seed/core/datetime_utils.py b/seed/python-sdk/extra-properties/src/seed/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/python-sdk/extra-properties/src/seed/core/datetime_utils.py +++ b/seed/python-sdk/extra-properties/src/seed/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/python-sdk/extra-properties/src/seed/core/file.py b/seed/python-sdk/extra-properties/src/seed/core/file.py index cb0d40bbbf3..6e0f92bfcb1 100644 --- a/seed/python-sdk/extra-properties/src/seed/core/file.py +++ b/seed/python-sdk/extra-properties/src/seed/core/file.py @@ -13,12 +13,17 @@ # (filename, file (or bytes), content_type) typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str]], # (filename, file (or bytes), content_type, headers) - typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str], typing.Mapping[str, str]], + typing.Tuple[ + typing.Optional[str], + FileContent, + typing.Optional[str], + typing.Mapping[str, str], + ], ] def convert_file_dict_to_httpx_tuples( - d: typing.Dict[str, typing.Union[File, typing.List[File]]] + d: typing.Dict[str, typing.Union[File, typing.List[File]]], ) -> typing.List[typing.Tuple[str, File]]: """ The format we use is a list of tuples, where the first element is the diff --git a/seed/python-sdk/extra-properties/src/seed/core/http_client.py b/seed/python-sdk/extra-properties/src/seed/core/http_client.py index 9333d8a7f15..091f71bc185 100644 --- a/seed/python-sdk/extra-properties/src/seed/core/http_client.py +++ b/seed/python-sdk/extra-properties/src/seed/core/http_client.py @@ -77,7 +77,9 @@ def _retry_timeout(response: httpx.Response, retries: int) -> float: return retry_after # Apply exponential backoff, capped at MAX_RETRY_DELAY_SECONDS. - retry_delay = min(INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS) + retry_delay = min( + INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS + ) # Add a randomness / jitter to the retry delay to avoid overwhelming the server with retries. timeout = retry_delay * (1 - 0.25 * random()) @@ -90,7 +92,8 @@ def _should_retry(response: httpx.Response) -> bool: def remove_omit_from_dict( - original: typing.Dict[str, typing.Optional[typing.Any]], omit: typing.Optional[typing.Any] + original: typing.Dict[str, typing.Optional[typing.Any]], + omit: typing.Optional[typing.Any], ) -> typing.Dict[str, typing.Any]: if omit is None: return original @@ -108,7 +111,8 @@ def maybe_filter_request_body( ) -> typing.Optional[typing.Any]: if data is None: return ( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else None ) @@ -118,7 +122,8 @@ def maybe_filter_request_body( data_content = { **(jsonable_encoder(remove_omit_from_dict(data, omit))), # type: ignore **( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else {} ), @@ -162,7 +167,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url def request( @@ -174,8 +181,12 @@ def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -184,11 +195,14 @@ def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) response = self.httpx_client.request( method=method, @@ -198,7 +212,11 @@ def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -209,7 +227,10 @@ def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -222,11 +243,15 @@ def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: time.sleep(_retry_timeout(response=response, retries=retries)) @@ -256,8 +281,12 @@ def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -266,11 +295,14 @@ def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) with self.httpx_client.stream( method=method, @@ -280,7 +312,11 @@ def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -291,7 +327,9 @@ def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -304,7 +342,9 @@ def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream @@ -327,7 +367,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url async def request( @@ -339,8 +381,12 @@ async def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -349,11 +395,14 @@ async def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) # Add the input to each of these and do None-safety checks response = await self.httpx_client.request( @@ -364,7 +413,11 @@ async def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -375,7 +428,10 @@ async def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -388,11 +444,15 @@ async def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: await asyncio.sleep(_retry_timeout(response=response, retries=retries)) @@ -421,8 +481,12 @@ async def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -431,11 +495,14 @@ async def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) async with self.httpx_client.stream( method=method, @@ -445,7 +512,11 @@ async def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -456,7 +527,9 @@ async def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -469,7 +542,9 @@ async def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream diff --git a/seed/python-sdk/extra-properties/src/seed/core/jsonable_encoder.py b/seed/python-sdk/extra-properties/src/seed/core/jsonable_encoder.py index d3fd328fd41..12a8b52fc22 100644 --- a/seed/python-sdk/extra-properties/src/seed/core/jsonable_encoder.py +++ b/seed/python-sdk/extra-properties/src/seed/core/jsonable_encoder.py @@ -19,13 +19,19 @@ import pydantic from .datetime_utils import serialize_datetime -from .pydantic_utilities import IS_PYDANTIC_V2, encode_by_type, to_jsonable_with_fallback +from .pydantic_utilities import ( + IS_PYDANTIC_V2, + encode_by_type, + to_jsonable_with_fallback, +) SetIntStr = Set[Union[int, str]] DictIntStrAny = Dict[Union[int, str], Any] -def jsonable_encoder(obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None) -> Any: +def jsonable_encoder( + obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None +) -> Any: custom_encoder = custom_encoder or {} if custom_encoder: if type(obj) in custom_encoder: diff --git a/seed/python-sdk/extra-properties/src/seed/core/pydantic_utilities.py b/seed/python-sdk/extra-properties/src/seed/core/pydantic_utilities.py index 170a563d6eb..c63935c32a2 100644 --- a/seed/python-sdk/extra-properties/src/seed/core/pydantic_utilities.py +++ b/seed/python-sdk/extra-properties/src/seed/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) # type: ignore # Pydantic v1 diff --git a/seed/python-sdk/extra-properties/src/seed/core/query_encoder.py b/seed/python-sdk/extra-properties/src/seed/core/query_encoder.py index 24076d72ee9..7cb98f52cd7 100644 --- a/seed/python-sdk/extra-properties/src/seed/core/query_encoder.py +++ b/seed/python-sdk/extra-properties/src/seed/core/query_encoder.py @@ -7,7 +7,9 @@ # Flattens dicts to be of the form {"key[subkey][subkey2]": value} where value is not a dict -def traverse_query_dict(dict_flat: Dict[str, Any], key_prefix: Optional[str] = None) -> Dict[str, Any]: +def traverse_query_dict( + dict_flat: Dict[str, Any], key_prefix: Optional[str] = None +) -> Dict[str, Any]: result = {} for k, v in dict_flat.items(): key = f"{key_prefix}[{k}]" if key_prefix is not None else k @@ -30,4 +32,8 @@ def single_query_encoder(query_key: str, query_value: Any) -> Dict[str, Any]: def encode_query(query: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: - return dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) if query is not None else None + return ( + dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) + if query is not None + else None + ) diff --git a/seed/python-sdk/extra-properties/src/seed/core/serialization.py b/seed/python-sdk/extra-properties/src/seed/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/python-sdk/extra-properties/src/seed/core/serialization.py +++ b/seed/python-sdk/extra-properties/src/seed/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/python-sdk/extra-properties/src/seed/types/failure.py b/seed/python-sdk/extra-properties/src/seed/types/failure.py index 379170ec4c0..2ed7db71481 100644 --- a/seed/python-sdk/extra-properties/src/seed/types/failure.py +++ b/seed/python-sdk/extra-properties/src/seed/types/failure.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ..core.pydantic_utilities import UniversalBaseModel import typing - +from ..core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class Failure(UniversalBaseModel): status: typing.Literal["failure"] = "failure" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/extra-properties/src/seed/user/client.py b/seed/python-sdk/extra-properties/src/seed/user/client.py index c614179f48d..a6122b68d7e 100644 --- a/seed/python-sdk/extra-properties/src/seed/user/client.py +++ b/seed/python-sdk/extra-properties/src/seed/user/client.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. import typing -from json.decoder import JSONDecodeError - -from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.pydantic_utilities import parse_obj_as +from ..core.client_wrapper import SyncClientWrapper from ..core.request_options import RequestOptions from .types.user import User +from ..core.pydantic_utilities import parse_obj_as +from json.decoder import JSONDecodeError +from ..core.api_error import ApiError +from ..core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -17,7 +17,9 @@ class UserClient: def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper - def create_user(self, *, name: str, request_options: typing.Optional[RequestOptions] = None) -> User: + def create_user( + self, *, name: str, request_options: typing.Optional[RequestOptions] = None + ) -> User: """ Parameters ---------- @@ -44,13 +46,19 @@ def create_user(self, *, name: str, request_options: typing.Optional[RequestOpti _response = self._client_wrapper.httpx_client.request( "user", method="POST", - json={"name": name, "_type": "CreateUserRequest", "_version": "v1"}, + json={ + "name": name, + "_type": "CreateUserRequest", + "_version": "v1", + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(User, parse_obj_as(type_=User, object_=_response.json())) # type: ignore + return typing.cast( + User, parse_obj_as(type_=User, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -61,7 +69,9 @@ class AsyncUserClient: def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper - async def create_user(self, *, name: str, request_options: typing.Optional[RequestOptions] = None) -> User: + async def create_user( + self, *, name: str, request_options: typing.Optional[RequestOptions] = None + ) -> User: """ Parameters ---------- @@ -96,13 +106,19 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( "user", method="POST", - json={"name": name, "_type": "CreateUserRequest", "_version": "v1"}, + json={ + "name": name, + "_type": "CreateUserRequest", + "_version": "v1", + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(User, parse_obj_as(type_=User, object_=_response.json())) # type: ignore + return typing.cast( + User, parse_obj_as(type_=User, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/extra-properties/src/seed/user/types/user.py b/seed/python-sdk/extra-properties/src/seed/user/types/user.py index af0fd1dde30..0c35ac62615 100644 --- a/seed/python-sdk/extra-properties/src/seed/user/types/user.py +++ b/seed/python-sdk/extra-properties/src/seed/user/types/user.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class User(UniversalBaseModel): name: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/extra-properties/src/seed/version.py b/seed/python-sdk/extra-properties/src/seed/version.py index 93d30be531e..3c4bb2fb34a 100644 --- a/seed/python-sdk/extra-properties/src/seed/version.py +++ b/seed/python-sdk/extra-properties/src/seed/version.py @@ -1,4 +1,3 @@ - from importlib import metadata __version__ = metadata.version("fern_extra-properties") diff --git a/seed/python-sdk/extra-properties/tests/conftest.py b/seed/python-sdk/extra-properties/tests/conftest.py index c5b295e083e..dde34fadab8 100644 --- a/seed/python-sdk/extra-properties/tests/conftest.py +++ b/seed/python-sdk/extra-properties/tests/conftest.py @@ -1,9 +1,9 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExtraProperties import os - import pytest -from seed import AsyncSeedExtraProperties, SeedExtraProperties +from seed import AsyncSeedExtraProperties @pytest.fixture diff --git a/seed/python-sdk/extra-properties/tests/custom/test_client.py b/seed/python-sdk/extra-properties/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/python-sdk/extra-properties/tests/custom/test_client.py +++ b/seed/python-sdk/extra-properties/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/python-sdk/extra-properties/tests/test_user.py b/seed/python-sdk/extra-properties/tests/test_user.py index e5165d17374..beeabde0675 100644 --- a/seed/python-sdk/extra-properties/tests/test_user.py +++ b/seed/python-sdk/extra-properties/tests/test_user.py @@ -1,13 +1,14 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedExtraProperties +from seed import AsyncSeedExtraProperties import typing - -from seed import AsyncSeedExtraProperties, SeedExtraProperties - from .utilities import validate_response -async def test_create_user(client: SeedExtraProperties, async_client: AsyncSeedExtraProperties) -> None: +async def test_create_user( + client: SeedExtraProperties, async_client: AsyncSeedExtraProperties +) -> None: expected_response: typing.Any = {"name": "string"} expected_types: typing.Any = {"name": None} response = client.user.create_user(name="string") diff --git a/seed/python-sdk/extra-properties/tests/utilities.py b/seed/python-sdk/extra-properties/tests/utilities.py index 13da208eb3a..e8f4472564c 100644 --- a/seed/python-sdk/extra-properties/tests/utilities.py +++ b/seed/python-sdk/extra-properties/tests/utilities.py @@ -3,11 +3,14 @@ import typing import uuid -import pydantic from dateutil import parser +import pydantic + -def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> typing.Any: +def cast_field( + json_expectation: typing.Any, type_expectation: typing.Any +) -> typing.Any: # Cast these specific types which come through as string and expect our # models to cast to the correct type. if type_expectation == "uuid": @@ -25,7 +28,9 @@ def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> ty return json_expectation -def validate_field(response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any) -> None: +def validate_field( + response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectation == "no_validate": return @@ -44,7 +49,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(entry_expectation, dict): is_container_of_complex_type = True validate_response( - response=response[idx], json_expectation=ex, type_expectations=entry_expectation + response=response[idx], + json_expectation=ex, + type_expectations=entry_expectation, ) else: cast_json_expectation.append(cast_field(ex, entry_expectation)) @@ -56,7 +63,10 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # if any of the values of the set have a type_expectation of a dict, we're assuming it's a pydantic # model and keeping it a list. if container_expectation != "set" or not any( - map(lambda value: isinstance(value, dict), list(contents_expectation.values())) + map( + lambda value: isinstance(value, dict), + list(contents_expectation.values()), + ) ): json_expectation = cast_field(json_expectation, container_expectation) elif isinstance(type_expectation, tuple): @@ -65,9 +75,15 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(contents_expectation, dict): json_expectation = { cast_field( - key, contents_expectation.get(idx)[0] if contents_expectation.get(idx) is not None else None # type: ignore + key, + contents_expectation.get(idx)[0] + if contents_expectation.get(idx) is not None + else None, # type: ignore ): cast_field( - value, contents_expectation.get(idx)[1] if contents_expectation.get(idx) is not None else None # type: ignore + value, + contents_expectation.get(idx)[1] + if contents_expectation.get(idx) is not None + else None, # type: ignore ) for idx, (key, value) in enumerate(json_expectation.items()) } @@ -86,7 +102,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # Arg type_expectations is a deeply nested structure that matches the response, but with the values replaced with the expected types -def validate_response(response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any) -> None: +def validate_response( + response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectations == "no_validate": return @@ -96,11 +114,17 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e and not isinstance(response, dict) and not issubclass(type(response), pydantic.BaseModel) ): - validate_field(response=response, json_expectation=json_expectation, type_expectation=type_expectations) + validate_field( + response=response, + json_expectation=json_expectation, + type_expectation=type_expectations, + ) return if isinstance(response, list): - assert len(response) == len(json_expectation), "Length mismatch, expected: {0}, Actual: {1}".format( + assert len(response) == len( + json_expectation + ), "Length mismatch, expected: {0}, Actual: {1}".format( len(response), len(json_expectation) ) content_expectation = type_expectations @@ -108,7 +132,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e content_expectation = type_expectations[1] for idx, item in enumerate(response): validate_response( - response=item, json_expectation=json_expectation[idx], type_expectations=content_expectation[idx] + response=item, + json_expectation=json_expectation[idx], + type_expectations=content_expectation[idx], ) else: response_json = response @@ -116,7 +142,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e response_json = response.dict(by_alias=True) for key, value in json_expectation.items(): - assert key in response_json, "Field {0} not found within the response object: {1}".format( + assert ( + key in response_json + ), "Field {0} not found within the response object: {1}".format( key, response_json ) @@ -128,11 +156,19 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e # Otherwise, we're just validating a single field that's a pydantic model. if isinstance(value, dict) and not isinstance(type_expectation, tuple): validate_response( - response=response_json[key], json_expectation=value, type_expectations=type_expectation + response=response_json[key], + json_expectation=value, + type_expectations=type_expectation, ) else: - validate_field(response=response_json[key], json_expectation=value, type_expectation=type_expectation) + validate_field( + response=response_json[key], + json_expectation=value, + type_expectation=type_expectation, + ) # Ensure there are no additional fields here either del response_json[key] - assert len(response_json) == 0, "Additional fields found, expected None: {0}".format(response_json) + assert ( + len(response_json) == 0 + ), "Additional fields found, expected None: {0}".format(response_json) diff --git a/seed/python-sdk/extra-properties/tests/utils/assets/models/__init__.py b/seed/python-sdk/extra-properties/tests/utils/assets/models/__init__.py index 2cf01263529..3a1c852e71e 100644 --- a/seed/python-sdk/extra-properties/tests/utils/assets/models/__init__.py +++ b/seed/python-sdk/extra-properties/tests/utils/assets/models/__init__.py @@ -5,7 +5,7 @@ from .circle import CircleParams from .object_with_defaults import ObjectWithDefaultsParams from .object_with_optional_field import ObjectWithOptionalFieldParams -from .shape import Shape_CircleParams, Shape_SquareParams, ShapeParams +from .shape import ShapeParams, Shape_CircleParams, Shape_SquareParams from .square import SquareParams from .undiscriminated_shape import UndiscriminatedShapeParams diff --git a/seed/python-sdk/extra-properties/tests/utils/assets/models/circle.py b/seed/python-sdk/extra-properties/tests/utils/assets/models/circle.py index af7a1bf8a8e..253f12d38b3 100644 --- a/seed/python-sdk/extra-properties/tests/utils/assets/models/circle.py +++ b/seed/python-sdk/extra-properties/tests/utils/assets/models/circle.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class CircleParams(typing_extensions.TypedDict): - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] diff --git a/seed/python-sdk/extra-properties/tests/utils/assets/models/object_with_optional_field.py b/seed/python-sdk/extra-properties/tests/utils/assets/models/object_with_optional_field.py index 3ad93d5f305..ebe7dc80547 100644 --- a/seed/python-sdk/extra-properties/tests/utils/assets/models/object_with_optional_field.py +++ b/seed/python-sdk/extra-properties/tests/utils/assets/models/object_with_optional_field.py @@ -7,8 +7,8 @@ import uuid import typing_extensions -from seed.core.serialization import FieldMetadata +from seed.core.serialization import FieldMetadata from .color import Color from .shape import ShapeParams from .undiscriminated_shape import UndiscriminatedShapeParams @@ -18,16 +18,30 @@ class ObjectWithOptionalFieldParams(typing_extensions.TypedDict): literal: typing.Literal["lit_one"] string: typing_extensions.NotRequired[str] integer: typing_extensions.NotRequired[int] - long_: typing_extensions.NotRequired[typing_extensions.Annotated[int, FieldMetadata(alias="long")]] + long_: typing_extensions.NotRequired[ + typing_extensions.Annotated[int, FieldMetadata(alias="long")] + ] double: typing_extensions.NotRequired[float] - bool_: typing_extensions.NotRequired[typing_extensions.Annotated[bool, FieldMetadata(alias="bool")]] + bool_: typing_extensions.NotRequired[ + typing_extensions.Annotated[bool, FieldMetadata(alias="bool")] + ] datetime: typing_extensions.NotRequired[dt.datetime] date: typing_extensions.NotRequired[dt.date] - uuid_: typing_extensions.NotRequired[typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")]] - base_64: typing_extensions.NotRequired[typing_extensions.Annotated[str, FieldMetadata(alias="base64")]] - list_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")]] - set_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")]] - map_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")]] + uuid_: typing_extensions.NotRequired[ + typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")] + ] + base_64: typing_extensions.NotRequired[ + typing_extensions.Annotated[str, FieldMetadata(alias="base64")] + ] + list_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")] + ] + set_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")] + ] + map_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")] + ] enum: typing_extensions.NotRequired[Color] union: typing_extensions.NotRequired[ShapeParams] second_union: typing_extensions.NotRequired[ShapeParams] diff --git a/seed/python-sdk/extra-properties/tests/utils/assets/models/shape.py b/seed/python-sdk/extra-properties/tests/utils/assets/models/shape.py index 2c33c877951..816ffc51bdc 100644 --- a/seed/python-sdk/extra-properties/tests/utils/assets/models/shape.py +++ b/seed/python-sdk/extra-properties/tests/utils/assets/models/shape.py @@ -7,6 +7,7 @@ import typing import typing_extensions + from seed.core.serialization import FieldMetadata @@ -15,13 +16,21 @@ class Base(typing_extensions.TypedDict): class Shape_CircleParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["circle"], FieldMetadata(alias="shapeType")] - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["circle"], FieldMetadata(alias="shapeType") + ] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] class Shape_SquareParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["square"], FieldMetadata(alias="shapeType")] - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["square"], FieldMetadata(alias="shapeType") + ] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] ShapeParams = typing.Union[Shape_CircleParams, Shape_SquareParams] diff --git a/seed/python-sdk/extra-properties/tests/utils/assets/models/square.py b/seed/python-sdk/extra-properties/tests/utils/assets/models/square.py index b9b7dd319bc..bcf08a723c5 100644 --- a/seed/python-sdk/extra-properties/tests/utils/assets/models/square.py +++ b/seed/python-sdk/extra-properties/tests/utils/assets/models/square.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class SquareParams(typing_extensions.TypedDict): - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] diff --git a/seed/python-sdk/extra-properties/tests/utils/test_http_client.py b/seed/python-sdk/extra-properties/tests/utils/test_http_client.py index edd11ca7afb..f5a874a75f3 100644 --- a/seed/python-sdk/extra-properties/tests/utils/test_http_client.py +++ b/seed/python-sdk/extra-properties/tests/utils/test_http_client.py @@ -9,12 +9,17 @@ def get_request_options() -> RequestOptions: def test_get_json_request_body() -> None: - json_body, data_body = get_request_body(json={"hello": "world"}, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json={"hello": "world"}, data=None, request_options=None, omit=None + ) assert json_body == {"hello": "world"} assert data_body is None json_body_extras, data_body_extras = get_request_body( - json={"goodbye": "world"}, data=None, request_options=get_request_options(), omit=None + json={"goodbye": "world"}, + data=None, + request_options=get_request_options(), + omit=None, ) assert json_body_extras == {"goodbye": "world", "see you": "later"} @@ -22,12 +27,17 @@ def test_get_json_request_body() -> None: def test_get_files_request_body() -> None: - json_body, data_body = get_request_body(json=None, data={"hello": "world"}, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data={"hello": "world"}, request_options=None, omit=None + ) assert data_body == {"hello": "world"} assert json_body is None json_body_extras, data_body_extras = get_request_body( - json=None, data={"goodbye": "world"}, request_options=get_request_options(), omit=None + json=None, + data={"goodbye": "world"}, + request_options=get_request_options(), + omit=None, ) assert data_body_extras == {"goodbye": "world", "see you": "later"} @@ -35,7 +45,9 @@ def test_get_files_request_body() -> None: def test_get_none_request_body() -> None: - json_body, data_body = get_request_body(json=None, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data=None, request_options=None, omit=None + ) assert data_body is None assert json_body is None diff --git a/seed/python-sdk/extra-properties/tests/utils/test_query_encoding.py b/seed/python-sdk/extra-properties/tests/utils/test_query_encoding.py index 247e1551b46..fbc8f402167 100644 --- a/seed/python-sdk/extra-properties/tests/utils/test_query_encoding.py +++ b/seed/python-sdk/extra-properties/tests/utils/test_query_encoding.py @@ -4,9 +4,15 @@ def test_query_encoding() -> None: - assert encode_query({"hello world": "hello world"}) == {"hello world": "hello world"} - assert encode_query({"hello_world": {"hello": "world"}}) == {"hello_world[hello]": "world"} - assert encode_query({"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"}) == { + assert encode_query({"hello world": "hello world"}) == { + "hello world": "hello world" + } + assert encode_query({"hello_world": {"hello": "world"}}) == { + "hello_world[hello]": "world" + } + assert encode_query( + {"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"} + ) == { "hello_world[hello][world]": "today", "hello_world[test]": "this", "hi": "there", diff --git a/seed/python-sdk/extra-properties/tests/utils/test_serialization.py b/seed/python-sdk/extra-properties/tests/utils/test_serialization.py index 58b1ed66e6d..5ca956916dd 100644 --- a/seed/python-sdk/extra-properties/tests/utils/test_serialization.py +++ b/seed/python-sdk/extra-properties/tests/utils/test_serialization.py @@ -1,10 +1,12 @@ # This file was auto-generated by Fern from our API Definition. -from typing import Any, List +from typing import List, Any -from seed.core.serialization import convert_and_respect_annotation_metadata +from seed.core.serialization import ( + convert_and_respect_annotation_metadata, +) +from .assets.models import ShapeParams, ObjectWithOptionalFieldParams -from .assets.models import ObjectWithOptionalFieldParams, ShapeParams UNION_TEST: ShapeParams = {"radius_measurement": 1.0, "shape_type": "circle", "id": "1"} UNION_TEST_CONVERTED = {"shapeType": "circle", "radiusMeasurement": 1.0, "id": "1"} @@ -18,20 +20,54 @@ def test_convert_and_respect_annotation_metadata() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) - assert converted == {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"} + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) + assert converted == { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + } def test_convert_and_respect_annotation_metadata_in_list() -> None: data: List[ObjectWithOptionalFieldParams] = [ - {"string": "string", "long_": 12345, "bool_": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long_": 67890, "list_": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long_": 12345, + "bool_": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long_": 67890, + "list_": [], + "literal": "lit_one", + "any": "any", + }, ] - converted = convert_and_respect_annotation_metadata(object_=data, annotation=List[ObjectWithOptionalFieldParams]) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=List[ObjectWithOptionalFieldParams] + ) assert converted == [ - {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long": 67890, "list": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long": 67890, + "list": [], + "literal": "lit_one", + "any": "any", + }, ] @@ -43,7 +79,9 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) assert converted == { "string": "string", @@ -55,12 +93,16 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: def test_convert_and_respect_annotation_metadata_in_union() -> None: - converted = convert_and_respect_annotation_metadata(object_=UNION_TEST, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=UNION_TEST, annotation=ShapeParams + ) assert converted == UNION_TEST_CONVERTED def test_convert_and_respect_annotation_metadata_with_empty_object() -> None: data: Any = {} - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ShapeParams + ) assert converted == data diff --git a/seed/python-sdk/file-download/pyproject.toml b/seed/python-sdk/file-download/pyproject.toml index 2f371e9b9a7..125efcc880a 100644 --- a/seed/python-sdk/file-download/pyproject.toml +++ b/seed/python-sdk/file-download/pyproject.toml @@ -43,6 +43,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/python-sdk/file-download/src/seed/client.py b/seed/python-sdk/file-download/src/seed/client.py index 348672d43a3..21802917777 100644 --- a/seed/python-sdk/file-download/src/seed/client.py +++ b/seed/python-sdk/file-download/src/seed/client.py @@ -1,11 +1,11 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from .service.client import AsyncServiceClient, ServiceClient +from .core.client_wrapper import SyncClientWrapper +from .service.client import ServiceClient +from .core.client_wrapper import AsyncClientWrapper +from .service.client import AsyncServiceClient class SeedFileDownload: @@ -41,14 +41,18 @@ def __init__( base_url: str, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.Client] = None + httpx_client: typing.Optional[httpx.Client] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = SyncClientWrapper( base_url=base_url, httpx_client=httpx_client if httpx_client is not None - else httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.Client( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.Client(timeout=_defaulted_timeout), timeout=_defaulted_timeout, @@ -89,14 +93,18 @@ def __init__( base_url: str, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.AsyncClient] = None + httpx_client: typing.Optional[httpx.AsyncClient] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = AsyncClientWrapper( base_url=base_url, httpx_client=httpx_client if httpx_client is not None - else httpx.AsyncClient(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.AsyncClient( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.AsyncClient(timeout=_defaulted_timeout), timeout=_defaulted_timeout, diff --git a/seed/python-sdk/file-download/src/seed/core/api_error.py b/seed/python-sdk/file-download/src/seed/core/api_error.py index 2e9fc5431cd..da734b58068 100644 --- a/seed/python-sdk/file-download/src/seed/core/api_error.py +++ b/seed/python-sdk/file-download/src/seed/core/api_error.py @@ -7,7 +7,9 @@ class ApiError(Exception): status_code: typing.Optional[int] body: typing.Any - def __init__(self, *, status_code: typing.Optional[int] = None, body: typing.Any = None): + def __init__( + self, *, status_code: typing.Optional[int] = None, body: typing.Any = None + ): self.status_code = status_code self.body = body diff --git a/seed/python-sdk/file-download/src/seed/core/client_wrapper.py b/seed/python-sdk/file-download/src/seed/core/client_wrapper.py index cee8e5684af..16cee650929 100644 --- a/seed/python-sdk/file-download/src/seed/core/client_wrapper.py +++ b/seed/python-sdk/file-download/src/seed/core/client_wrapper.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .http_client import AsyncHttpClient, HttpClient +from .http_client import HttpClient +from .http_client import AsyncHttpClient class BaseClientWrapper: @@ -28,7 +27,13 @@ def get_timeout(self) -> typing.Optional[float]: class SyncClientWrapper(BaseClientWrapper): - def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, httpx_client: httpx.Client): + def __init__( + self, + *, + base_url: str, + timeout: typing.Optional[float] = None, + httpx_client: httpx.Client, + ): super().__init__(base_url=base_url, timeout=timeout) self.httpx_client = HttpClient( httpx_client=httpx_client, @@ -39,7 +44,13 @@ def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, htt class AsyncClientWrapper(BaseClientWrapper): - def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, httpx_client: httpx.AsyncClient): + def __init__( + self, + *, + base_url: str, + timeout: typing.Optional[float] = None, + httpx_client: httpx.AsyncClient, + ): super().__init__(base_url=base_url, timeout=timeout) self.httpx_client = AsyncHttpClient( httpx_client=httpx_client, diff --git a/seed/python-sdk/file-download/src/seed/core/datetime_utils.py b/seed/python-sdk/file-download/src/seed/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/python-sdk/file-download/src/seed/core/datetime_utils.py +++ b/seed/python-sdk/file-download/src/seed/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/python-sdk/file-download/src/seed/core/file.py b/seed/python-sdk/file-download/src/seed/core/file.py index cb0d40bbbf3..6e0f92bfcb1 100644 --- a/seed/python-sdk/file-download/src/seed/core/file.py +++ b/seed/python-sdk/file-download/src/seed/core/file.py @@ -13,12 +13,17 @@ # (filename, file (or bytes), content_type) typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str]], # (filename, file (or bytes), content_type, headers) - typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str], typing.Mapping[str, str]], + typing.Tuple[ + typing.Optional[str], + FileContent, + typing.Optional[str], + typing.Mapping[str, str], + ], ] def convert_file_dict_to_httpx_tuples( - d: typing.Dict[str, typing.Union[File, typing.List[File]]] + d: typing.Dict[str, typing.Union[File, typing.List[File]]], ) -> typing.List[typing.Tuple[str, File]]: """ The format we use is a list of tuples, where the first element is the diff --git a/seed/python-sdk/file-download/src/seed/core/http_client.py b/seed/python-sdk/file-download/src/seed/core/http_client.py index 9333d8a7f15..091f71bc185 100644 --- a/seed/python-sdk/file-download/src/seed/core/http_client.py +++ b/seed/python-sdk/file-download/src/seed/core/http_client.py @@ -77,7 +77,9 @@ def _retry_timeout(response: httpx.Response, retries: int) -> float: return retry_after # Apply exponential backoff, capped at MAX_RETRY_DELAY_SECONDS. - retry_delay = min(INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS) + retry_delay = min( + INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS + ) # Add a randomness / jitter to the retry delay to avoid overwhelming the server with retries. timeout = retry_delay * (1 - 0.25 * random()) @@ -90,7 +92,8 @@ def _should_retry(response: httpx.Response) -> bool: def remove_omit_from_dict( - original: typing.Dict[str, typing.Optional[typing.Any]], omit: typing.Optional[typing.Any] + original: typing.Dict[str, typing.Optional[typing.Any]], + omit: typing.Optional[typing.Any], ) -> typing.Dict[str, typing.Any]: if omit is None: return original @@ -108,7 +111,8 @@ def maybe_filter_request_body( ) -> typing.Optional[typing.Any]: if data is None: return ( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else None ) @@ -118,7 +122,8 @@ def maybe_filter_request_body( data_content = { **(jsonable_encoder(remove_omit_from_dict(data, omit))), # type: ignore **( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else {} ), @@ -162,7 +167,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url def request( @@ -174,8 +181,12 @@ def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -184,11 +195,14 @@ def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) response = self.httpx_client.request( method=method, @@ -198,7 +212,11 @@ def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -209,7 +227,10 @@ def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -222,11 +243,15 @@ def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: time.sleep(_retry_timeout(response=response, retries=retries)) @@ -256,8 +281,12 @@ def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -266,11 +295,14 @@ def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) with self.httpx_client.stream( method=method, @@ -280,7 +312,11 @@ def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -291,7 +327,9 @@ def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -304,7 +342,9 @@ def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream @@ -327,7 +367,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url async def request( @@ -339,8 +381,12 @@ async def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -349,11 +395,14 @@ async def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) # Add the input to each of these and do None-safety checks response = await self.httpx_client.request( @@ -364,7 +413,11 @@ async def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -375,7 +428,10 @@ async def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -388,11 +444,15 @@ async def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: await asyncio.sleep(_retry_timeout(response=response, retries=retries)) @@ -421,8 +481,12 @@ async def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -431,11 +495,14 @@ async def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) async with self.httpx_client.stream( method=method, @@ -445,7 +512,11 @@ async def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -456,7 +527,9 @@ async def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -469,7 +542,9 @@ async def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream diff --git a/seed/python-sdk/file-download/src/seed/core/jsonable_encoder.py b/seed/python-sdk/file-download/src/seed/core/jsonable_encoder.py index d3fd328fd41..12a8b52fc22 100644 --- a/seed/python-sdk/file-download/src/seed/core/jsonable_encoder.py +++ b/seed/python-sdk/file-download/src/seed/core/jsonable_encoder.py @@ -19,13 +19,19 @@ import pydantic from .datetime_utils import serialize_datetime -from .pydantic_utilities import IS_PYDANTIC_V2, encode_by_type, to_jsonable_with_fallback +from .pydantic_utilities import ( + IS_PYDANTIC_V2, + encode_by_type, + to_jsonable_with_fallback, +) SetIntStr = Set[Union[int, str]] DictIntStrAny = Dict[Union[int, str], Any] -def jsonable_encoder(obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None) -> Any: +def jsonable_encoder( + obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None +) -> Any: custom_encoder = custom_encoder or {} if custom_encoder: if type(obj) in custom_encoder: diff --git a/seed/python-sdk/file-download/src/seed/core/pydantic_utilities.py b/seed/python-sdk/file-download/src/seed/core/pydantic_utilities.py index 170a563d6eb..c63935c32a2 100644 --- a/seed/python-sdk/file-download/src/seed/core/pydantic_utilities.py +++ b/seed/python-sdk/file-download/src/seed/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) # type: ignore # Pydantic v1 diff --git a/seed/python-sdk/file-download/src/seed/core/query_encoder.py b/seed/python-sdk/file-download/src/seed/core/query_encoder.py index 24076d72ee9..7cb98f52cd7 100644 --- a/seed/python-sdk/file-download/src/seed/core/query_encoder.py +++ b/seed/python-sdk/file-download/src/seed/core/query_encoder.py @@ -7,7 +7,9 @@ # Flattens dicts to be of the form {"key[subkey][subkey2]": value} where value is not a dict -def traverse_query_dict(dict_flat: Dict[str, Any], key_prefix: Optional[str] = None) -> Dict[str, Any]: +def traverse_query_dict( + dict_flat: Dict[str, Any], key_prefix: Optional[str] = None +) -> Dict[str, Any]: result = {} for k, v in dict_flat.items(): key = f"{key_prefix}[{k}]" if key_prefix is not None else k @@ -30,4 +32,8 @@ def single_query_encoder(query_key: str, query_value: Any) -> Dict[str, Any]: def encode_query(query: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: - return dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) if query is not None else None + return ( + dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) + if query is not None + else None + ) diff --git a/seed/python-sdk/file-download/src/seed/core/serialization.py b/seed/python-sdk/file-download/src/seed/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/python-sdk/file-download/src/seed/core/serialization.py +++ b/seed/python-sdk/file-download/src/seed/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/python-sdk/file-download/src/seed/service/client.py b/seed/python-sdk/file-download/src/seed/service/client.py index e06d8f773c1..e174a017955 100644 --- a/seed/python-sdk/file-download/src/seed/service/client.py +++ b/seed/python-sdk/file-download/src/seed/service/client.py @@ -1,18 +1,20 @@ # This file was auto-generated by Fern from our API Definition. +from ..core.client_wrapper import SyncClientWrapper import typing +from ..core.request_options import RequestOptions from json.decoder import JSONDecodeError - from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.request_options import RequestOptions +from ..core.client_wrapper import AsyncClientWrapper class ServiceClient: def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper - def download_file(self, *, request_options: typing.Optional[RequestOptions] = None) -> typing.Iterator[bytes]: + def download_file( + self, *, request_options: typing.Optional[RequestOptions] = None + ) -> typing.Iterator[bytes]: """ Parameters ---------- @@ -32,7 +34,10 @@ def download_file(self, *, request_options: typing.Optional[RequestOptions] = No ) client.service.download_file() """ - with self._client_wrapper.httpx_client.stream(method="POST", request_options=request_options) as _response: + with self._client_wrapper.httpx_client.stream( + method="POST", + request_options=request_options, + ) as _response: try: if 200 <= _response.status_code < 300: for _chunk in _response.iter_bytes(): @@ -80,7 +85,8 @@ async def main() -> None: asyncio.run(main()) """ async with self._client_wrapper.httpx_client.stream( - method="POST", request_options=request_options + method="POST", + request_options=request_options, ) as _response: try: if 200 <= _response.status_code < 300: diff --git a/seed/python-sdk/file-download/src/seed/version.py b/seed/python-sdk/file-download/src/seed/version.py index 310eb4af8a1..70803813645 100644 --- a/seed/python-sdk/file-download/src/seed/version.py +++ b/seed/python-sdk/file-download/src/seed/version.py @@ -1,4 +1,3 @@ - from importlib import metadata __version__ = metadata.version("fern_file-download") diff --git a/seed/python-sdk/file-download/tests/conftest.py b/seed/python-sdk/file-download/tests/conftest.py index e2c92db6b92..c03dd6f2c9e 100644 --- a/seed/python-sdk/file-download/tests/conftest.py +++ b/seed/python-sdk/file-download/tests/conftest.py @@ -1,9 +1,9 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedFileDownload import os - import pytest -from seed import AsyncSeedFileDownload, SeedFileDownload +from seed import AsyncSeedFileDownload @pytest.fixture diff --git a/seed/python-sdk/file-download/tests/custom/test_client.py b/seed/python-sdk/file-download/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/python-sdk/file-download/tests/custom/test_client.py +++ b/seed/python-sdk/file-download/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/python-sdk/file-download/tests/utilities.py b/seed/python-sdk/file-download/tests/utilities.py index 13da208eb3a..e8f4472564c 100644 --- a/seed/python-sdk/file-download/tests/utilities.py +++ b/seed/python-sdk/file-download/tests/utilities.py @@ -3,11 +3,14 @@ import typing import uuid -import pydantic from dateutil import parser +import pydantic + -def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> typing.Any: +def cast_field( + json_expectation: typing.Any, type_expectation: typing.Any +) -> typing.Any: # Cast these specific types which come through as string and expect our # models to cast to the correct type. if type_expectation == "uuid": @@ -25,7 +28,9 @@ def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> ty return json_expectation -def validate_field(response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any) -> None: +def validate_field( + response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectation == "no_validate": return @@ -44,7 +49,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(entry_expectation, dict): is_container_of_complex_type = True validate_response( - response=response[idx], json_expectation=ex, type_expectations=entry_expectation + response=response[idx], + json_expectation=ex, + type_expectations=entry_expectation, ) else: cast_json_expectation.append(cast_field(ex, entry_expectation)) @@ -56,7 +63,10 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # if any of the values of the set have a type_expectation of a dict, we're assuming it's a pydantic # model and keeping it a list. if container_expectation != "set" or not any( - map(lambda value: isinstance(value, dict), list(contents_expectation.values())) + map( + lambda value: isinstance(value, dict), + list(contents_expectation.values()), + ) ): json_expectation = cast_field(json_expectation, container_expectation) elif isinstance(type_expectation, tuple): @@ -65,9 +75,15 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(contents_expectation, dict): json_expectation = { cast_field( - key, contents_expectation.get(idx)[0] if contents_expectation.get(idx) is not None else None # type: ignore + key, + contents_expectation.get(idx)[0] + if contents_expectation.get(idx) is not None + else None, # type: ignore ): cast_field( - value, contents_expectation.get(idx)[1] if contents_expectation.get(idx) is not None else None # type: ignore + value, + contents_expectation.get(idx)[1] + if contents_expectation.get(idx) is not None + else None, # type: ignore ) for idx, (key, value) in enumerate(json_expectation.items()) } @@ -86,7 +102,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # Arg type_expectations is a deeply nested structure that matches the response, but with the values replaced with the expected types -def validate_response(response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any) -> None: +def validate_response( + response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectations == "no_validate": return @@ -96,11 +114,17 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e and not isinstance(response, dict) and not issubclass(type(response), pydantic.BaseModel) ): - validate_field(response=response, json_expectation=json_expectation, type_expectation=type_expectations) + validate_field( + response=response, + json_expectation=json_expectation, + type_expectation=type_expectations, + ) return if isinstance(response, list): - assert len(response) == len(json_expectation), "Length mismatch, expected: {0}, Actual: {1}".format( + assert len(response) == len( + json_expectation + ), "Length mismatch, expected: {0}, Actual: {1}".format( len(response), len(json_expectation) ) content_expectation = type_expectations @@ -108,7 +132,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e content_expectation = type_expectations[1] for idx, item in enumerate(response): validate_response( - response=item, json_expectation=json_expectation[idx], type_expectations=content_expectation[idx] + response=item, + json_expectation=json_expectation[idx], + type_expectations=content_expectation[idx], ) else: response_json = response @@ -116,7 +142,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e response_json = response.dict(by_alias=True) for key, value in json_expectation.items(): - assert key in response_json, "Field {0} not found within the response object: {1}".format( + assert ( + key in response_json + ), "Field {0} not found within the response object: {1}".format( key, response_json ) @@ -128,11 +156,19 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e # Otherwise, we're just validating a single field that's a pydantic model. if isinstance(value, dict) and not isinstance(type_expectation, tuple): validate_response( - response=response_json[key], json_expectation=value, type_expectations=type_expectation + response=response_json[key], + json_expectation=value, + type_expectations=type_expectation, ) else: - validate_field(response=response_json[key], json_expectation=value, type_expectation=type_expectation) + validate_field( + response=response_json[key], + json_expectation=value, + type_expectation=type_expectation, + ) # Ensure there are no additional fields here either del response_json[key] - assert len(response_json) == 0, "Additional fields found, expected None: {0}".format(response_json) + assert ( + len(response_json) == 0 + ), "Additional fields found, expected None: {0}".format(response_json) diff --git a/seed/python-sdk/file-download/tests/utils/assets/models/__init__.py b/seed/python-sdk/file-download/tests/utils/assets/models/__init__.py index 2cf01263529..3a1c852e71e 100644 --- a/seed/python-sdk/file-download/tests/utils/assets/models/__init__.py +++ b/seed/python-sdk/file-download/tests/utils/assets/models/__init__.py @@ -5,7 +5,7 @@ from .circle import CircleParams from .object_with_defaults import ObjectWithDefaultsParams from .object_with_optional_field import ObjectWithOptionalFieldParams -from .shape import Shape_CircleParams, Shape_SquareParams, ShapeParams +from .shape import ShapeParams, Shape_CircleParams, Shape_SquareParams from .square import SquareParams from .undiscriminated_shape import UndiscriminatedShapeParams diff --git a/seed/python-sdk/file-download/tests/utils/assets/models/circle.py b/seed/python-sdk/file-download/tests/utils/assets/models/circle.py index af7a1bf8a8e..253f12d38b3 100644 --- a/seed/python-sdk/file-download/tests/utils/assets/models/circle.py +++ b/seed/python-sdk/file-download/tests/utils/assets/models/circle.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class CircleParams(typing_extensions.TypedDict): - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] diff --git a/seed/python-sdk/file-download/tests/utils/assets/models/object_with_optional_field.py b/seed/python-sdk/file-download/tests/utils/assets/models/object_with_optional_field.py index 3ad93d5f305..ebe7dc80547 100644 --- a/seed/python-sdk/file-download/tests/utils/assets/models/object_with_optional_field.py +++ b/seed/python-sdk/file-download/tests/utils/assets/models/object_with_optional_field.py @@ -7,8 +7,8 @@ import uuid import typing_extensions -from seed.core.serialization import FieldMetadata +from seed.core.serialization import FieldMetadata from .color import Color from .shape import ShapeParams from .undiscriminated_shape import UndiscriminatedShapeParams @@ -18,16 +18,30 @@ class ObjectWithOptionalFieldParams(typing_extensions.TypedDict): literal: typing.Literal["lit_one"] string: typing_extensions.NotRequired[str] integer: typing_extensions.NotRequired[int] - long_: typing_extensions.NotRequired[typing_extensions.Annotated[int, FieldMetadata(alias="long")]] + long_: typing_extensions.NotRequired[ + typing_extensions.Annotated[int, FieldMetadata(alias="long")] + ] double: typing_extensions.NotRequired[float] - bool_: typing_extensions.NotRequired[typing_extensions.Annotated[bool, FieldMetadata(alias="bool")]] + bool_: typing_extensions.NotRequired[ + typing_extensions.Annotated[bool, FieldMetadata(alias="bool")] + ] datetime: typing_extensions.NotRequired[dt.datetime] date: typing_extensions.NotRequired[dt.date] - uuid_: typing_extensions.NotRequired[typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")]] - base_64: typing_extensions.NotRequired[typing_extensions.Annotated[str, FieldMetadata(alias="base64")]] - list_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")]] - set_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")]] - map_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")]] + uuid_: typing_extensions.NotRequired[ + typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")] + ] + base_64: typing_extensions.NotRequired[ + typing_extensions.Annotated[str, FieldMetadata(alias="base64")] + ] + list_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")] + ] + set_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")] + ] + map_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")] + ] enum: typing_extensions.NotRequired[Color] union: typing_extensions.NotRequired[ShapeParams] second_union: typing_extensions.NotRequired[ShapeParams] diff --git a/seed/python-sdk/file-download/tests/utils/assets/models/shape.py b/seed/python-sdk/file-download/tests/utils/assets/models/shape.py index 2c33c877951..816ffc51bdc 100644 --- a/seed/python-sdk/file-download/tests/utils/assets/models/shape.py +++ b/seed/python-sdk/file-download/tests/utils/assets/models/shape.py @@ -7,6 +7,7 @@ import typing import typing_extensions + from seed.core.serialization import FieldMetadata @@ -15,13 +16,21 @@ class Base(typing_extensions.TypedDict): class Shape_CircleParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["circle"], FieldMetadata(alias="shapeType")] - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["circle"], FieldMetadata(alias="shapeType") + ] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] class Shape_SquareParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["square"], FieldMetadata(alias="shapeType")] - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["square"], FieldMetadata(alias="shapeType") + ] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] ShapeParams = typing.Union[Shape_CircleParams, Shape_SquareParams] diff --git a/seed/python-sdk/file-download/tests/utils/assets/models/square.py b/seed/python-sdk/file-download/tests/utils/assets/models/square.py index b9b7dd319bc..bcf08a723c5 100644 --- a/seed/python-sdk/file-download/tests/utils/assets/models/square.py +++ b/seed/python-sdk/file-download/tests/utils/assets/models/square.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class SquareParams(typing_extensions.TypedDict): - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] diff --git a/seed/python-sdk/file-download/tests/utils/test_http_client.py b/seed/python-sdk/file-download/tests/utils/test_http_client.py index edd11ca7afb..f5a874a75f3 100644 --- a/seed/python-sdk/file-download/tests/utils/test_http_client.py +++ b/seed/python-sdk/file-download/tests/utils/test_http_client.py @@ -9,12 +9,17 @@ def get_request_options() -> RequestOptions: def test_get_json_request_body() -> None: - json_body, data_body = get_request_body(json={"hello": "world"}, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json={"hello": "world"}, data=None, request_options=None, omit=None + ) assert json_body == {"hello": "world"} assert data_body is None json_body_extras, data_body_extras = get_request_body( - json={"goodbye": "world"}, data=None, request_options=get_request_options(), omit=None + json={"goodbye": "world"}, + data=None, + request_options=get_request_options(), + omit=None, ) assert json_body_extras == {"goodbye": "world", "see you": "later"} @@ -22,12 +27,17 @@ def test_get_json_request_body() -> None: def test_get_files_request_body() -> None: - json_body, data_body = get_request_body(json=None, data={"hello": "world"}, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data={"hello": "world"}, request_options=None, omit=None + ) assert data_body == {"hello": "world"} assert json_body is None json_body_extras, data_body_extras = get_request_body( - json=None, data={"goodbye": "world"}, request_options=get_request_options(), omit=None + json=None, + data={"goodbye": "world"}, + request_options=get_request_options(), + omit=None, ) assert data_body_extras == {"goodbye": "world", "see you": "later"} @@ -35,7 +45,9 @@ def test_get_files_request_body() -> None: def test_get_none_request_body() -> None: - json_body, data_body = get_request_body(json=None, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data=None, request_options=None, omit=None + ) assert data_body is None assert json_body is None diff --git a/seed/python-sdk/file-download/tests/utils/test_query_encoding.py b/seed/python-sdk/file-download/tests/utils/test_query_encoding.py index 247e1551b46..fbc8f402167 100644 --- a/seed/python-sdk/file-download/tests/utils/test_query_encoding.py +++ b/seed/python-sdk/file-download/tests/utils/test_query_encoding.py @@ -4,9 +4,15 @@ def test_query_encoding() -> None: - assert encode_query({"hello world": "hello world"}) == {"hello world": "hello world"} - assert encode_query({"hello_world": {"hello": "world"}}) == {"hello_world[hello]": "world"} - assert encode_query({"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"}) == { + assert encode_query({"hello world": "hello world"}) == { + "hello world": "hello world" + } + assert encode_query({"hello_world": {"hello": "world"}}) == { + "hello_world[hello]": "world" + } + assert encode_query( + {"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"} + ) == { "hello_world[hello][world]": "today", "hello_world[test]": "this", "hi": "there", diff --git a/seed/python-sdk/file-download/tests/utils/test_serialization.py b/seed/python-sdk/file-download/tests/utils/test_serialization.py index 58b1ed66e6d..5ca956916dd 100644 --- a/seed/python-sdk/file-download/tests/utils/test_serialization.py +++ b/seed/python-sdk/file-download/tests/utils/test_serialization.py @@ -1,10 +1,12 @@ # This file was auto-generated by Fern from our API Definition. -from typing import Any, List +from typing import List, Any -from seed.core.serialization import convert_and_respect_annotation_metadata +from seed.core.serialization import ( + convert_and_respect_annotation_metadata, +) +from .assets.models import ShapeParams, ObjectWithOptionalFieldParams -from .assets.models import ObjectWithOptionalFieldParams, ShapeParams UNION_TEST: ShapeParams = {"radius_measurement": 1.0, "shape_type": "circle", "id": "1"} UNION_TEST_CONVERTED = {"shapeType": "circle", "radiusMeasurement": 1.0, "id": "1"} @@ -18,20 +20,54 @@ def test_convert_and_respect_annotation_metadata() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) - assert converted == {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"} + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) + assert converted == { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + } def test_convert_and_respect_annotation_metadata_in_list() -> None: data: List[ObjectWithOptionalFieldParams] = [ - {"string": "string", "long_": 12345, "bool_": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long_": 67890, "list_": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long_": 12345, + "bool_": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long_": 67890, + "list_": [], + "literal": "lit_one", + "any": "any", + }, ] - converted = convert_and_respect_annotation_metadata(object_=data, annotation=List[ObjectWithOptionalFieldParams]) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=List[ObjectWithOptionalFieldParams] + ) assert converted == [ - {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long": 67890, "list": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long": 67890, + "list": [], + "literal": "lit_one", + "any": "any", + }, ] @@ -43,7 +79,9 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) assert converted == { "string": "string", @@ -55,12 +93,16 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: def test_convert_and_respect_annotation_metadata_in_union() -> None: - converted = convert_and_respect_annotation_metadata(object_=UNION_TEST, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=UNION_TEST, annotation=ShapeParams + ) assert converted == UNION_TEST_CONVERTED def test_convert_and_respect_annotation_metadata_with_empty_object() -> None: data: Any = {} - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ShapeParams + ) assert converted == data diff --git a/seed/python-sdk/file-upload/pyproject.toml b/seed/python-sdk/file-upload/pyproject.toml index 44ce09d302c..58fd9597115 100644 --- a/seed/python-sdk/file-upload/pyproject.toml +++ b/seed/python-sdk/file-upload/pyproject.toml @@ -43,6 +43,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/python-sdk/file-upload/src/seed/__init__.py b/seed/python-sdk/file-upload/src/seed/__init__.py index cafd35eedcd..5ef802e47a9 100644 --- a/seed/python-sdk/file-upload/src/seed/__init__.py +++ b/seed/python-sdk/file-upload/src/seed/__init__.py @@ -5,4 +5,10 @@ from .service import MyObject from .version import __version__ -__all__ = ["AsyncSeedFileUpload", "MyObject", "SeedFileUpload", "__version__", "service"] +__all__ = [ + "AsyncSeedFileUpload", + "MyObject", + "SeedFileUpload", + "__version__", + "service", +] diff --git a/seed/python-sdk/file-upload/src/seed/client.py b/seed/python-sdk/file-upload/src/seed/client.py index 8ee401899e0..2289f05db0d 100644 --- a/seed/python-sdk/file-upload/src/seed/client.py +++ b/seed/python-sdk/file-upload/src/seed/client.py @@ -1,11 +1,11 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from .service.client import AsyncServiceClient, ServiceClient +from .core.client_wrapper import SyncClientWrapper +from .service.client import ServiceClient +from .core.client_wrapper import AsyncClientWrapper +from .service.client import AsyncServiceClient class SeedFileUpload: @@ -41,14 +41,18 @@ def __init__( base_url: str, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.Client] = None + httpx_client: typing.Optional[httpx.Client] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = SyncClientWrapper( base_url=base_url, httpx_client=httpx_client if httpx_client is not None - else httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.Client( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.Client(timeout=_defaulted_timeout), timeout=_defaulted_timeout, @@ -89,14 +93,18 @@ def __init__( base_url: str, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.AsyncClient] = None + httpx_client: typing.Optional[httpx.AsyncClient] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = AsyncClientWrapper( base_url=base_url, httpx_client=httpx_client if httpx_client is not None - else httpx.AsyncClient(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.AsyncClient( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.AsyncClient(timeout=_defaulted_timeout), timeout=_defaulted_timeout, diff --git a/seed/python-sdk/file-upload/src/seed/core/api_error.py b/seed/python-sdk/file-upload/src/seed/core/api_error.py index 2e9fc5431cd..da734b58068 100644 --- a/seed/python-sdk/file-upload/src/seed/core/api_error.py +++ b/seed/python-sdk/file-upload/src/seed/core/api_error.py @@ -7,7 +7,9 @@ class ApiError(Exception): status_code: typing.Optional[int] body: typing.Any - def __init__(self, *, status_code: typing.Optional[int] = None, body: typing.Any = None): + def __init__( + self, *, status_code: typing.Optional[int] = None, body: typing.Any = None + ): self.status_code = status_code self.body = body diff --git a/seed/python-sdk/file-upload/src/seed/core/client_wrapper.py b/seed/python-sdk/file-upload/src/seed/core/client_wrapper.py index dfe35a2131d..968ad6f220b 100644 --- a/seed/python-sdk/file-upload/src/seed/core/client_wrapper.py +++ b/seed/python-sdk/file-upload/src/seed/core/client_wrapper.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .http_client import AsyncHttpClient, HttpClient +from .http_client import HttpClient +from .http_client import AsyncHttpClient class BaseClientWrapper: @@ -28,7 +27,13 @@ def get_timeout(self) -> typing.Optional[float]: class SyncClientWrapper(BaseClientWrapper): - def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, httpx_client: httpx.Client): + def __init__( + self, + *, + base_url: str, + timeout: typing.Optional[float] = None, + httpx_client: httpx.Client, + ): super().__init__(base_url=base_url, timeout=timeout) self.httpx_client = HttpClient( httpx_client=httpx_client, @@ -39,7 +44,13 @@ def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, htt class AsyncClientWrapper(BaseClientWrapper): - def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, httpx_client: httpx.AsyncClient): + def __init__( + self, + *, + base_url: str, + timeout: typing.Optional[float] = None, + httpx_client: httpx.AsyncClient, + ): super().__init__(base_url=base_url, timeout=timeout) self.httpx_client = AsyncHttpClient( httpx_client=httpx_client, diff --git a/seed/python-sdk/file-upload/src/seed/core/datetime_utils.py b/seed/python-sdk/file-upload/src/seed/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/python-sdk/file-upload/src/seed/core/datetime_utils.py +++ b/seed/python-sdk/file-upload/src/seed/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/python-sdk/file-upload/src/seed/core/file.py b/seed/python-sdk/file-upload/src/seed/core/file.py index cb0d40bbbf3..6e0f92bfcb1 100644 --- a/seed/python-sdk/file-upload/src/seed/core/file.py +++ b/seed/python-sdk/file-upload/src/seed/core/file.py @@ -13,12 +13,17 @@ # (filename, file (or bytes), content_type) typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str]], # (filename, file (or bytes), content_type, headers) - typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str], typing.Mapping[str, str]], + typing.Tuple[ + typing.Optional[str], + FileContent, + typing.Optional[str], + typing.Mapping[str, str], + ], ] def convert_file_dict_to_httpx_tuples( - d: typing.Dict[str, typing.Union[File, typing.List[File]]] + d: typing.Dict[str, typing.Union[File, typing.List[File]]], ) -> typing.List[typing.Tuple[str, File]]: """ The format we use is a list of tuples, where the first element is the diff --git a/seed/python-sdk/file-upload/src/seed/core/http_client.py b/seed/python-sdk/file-upload/src/seed/core/http_client.py index 9333d8a7f15..091f71bc185 100644 --- a/seed/python-sdk/file-upload/src/seed/core/http_client.py +++ b/seed/python-sdk/file-upload/src/seed/core/http_client.py @@ -77,7 +77,9 @@ def _retry_timeout(response: httpx.Response, retries: int) -> float: return retry_after # Apply exponential backoff, capped at MAX_RETRY_DELAY_SECONDS. - retry_delay = min(INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS) + retry_delay = min( + INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS + ) # Add a randomness / jitter to the retry delay to avoid overwhelming the server with retries. timeout = retry_delay * (1 - 0.25 * random()) @@ -90,7 +92,8 @@ def _should_retry(response: httpx.Response) -> bool: def remove_omit_from_dict( - original: typing.Dict[str, typing.Optional[typing.Any]], omit: typing.Optional[typing.Any] + original: typing.Dict[str, typing.Optional[typing.Any]], + omit: typing.Optional[typing.Any], ) -> typing.Dict[str, typing.Any]: if omit is None: return original @@ -108,7 +111,8 @@ def maybe_filter_request_body( ) -> typing.Optional[typing.Any]: if data is None: return ( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else None ) @@ -118,7 +122,8 @@ def maybe_filter_request_body( data_content = { **(jsonable_encoder(remove_omit_from_dict(data, omit))), # type: ignore **( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else {} ), @@ -162,7 +167,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url def request( @@ -174,8 +181,12 @@ def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -184,11 +195,14 @@ def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) response = self.httpx_client.request( method=method, @@ -198,7 +212,11 @@ def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -209,7 +227,10 @@ def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -222,11 +243,15 @@ def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: time.sleep(_retry_timeout(response=response, retries=retries)) @@ -256,8 +281,12 @@ def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -266,11 +295,14 @@ def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) with self.httpx_client.stream( method=method, @@ -280,7 +312,11 @@ def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -291,7 +327,9 @@ def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -304,7 +342,9 @@ def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream @@ -327,7 +367,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url async def request( @@ -339,8 +381,12 @@ async def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -349,11 +395,14 @@ async def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) # Add the input to each of these and do None-safety checks response = await self.httpx_client.request( @@ -364,7 +413,11 @@ async def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -375,7 +428,10 @@ async def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -388,11 +444,15 @@ async def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: await asyncio.sleep(_retry_timeout(response=response, retries=retries)) @@ -421,8 +481,12 @@ async def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -431,11 +495,14 @@ async def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) async with self.httpx_client.stream( method=method, @@ -445,7 +512,11 @@ async def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -456,7 +527,9 @@ async def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -469,7 +542,9 @@ async def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream diff --git a/seed/python-sdk/file-upload/src/seed/core/jsonable_encoder.py b/seed/python-sdk/file-upload/src/seed/core/jsonable_encoder.py index d3fd328fd41..12a8b52fc22 100644 --- a/seed/python-sdk/file-upload/src/seed/core/jsonable_encoder.py +++ b/seed/python-sdk/file-upload/src/seed/core/jsonable_encoder.py @@ -19,13 +19,19 @@ import pydantic from .datetime_utils import serialize_datetime -from .pydantic_utilities import IS_PYDANTIC_V2, encode_by_type, to_jsonable_with_fallback +from .pydantic_utilities import ( + IS_PYDANTIC_V2, + encode_by_type, + to_jsonable_with_fallback, +) SetIntStr = Set[Union[int, str]] DictIntStrAny = Dict[Union[int, str], Any] -def jsonable_encoder(obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None) -> Any: +def jsonable_encoder( + obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None +) -> Any: custom_encoder = custom_encoder or {} if custom_encoder: if type(obj) in custom_encoder: diff --git a/seed/python-sdk/file-upload/src/seed/core/pydantic_utilities.py b/seed/python-sdk/file-upload/src/seed/core/pydantic_utilities.py index 170a563d6eb..c63935c32a2 100644 --- a/seed/python-sdk/file-upload/src/seed/core/pydantic_utilities.py +++ b/seed/python-sdk/file-upload/src/seed/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) # type: ignore # Pydantic v1 diff --git a/seed/python-sdk/file-upload/src/seed/core/query_encoder.py b/seed/python-sdk/file-upload/src/seed/core/query_encoder.py index 24076d72ee9..7cb98f52cd7 100644 --- a/seed/python-sdk/file-upload/src/seed/core/query_encoder.py +++ b/seed/python-sdk/file-upload/src/seed/core/query_encoder.py @@ -7,7 +7,9 @@ # Flattens dicts to be of the form {"key[subkey][subkey2]": value} where value is not a dict -def traverse_query_dict(dict_flat: Dict[str, Any], key_prefix: Optional[str] = None) -> Dict[str, Any]: +def traverse_query_dict( + dict_flat: Dict[str, Any], key_prefix: Optional[str] = None +) -> Dict[str, Any]: result = {} for k, v in dict_flat.items(): key = f"{key_prefix}[{k}]" if key_prefix is not None else k @@ -30,4 +32,8 @@ def single_query_encoder(query_key: str, query_value: Any) -> Dict[str, Any]: def encode_query(query: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: - return dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) if query is not None else None + return ( + dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) + if query is not None + else None + ) diff --git a/seed/python-sdk/file-upload/src/seed/core/serialization.py b/seed/python-sdk/file-upload/src/seed/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/python-sdk/file-upload/src/seed/core/serialization.py +++ b/seed/python-sdk/file-upload/src/seed/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/python-sdk/file-upload/src/seed/service/client.py b/seed/python-sdk/file-upload/src/seed/service/client.py index 9508b8f0b5d..884b0e842a4 100644 --- a/seed/python-sdk/file-upload/src/seed/service/client.py +++ b/seed/python-sdk/file-upload/src/seed/service/client.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. import typing -from json.decoder import JSONDecodeError - +from ..core.client_wrapper import SyncClientWrapper from .. import core -from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.request_options import RequestOptions from .types.my_object import MyObject +from ..core.request_options import RequestOptions +from json.decoder import JSONDecodeError +from ..core.api_error import ApiError +from ..core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -29,7 +29,7 @@ def post( maybe_file_list: typing.Optional[typing.List[core.File]] = None, maybe_integer: typing.Optional[int] = None, optional_list_of_strings: typing.Optional[typing.List[str]] = None, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ Parameters @@ -81,7 +81,12 @@ def post( "optionalListOfStrings": optional_list_of_strings, "listOfObjects": list_of_objects, }, - files={"file": file, "fileList": file_list, "maybeFile": maybe_file, "maybeFileList": maybe_file_list}, + files={ + "file": file, + "fileList": file_list, + "maybeFile": maybe_file, + "maybeFileList": maybe_file_list, + }, request_options=request_options, omit=OMIT, ) @@ -93,7 +98,12 @@ def post( raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def just_file(self, *, file: core.File, request_options: typing.Optional[RequestOptions] = None) -> None: + def just_file( + self, + *, + file: core.File, + request_options: typing.Optional[RequestOptions] = None, + ) -> None: """ Parameters ---------- @@ -117,7 +127,14 @@ def just_file(self, *, file: core.File, request_options: typing.Optional[Request client.service.just_file() """ _response = self._client_wrapper.httpx_client.request( - "just-file", method="POST", data={}, files={"file": file}, request_options=request_options, omit=OMIT + "just-file", + method="POST", + data={}, + files={ + "file": file, + }, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: @@ -135,8 +152,10 @@ def just_file_with_query_params( file: core.File, maybe_string: typing.Optional[str] = None, maybe_integer: typing.Optional[int] = None, - optional_list_of_strings: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None, - request_options: typing.Optional[RequestOptions] = None + optional_list_of_strings: typing.Optional[ + typing.Union[str, typing.Sequence[str]] + ] = None, + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ Parameters @@ -187,7 +206,9 @@ def just_file_with_query_params( "optionalListOfStrings": optional_list_of_strings, }, data={}, - files={"file": file}, + files={ + "file": file, + }, request_options=request_options, omit=OMIT, ) @@ -216,7 +237,7 @@ async def post( maybe_file_list: typing.Optional[typing.List[core.File]] = None, maybe_integer: typing.Optional[int] = None, optional_list_of_strings: typing.Optional[typing.List[str]] = None, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ Parameters @@ -276,7 +297,12 @@ async def main() -> None: "optionalListOfStrings": optional_list_of_strings, "listOfObjects": list_of_objects, }, - files={"file": file, "fileList": file_list, "maybeFile": maybe_file, "maybeFileList": maybe_file_list}, + files={ + "file": file, + "fileList": file_list, + "maybeFile": maybe_file, + "maybeFileList": maybe_file_list, + }, request_options=request_options, omit=OMIT, ) @@ -288,7 +314,12 @@ async def main() -> None: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - async def just_file(self, *, file: core.File, request_options: typing.Optional[RequestOptions] = None) -> None: + async def just_file( + self, + *, + file: core.File, + request_options: typing.Optional[RequestOptions] = None, + ) -> None: """ Parameters ---------- @@ -320,7 +351,14 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "just-file", method="POST", data={}, files={"file": file}, request_options=request_options, omit=OMIT + "just-file", + method="POST", + data={}, + files={ + "file": file, + }, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: @@ -338,8 +376,10 @@ async def just_file_with_query_params( file: core.File, maybe_string: typing.Optional[str] = None, maybe_integer: typing.Optional[int] = None, - optional_list_of_strings: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None, - request_options: typing.Optional[RequestOptions] = None + optional_list_of_strings: typing.Optional[ + typing.Union[str, typing.Sequence[str]] + ] = None, + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ Parameters @@ -398,7 +438,9 @@ async def main() -> None: "optionalListOfStrings": optional_list_of_strings, }, data={}, - files={"file": file}, + files={ + "file": file, + }, request_options=request_options, omit=OMIT, ) diff --git a/seed/python-sdk/file-upload/src/seed/service/types/my_object.py b/seed/python-sdk/file-upload/src/seed/service/types/my_object.py index e2c98c9c2bc..223c8f2150f 100644 --- a/seed/python-sdk/file-upload/src/seed/service/types/my_object.py +++ b/seed/python-sdk/file-upload/src/seed/service/types/my_object.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class MyObject(UniversalBaseModel): foo: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/file-upload/src/seed/version.py b/seed/python-sdk/file-upload/src/seed/version.py index b4889681d9e..ff701e22ec6 100644 --- a/seed/python-sdk/file-upload/src/seed/version.py +++ b/seed/python-sdk/file-upload/src/seed/version.py @@ -1,4 +1,3 @@ - from importlib import metadata __version__ = metadata.version("fern_file-upload") diff --git a/seed/python-sdk/file-upload/tests/conftest.py b/seed/python-sdk/file-upload/tests/conftest.py index 5483dbd9529..d20a60e52bd 100644 --- a/seed/python-sdk/file-upload/tests/conftest.py +++ b/seed/python-sdk/file-upload/tests/conftest.py @@ -1,9 +1,9 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedFileUpload import os - import pytest -from seed import AsyncSeedFileUpload, SeedFileUpload +from seed import AsyncSeedFileUpload @pytest.fixture diff --git a/seed/python-sdk/file-upload/tests/custom/test_client.py b/seed/python-sdk/file-upload/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/python-sdk/file-upload/tests/custom/test_client.py +++ b/seed/python-sdk/file-upload/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/python-sdk/file-upload/tests/utilities.py b/seed/python-sdk/file-upload/tests/utilities.py index 13da208eb3a..e8f4472564c 100644 --- a/seed/python-sdk/file-upload/tests/utilities.py +++ b/seed/python-sdk/file-upload/tests/utilities.py @@ -3,11 +3,14 @@ import typing import uuid -import pydantic from dateutil import parser +import pydantic + -def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> typing.Any: +def cast_field( + json_expectation: typing.Any, type_expectation: typing.Any +) -> typing.Any: # Cast these specific types which come through as string and expect our # models to cast to the correct type. if type_expectation == "uuid": @@ -25,7 +28,9 @@ def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> ty return json_expectation -def validate_field(response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any) -> None: +def validate_field( + response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectation == "no_validate": return @@ -44,7 +49,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(entry_expectation, dict): is_container_of_complex_type = True validate_response( - response=response[idx], json_expectation=ex, type_expectations=entry_expectation + response=response[idx], + json_expectation=ex, + type_expectations=entry_expectation, ) else: cast_json_expectation.append(cast_field(ex, entry_expectation)) @@ -56,7 +63,10 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # if any of the values of the set have a type_expectation of a dict, we're assuming it's a pydantic # model and keeping it a list. if container_expectation != "set" or not any( - map(lambda value: isinstance(value, dict), list(contents_expectation.values())) + map( + lambda value: isinstance(value, dict), + list(contents_expectation.values()), + ) ): json_expectation = cast_field(json_expectation, container_expectation) elif isinstance(type_expectation, tuple): @@ -65,9 +75,15 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(contents_expectation, dict): json_expectation = { cast_field( - key, contents_expectation.get(idx)[0] if contents_expectation.get(idx) is not None else None # type: ignore + key, + contents_expectation.get(idx)[0] + if contents_expectation.get(idx) is not None + else None, # type: ignore ): cast_field( - value, contents_expectation.get(idx)[1] if contents_expectation.get(idx) is not None else None # type: ignore + value, + contents_expectation.get(idx)[1] + if contents_expectation.get(idx) is not None + else None, # type: ignore ) for idx, (key, value) in enumerate(json_expectation.items()) } @@ -86,7 +102,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # Arg type_expectations is a deeply nested structure that matches the response, but with the values replaced with the expected types -def validate_response(response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any) -> None: +def validate_response( + response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectations == "no_validate": return @@ -96,11 +114,17 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e and not isinstance(response, dict) and not issubclass(type(response), pydantic.BaseModel) ): - validate_field(response=response, json_expectation=json_expectation, type_expectation=type_expectations) + validate_field( + response=response, + json_expectation=json_expectation, + type_expectation=type_expectations, + ) return if isinstance(response, list): - assert len(response) == len(json_expectation), "Length mismatch, expected: {0}, Actual: {1}".format( + assert len(response) == len( + json_expectation + ), "Length mismatch, expected: {0}, Actual: {1}".format( len(response), len(json_expectation) ) content_expectation = type_expectations @@ -108,7 +132,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e content_expectation = type_expectations[1] for idx, item in enumerate(response): validate_response( - response=item, json_expectation=json_expectation[idx], type_expectations=content_expectation[idx] + response=item, + json_expectation=json_expectation[idx], + type_expectations=content_expectation[idx], ) else: response_json = response @@ -116,7 +142,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e response_json = response.dict(by_alias=True) for key, value in json_expectation.items(): - assert key in response_json, "Field {0} not found within the response object: {1}".format( + assert ( + key in response_json + ), "Field {0} not found within the response object: {1}".format( key, response_json ) @@ -128,11 +156,19 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e # Otherwise, we're just validating a single field that's a pydantic model. if isinstance(value, dict) and not isinstance(type_expectation, tuple): validate_response( - response=response_json[key], json_expectation=value, type_expectations=type_expectation + response=response_json[key], + json_expectation=value, + type_expectations=type_expectation, ) else: - validate_field(response=response_json[key], json_expectation=value, type_expectation=type_expectation) + validate_field( + response=response_json[key], + json_expectation=value, + type_expectation=type_expectation, + ) # Ensure there are no additional fields here either del response_json[key] - assert len(response_json) == 0, "Additional fields found, expected None: {0}".format(response_json) + assert ( + len(response_json) == 0 + ), "Additional fields found, expected None: {0}".format(response_json) diff --git a/seed/python-sdk/file-upload/tests/utils/assets/models/__init__.py b/seed/python-sdk/file-upload/tests/utils/assets/models/__init__.py index 2cf01263529..3a1c852e71e 100644 --- a/seed/python-sdk/file-upload/tests/utils/assets/models/__init__.py +++ b/seed/python-sdk/file-upload/tests/utils/assets/models/__init__.py @@ -5,7 +5,7 @@ from .circle import CircleParams from .object_with_defaults import ObjectWithDefaultsParams from .object_with_optional_field import ObjectWithOptionalFieldParams -from .shape import Shape_CircleParams, Shape_SquareParams, ShapeParams +from .shape import ShapeParams, Shape_CircleParams, Shape_SquareParams from .square import SquareParams from .undiscriminated_shape import UndiscriminatedShapeParams diff --git a/seed/python-sdk/file-upload/tests/utils/assets/models/circle.py b/seed/python-sdk/file-upload/tests/utils/assets/models/circle.py index af7a1bf8a8e..253f12d38b3 100644 --- a/seed/python-sdk/file-upload/tests/utils/assets/models/circle.py +++ b/seed/python-sdk/file-upload/tests/utils/assets/models/circle.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class CircleParams(typing_extensions.TypedDict): - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] diff --git a/seed/python-sdk/file-upload/tests/utils/assets/models/object_with_optional_field.py b/seed/python-sdk/file-upload/tests/utils/assets/models/object_with_optional_field.py index 3ad93d5f305..ebe7dc80547 100644 --- a/seed/python-sdk/file-upload/tests/utils/assets/models/object_with_optional_field.py +++ b/seed/python-sdk/file-upload/tests/utils/assets/models/object_with_optional_field.py @@ -7,8 +7,8 @@ import uuid import typing_extensions -from seed.core.serialization import FieldMetadata +from seed.core.serialization import FieldMetadata from .color import Color from .shape import ShapeParams from .undiscriminated_shape import UndiscriminatedShapeParams @@ -18,16 +18,30 @@ class ObjectWithOptionalFieldParams(typing_extensions.TypedDict): literal: typing.Literal["lit_one"] string: typing_extensions.NotRequired[str] integer: typing_extensions.NotRequired[int] - long_: typing_extensions.NotRequired[typing_extensions.Annotated[int, FieldMetadata(alias="long")]] + long_: typing_extensions.NotRequired[ + typing_extensions.Annotated[int, FieldMetadata(alias="long")] + ] double: typing_extensions.NotRequired[float] - bool_: typing_extensions.NotRequired[typing_extensions.Annotated[bool, FieldMetadata(alias="bool")]] + bool_: typing_extensions.NotRequired[ + typing_extensions.Annotated[bool, FieldMetadata(alias="bool")] + ] datetime: typing_extensions.NotRequired[dt.datetime] date: typing_extensions.NotRequired[dt.date] - uuid_: typing_extensions.NotRequired[typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")]] - base_64: typing_extensions.NotRequired[typing_extensions.Annotated[str, FieldMetadata(alias="base64")]] - list_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")]] - set_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")]] - map_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")]] + uuid_: typing_extensions.NotRequired[ + typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")] + ] + base_64: typing_extensions.NotRequired[ + typing_extensions.Annotated[str, FieldMetadata(alias="base64")] + ] + list_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")] + ] + set_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")] + ] + map_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")] + ] enum: typing_extensions.NotRequired[Color] union: typing_extensions.NotRequired[ShapeParams] second_union: typing_extensions.NotRequired[ShapeParams] diff --git a/seed/python-sdk/file-upload/tests/utils/assets/models/shape.py b/seed/python-sdk/file-upload/tests/utils/assets/models/shape.py index 2c33c877951..816ffc51bdc 100644 --- a/seed/python-sdk/file-upload/tests/utils/assets/models/shape.py +++ b/seed/python-sdk/file-upload/tests/utils/assets/models/shape.py @@ -7,6 +7,7 @@ import typing import typing_extensions + from seed.core.serialization import FieldMetadata @@ -15,13 +16,21 @@ class Base(typing_extensions.TypedDict): class Shape_CircleParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["circle"], FieldMetadata(alias="shapeType")] - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["circle"], FieldMetadata(alias="shapeType") + ] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] class Shape_SquareParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["square"], FieldMetadata(alias="shapeType")] - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["square"], FieldMetadata(alias="shapeType") + ] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] ShapeParams = typing.Union[Shape_CircleParams, Shape_SquareParams] diff --git a/seed/python-sdk/file-upload/tests/utils/assets/models/square.py b/seed/python-sdk/file-upload/tests/utils/assets/models/square.py index b9b7dd319bc..bcf08a723c5 100644 --- a/seed/python-sdk/file-upload/tests/utils/assets/models/square.py +++ b/seed/python-sdk/file-upload/tests/utils/assets/models/square.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class SquareParams(typing_extensions.TypedDict): - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] diff --git a/seed/python-sdk/file-upload/tests/utils/test_http_client.py b/seed/python-sdk/file-upload/tests/utils/test_http_client.py index edd11ca7afb..f5a874a75f3 100644 --- a/seed/python-sdk/file-upload/tests/utils/test_http_client.py +++ b/seed/python-sdk/file-upload/tests/utils/test_http_client.py @@ -9,12 +9,17 @@ def get_request_options() -> RequestOptions: def test_get_json_request_body() -> None: - json_body, data_body = get_request_body(json={"hello": "world"}, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json={"hello": "world"}, data=None, request_options=None, omit=None + ) assert json_body == {"hello": "world"} assert data_body is None json_body_extras, data_body_extras = get_request_body( - json={"goodbye": "world"}, data=None, request_options=get_request_options(), omit=None + json={"goodbye": "world"}, + data=None, + request_options=get_request_options(), + omit=None, ) assert json_body_extras == {"goodbye": "world", "see you": "later"} @@ -22,12 +27,17 @@ def test_get_json_request_body() -> None: def test_get_files_request_body() -> None: - json_body, data_body = get_request_body(json=None, data={"hello": "world"}, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data={"hello": "world"}, request_options=None, omit=None + ) assert data_body == {"hello": "world"} assert json_body is None json_body_extras, data_body_extras = get_request_body( - json=None, data={"goodbye": "world"}, request_options=get_request_options(), omit=None + json=None, + data={"goodbye": "world"}, + request_options=get_request_options(), + omit=None, ) assert data_body_extras == {"goodbye": "world", "see you": "later"} @@ -35,7 +45,9 @@ def test_get_files_request_body() -> None: def test_get_none_request_body() -> None: - json_body, data_body = get_request_body(json=None, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data=None, request_options=None, omit=None + ) assert data_body is None assert json_body is None diff --git a/seed/python-sdk/file-upload/tests/utils/test_query_encoding.py b/seed/python-sdk/file-upload/tests/utils/test_query_encoding.py index 247e1551b46..fbc8f402167 100644 --- a/seed/python-sdk/file-upload/tests/utils/test_query_encoding.py +++ b/seed/python-sdk/file-upload/tests/utils/test_query_encoding.py @@ -4,9 +4,15 @@ def test_query_encoding() -> None: - assert encode_query({"hello world": "hello world"}) == {"hello world": "hello world"} - assert encode_query({"hello_world": {"hello": "world"}}) == {"hello_world[hello]": "world"} - assert encode_query({"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"}) == { + assert encode_query({"hello world": "hello world"}) == { + "hello world": "hello world" + } + assert encode_query({"hello_world": {"hello": "world"}}) == { + "hello_world[hello]": "world" + } + assert encode_query( + {"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"} + ) == { "hello_world[hello][world]": "today", "hello_world[test]": "this", "hi": "there", diff --git a/seed/python-sdk/file-upload/tests/utils/test_serialization.py b/seed/python-sdk/file-upload/tests/utils/test_serialization.py index 58b1ed66e6d..5ca956916dd 100644 --- a/seed/python-sdk/file-upload/tests/utils/test_serialization.py +++ b/seed/python-sdk/file-upload/tests/utils/test_serialization.py @@ -1,10 +1,12 @@ # This file was auto-generated by Fern from our API Definition. -from typing import Any, List +from typing import List, Any -from seed.core.serialization import convert_and_respect_annotation_metadata +from seed.core.serialization import ( + convert_and_respect_annotation_metadata, +) +from .assets.models import ShapeParams, ObjectWithOptionalFieldParams -from .assets.models import ObjectWithOptionalFieldParams, ShapeParams UNION_TEST: ShapeParams = {"radius_measurement": 1.0, "shape_type": "circle", "id": "1"} UNION_TEST_CONVERTED = {"shapeType": "circle", "radiusMeasurement": 1.0, "id": "1"} @@ -18,20 +20,54 @@ def test_convert_and_respect_annotation_metadata() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) - assert converted == {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"} + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) + assert converted == { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + } def test_convert_and_respect_annotation_metadata_in_list() -> None: data: List[ObjectWithOptionalFieldParams] = [ - {"string": "string", "long_": 12345, "bool_": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long_": 67890, "list_": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long_": 12345, + "bool_": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long_": 67890, + "list_": [], + "literal": "lit_one", + "any": "any", + }, ] - converted = convert_and_respect_annotation_metadata(object_=data, annotation=List[ObjectWithOptionalFieldParams]) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=List[ObjectWithOptionalFieldParams] + ) assert converted == [ - {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long": 67890, "list": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long": 67890, + "list": [], + "literal": "lit_one", + "any": "any", + }, ] @@ -43,7 +79,9 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) assert converted == { "string": "string", @@ -55,12 +93,16 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: def test_convert_and_respect_annotation_metadata_in_union() -> None: - converted = convert_and_respect_annotation_metadata(object_=UNION_TEST, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=UNION_TEST, annotation=ShapeParams + ) assert converted == UNION_TEST_CONVERTED def test_convert_and_respect_annotation_metadata_with_empty_object() -> None: data: Any = {} - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ShapeParams + ) assert converted == data diff --git a/seed/python-sdk/folders/pyproject.toml b/seed/python-sdk/folders/pyproject.toml index 417da702780..bf5efffa6db 100644 --- a/seed/python-sdk/folders/pyproject.toml +++ b/seed/python-sdk/folders/pyproject.toml @@ -43,6 +43,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/python-sdk/folders/src/seed/a/b/client.py b/seed/python-sdk/folders/src/seed/a/b/client.py index d18d03352f6..b27c9e43def 100644 --- a/seed/python-sdk/folders/src/seed/a/b/client.py +++ b/seed/python-sdk/folders/src/seed/a/b/client.py @@ -1,11 +1,11 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.client_wrapper import SyncClientWrapper import typing +from ...core.request_options import RequestOptions from json.decoder import JSONDecodeError - from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ...core.request_options import RequestOptions +from ...core.client_wrapper import AsyncClientWrapper class BClient: @@ -32,7 +32,10 @@ def foo(self, *, request_options: typing.Optional[RequestOptions] = None) -> Non ) client.a.b.foo() """ - _response = self._client_wrapper.httpx_client.request(method="POST", request_options=request_options) + _response = self._client_wrapper.httpx_client.request( + method="POST", + request_options=request_options, + ) try: if 200 <= _response.status_code < 300: return @@ -46,7 +49,9 @@ class AsyncBClient: def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper - async def foo(self, *, request_options: typing.Optional[RequestOptions] = None) -> None: + async def foo( + self, *, request_options: typing.Optional[RequestOptions] = None + ) -> None: """ Parameters ---------- @@ -74,7 +79,10 @@ async def main() -> None: asyncio.run(main()) """ - _response = await self._client_wrapper.httpx_client.request(method="POST", request_options=request_options) + _response = await self._client_wrapper.httpx_client.request( + method="POST", + request_options=request_options, + ) try: if 200 <= _response.status_code < 300: return diff --git a/seed/python-sdk/folders/src/seed/a/c/client.py b/seed/python-sdk/folders/src/seed/a/c/client.py index ad15cc1ba08..9de73c7aa2f 100644 --- a/seed/python-sdk/folders/src/seed/a/c/client.py +++ b/seed/python-sdk/folders/src/seed/a/c/client.py @@ -1,11 +1,11 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.client_wrapper import SyncClientWrapper import typing +from ...core.request_options import RequestOptions from json.decoder import JSONDecodeError - from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ...core.request_options import RequestOptions +from ...core.client_wrapper import AsyncClientWrapper class CClient: @@ -32,7 +32,10 @@ def foo(self, *, request_options: typing.Optional[RequestOptions] = None) -> Non ) client.a.c.foo() """ - _response = self._client_wrapper.httpx_client.request(method="POST", request_options=request_options) + _response = self._client_wrapper.httpx_client.request( + method="POST", + request_options=request_options, + ) try: if 200 <= _response.status_code < 300: return @@ -46,7 +49,9 @@ class AsyncCClient: def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper - async def foo(self, *, request_options: typing.Optional[RequestOptions] = None) -> None: + async def foo( + self, *, request_options: typing.Optional[RequestOptions] = None + ) -> None: """ Parameters ---------- @@ -74,7 +79,10 @@ async def main() -> None: asyncio.run(main()) """ - _response = await self._client_wrapper.httpx_client.request(method="POST", request_options=request_options) + _response = await self._client_wrapper.httpx_client.request( + method="POST", + request_options=request_options, + ) try: if 200 <= _response.status_code < 300: return diff --git a/seed/python-sdk/folders/src/seed/a/client.py b/seed/python-sdk/folders/src/seed/a/client.py index 5b394957350..9d972dc2796 100644 --- a/seed/python-sdk/folders/src/seed/a/client.py +++ b/seed/python-sdk/folders/src/seed/a/client.py @@ -1,8 +1,11 @@ # This file was auto-generated by Fern from our API Definition. -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from .b.client import AsyncBClient, BClient -from .c.client import AsyncCClient, CClient +from ..core.client_wrapper import SyncClientWrapper +from .b.client import BClient +from .c.client import CClient +from ..core.client_wrapper import AsyncClientWrapper +from .b.client import AsyncBClient +from .c.client import AsyncCClient class AClient: diff --git a/seed/python-sdk/folders/src/seed/client.py b/seed/python-sdk/folders/src/seed/client.py index c8e70adc909..a302b3f38b3 100644 --- a/seed/python-sdk/folders/src/seed/client.py +++ b/seed/python-sdk/folders/src/seed/client.py @@ -1,15 +1,16 @@ # This file was auto-generated by Fern from our API Definition. import typing -from json.decoder import JSONDecodeError - import httpx - -from .a.client import AClient, AsyncAClient -from .core.api_error import ApiError -from .core.client_wrapper import AsyncClientWrapper, SyncClientWrapper +from .core.client_wrapper import SyncClientWrapper +from .a.client import AClient +from .folder.client import FolderClient from .core.request_options import RequestOptions -from .folder.client import AsyncFolderClient, FolderClient +from json.decoder import JSONDecodeError +from .core.api_error import ApiError +from .core.client_wrapper import AsyncClientWrapper +from .a.client import AsyncAClient +from .folder.client import AsyncFolderClient class SeedApi: @@ -45,14 +46,18 @@ def __init__( base_url: str, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.Client] = None + httpx_client: typing.Optional[httpx.Client] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = SyncClientWrapper( base_url=base_url, httpx_client=httpx_client if httpx_client is not None - else httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.Client( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.Client(timeout=_defaulted_timeout), timeout=_defaulted_timeout, @@ -80,7 +85,10 @@ def foo(self, *, request_options: typing.Optional[RequestOptions] = None) -> Non ) client.foo() """ - _response = self._client_wrapper.httpx_client.request(method="POST", request_options=request_options) + _response = self._client_wrapper.httpx_client.request( + method="POST", + request_options=request_options, + ) try: if 200 <= _response.status_code < 300: return @@ -123,14 +131,18 @@ def __init__( base_url: str, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.AsyncClient] = None + httpx_client: typing.Optional[httpx.AsyncClient] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = AsyncClientWrapper( base_url=base_url, httpx_client=httpx_client if httpx_client is not None - else httpx.AsyncClient(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.AsyncClient( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.AsyncClient(timeout=_defaulted_timeout), timeout=_defaulted_timeout, @@ -138,7 +150,9 @@ def __init__( self.a = AsyncAClient(client_wrapper=self._client_wrapper) self.folder = AsyncFolderClient(client_wrapper=self._client_wrapper) - async def foo(self, *, request_options: typing.Optional[RequestOptions] = None) -> None: + async def foo( + self, *, request_options: typing.Optional[RequestOptions] = None + ) -> None: """ Parameters ---------- @@ -166,7 +180,10 @@ async def main() -> None: asyncio.run(main()) """ - _response = await self._client_wrapper.httpx_client.request(method="POST", request_options=request_options) + _response = await self._client_wrapper.httpx_client.request( + method="POST", + request_options=request_options, + ) try: if 200 <= _response.status_code < 300: return diff --git a/seed/python-sdk/folders/src/seed/core/api_error.py b/seed/python-sdk/folders/src/seed/core/api_error.py index 2e9fc5431cd..da734b58068 100644 --- a/seed/python-sdk/folders/src/seed/core/api_error.py +++ b/seed/python-sdk/folders/src/seed/core/api_error.py @@ -7,7 +7,9 @@ class ApiError(Exception): status_code: typing.Optional[int] body: typing.Any - def __init__(self, *, status_code: typing.Optional[int] = None, body: typing.Any = None): + def __init__( + self, *, status_code: typing.Optional[int] = None, body: typing.Any = None + ): self.status_code = status_code self.body = body diff --git a/seed/python-sdk/folders/src/seed/core/client_wrapper.py b/seed/python-sdk/folders/src/seed/core/client_wrapper.py index 71f786114c6..798e4a2c311 100644 --- a/seed/python-sdk/folders/src/seed/core/client_wrapper.py +++ b/seed/python-sdk/folders/src/seed/core/client_wrapper.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .http_client import AsyncHttpClient, HttpClient +from .http_client import HttpClient +from .http_client import AsyncHttpClient class BaseClientWrapper: @@ -28,7 +27,13 @@ def get_timeout(self) -> typing.Optional[float]: class SyncClientWrapper(BaseClientWrapper): - def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, httpx_client: httpx.Client): + def __init__( + self, + *, + base_url: str, + timeout: typing.Optional[float] = None, + httpx_client: httpx.Client, + ): super().__init__(base_url=base_url, timeout=timeout) self.httpx_client = HttpClient( httpx_client=httpx_client, @@ -39,7 +44,13 @@ def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, htt class AsyncClientWrapper(BaseClientWrapper): - def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, httpx_client: httpx.AsyncClient): + def __init__( + self, + *, + base_url: str, + timeout: typing.Optional[float] = None, + httpx_client: httpx.AsyncClient, + ): super().__init__(base_url=base_url, timeout=timeout) self.httpx_client = AsyncHttpClient( httpx_client=httpx_client, diff --git a/seed/python-sdk/folders/src/seed/core/datetime_utils.py b/seed/python-sdk/folders/src/seed/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/python-sdk/folders/src/seed/core/datetime_utils.py +++ b/seed/python-sdk/folders/src/seed/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/python-sdk/folders/src/seed/core/file.py b/seed/python-sdk/folders/src/seed/core/file.py index cb0d40bbbf3..6e0f92bfcb1 100644 --- a/seed/python-sdk/folders/src/seed/core/file.py +++ b/seed/python-sdk/folders/src/seed/core/file.py @@ -13,12 +13,17 @@ # (filename, file (or bytes), content_type) typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str]], # (filename, file (or bytes), content_type, headers) - typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str], typing.Mapping[str, str]], + typing.Tuple[ + typing.Optional[str], + FileContent, + typing.Optional[str], + typing.Mapping[str, str], + ], ] def convert_file_dict_to_httpx_tuples( - d: typing.Dict[str, typing.Union[File, typing.List[File]]] + d: typing.Dict[str, typing.Union[File, typing.List[File]]], ) -> typing.List[typing.Tuple[str, File]]: """ The format we use is a list of tuples, where the first element is the diff --git a/seed/python-sdk/folders/src/seed/core/http_client.py b/seed/python-sdk/folders/src/seed/core/http_client.py index 9333d8a7f15..091f71bc185 100644 --- a/seed/python-sdk/folders/src/seed/core/http_client.py +++ b/seed/python-sdk/folders/src/seed/core/http_client.py @@ -77,7 +77,9 @@ def _retry_timeout(response: httpx.Response, retries: int) -> float: return retry_after # Apply exponential backoff, capped at MAX_RETRY_DELAY_SECONDS. - retry_delay = min(INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS) + retry_delay = min( + INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS + ) # Add a randomness / jitter to the retry delay to avoid overwhelming the server with retries. timeout = retry_delay * (1 - 0.25 * random()) @@ -90,7 +92,8 @@ def _should_retry(response: httpx.Response) -> bool: def remove_omit_from_dict( - original: typing.Dict[str, typing.Optional[typing.Any]], omit: typing.Optional[typing.Any] + original: typing.Dict[str, typing.Optional[typing.Any]], + omit: typing.Optional[typing.Any], ) -> typing.Dict[str, typing.Any]: if omit is None: return original @@ -108,7 +111,8 @@ def maybe_filter_request_body( ) -> typing.Optional[typing.Any]: if data is None: return ( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else None ) @@ -118,7 +122,8 @@ def maybe_filter_request_body( data_content = { **(jsonable_encoder(remove_omit_from_dict(data, omit))), # type: ignore **( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else {} ), @@ -162,7 +167,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url def request( @@ -174,8 +181,12 @@ def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -184,11 +195,14 @@ def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) response = self.httpx_client.request( method=method, @@ -198,7 +212,11 @@ def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -209,7 +227,10 @@ def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -222,11 +243,15 @@ def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: time.sleep(_retry_timeout(response=response, retries=retries)) @@ -256,8 +281,12 @@ def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -266,11 +295,14 @@ def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) with self.httpx_client.stream( method=method, @@ -280,7 +312,11 @@ def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -291,7 +327,9 @@ def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -304,7 +342,9 @@ def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream @@ -327,7 +367,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url async def request( @@ -339,8 +381,12 @@ async def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -349,11 +395,14 @@ async def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) # Add the input to each of these and do None-safety checks response = await self.httpx_client.request( @@ -364,7 +413,11 @@ async def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -375,7 +428,10 @@ async def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -388,11 +444,15 @@ async def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: await asyncio.sleep(_retry_timeout(response=response, retries=retries)) @@ -421,8 +481,12 @@ async def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -431,11 +495,14 @@ async def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) async with self.httpx_client.stream( method=method, @@ -445,7 +512,11 @@ async def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -456,7 +527,9 @@ async def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -469,7 +542,9 @@ async def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream diff --git a/seed/python-sdk/folders/src/seed/core/jsonable_encoder.py b/seed/python-sdk/folders/src/seed/core/jsonable_encoder.py index d3fd328fd41..12a8b52fc22 100644 --- a/seed/python-sdk/folders/src/seed/core/jsonable_encoder.py +++ b/seed/python-sdk/folders/src/seed/core/jsonable_encoder.py @@ -19,13 +19,19 @@ import pydantic from .datetime_utils import serialize_datetime -from .pydantic_utilities import IS_PYDANTIC_V2, encode_by_type, to_jsonable_with_fallback +from .pydantic_utilities import ( + IS_PYDANTIC_V2, + encode_by_type, + to_jsonable_with_fallback, +) SetIntStr = Set[Union[int, str]] DictIntStrAny = Dict[Union[int, str], Any] -def jsonable_encoder(obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None) -> Any: +def jsonable_encoder( + obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None +) -> Any: custom_encoder = custom_encoder or {} if custom_encoder: if type(obj) in custom_encoder: diff --git a/seed/python-sdk/folders/src/seed/core/pydantic_utilities.py b/seed/python-sdk/folders/src/seed/core/pydantic_utilities.py index 170a563d6eb..c63935c32a2 100644 --- a/seed/python-sdk/folders/src/seed/core/pydantic_utilities.py +++ b/seed/python-sdk/folders/src/seed/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) # type: ignore # Pydantic v1 diff --git a/seed/python-sdk/folders/src/seed/core/query_encoder.py b/seed/python-sdk/folders/src/seed/core/query_encoder.py index 24076d72ee9..7cb98f52cd7 100644 --- a/seed/python-sdk/folders/src/seed/core/query_encoder.py +++ b/seed/python-sdk/folders/src/seed/core/query_encoder.py @@ -7,7 +7,9 @@ # Flattens dicts to be of the form {"key[subkey][subkey2]": value} where value is not a dict -def traverse_query_dict(dict_flat: Dict[str, Any], key_prefix: Optional[str] = None) -> Dict[str, Any]: +def traverse_query_dict( + dict_flat: Dict[str, Any], key_prefix: Optional[str] = None +) -> Dict[str, Any]: result = {} for k, v in dict_flat.items(): key = f"{key_prefix}[{k}]" if key_prefix is not None else k @@ -30,4 +32,8 @@ def single_query_encoder(query_key: str, query_value: Any) -> Dict[str, Any]: def encode_query(query: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: - return dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) if query is not None else None + return ( + dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) + if query is not None + else None + ) diff --git a/seed/python-sdk/folders/src/seed/core/serialization.py b/seed/python-sdk/folders/src/seed/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/python-sdk/folders/src/seed/core/serialization.py +++ b/seed/python-sdk/folders/src/seed/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/python-sdk/folders/src/seed/folder/client.py b/seed/python-sdk/folders/src/seed/folder/client.py index d38a12a90ab..09b9c67b4b9 100644 --- a/seed/python-sdk/folders/src/seed/folder/client.py +++ b/seed/python-sdk/folders/src/seed/folder/client.py @@ -1,12 +1,13 @@ # This file was auto-generated by Fern from our API Definition. +from ..core.client_wrapper import SyncClientWrapper +from .service.client import ServiceClient import typing +from ..core.request_options import RequestOptions from json.decoder import JSONDecodeError - from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.request_options import RequestOptions -from .service.client import AsyncServiceClient, ServiceClient +from ..core.client_wrapper import AsyncClientWrapper +from .service.client import AsyncServiceClient class FolderClient: @@ -34,7 +35,10 @@ def foo(self, *, request_options: typing.Optional[RequestOptions] = None) -> Non ) client.folder.foo() """ - _response = self._client_wrapper.httpx_client.request(method="POST", request_options=request_options) + _response = self._client_wrapper.httpx_client.request( + method="POST", + request_options=request_options, + ) try: if 200 <= _response.status_code < 300: return @@ -49,7 +53,9 @@ def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper self.service = AsyncServiceClient(client_wrapper=self._client_wrapper) - async def foo(self, *, request_options: typing.Optional[RequestOptions] = None) -> None: + async def foo( + self, *, request_options: typing.Optional[RequestOptions] = None + ) -> None: """ Parameters ---------- @@ -77,7 +83,10 @@ async def main() -> None: asyncio.run(main()) """ - _response = await self._client_wrapper.httpx_client.request(method="POST", request_options=request_options) + _response = await self._client_wrapper.httpx_client.request( + method="POST", + request_options=request_options, + ) try: if 200 <= _response.status_code < 300: return diff --git a/seed/python-sdk/folders/src/seed/folder/service/client.py b/seed/python-sdk/folders/src/seed/folder/service/client.py index dd4758769d1..5568ca552a3 100644 --- a/seed/python-sdk/folders/src/seed/folder/service/client.py +++ b/seed/python-sdk/folders/src/seed/folder/service/client.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. import typing +from ...core.client_wrapper import SyncClientWrapper +from ...core.request_options import RequestOptions from json.decoder import JSONDecodeError - from ...core.api_error import ApiError -from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ...core.pydantic_utilities import parse_obj_as -from ...core.request_options import RequestOptions from .errors.not_found_error import NotFoundError +from ...core.pydantic_utilities import parse_obj_as +from ...core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -17,7 +17,9 @@ class ServiceClient: def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper - def endpoint(self, *, request_options: typing.Optional[RequestOptions] = None) -> None: + def endpoint( + self, *, request_options: typing.Optional[RequestOptions] = None + ) -> None: """ Parameters ---------- @@ -37,7 +39,11 @@ def endpoint(self, *, request_options: typing.Optional[RequestOptions] = None) - ) client.folder.service.endpoint() """ - _response = self._client_wrapper.httpx_client.request("service", method="GET", request_options=request_options) + _response = self._client_wrapper.httpx_client.request( + "service", + method="GET", + request_options=request_options, + ) try: if 200 <= _response.status_code < 300: return @@ -46,7 +52,12 @@ def endpoint(self, *, request_options: typing.Optional[RequestOptions] = None) - raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def unknown_request(self, *, request: typing.Any, request_options: typing.Optional[RequestOptions] = None) -> None: + def unknown_request( + self, + *, + request: typing.Any, + request_options: typing.Optional[RequestOptions] = None, + ) -> None: """ Parameters ---------- @@ -71,13 +82,19 @@ def unknown_request(self, *, request: typing.Any, request_options: typing.Option ) """ _response = self._client_wrapper.httpx_client.request( - "service", method="POST", json=request, request_options=request_options, omit=OMIT + "service", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: return if _response.status_code == 404: - raise NotFoundError(typing.cast(str, parse_obj_as(type_=str, object_=_response.json()))) # type: ignore + raise NotFoundError( + typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + ) _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -88,7 +105,9 @@ class AsyncServiceClient: def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper - async def endpoint(self, *, request_options: typing.Optional[RequestOptions] = None) -> None: + async def endpoint( + self, *, request_options: typing.Optional[RequestOptions] = None + ) -> None: """ Parameters ---------- @@ -117,7 +136,9 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "service", method="GET", request_options=request_options + "service", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: @@ -128,7 +149,10 @@ async def main() -> None: raise ApiError(status_code=_response.status_code, body=_response_json) async def unknown_request( - self, *, request: typing.Any, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Any, + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ Parameters @@ -162,13 +186,19 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "service", method="POST", json=request, request_options=request_options, omit=OMIT + "service", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: return if _response.status_code == 404: - raise NotFoundError(typing.cast(str, parse_obj_as(type_=str, object_=_response.json()))) # type: ignore + raise NotFoundError( + typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + ) _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/folders/src/seed/version.py b/seed/python-sdk/folders/src/seed/version.py index 866fb71fdcd..0d89f53e3c6 100644 --- a/seed/python-sdk/folders/src/seed/version.py +++ b/seed/python-sdk/folders/src/seed/version.py @@ -1,4 +1,3 @@ - from importlib import metadata __version__ = metadata.version("fern_folders") diff --git a/seed/python-sdk/folders/tests/a/b/test_root.py b/seed/python-sdk/folders/tests/a/b/test_root.py index eeef7ddd194..8d2576876d5 100644 --- a/seed/python-sdk/folders/tests/a/b/test_root.py +++ b/seed/python-sdk/folders/tests/a/b/test_root.py @@ -1,6 +1,7 @@ # This file was auto-generated by Fern from our API Definition. -from seed import AsyncSeedApi, SeedApi +from seed import SeedApi +from seed import AsyncSeedApi async def test_foo(client: SeedApi, async_client: AsyncSeedApi) -> None: diff --git a/seed/python-sdk/folders/tests/a/c/test_root.py b/seed/python-sdk/folders/tests/a/c/test_root.py index 8cced88e3c5..b29c0eecd1b 100644 --- a/seed/python-sdk/folders/tests/a/c/test_root.py +++ b/seed/python-sdk/folders/tests/a/c/test_root.py @@ -1,6 +1,7 @@ # This file was auto-generated by Fern from our API Definition. -from seed import AsyncSeedApi, SeedApi +from seed import SeedApi +from seed import AsyncSeedApi async def test_foo(client: SeedApi, async_client: AsyncSeedApi) -> None: diff --git a/seed/python-sdk/folders/tests/conftest.py b/seed/python-sdk/folders/tests/conftest.py index c39a48a47ef..f92e935f947 100644 --- a/seed/python-sdk/folders/tests/conftest.py +++ b/seed/python-sdk/folders/tests/conftest.py @@ -1,9 +1,9 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedApi import os - import pytest -from seed import AsyncSeedApi, SeedApi +from seed import AsyncSeedApi @pytest.fixture diff --git a/seed/python-sdk/folders/tests/custom/test_client.py b/seed/python-sdk/folders/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/python-sdk/folders/tests/custom/test_client.py +++ b/seed/python-sdk/folders/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/python-sdk/folders/tests/folder/test_root.py b/seed/python-sdk/folders/tests/folder/test_root.py index 2585e419296..7bd3eea06e7 100644 --- a/seed/python-sdk/folders/tests/folder/test_root.py +++ b/seed/python-sdk/folders/tests/folder/test_root.py @@ -1,6 +1,7 @@ # This file was auto-generated by Fern from our API Definition. -from seed import AsyncSeedApi, SeedApi +from seed import SeedApi +from seed import AsyncSeedApi async def test_foo(client: SeedApi, async_client: AsyncSeedApi) -> None: diff --git a/seed/python-sdk/folders/tests/folder/test_service.py b/seed/python-sdk/folders/tests/folder/test_service.py index 34bb8017b7b..5b22d09a30c 100644 --- a/seed/python-sdk/folders/tests/folder/test_service.py +++ b/seed/python-sdk/folders/tests/folder/test_service.py @@ -1,6 +1,7 @@ # This file was auto-generated by Fern from our API Definition. -from seed import AsyncSeedApi, SeedApi +from seed import SeedApi +from seed import AsyncSeedApi async def test_endpoint(client: SeedApi, async_client: AsyncSeedApi) -> None: @@ -14,4 +15,7 @@ async def test_unknown_request(client: SeedApi, async_client: AsyncSeedApi) -> N # Type ignore to avoid mypy complaining about the function not being meant to return a value assert client.folder.service.unknown_request(request={"key": "value"}) is None # type: ignore[func-returns-value] - assert await async_client.folder.service.unknown_request(request={"key": "value"}) is None # type: ignore[func-returns-value] + assert ( + await async_client.folder.service.unknown_request(request={"key": "value"}) + is None + ) # type: ignore[func-returns-value] diff --git a/seed/python-sdk/folders/tests/test_root.py b/seed/python-sdk/folders/tests/test_root.py index cded6ffa8d6..4ce7f57ba1f 100644 --- a/seed/python-sdk/folders/tests/test_root.py +++ b/seed/python-sdk/folders/tests/test_root.py @@ -1,6 +1,7 @@ # This file was auto-generated by Fern from our API Definition. -from seed import AsyncSeedApi, SeedApi +from seed import SeedApi +from seed import AsyncSeedApi async def test_foo(client: SeedApi, async_client: AsyncSeedApi) -> None: diff --git a/seed/python-sdk/folders/tests/utilities.py b/seed/python-sdk/folders/tests/utilities.py index 13da208eb3a..e8f4472564c 100644 --- a/seed/python-sdk/folders/tests/utilities.py +++ b/seed/python-sdk/folders/tests/utilities.py @@ -3,11 +3,14 @@ import typing import uuid -import pydantic from dateutil import parser +import pydantic + -def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> typing.Any: +def cast_field( + json_expectation: typing.Any, type_expectation: typing.Any +) -> typing.Any: # Cast these specific types which come through as string and expect our # models to cast to the correct type. if type_expectation == "uuid": @@ -25,7 +28,9 @@ def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> ty return json_expectation -def validate_field(response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any) -> None: +def validate_field( + response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectation == "no_validate": return @@ -44,7 +49,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(entry_expectation, dict): is_container_of_complex_type = True validate_response( - response=response[idx], json_expectation=ex, type_expectations=entry_expectation + response=response[idx], + json_expectation=ex, + type_expectations=entry_expectation, ) else: cast_json_expectation.append(cast_field(ex, entry_expectation)) @@ -56,7 +63,10 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # if any of the values of the set have a type_expectation of a dict, we're assuming it's a pydantic # model and keeping it a list. if container_expectation != "set" or not any( - map(lambda value: isinstance(value, dict), list(contents_expectation.values())) + map( + lambda value: isinstance(value, dict), + list(contents_expectation.values()), + ) ): json_expectation = cast_field(json_expectation, container_expectation) elif isinstance(type_expectation, tuple): @@ -65,9 +75,15 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(contents_expectation, dict): json_expectation = { cast_field( - key, contents_expectation.get(idx)[0] if contents_expectation.get(idx) is not None else None # type: ignore + key, + contents_expectation.get(idx)[0] + if contents_expectation.get(idx) is not None + else None, # type: ignore ): cast_field( - value, contents_expectation.get(idx)[1] if contents_expectation.get(idx) is not None else None # type: ignore + value, + contents_expectation.get(idx)[1] + if contents_expectation.get(idx) is not None + else None, # type: ignore ) for idx, (key, value) in enumerate(json_expectation.items()) } @@ -86,7 +102,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # Arg type_expectations is a deeply nested structure that matches the response, but with the values replaced with the expected types -def validate_response(response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any) -> None: +def validate_response( + response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectations == "no_validate": return @@ -96,11 +114,17 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e and not isinstance(response, dict) and not issubclass(type(response), pydantic.BaseModel) ): - validate_field(response=response, json_expectation=json_expectation, type_expectation=type_expectations) + validate_field( + response=response, + json_expectation=json_expectation, + type_expectation=type_expectations, + ) return if isinstance(response, list): - assert len(response) == len(json_expectation), "Length mismatch, expected: {0}, Actual: {1}".format( + assert len(response) == len( + json_expectation + ), "Length mismatch, expected: {0}, Actual: {1}".format( len(response), len(json_expectation) ) content_expectation = type_expectations @@ -108,7 +132,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e content_expectation = type_expectations[1] for idx, item in enumerate(response): validate_response( - response=item, json_expectation=json_expectation[idx], type_expectations=content_expectation[idx] + response=item, + json_expectation=json_expectation[idx], + type_expectations=content_expectation[idx], ) else: response_json = response @@ -116,7 +142,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e response_json = response.dict(by_alias=True) for key, value in json_expectation.items(): - assert key in response_json, "Field {0} not found within the response object: {1}".format( + assert ( + key in response_json + ), "Field {0} not found within the response object: {1}".format( key, response_json ) @@ -128,11 +156,19 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e # Otherwise, we're just validating a single field that's a pydantic model. if isinstance(value, dict) and not isinstance(type_expectation, tuple): validate_response( - response=response_json[key], json_expectation=value, type_expectations=type_expectation + response=response_json[key], + json_expectation=value, + type_expectations=type_expectation, ) else: - validate_field(response=response_json[key], json_expectation=value, type_expectation=type_expectation) + validate_field( + response=response_json[key], + json_expectation=value, + type_expectation=type_expectation, + ) # Ensure there are no additional fields here either del response_json[key] - assert len(response_json) == 0, "Additional fields found, expected None: {0}".format(response_json) + assert ( + len(response_json) == 0 + ), "Additional fields found, expected None: {0}".format(response_json) diff --git a/seed/python-sdk/folders/tests/utils/assets/models/__init__.py b/seed/python-sdk/folders/tests/utils/assets/models/__init__.py index 2cf01263529..3a1c852e71e 100644 --- a/seed/python-sdk/folders/tests/utils/assets/models/__init__.py +++ b/seed/python-sdk/folders/tests/utils/assets/models/__init__.py @@ -5,7 +5,7 @@ from .circle import CircleParams from .object_with_defaults import ObjectWithDefaultsParams from .object_with_optional_field import ObjectWithOptionalFieldParams -from .shape import Shape_CircleParams, Shape_SquareParams, ShapeParams +from .shape import ShapeParams, Shape_CircleParams, Shape_SquareParams from .square import SquareParams from .undiscriminated_shape import UndiscriminatedShapeParams diff --git a/seed/python-sdk/folders/tests/utils/assets/models/circle.py b/seed/python-sdk/folders/tests/utils/assets/models/circle.py index af7a1bf8a8e..253f12d38b3 100644 --- a/seed/python-sdk/folders/tests/utils/assets/models/circle.py +++ b/seed/python-sdk/folders/tests/utils/assets/models/circle.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class CircleParams(typing_extensions.TypedDict): - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] diff --git a/seed/python-sdk/folders/tests/utils/assets/models/object_with_optional_field.py b/seed/python-sdk/folders/tests/utils/assets/models/object_with_optional_field.py index 3ad93d5f305..ebe7dc80547 100644 --- a/seed/python-sdk/folders/tests/utils/assets/models/object_with_optional_field.py +++ b/seed/python-sdk/folders/tests/utils/assets/models/object_with_optional_field.py @@ -7,8 +7,8 @@ import uuid import typing_extensions -from seed.core.serialization import FieldMetadata +from seed.core.serialization import FieldMetadata from .color import Color from .shape import ShapeParams from .undiscriminated_shape import UndiscriminatedShapeParams @@ -18,16 +18,30 @@ class ObjectWithOptionalFieldParams(typing_extensions.TypedDict): literal: typing.Literal["lit_one"] string: typing_extensions.NotRequired[str] integer: typing_extensions.NotRequired[int] - long_: typing_extensions.NotRequired[typing_extensions.Annotated[int, FieldMetadata(alias="long")]] + long_: typing_extensions.NotRequired[ + typing_extensions.Annotated[int, FieldMetadata(alias="long")] + ] double: typing_extensions.NotRequired[float] - bool_: typing_extensions.NotRequired[typing_extensions.Annotated[bool, FieldMetadata(alias="bool")]] + bool_: typing_extensions.NotRequired[ + typing_extensions.Annotated[bool, FieldMetadata(alias="bool")] + ] datetime: typing_extensions.NotRequired[dt.datetime] date: typing_extensions.NotRequired[dt.date] - uuid_: typing_extensions.NotRequired[typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")]] - base_64: typing_extensions.NotRequired[typing_extensions.Annotated[str, FieldMetadata(alias="base64")]] - list_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")]] - set_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")]] - map_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")]] + uuid_: typing_extensions.NotRequired[ + typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")] + ] + base_64: typing_extensions.NotRequired[ + typing_extensions.Annotated[str, FieldMetadata(alias="base64")] + ] + list_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")] + ] + set_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")] + ] + map_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")] + ] enum: typing_extensions.NotRequired[Color] union: typing_extensions.NotRequired[ShapeParams] second_union: typing_extensions.NotRequired[ShapeParams] diff --git a/seed/python-sdk/folders/tests/utils/assets/models/shape.py b/seed/python-sdk/folders/tests/utils/assets/models/shape.py index 2c33c877951..816ffc51bdc 100644 --- a/seed/python-sdk/folders/tests/utils/assets/models/shape.py +++ b/seed/python-sdk/folders/tests/utils/assets/models/shape.py @@ -7,6 +7,7 @@ import typing import typing_extensions + from seed.core.serialization import FieldMetadata @@ -15,13 +16,21 @@ class Base(typing_extensions.TypedDict): class Shape_CircleParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["circle"], FieldMetadata(alias="shapeType")] - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["circle"], FieldMetadata(alias="shapeType") + ] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] class Shape_SquareParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["square"], FieldMetadata(alias="shapeType")] - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["square"], FieldMetadata(alias="shapeType") + ] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] ShapeParams = typing.Union[Shape_CircleParams, Shape_SquareParams] diff --git a/seed/python-sdk/folders/tests/utils/assets/models/square.py b/seed/python-sdk/folders/tests/utils/assets/models/square.py index b9b7dd319bc..bcf08a723c5 100644 --- a/seed/python-sdk/folders/tests/utils/assets/models/square.py +++ b/seed/python-sdk/folders/tests/utils/assets/models/square.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class SquareParams(typing_extensions.TypedDict): - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] diff --git a/seed/python-sdk/folders/tests/utils/test_http_client.py b/seed/python-sdk/folders/tests/utils/test_http_client.py index edd11ca7afb..f5a874a75f3 100644 --- a/seed/python-sdk/folders/tests/utils/test_http_client.py +++ b/seed/python-sdk/folders/tests/utils/test_http_client.py @@ -9,12 +9,17 @@ def get_request_options() -> RequestOptions: def test_get_json_request_body() -> None: - json_body, data_body = get_request_body(json={"hello": "world"}, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json={"hello": "world"}, data=None, request_options=None, omit=None + ) assert json_body == {"hello": "world"} assert data_body is None json_body_extras, data_body_extras = get_request_body( - json={"goodbye": "world"}, data=None, request_options=get_request_options(), omit=None + json={"goodbye": "world"}, + data=None, + request_options=get_request_options(), + omit=None, ) assert json_body_extras == {"goodbye": "world", "see you": "later"} @@ -22,12 +27,17 @@ def test_get_json_request_body() -> None: def test_get_files_request_body() -> None: - json_body, data_body = get_request_body(json=None, data={"hello": "world"}, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data={"hello": "world"}, request_options=None, omit=None + ) assert data_body == {"hello": "world"} assert json_body is None json_body_extras, data_body_extras = get_request_body( - json=None, data={"goodbye": "world"}, request_options=get_request_options(), omit=None + json=None, + data={"goodbye": "world"}, + request_options=get_request_options(), + omit=None, ) assert data_body_extras == {"goodbye": "world", "see you": "later"} @@ -35,7 +45,9 @@ def test_get_files_request_body() -> None: def test_get_none_request_body() -> None: - json_body, data_body = get_request_body(json=None, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data=None, request_options=None, omit=None + ) assert data_body is None assert json_body is None diff --git a/seed/python-sdk/folders/tests/utils/test_query_encoding.py b/seed/python-sdk/folders/tests/utils/test_query_encoding.py index 247e1551b46..fbc8f402167 100644 --- a/seed/python-sdk/folders/tests/utils/test_query_encoding.py +++ b/seed/python-sdk/folders/tests/utils/test_query_encoding.py @@ -4,9 +4,15 @@ def test_query_encoding() -> None: - assert encode_query({"hello world": "hello world"}) == {"hello world": "hello world"} - assert encode_query({"hello_world": {"hello": "world"}}) == {"hello_world[hello]": "world"} - assert encode_query({"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"}) == { + assert encode_query({"hello world": "hello world"}) == { + "hello world": "hello world" + } + assert encode_query({"hello_world": {"hello": "world"}}) == { + "hello_world[hello]": "world" + } + assert encode_query( + {"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"} + ) == { "hello_world[hello][world]": "today", "hello_world[test]": "this", "hi": "there", diff --git a/seed/python-sdk/folders/tests/utils/test_serialization.py b/seed/python-sdk/folders/tests/utils/test_serialization.py index 58b1ed66e6d..5ca956916dd 100644 --- a/seed/python-sdk/folders/tests/utils/test_serialization.py +++ b/seed/python-sdk/folders/tests/utils/test_serialization.py @@ -1,10 +1,12 @@ # This file was auto-generated by Fern from our API Definition. -from typing import Any, List +from typing import List, Any -from seed.core.serialization import convert_and_respect_annotation_metadata +from seed.core.serialization import ( + convert_and_respect_annotation_metadata, +) +from .assets.models import ShapeParams, ObjectWithOptionalFieldParams -from .assets.models import ObjectWithOptionalFieldParams, ShapeParams UNION_TEST: ShapeParams = {"radius_measurement": 1.0, "shape_type": "circle", "id": "1"} UNION_TEST_CONVERTED = {"shapeType": "circle", "radiusMeasurement": 1.0, "id": "1"} @@ -18,20 +20,54 @@ def test_convert_and_respect_annotation_metadata() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) - assert converted == {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"} + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) + assert converted == { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + } def test_convert_and_respect_annotation_metadata_in_list() -> None: data: List[ObjectWithOptionalFieldParams] = [ - {"string": "string", "long_": 12345, "bool_": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long_": 67890, "list_": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long_": 12345, + "bool_": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long_": 67890, + "list_": [], + "literal": "lit_one", + "any": "any", + }, ] - converted = convert_and_respect_annotation_metadata(object_=data, annotation=List[ObjectWithOptionalFieldParams]) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=List[ObjectWithOptionalFieldParams] + ) assert converted == [ - {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long": 67890, "list": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long": 67890, + "list": [], + "literal": "lit_one", + "any": "any", + }, ] @@ -43,7 +79,9 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) assert converted == { "string": "string", @@ -55,12 +93,16 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: def test_convert_and_respect_annotation_metadata_in_union() -> None: - converted = convert_and_respect_annotation_metadata(object_=UNION_TEST, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=UNION_TEST, annotation=ShapeParams + ) assert converted == UNION_TEST_CONVERTED def test_convert_and_respect_annotation_metadata_with_empty_object() -> None: data: Any = {} - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ShapeParams + ) assert converted == data diff --git a/seed/python-sdk/idempotency-headers/pyproject.toml b/seed/python-sdk/idempotency-headers/pyproject.toml index ba2446680ad..07574d74957 100644 --- a/seed/python-sdk/idempotency-headers/pyproject.toml +++ b/seed/python-sdk/idempotency-headers/pyproject.toml @@ -43,6 +43,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/python-sdk/idempotency-headers/src/seed/__init__.py b/seed/python-sdk/idempotency-headers/src/seed/__init__.py index 6951d61bfb9..43b71310034 100644 --- a/seed/python-sdk/idempotency-headers/src/seed/__init__.py +++ b/seed/python-sdk/idempotency-headers/src/seed/__init__.py @@ -5,4 +5,10 @@ from .payment import Currency from .version import __version__ -__all__ = ["AsyncSeedIdempotencyHeaders", "Currency", "SeedIdempotencyHeaders", "__version__", "payment"] +__all__ = [ + "AsyncSeedIdempotencyHeaders", + "Currency", + "SeedIdempotencyHeaders", + "__version__", + "payment", +] diff --git a/seed/python-sdk/idempotency-headers/src/seed/client.py b/seed/python-sdk/idempotency-headers/src/seed/client.py index 0f0cb8d3474..46e26fcf7cb 100644 --- a/seed/python-sdk/idempotency-headers/src/seed/client.py +++ b/seed/python-sdk/idempotency-headers/src/seed/client.py @@ -1,11 +1,11 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from .payment.client import AsyncPaymentClient, PaymentClient +from .core.client_wrapper import SyncClientWrapper +from .payment.client import PaymentClient +from .core.client_wrapper import AsyncClientWrapper +from .payment.client import AsyncPaymentClient class SeedIdempotencyHeaders: @@ -44,15 +44,19 @@ def __init__( token: typing.Union[str, typing.Callable[[], str]], timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.Client] = None + httpx_client: typing.Optional[httpx.Client] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = SyncClientWrapper( base_url=base_url, token=token, httpx_client=httpx_client if httpx_client is not None - else httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.Client( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.Client(timeout=_defaulted_timeout), timeout=_defaulted_timeout, @@ -96,15 +100,19 @@ def __init__( token: typing.Union[str, typing.Callable[[], str]], timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.AsyncClient] = None + httpx_client: typing.Optional[httpx.AsyncClient] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = AsyncClientWrapper( base_url=base_url, token=token, httpx_client=httpx_client if httpx_client is not None - else httpx.AsyncClient(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.AsyncClient( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.AsyncClient(timeout=_defaulted_timeout), timeout=_defaulted_timeout, diff --git a/seed/python-sdk/idempotency-headers/src/seed/core/api_error.py b/seed/python-sdk/idempotency-headers/src/seed/core/api_error.py index 2e9fc5431cd..da734b58068 100644 --- a/seed/python-sdk/idempotency-headers/src/seed/core/api_error.py +++ b/seed/python-sdk/idempotency-headers/src/seed/core/api_error.py @@ -7,7 +7,9 @@ class ApiError(Exception): status_code: typing.Optional[int] body: typing.Any - def __init__(self, *, status_code: typing.Optional[int] = None, body: typing.Any = None): + def __init__( + self, *, status_code: typing.Optional[int] = None, body: typing.Any = None + ): self.status_code = status_code self.body = body diff --git a/seed/python-sdk/idempotency-headers/src/seed/core/client_wrapper.py b/seed/python-sdk/idempotency-headers/src/seed/core/client_wrapper.py index 918a9e30a0f..54611ca320b 100644 --- a/seed/python-sdk/idempotency-headers/src/seed/core/client_wrapper.py +++ b/seed/python-sdk/idempotency-headers/src/seed/core/client_wrapper.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .http_client import AsyncHttpClient, HttpClient +from .http_client import HttpClient +from .http_client import AsyncHttpClient class BaseClientWrapper: diff --git a/seed/python-sdk/idempotency-headers/src/seed/core/datetime_utils.py b/seed/python-sdk/idempotency-headers/src/seed/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/python-sdk/idempotency-headers/src/seed/core/datetime_utils.py +++ b/seed/python-sdk/idempotency-headers/src/seed/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/python-sdk/idempotency-headers/src/seed/core/file.py b/seed/python-sdk/idempotency-headers/src/seed/core/file.py index cb0d40bbbf3..6e0f92bfcb1 100644 --- a/seed/python-sdk/idempotency-headers/src/seed/core/file.py +++ b/seed/python-sdk/idempotency-headers/src/seed/core/file.py @@ -13,12 +13,17 @@ # (filename, file (or bytes), content_type) typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str]], # (filename, file (or bytes), content_type, headers) - typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str], typing.Mapping[str, str]], + typing.Tuple[ + typing.Optional[str], + FileContent, + typing.Optional[str], + typing.Mapping[str, str], + ], ] def convert_file_dict_to_httpx_tuples( - d: typing.Dict[str, typing.Union[File, typing.List[File]]] + d: typing.Dict[str, typing.Union[File, typing.List[File]]], ) -> typing.List[typing.Tuple[str, File]]: """ The format we use is a list of tuples, where the first element is the diff --git a/seed/python-sdk/idempotency-headers/src/seed/core/http_client.py b/seed/python-sdk/idempotency-headers/src/seed/core/http_client.py index 9333d8a7f15..091f71bc185 100644 --- a/seed/python-sdk/idempotency-headers/src/seed/core/http_client.py +++ b/seed/python-sdk/idempotency-headers/src/seed/core/http_client.py @@ -77,7 +77,9 @@ def _retry_timeout(response: httpx.Response, retries: int) -> float: return retry_after # Apply exponential backoff, capped at MAX_RETRY_DELAY_SECONDS. - retry_delay = min(INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS) + retry_delay = min( + INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS + ) # Add a randomness / jitter to the retry delay to avoid overwhelming the server with retries. timeout = retry_delay * (1 - 0.25 * random()) @@ -90,7 +92,8 @@ def _should_retry(response: httpx.Response) -> bool: def remove_omit_from_dict( - original: typing.Dict[str, typing.Optional[typing.Any]], omit: typing.Optional[typing.Any] + original: typing.Dict[str, typing.Optional[typing.Any]], + omit: typing.Optional[typing.Any], ) -> typing.Dict[str, typing.Any]: if omit is None: return original @@ -108,7 +111,8 @@ def maybe_filter_request_body( ) -> typing.Optional[typing.Any]: if data is None: return ( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else None ) @@ -118,7 +122,8 @@ def maybe_filter_request_body( data_content = { **(jsonable_encoder(remove_omit_from_dict(data, omit))), # type: ignore **( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else {} ), @@ -162,7 +167,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url def request( @@ -174,8 +181,12 @@ def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -184,11 +195,14 @@ def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) response = self.httpx_client.request( method=method, @@ -198,7 +212,11 @@ def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -209,7 +227,10 @@ def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -222,11 +243,15 @@ def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: time.sleep(_retry_timeout(response=response, retries=retries)) @@ -256,8 +281,12 @@ def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -266,11 +295,14 @@ def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) with self.httpx_client.stream( method=method, @@ -280,7 +312,11 @@ def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -291,7 +327,9 @@ def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -304,7 +342,9 @@ def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream @@ -327,7 +367,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url async def request( @@ -339,8 +381,12 @@ async def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -349,11 +395,14 @@ async def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) # Add the input to each of these and do None-safety checks response = await self.httpx_client.request( @@ -364,7 +413,11 @@ async def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -375,7 +428,10 @@ async def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -388,11 +444,15 @@ async def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: await asyncio.sleep(_retry_timeout(response=response, retries=retries)) @@ -421,8 +481,12 @@ async def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -431,11 +495,14 @@ async def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) async with self.httpx_client.stream( method=method, @@ -445,7 +512,11 @@ async def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -456,7 +527,9 @@ async def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -469,7 +542,9 @@ async def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream diff --git a/seed/python-sdk/idempotency-headers/src/seed/core/jsonable_encoder.py b/seed/python-sdk/idempotency-headers/src/seed/core/jsonable_encoder.py index d3fd328fd41..12a8b52fc22 100644 --- a/seed/python-sdk/idempotency-headers/src/seed/core/jsonable_encoder.py +++ b/seed/python-sdk/idempotency-headers/src/seed/core/jsonable_encoder.py @@ -19,13 +19,19 @@ import pydantic from .datetime_utils import serialize_datetime -from .pydantic_utilities import IS_PYDANTIC_V2, encode_by_type, to_jsonable_with_fallback +from .pydantic_utilities import ( + IS_PYDANTIC_V2, + encode_by_type, + to_jsonable_with_fallback, +) SetIntStr = Set[Union[int, str]] DictIntStrAny = Dict[Union[int, str], Any] -def jsonable_encoder(obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None) -> Any: +def jsonable_encoder( + obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None +) -> Any: custom_encoder = custom_encoder or {} if custom_encoder: if type(obj) in custom_encoder: diff --git a/seed/python-sdk/idempotency-headers/src/seed/core/pydantic_utilities.py b/seed/python-sdk/idempotency-headers/src/seed/core/pydantic_utilities.py index 170a563d6eb..c63935c32a2 100644 --- a/seed/python-sdk/idempotency-headers/src/seed/core/pydantic_utilities.py +++ b/seed/python-sdk/idempotency-headers/src/seed/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) # type: ignore # Pydantic v1 diff --git a/seed/python-sdk/idempotency-headers/src/seed/core/query_encoder.py b/seed/python-sdk/idempotency-headers/src/seed/core/query_encoder.py index 24076d72ee9..7cb98f52cd7 100644 --- a/seed/python-sdk/idempotency-headers/src/seed/core/query_encoder.py +++ b/seed/python-sdk/idempotency-headers/src/seed/core/query_encoder.py @@ -7,7 +7,9 @@ # Flattens dicts to be of the form {"key[subkey][subkey2]": value} where value is not a dict -def traverse_query_dict(dict_flat: Dict[str, Any], key_prefix: Optional[str] = None) -> Dict[str, Any]: +def traverse_query_dict( + dict_flat: Dict[str, Any], key_prefix: Optional[str] = None +) -> Dict[str, Any]: result = {} for k, v in dict_flat.items(): key = f"{key_prefix}[{k}]" if key_prefix is not None else k @@ -30,4 +32,8 @@ def single_query_encoder(query_key: str, query_value: Any) -> Dict[str, Any]: def encode_query(query: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: - return dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) if query is not None else None + return ( + dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) + if query is not None + else None + ) diff --git a/seed/python-sdk/idempotency-headers/src/seed/core/serialization.py b/seed/python-sdk/idempotency-headers/src/seed/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/python-sdk/idempotency-headers/src/seed/core/serialization.py +++ b/seed/python-sdk/idempotency-headers/src/seed/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/python-sdk/idempotency-headers/src/seed/payment/client.py b/seed/python-sdk/idempotency-headers/src/seed/payment/client.py index 8ab6daab221..996faee377c 100644 --- a/seed/python-sdk/idempotency-headers/src/seed/payment/client.py +++ b/seed/python-sdk/idempotency-headers/src/seed/payment/client.py @@ -1,15 +1,15 @@ # This file was auto-generated by Fern from our API Definition. import typing +from ..core.client_wrapper import SyncClientWrapper +from .types.currency import Currency +from ..core.request_options import RequestOptions import uuid +from ..core.pydantic_utilities import parse_obj_as from json.decoder import JSONDecodeError - from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper from ..core.jsonable_encoder import jsonable_encoder -from ..core.pydantic_utilities import parse_obj_as -from ..core.request_options import RequestOptions -from .types.currency import Currency +from ..core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -62,23 +62,37 @@ def create( _response = self._client_wrapper.httpx_client.request( "payment", method="POST", - json={"amount": amount, "currency": currency}, + json={ + "amount": amount, + "currency": currency, + }, headers={ - "Idempotency-Key": str(idempotency_key) if idempotency_key is not None else None, - "Idempotency-Expiration": str(idempotency_expiration) if idempotency_expiration is not None else None, + "Idempotency-Key": str(idempotency_key) + if idempotency_key is not None + else None, + "Idempotency-Expiration": str(idempotency_expiration) + if idempotency_expiration is not None + else None, }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(uuid.UUID, parse_obj_as(type_=uuid.UUID, object_=_response.json())) # type: ignore + return typing.cast( + uuid.UUID, parse_obj_as(type_=uuid.UUID, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def delete(self, payment_id: str, *, request_options: typing.Optional[RequestOptions] = None) -> None: + def delete( + self, + payment_id: str, + *, + request_options: typing.Optional[RequestOptions] = None, + ) -> None: """ Parameters ---------- @@ -104,7 +118,9 @@ def delete(self, payment_id: str, *, request_options: typing.Optional[RequestOpt ) """ _response = self._client_wrapper.httpx_client.request( - f"payment/{jsonable_encoder(payment_id)}", method="DELETE", request_options=request_options + f"payment/{jsonable_encoder(payment_id)}", + method="DELETE", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: @@ -170,23 +186,37 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( "payment", method="POST", - json={"amount": amount, "currency": currency}, + json={ + "amount": amount, + "currency": currency, + }, headers={ - "Idempotency-Key": str(idempotency_key) if idempotency_key is not None else None, - "Idempotency-Expiration": str(idempotency_expiration) if idempotency_expiration is not None else None, + "Idempotency-Key": str(idempotency_key) + if idempotency_key is not None + else None, + "Idempotency-Expiration": str(idempotency_expiration) + if idempotency_expiration is not None + else None, }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(uuid.UUID, parse_obj_as(type_=uuid.UUID, object_=_response.json())) # type: ignore + return typing.cast( + uuid.UUID, parse_obj_as(type_=uuid.UUID, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - async def delete(self, payment_id: str, *, request_options: typing.Optional[RequestOptions] = None) -> None: + async def delete( + self, + payment_id: str, + *, + request_options: typing.Optional[RequestOptions] = None, + ) -> None: """ Parameters ---------- @@ -220,7 +250,9 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - f"payment/{jsonable_encoder(payment_id)}", method="DELETE", request_options=request_options + f"payment/{jsonable_encoder(payment_id)}", + method="DELETE", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: diff --git a/seed/python-sdk/idempotency-headers/src/seed/version.py b/seed/python-sdk/idempotency-headers/src/seed/version.py index ea222c63ec6..bd29f25db89 100644 --- a/seed/python-sdk/idempotency-headers/src/seed/version.py +++ b/seed/python-sdk/idempotency-headers/src/seed/version.py @@ -1,4 +1,3 @@ - from importlib import metadata __version__ = metadata.version("fern_idempotency-headers") diff --git a/seed/python-sdk/idempotency-headers/tests/conftest.py b/seed/python-sdk/idempotency-headers/tests/conftest.py index ff00c26b1eb..eca55a5dd7d 100644 --- a/seed/python-sdk/idempotency-headers/tests/conftest.py +++ b/seed/python-sdk/idempotency-headers/tests/conftest.py @@ -1,20 +1,22 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedIdempotencyHeaders import os - import pytest -from seed import AsyncSeedIdempotencyHeaders, SeedIdempotencyHeaders +from seed import AsyncSeedIdempotencyHeaders @pytest.fixture def client() -> SeedIdempotencyHeaders: return SeedIdempotencyHeaders( - token=os.getenv("ENV_TOKEN", "token"), base_url=os.getenv("TESTS_BASE_URL", "base_url") + token=os.getenv("ENV_TOKEN", "token"), + base_url=os.getenv("TESTS_BASE_URL", "base_url"), ) @pytest.fixture def async_client() -> AsyncSeedIdempotencyHeaders: return AsyncSeedIdempotencyHeaders( - token=os.getenv("ENV_TOKEN", "token"), base_url=os.getenv("TESTS_BASE_URL", "base_url") + token=os.getenv("ENV_TOKEN", "token"), + base_url=os.getenv("TESTS_BASE_URL", "base_url"), ) diff --git a/seed/python-sdk/idempotency-headers/tests/custom/test_client.py b/seed/python-sdk/idempotency-headers/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/python-sdk/idempotency-headers/tests/custom/test_client.py +++ b/seed/python-sdk/idempotency-headers/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/python-sdk/idempotency-headers/tests/test_payment.py b/seed/python-sdk/idempotency-headers/tests/test_payment.py index 55a15b2a272..5c15dad85b7 100644 --- a/seed/python-sdk/idempotency-headers/tests/test_payment.py +++ b/seed/python-sdk/idempotency-headers/tests/test_payment.py @@ -1,9 +1,12 @@ # This file was auto-generated by Fern from our API Definition. -from seed import AsyncSeedIdempotencyHeaders, SeedIdempotencyHeaders +from seed import SeedIdempotencyHeaders +from seed import AsyncSeedIdempotencyHeaders -async def test_delete(client: SeedIdempotencyHeaders, async_client: AsyncSeedIdempotencyHeaders) -> None: +async def test_delete( + client: SeedIdempotencyHeaders, async_client: AsyncSeedIdempotencyHeaders +) -> None: # Type ignore to avoid mypy complaining about the function not being meant to return a value assert client.payment.delete(payment_id="string") is None # type: ignore[func-returns-value] diff --git a/seed/python-sdk/idempotency-headers/tests/utilities.py b/seed/python-sdk/idempotency-headers/tests/utilities.py index 13da208eb3a..e8f4472564c 100644 --- a/seed/python-sdk/idempotency-headers/tests/utilities.py +++ b/seed/python-sdk/idempotency-headers/tests/utilities.py @@ -3,11 +3,14 @@ import typing import uuid -import pydantic from dateutil import parser +import pydantic + -def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> typing.Any: +def cast_field( + json_expectation: typing.Any, type_expectation: typing.Any +) -> typing.Any: # Cast these specific types which come through as string and expect our # models to cast to the correct type. if type_expectation == "uuid": @@ -25,7 +28,9 @@ def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> ty return json_expectation -def validate_field(response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any) -> None: +def validate_field( + response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectation == "no_validate": return @@ -44,7 +49,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(entry_expectation, dict): is_container_of_complex_type = True validate_response( - response=response[idx], json_expectation=ex, type_expectations=entry_expectation + response=response[idx], + json_expectation=ex, + type_expectations=entry_expectation, ) else: cast_json_expectation.append(cast_field(ex, entry_expectation)) @@ -56,7 +63,10 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # if any of the values of the set have a type_expectation of a dict, we're assuming it's a pydantic # model and keeping it a list. if container_expectation != "set" or not any( - map(lambda value: isinstance(value, dict), list(contents_expectation.values())) + map( + lambda value: isinstance(value, dict), + list(contents_expectation.values()), + ) ): json_expectation = cast_field(json_expectation, container_expectation) elif isinstance(type_expectation, tuple): @@ -65,9 +75,15 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(contents_expectation, dict): json_expectation = { cast_field( - key, contents_expectation.get(idx)[0] if contents_expectation.get(idx) is not None else None # type: ignore + key, + contents_expectation.get(idx)[0] + if contents_expectation.get(idx) is not None + else None, # type: ignore ): cast_field( - value, contents_expectation.get(idx)[1] if contents_expectation.get(idx) is not None else None # type: ignore + value, + contents_expectation.get(idx)[1] + if contents_expectation.get(idx) is not None + else None, # type: ignore ) for idx, (key, value) in enumerate(json_expectation.items()) } @@ -86,7 +102,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # Arg type_expectations is a deeply nested structure that matches the response, but with the values replaced with the expected types -def validate_response(response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any) -> None: +def validate_response( + response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectations == "no_validate": return @@ -96,11 +114,17 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e and not isinstance(response, dict) and not issubclass(type(response), pydantic.BaseModel) ): - validate_field(response=response, json_expectation=json_expectation, type_expectation=type_expectations) + validate_field( + response=response, + json_expectation=json_expectation, + type_expectation=type_expectations, + ) return if isinstance(response, list): - assert len(response) == len(json_expectation), "Length mismatch, expected: {0}, Actual: {1}".format( + assert len(response) == len( + json_expectation + ), "Length mismatch, expected: {0}, Actual: {1}".format( len(response), len(json_expectation) ) content_expectation = type_expectations @@ -108,7 +132,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e content_expectation = type_expectations[1] for idx, item in enumerate(response): validate_response( - response=item, json_expectation=json_expectation[idx], type_expectations=content_expectation[idx] + response=item, + json_expectation=json_expectation[idx], + type_expectations=content_expectation[idx], ) else: response_json = response @@ -116,7 +142,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e response_json = response.dict(by_alias=True) for key, value in json_expectation.items(): - assert key in response_json, "Field {0} not found within the response object: {1}".format( + assert ( + key in response_json + ), "Field {0} not found within the response object: {1}".format( key, response_json ) @@ -128,11 +156,19 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e # Otherwise, we're just validating a single field that's a pydantic model. if isinstance(value, dict) and not isinstance(type_expectation, tuple): validate_response( - response=response_json[key], json_expectation=value, type_expectations=type_expectation + response=response_json[key], + json_expectation=value, + type_expectations=type_expectation, ) else: - validate_field(response=response_json[key], json_expectation=value, type_expectation=type_expectation) + validate_field( + response=response_json[key], + json_expectation=value, + type_expectation=type_expectation, + ) # Ensure there are no additional fields here either del response_json[key] - assert len(response_json) == 0, "Additional fields found, expected None: {0}".format(response_json) + assert ( + len(response_json) == 0 + ), "Additional fields found, expected None: {0}".format(response_json) diff --git a/seed/python-sdk/idempotency-headers/tests/utils/assets/models/__init__.py b/seed/python-sdk/idempotency-headers/tests/utils/assets/models/__init__.py index 2cf01263529..3a1c852e71e 100644 --- a/seed/python-sdk/idempotency-headers/tests/utils/assets/models/__init__.py +++ b/seed/python-sdk/idempotency-headers/tests/utils/assets/models/__init__.py @@ -5,7 +5,7 @@ from .circle import CircleParams from .object_with_defaults import ObjectWithDefaultsParams from .object_with_optional_field import ObjectWithOptionalFieldParams -from .shape import Shape_CircleParams, Shape_SquareParams, ShapeParams +from .shape import ShapeParams, Shape_CircleParams, Shape_SquareParams from .square import SquareParams from .undiscriminated_shape import UndiscriminatedShapeParams diff --git a/seed/python-sdk/idempotency-headers/tests/utils/assets/models/circle.py b/seed/python-sdk/idempotency-headers/tests/utils/assets/models/circle.py index af7a1bf8a8e..253f12d38b3 100644 --- a/seed/python-sdk/idempotency-headers/tests/utils/assets/models/circle.py +++ b/seed/python-sdk/idempotency-headers/tests/utils/assets/models/circle.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class CircleParams(typing_extensions.TypedDict): - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] diff --git a/seed/python-sdk/idempotency-headers/tests/utils/assets/models/object_with_optional_field.py b/seed/python-sdk/idempotency-headers/tests/utils/assets/models/object_with_optional_field.py index 3ad93d5f305..ebe7dc80547 100644 --- a/seed/python-sdk/idempotency-headers/tests/utils/assets/models/object_with_optional_field.py +++ b/seed/python-sdk/idempotency-headers/tests/utils/assets/models/object_with_optional_field.py @@ -7,8 +7,8 @@ import uuid import typing_extensions -from seed.core.serialization import FieldMetadata +from seed.core.serialization import FieldMetadata from .color import Color from .shape import ShapeParams from .undiscriminated_shape import UndiscriminatedShapeParams @@ -18,16 +18,30 @@ class ObjectWithOptionalFieldParams(typing_extensions.TypedDict): literal: typing.Literal["lit_one"] string: typing_extensions.NotRequired[str] integer: typing_extensions.NotRequired[int] - long_: typing_extensions.NotRequired[typing_extensions.Annotated[int, FieldMetadata(alias="long")]] + long_: typing_extensions.NotRequired[ + typing_extensions.Annotated[int, FieldMetadata(alias="long")] + ] double: typing_extensions.NotRequired[float] - bool_: typing_extensions.NotRequired[typing_extensions.Annotated[bool, FieldMetadata(alias="bool")]] + bool_: typing_extensions.NotRequired[ + typing_extensions.Annotated[bool, FieldMetadata(alias="bool")] + ] datetime: typing_extensions.NotRequired[dt.datetime] date: typing_extensions.NotRequired[dt.date] - uuid_: typing_extensions.NotRequired[typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")]] - base_64: typing_extensions.NotRequired[typing_extensions.Annotated[str, FieldMetadata(alias="base64")]] - list_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")]] - set_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")]] - map_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")]] + uuid_: typing_extensions.NotRequired[ + typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")] + ] + base_64: typing_extensions.NotRequired[ + typing_extensions.Annotated[str, FieldMetadata(alias="base64")] + ] + list_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")] + ] + set_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")] + ] + map_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")] + ] enum: typing_extensions.NotRequired[Color] union: typing_extensions.NotRequired[ShapeParams] second_union: typing_extensions.NotRequired[ShapeParams] diff --git a/seed/python-sdk/idempotency-headers/tests/utils/assets/models/shape.py b/seed/python-sdk/idempotency-headers/tests/utils/assets/models/shape.py index 2c33c877951..816ffc51bdc 100644 --- a/seed/python-sdk/idempotency-headers/tests/utils/assets/models/shape.py +++ b/seed/python-sdk/idempotency-headers/tests/utils/assets/models/shape.py @@ -7,6 +7,7 @@ import typing import typing_extensions + from seed.core.serialization import FieldMetadata @@ -15,13 +16,21 @@ class Base(typing_extensions.TypedDict): class Shape_CircleParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["circle"], FieldMetadata(alias="shapeType")] - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["circle"], FieldMetadata(alias="shapeType") + ] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] class Shape_SquareParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["square"], FieldMetadata(alias="shapeType")] - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["square"], FieldMetadata(alias="shapeType") + ] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] ShapeParams = typing.Union[Shape_CircleParams, Shape_SquareParams] diff --git a/seed/python-sdk/idempotency-headers/tests/utils/assets/models/square.py b/seed/python-sdk/idempotency-headers/tests/utils/assets/models/square.py index b9b7dd319bc..bcf08a723c5 100644 --- a/seed/python-sdk/idempotency-headers/tests/utils/assets/models/square.py +++ b/seed/python-sdk/idempotency-headers/tests/utils/assets/models/square.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class SquareParams(typing_extensions.TypedDict): - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] diff --git a/seed/python-sdk/idempotency-headers/tests/utils/test_http_client.py b/seed/python-sdk/idempotency-headers/tests/utils/test_http_client.py index edd11ca7afb..f5a874a75f3 100644 --- a/seed/python-sdk/idempotency-headers/tests/utils/test_http_client.py +++ b/seed/python-sdk/idempotency-headers/tests/utils/test_http_client.py @@ -9,12 +9,17 @@ def get_request_options() -> RequestOptions: def test_get_json_request_body() -> None: - json_body, data_body = get_request_body(json={"hello": "world"}, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json={"hello": "world"}, data=None, request_options=None, omit=None + ) assert json_body == {"hello": "world"} assert data_body is None json_body_extras, data_body_extras = get_request_body( - json={"goodbye": "world"}, data=None, request_options=get_request_options(), omit=None + json={"goodbye": "world"}, + data=None, + request_options=get_request_options(), + omit=None, ) assert json_body_extras == {"goodbye": "world", "see you": "later"} @@ -22,12 +27,17 @@ def test_get_json_request_body() -> None: def test_get_files_request_body() -> None: - json_body, data_body = get_request_body(json=None, data={"hello": "world"}, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data={"hello": "world"}, request_options=None, omit=None + ) assert data_body == {"hello": "world"} assert json_body is None json_body_extras, data_body_extras = get_request_body( - json=None, data={"goodbye": "world"}, request_options=get_request_options(), omit=None + json=None, + data={"goodbye": "world"}, + request_options=get_request_options(), + omit=None, ) assert data_body_extras == {"goodbye": "world", "see you": "later"} @@ -35,7 +45,9 @@ def test_get_files_request_body() -> None: def test_get_none_request_body() -> None: - json_body, data_body = get_request_body(json=None, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data=None, request_options=None, omit=None + ) assert data_body is None assert json_body is None diff --git a/seed/python-sdk/idempotency-headers/tests/utils/test_query_encoding.py b/seed/python-sdk/idempotency-headers/tests/utils/test_query_encoding.py index 247e1551b46..fbc8f402167 100644 --- a/seed/python-sdk/idempotency-headers/tests/utils/test_query_encoding.py +++ b/seed/python-sdk/idempotency-headers/tests/utils/test_query_encoding.py @@ -4,9 +4,15 @@ def test_query_encoding() -> None: - assert encode_query({"hello world": "hello world"}) == {"hello world": "hello world"} - assert encode_query({"hello_world": {"hello": "world"}}) == {"hello_world[hello]": "world"} - assert encode_query({"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"}) == { + assert encode_query({"hello world": "hello world"}) == { + "hello world": "hello world" + } + assert encode_query({"hello_world": {"hello": "world"}}) == { + "hello_world[hello]": "world" + } + assert encode_query( + {"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"} + ) == { "hello_world[hello][world]": "today", "hello_world[test]": "this", "hi": "there", diff --git a/seed/python-sdk/idempotency-headers/tests/utils/test_serialization.py b/seed/python-sdk/idempotency-headers/tests/utils/test_serialization.py index 58b1ed66e6d..5ca956916dd 100644 --- a/seed/python-sdk/idempotency-headers/tests/utils/test_serialization.py +++ b/seed/python-sdk/idempotency-headers/tests/utils/test_serialization.py @@ -1,10 +1,12 @@ # This file was auto-generated by Fern from our API Definition. -from typing import Any, List +from typing import List, Any -from seed.core.serialization import convert_and_respect_annotation_metadata +from seed.core.serialization import ( + convert_and_respect_annotation_metadata, +) +from .assets.models import ShapeParams, ObjectWithOptionalFieldParams -from .assets.models import ObjectWithOptionalFieldParams, ShapeParams UNION_TEST: ShapeParams = {"radius_measurement": 1.0, "shape_type": "circle", "id": "1"} UNION_TEST_CONVERTED = {"shapeType": "circle", "radiusMeasurement": 1.0, "id": "1"} @@ -18,20 +20,54 @@ def test_convert_and_respect_annotation_metadata() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) - assert converted == {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"} + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) + assert converted == { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + } def test_convert_and_respect_annotation_metadata_in_list() -> None: data: List[ObjectWithOptionalFieldParams] = [ - {"string": "string", "long_": 12345, "bool_": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long_": 67890, "list_": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long_": 12345, + "bool_": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long_": 67890, + "list_": [], + "literal": "lit_one", + "any": "any", + }, ] - converted = convert_and_respect_annotation_metadata(object_=data, annotation=List[ObjectWithOptionalFieldParams]) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=List[ObjectWithOptionalFieldParams] + ) assert converted == [ - {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long": 67890, "list": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long": 67890, + "list": [], + "literal": "lit_one", + "any": "any", + }, ] @@ -43,7 +79,9 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) assert converted == { "string": "string", @@ -55,12 +93,16 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: def test_convert_and_respect_annotation_metadata_in_union() -> None: - converted = convert_and_respect_annotation_metadata(object_=UNION_TEST, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=UNION_TEST, annotation=ShapeParams + ) assert converted == UNION_TEST_CONVERTED def test_convert_and_respect_annotation_metadata_with_empty_object() -> None: data: Any = {} - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ShapeParams + ) assert converted == data diff --git a/seed/python-sdk/imdb/pyproject.toml b/seed/python-sdk/imdb/pyproject.toml index 71a77d4a56c..70b32ddbaa6 100644 --- a/seed/python-sdk/imdb/pyproject.toml +++ b/seed/python-sdk/imdb/pyproject.toml @@ -43,6 +43,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/python-sdk/imdb/src/seed/client.py b/seed/python-sdk/imdb/src/seed/client.py index c4528b00a83..58310af5477 100644 --- a/seed/python-sdk/imdb/src/seed/client.py +++ b/seed/python-sdk/imdb/src/seed/client.py @@ -1,11 +1,11 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from .imdb.client import AsyncImdbClient, ImdbClient +from .core.client_wrapper import SyncClientWrapper +from .imdb.client import ImdbClient +from .core.client_wrapper import AsyncClientWrapper +from .imdb.client import AsyncImdbClient class SeedApi: @@ -44,15 +44,19 @@ def __init__( token: typing.Optional[typing.Union[str, typing.Callable[[], str]]] = None, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.Client] = None + httpx_client: typing.Optional[httpx.Client] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = SyncClientWrapper( base_url=base_url, token=token, httpx_client=httpx_client if httpx_client is not None - else httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.Client( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.Client(timeout=_defaulted_timeout), timeout=_defaulted_timeout, @@ -96,15 +100,19 @@ def __init__( token: typing.Optional[typing.Union[str, typing.Callable[[], str]]] = None, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.AsyncClient] = None + httpx_client: typing.Optional[httpx.AsyncClient] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = AsyncClientWrapper( base_url=base_url, token=token, httpx_client=httpx_client if httpx_client is not None - else httpx.AsyncClient(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.AsyncClient( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.AsyncClient(timeout=_defaulted_timeout), timeout=_defaulted_timeout, diff --git a/seed/python-sdk/imdb/src/seed/core/api_error.py b/seed/python-sdk/imdb/src/seed/core/api_error.py index 2e9fc5431cd..da734b58068 100644 --- a/seed/python-sdk/imdb/src/seed/core/api_error.py +++ b/seed/python-sdk/imdb/src/seed/core/api_error.py @@ -7,7 +7,9 @@ class ApiError(Exception): status_code: typing.Optional[int] body: typing.Any - def __init__(self, *, status_code: typing.Optional[int] = None, body: typing.Any = None): + def __init__( + self, *, status_code: typing.Optional[int] = None, body: typing.Any = None + ): self.status_code = status_code self.body = body diff --git a/seed/python-sdk/imdb/src/seed/core/client_wrapper.py b/seed/python-sdk/imdb/src/seed/core/client_wrapper.py index 97c8b5064a8..8d7a340e9b5 100644 --- a/seed/python-sdk/imdb/src/seed/core/client_wrapper.py +++ b/seed/python-sdk/imdb/src/seed/core/client_wrapper.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .http_client import AsyncHttpClient, HttpClient +from .http_client import HttpClient +from .http_client import AsyncHttpClient class BaseClientWrapper: diff --git a/seed/python-sdk/imdb/src/seed/core/datetime_utils.py b/seed/python-sdk/imdb/src/seed/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/python-sdk/imdb/src/seed/core/datetime_utils.py +++ b/seed/python-sdk/imdb/src/seed/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/python-sdk/imdb/src/seed/core/file.py b/seed/python-sdk/imdb/src/seed/core/file.py index cb0d40bbbf3..6e0f92bfcb1 100644 --- a/seed/python-sdk/imdb/src/seed/core/file.py +++ b/seed/python-sdk/imdb/src/seed/core/file.py @@ -13,12 +13,17 @@ # (filename, file (or bytes), content_type) typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str]], # (filename, file (or bytes), content_type, headers) - typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str], typing.Mapping[str, str]], + typing.Tuple[ + typing.Optional[str], + FileContent, + typing.Optional[str], + typing.Mapping[str, str], + ], ] def convert_file_dict_to_httpx_tuples( - d: typing.Dict[str, typing.Union[File, typing.List[File]]] + d: typing.Dict[str, typing.Union[File, typing.List[File]]], ) -> typing.List[typing.Tuple[str, File]]: """ The format we use is a list of tuples, where the first element is the diff --git a/seed/python-sdk/imdb/src/seed/core/http_client.py b/seed/python-sdk/imdb/src/seed/core/http_client.py index 9333d8a7f15..091f71bc185 100644 --- a/seed/python-sdk/imdb/src/seed/core/http_client.py +++ b/seed/python-sdk/imdb/src/seed/core/http_client.py @@ -77,7 +77,9 @@ def _retry_timeout(response: httpx.Response, retries: int) -> float: return retry_after # Apply exponential backoff, capped at MAX_RETRY_DELAY_SECONDS. - retry_delay = min(INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS) + retry_delay = min( + INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS + ) # Add a randomness / jitter to the retry delay to avoid overwhelming the server with retries. timeout = retry_delay * (1 - 0.25 * random()) @@ -90,7 +92,8 @@ def _should_retry(response: httpx.Response) -> bool: def remove_omit_from_dict( - original: typing.Dict[str, typing.Optional[typing.Any]], omit: typing.Optional[typing.Any] + original: typing.Dict[str, typing.Optional[typing.Any]], + omit: typing.Optional[typing.Any], ) -> typing.Dict[str, typing.Any]: if omit is None: return original @@ -108,7 +111,8 @@ def maybe_filter_request_body( ) -> typing.Optional[typing.Any]: if data is None: return ( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else None ) @@ -118,7 +122,8 @@ def maybe_filter_request_body( data_content = { **(jsonable_encoder(remove_omit_from_dict(data, omit))), # type: ignore **( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else {} ), @@ -162,7 +167,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url def request( @@ -174,8 +181,12 @@ def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -184,11 +195,14 @@ def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) response = self.httpx_client.request( method=method, @@ -198,7 +212,11 @@ def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -209,7 +227,10 @@ def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -222,11 +243,15 @@ def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: time.sleep(_retry_timeout(response=response, retries=retries)) @@ -256,8 +281,12 @@ def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -266,11 +295,14 @@ def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) with self.httpx_client.stream( method=method, @@ -280,7 +312,11 @@ def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -291,7 +327,9 @@ def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -304,7 +342,9 @@ def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream @@ -327,7 +367,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url async def request( @@ -339,8 +381,12 @@ async def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -349,11 +395,14 @@ async def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) # Add the input to each of these and do None-safety checks response = await self.httpx_client.request( @@ -364,7 +413,11 @@ async def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -375,7 +428,10 @@ async def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -388,11 +444,15 @@ async def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: await asyncio.sleep(_retry_timeout(response=response, retries=retries)) @@ -421,8 +481,12 @@ async def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -431,11 +495,14 @@ async def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) async with self.httpx_client.stream( method=method, @@ -445,7 +512,11 @@ async def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -456,7 +527,9 @@ async def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -469,7 +542,9 @@ async def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream diff --git a/seed/python-sdk/imdb/src/seed/core/jsonable_encoder.py b/seed/python-sdk/imdb/src/seed/core/jsonable_encoder.py index d3fd328fd41..12a8b52fc22 100644 --- a/seed/python-sdk/imdb/src/seed/core/jsonable_encoder.py +++ b/seed/python-sdk/imdb/src/seed/core/jsonable_encoder.py @@ -19,13 +19,19 @@ import pydantic from .datetime_utils import serialize_datetime -from .pydantic_utilities import IS_PYDANTIC_V2, encode_by_type, to_jsonable_with_fallback +from .pydantic_utilities import ( + IS_PYDANTIC_V2, + encode_by_type, + to_jsonable_with_fallback, +) SetIntStr = Set[Union[int, str]] DictIntStrAny = Dict[Union[int, str], Any] -def jsonable_encoder(obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None) -> Any: +def jsonable_encoder( + obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None +) -> Any: custom_encoder = custom_encoder or {} if custom_encoder: if type(obj) in custom_encoder: diff --git a/seed/python-sdk/imdb/src/seed/core/pydantic_utilities.py b/seed/python-sdk/imdb/src/seed/core/pydantic_utilities.py index 170a563d6eb..c63935c32a2 100644 --- a/seed/python-sdk/imdb/src/seed/core/pydantic_utilities.py +++ b/seed/python-sdk/imdb/src/seed/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) # type: ignore # Pydantic v1 diff --git a/seed/python-sdk/imdb/src/seed/core/query_encoder.py b/seed/python-sdk/imdb/src/seed/core/query_encoder.py index 24076d72ee9..7cb98f52cd7 100644 --- a/seed/python-sdk/imdb/src/seed/core/query_encoder.py +++ b/seed/python-sdk/imdb/src/seed/core/query_encoder.py @@ -7,7 +7,9 @@ # Flattens dicts to be of the form {"key[subkey][subkey2]": value} where value is not a dict -def traverse_query_dict(dict_flat: Dict[str, Any], key_prefix: Optional[str] = None) -> Dict[str, Any]: +def traverse_query_dict( + dict_flat: Dict[str, Any], key_prefix: Optional[str] = None +) -> Dict[str, Any]: result = {} for k, v in dict_flat.items(): key = f"{key_prefix}[{k}]" if key_prefix is not None else k @@ -30,4 +32,8 @@ def single_query_encoder(query_key: str, query_value: Any) -> Dict[str, Any]: def encode_query(query: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: - return dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) if query is not None else None + return ( + dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) + if query is not None + else None + ) diff --git a/seed/python-sdk/imdb/src/seed/core/serialization.py b/seed/python-sdk/imdb/src/seed/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/python-sdk/imdb/src/seed/core/serialization.py +++ b/seed/python-sdk/imdb/src/seed/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/python-sdk/imdb/src/seed/imdb/client.py b/seed/python-sdk/imdb/src/seed/imdb/client.py index 5ab0e27e473..4e5150e3c91 100644 --- a/seed/python-sdk/imdb/src/seed/imdb/client.py +++ b/seed/python-sdk/imdb/src/seed/imdb/client.py @@ -1,16 +1,16 @@ # This file was auto-generated by Fern from our API Definition. import typing +from ..core.client_wrapper import SyncClientWrapper +from ..core.request_options import RequestOptions +from .types.movie_id import MovieId +from ..core.pydantic_utilities import parse_obj_as from json.decoder import JSONDecodeError - from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper +from .types.movie import Movie from ..core.jsonable_encoder import jsonable_encoder -from ..core.pydantic_utilities import parse_obj_as -from ..core.request_options import RequestOptions from .errors.movie_does_not_exist_error import MovieDoesNotExistError -from .types.movie import Movie -from .types.movie_id import MovieId +from ..core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -21,7 +21,11 @@ def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper def create_movie( - self, *, title: str, rating: float, request_options: typing.Optional[RequestOptions] = None + self, + *, + title: str, + rating: float, + request_options: typing.Optional[RequestOptions] = None, ) -> MovieId: """ Add a movie to the database @@ -55,19 +59,29 @@ def create_movie( _response = self._client_wrapper.httpx_client.request( "movies/create-movie", method="POST", - json={"title": title, "rating": rating}, + json={ + "title": title, + "rating": rating, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(MovieId, parse_obj_as(type_=MovieId, object_=_response.json())) # type: ignore + return typing.cast( + MovieId, parse_obj_as(type_=MovieId, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def get_movie(self, movie_id: MovieId, *, request_options: typing.Optional[RequestOptions] = None) -> Movie: + def get_movie( + self, + movie_id: MovieId, + *, + request_options: typing.Optional[RequestOptions] = None, + ) -> Movie: """ Parameters ---------- @@ -93,14 +107,20 @@ def get_movie(self, movie_id: MovieId, *, request_options: typing.Optional[Reque ) """ _response = self._client_wrapper.httpx_client.request( - f"movies/{jsonable_encoder(movie_id)}", method="GET", request_options=request_options + f"movies/{jsonable_encoder(movie_id)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(Movie, parse_obj_as(type_=Movie, object_=_response.json())) # type: ignore + return typing.cast( + Movie, parse_obj_as(type_=Movie, object_=_response.json()) + ) # type: ignore if _response.status_code == 404: raise MovieDoesNotExistError( - typing.cast(MovieId, parse_obj_as(type_=MovieId, object_=_response.json())) # type: ignore + typing.cast( + MovieId, parse_obj_as(type_=MovieId, object_=_response.json()) + ) # type: ignore ) _response_json = _response.json() except JSONDecodeError: @@ -113,7 +133,11 @@ def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper async def create_movie( - self, *, title: str, rating: float, request_options: typing.Optional[RequestOptions] = None + self, + *, + title: str, + rating: float, + request_options: typing.Optional[RequestOptions] = None, ) -> MovieId: """ Add a movie to the database @@ -155,19 +179,29 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( "movies/create-movie", method="POST", - json={"title": title, "rating": rating}, + json={ + "title": title, + "rating": rating, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(MovieId, parse_obj_as(type_=MovieId, object_=_response.json())) # type: ignore + return typing.cast( + MovieId, parse_obj_as(type_=MovieId, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - async def get_movie(self, movie_id: MovieId, *, request_options: typing.Optional[RequestOptions] = None) -> Movie: + async def get_movie( + self, + movie_id: MovieId, + *, + request_options: typing.Optional[RequestOptions] = None, + ) -> Movie: """ Parameters ---------- @@ -201,14 +235,20 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - f"movies/{jsonable_encoder(movie_id)}", method="GET", request_options=request_options + f"movies/{jsonable_encoder(movie_id)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(Movie, parse_obj_as(type_=Movie, object_=_response.json())) # type: ignore + return typing.cast( + Movie, parse_obj_as(type_=Movie, object_=_response.json()) + ) # type: ignore if _response.status_code == 404: raise MovieDoesNotExistError( - typing.cast(MovieId, parse_obj_as(type_=MovieId, object_=_response.json())) # type: ignore + typing.cast( + MovieId, parse_obj_as(type_=MovieId, object_=_response.json()) + ) # type: ignore ) _response_json = _response.json() except JSONDecodeError: diff --git a/seed/python-sdk/imdb/src/seed/imdb/types/create_movie_request.py b/seed/python-sdk/imdb/src/seed/imdb/types/create_movie_request.py index aa0edfda76a..6567c0e16f4 100644 --- a/seed/python-sdk/imdb/src/seed/imdb/types/create_movie_request.py +++ b/seed/python-sdk/imdb/src/seed/imdb/types/create_movie_request.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class CreateMovieRequest(UniversalBaseModel): title: str rating: float if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/imdb/src/seed/imdb/types/movie.py b/seed/python-sdk/imdb/src/seed/imdb/types/movie.py index 0d3349e58f0..3f8937d9aac 100644 --- a/seed/python-sdk/imdb/src/seed/imdb/types/movie.py +++ b/seed/python-sdk/imdb/src/seed/imdb/types/movie.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. -import typing - -import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ...core.pydantic_utilities import UniversalBaseModel from .movie_id import MovieId +import pydantic +from ...core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class Movie(UniversalBaseModel): @@ -17,7 +16,9 @@ class Movie(UniversalBaseModel): """ if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/imdb/src/seed/version.py b/seed/python-sdk/imdb/src/seed/version.py index bb0a7dff9b0..3ba617feb0b 100644 --- a/seed/python-sdk/imdb/src/seed/version.py +++ b/seed/python-sdk/imdb/src/seed/version.py @@ -1,4 +1,3 @@ - from importlib import metadata __version__ = metadata.version("fern_imdb") diff --git a/seed/python-sdk/imdb/tests/conftest.py b/seed/python-sdk/imdb/tests/conftest.py index f9a97c1162c..d4a4d6c804c 100644 --- a/seed/python-sdk/imdb/tests/conftest.py +++ b/seed/python-sdk/imdb/tests/conftest.py @@ -1,16 +1,22 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedApi import os - import pytest -from seed import AsyncSeedApi, SeedApi +from seed import AsyncSeedApi @pytest.fixture def client() -> SeedApi: - return SeedApi(token=os.getenv("ENV_TOKEN", "token"), base_url=os.getenv("TESTS_BASE_URL", "base_url")) + return SeedApi( + token=os.getenv("ENV_TOKEN", "token"), + base_url=os.getenv("TESTS_BASE_URL", "base_url"), + ) @pytest.fixture def async_client() -> AsyncSeedApi: - return AsyncSeedApi(token=os.getenv("ENV_TOKEN", "token"), base_url=os.getenv("TESTS_BASE_URL", "base_url")) + return AsyncSeedApi( + token=os.getenv("ENV_TOKEN", "token"), + base_url=os.getenv("TESTS_BASE_URL", "base_url"), + ) diff --git a/seed/python-sdk/imdb/tests/custom/test_client.py b/seed/python-sdk/imdb/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/python-sdk/imdb/tests/custom/test_client.py +++ b/seed/python-sdk/imdb/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/python-sdk/imdb/tests/test_imdb.py b/seed/python-sdk/imdb/tests/test_imdb.py index 8b31c3e485b..40a0425b138 100644 --- a/seed/python-sdk/imdb/tests/test_imdb.py +++ b/seed/python-sdk/imdb/tests/test_imdb.py @@ -1,9 +1,8 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedApi +from seed import AsyncSeedApi import typing - -from seed import AsyncSeedApi, SeedApi - from .utilities import validate_response diff --git a/seed/python-sdk/imdb/tests/utilities.py b/seed/python-sdk/imdb/tests/utilities.py index 13da208eb3a..e8f4472564c 100644 --- a/seed/python-sdk/imdb/tests/utilities.py +++ b/seed/python-sdk/imdb/tests/utilities.py @@ -3,11 +3,14 @@ import typing import uuid -import pydantic from dateutil import parser +import pydantic + -def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> typing.Any: +def cast_field( + json_expectation: typing.Any, type_expectation: typing.Any +) -> typing.Any: # Cast these specific types which come through as string and expect our # models to cast to the correct type. if type_expectation == "uuid": @@ -25,7 +28,9 @@ def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> ty return json_expectation -def validate_field(response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any) -> None: +def validate_field( + response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectation == "no_validate": return @@ -44,7 +49,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(entry_expectation, dict): is_container_of_complex_type = True validate_response( - response=response[idx], json_expectation=ex, type_expectations=entry_expectation + response=response[idx], + json_expectation=ex, + type_expectations=entry_expectation, ) else: cast_json_expectation.append(cast_field(ex, entry_expectation)) @@ -56,7 +63,10 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # if any of the values of the set have a type_expectation of a dict, we're assuming it's a pydantic # model and keeping it a list. if container_expectation != "set" or not any( - map(lambda value: isinstance(value, dict), list(contents_expectation.values())) + map( + lambda value: isinstance(value, dict), + list(contents_expectation.values()), + ) ): json_expectation = cast_field(json_expectation, container_expectation) elif isinstance(type_expectation, tuple): @@ -65,9 +75,15 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(contents_expectation, dict): json_expectation = { cast_field( - key, contents_expectation.get(idx)[0] if contents_expectation.get(idx) is not None else None # type: ignore + key, + contents_expectation.get(idx)[0] + if contents_expectation.get(idx) is not None + else None, # type: ignore ): cast_field( - value, contents_expectation.get(idx)[1] if contents_expectation.get(idx) is not None else None # type: ignore + value, + contents_expectation.get(idx)[1] + if contents_expectation.get(idx) is not None + else None, # type: ignore ) for idx, (key, value) in enumerate(json_expectation.items()) } @@ -86,7 +102,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # Arg type_expectations is a deeply nested structure that matches the response, but with the values replaced with the expected types -def validate_response(response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any) -> None: +def validate_response( + response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectations == "no_validate": return @@ -96,11 +114,17 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e and not isinstance(response, dict) and not issubclass(type(response), pydantic.BaseModel) ): - validate_field(response=response, json_expectation=json_expectation, type_expectation=type_expectations) + validate_field( + response=response, + json_expectation=json_expectation, + type_expectation=type_expectations, + ) return if isinstance(response, list): - assert len(response) == len(json_expectation), "Length mismatch, expected: {0}, Actual: {1}".format( + assert len(response) == len( + json_expectation + ), "Length mismatch, expected: {0}, Actual: {1}".format( len(response), len(json_expectation) ) content_expectation = type_expectations @@ -108,7 +132,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e content_expectation = type_expectations[1] for idx, item in enumerate(response): validate_response( - response=item, json_expectation=json_expectation[idx], type_expectations=content_expectation[idx] + response=item, + json_expectation=json_expectation[idx], + type_expectations=content_expectation[idx], ) else: response_json = response @@ -116,7 +142,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e response_json = response.dict(by_alias=True) for key, value in json_expectation.items(): - assert key in response_json, "Field {0} not found within the response object: {1}".format( + assert ( + key in response_json + ), "Field {0} not found within the response object: {1}".format( key, response_json ) @@ -128,11 +156,19 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e # Otherwise, we're just validating a single field that's a pydantic model. if isinstance(value, dict) and not isinstance(type_expectation, tuple): validate_response( - response=response_json[key], json_expectation=value, type_expectations=type_expectation + response=response_json[key], + json_expectation=value, + type_expectations=type_expectation, ) else: - validate_field(response=response_json[key], json_expectation=value, type_expectation=type_expectation) + validate_field( + response=response_json[key], + json_expectation=value, + type_expectation=type_expectation, + ) # Ensure there are no additional fields here either del response_json[key] - assert len(response_json) == 0, "Additional fields found, expected None: {0}".format(response_json) + assert ( + len(response_json) == 0 + ), "Additional fields found, expected None: {0}".format(response_json) diff --git a/seed/python-sdk/imdb/tests/utils/assets/models/__init__.py b/seed/python-sdk/imdb/tests/utils/assets/models/__init__.py index 2cf01263529..3a1c852e71e 100644 --- a/seed/python-sdk/imdb/tests/utils/assets/models/__init__.py +++ b/seed/python-sdk/imdb/tests/utils/assets/models/__init__.py @@ -5,7 +5,7 @@ from .circle import CircleParams from .object_with_defaults import ObjectWithDefaultsParams from .object_with_optional_field import ObjectWithOptionalFieldParams -from .shape import Shape_CircleParams, Shape_SquareParams, ShapeParams +from .shape import ShapeParams, Shape_CircleParams, Shape_SquareParams from .square import SquareParams from .undiscriminated_shape import UndiscriminatedShapeParams diff --git a/seed/python-sdk/imdb/tests/utils/assets/models/circle.py b/seed/python-sdk/imdb/tests/utils/assets/models/circle.py index af7a1bf8a8e..253f12d38b3 100644 --- a/seed/python-sdk/imdb/tests/utils/assets/models/circle.py +++ b/seed/python-sdk/imdb/tests/utils/assets/models/circle.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class CircleParams(typing_extensions.TypedDict): - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] diff --git a/seed/python-sdk/imdb/tests/utils/assets/models/object_with_optional_field.py b/seed/python-sdk/imdb/tests/utils/assets/models/object_with_optional_field.py index 3ad93d5f305..ebe7dc80547 100644 --- a/seed/python-sdk/imdb/tests/utils/assets/models/object_with_optional_field.py +++ b/seed/python-sdk/imdb/tests/utils/assets/models/object_with_optional_field.py @@ -7,8 +7,8 @@ import uuid import typing_extensions -from seed.core.serialization import FieldMetadata +from seed.core.serialization import FieldMetadata from .color import Color from .shape import ShapeParams from .undiscriminated_shape import UndiscriminatedShapeParams @@ -18,16 +18,30 @@ class ObjectWithOptionalFieldParams(typing_extensions.TypedDict): literal: typing.Literal["lit_one"] string: typing_extensions.NotRequired[str] integer: typing_extensions.NotRequired[int] - long_: typing_extensions.NotRequired[typing_extensions.Annotated[int, FieldMetadata(alias="long")]] + long_: typing_extensions.NotRequired[ + typing_extensions.Annotated[int, FieldMetadata(alias="long")] + ] double: typing_extensions.NotRequired[float] - bool_: typing_extensions.NotRequired[typing_extensions.Annotated[bool, FieldMetadata(alias="bool")]] + bool_: typing_extensions.NotRequired[ + typing_extensions.Annotated[bool, FieldMetadata(alias="bool")] + ] datetime: typing_extensions.NotRequired[dt.datetime] date: typing_extensions.NotRequired[dt.date] - uuid_: typing_extensions.NotRequired[typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")]] - base_64: typing_extensions.NotRequired[typing_extensions.Annotated[str, FieldMetadata(alias="base64")]] - list_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")]] - set_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")]] - map_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")]] + uuid_: typing_extensions.NotRequired[ + typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")] + ] + base_64: typing_extensions.NotRequired[ + typing_extensions.Annotated[str, FieldMetadata(alias="base64")] + ] + list_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")] + ] + set_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")] + ] + map_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")] + ] enum: typing_extensions.NotRequired[Color] union: typing_extensions.NotRequired[ShapeParams] second_union: typing_extensions.NotRequired[ShapeParams] diff --git a/seed/python-sdk/imdb/tests/utils/assets/models/shape.py b/seed/python-sdk/imdb/tests/utils/assets/models/shape.py index 2c33c877951..816ffc51bdc 100644 --- a/seed/python-sdk/imdb/tests/utils/assets/models/shape.py +++ b/seed/python-sdk/imdb/tests/utils/assets/models/shape.py @@ -7,6 +7,7 @@ import typing import typing_extensions + from seed.core.serialization import FieldMetadata @@ -15,13 +16,21 @@ class Base(typing_extensions.TypedDict): class Shape_CircleParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["circle"], FieldMetadata(alias="shapeType")] - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["circle"], FieldMetadata(alias="shapeType") + ] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] class Shape_SquareParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["square"], FieldMetadata(alias="shapeType")] - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["square"], FieldMetadata(alias="shapeType") + ] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] ShapeParams = typing.Union[Shape_CircleParams, Shape_SquareParams] diff --git a/seed/python-sdk/imdb/tests/utils/assets/models/square.py b/seed/python-sdk/imdb/tests/utils/assets/models/square.py index b9b7dd319bc..bcf08a723c5 100644 --- a/seed/python-sdk/imdb/tests/utils/assets/models/square.py +++ b/seed/python-sdk/imdb/tests/utils/assets/models/square.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class SquareParams(typing_extensions.TypedDict): - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] diff --git a/seed/python-sdk/imdb/tests/utils/test_http_client.py b/seed/python-sdk/imdb/tests/utils/test_http_client.py index edd11ca7afb..f5a874a75f3 100644 --- a/seed/python-sdk/imdb/tests/utils/test_http_client.py +++ b/seed/python-sdk/imdb/tests/utils/test_http_client.py @@ -9,12 +9,17 @@ def get_request_options() -> RequestOptions: def test_get_json_request_body() -> None: - json_body, data_body = get_request_body(json={"hello": "world"}, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json={"hello": "world"}, data=None, request_options=None, omit=None + ) assert json_body == {"hello": "world"} assert data_body is None json_body_extras, data_body_extras = get_request_body( - json={"goodbye": "world"}, data=None, request_options=get_request_options(), omit=None + json={"goodbye": "world"}, + data=None, + request_options=get_request_options(), + omit=None, ) assert json_body_extras == {"goodbye": "world", "see you": "later"} @@ -22,12 +27,17 @@ def test_get_json_request_body() -> None: def test_get_files_request_body() -> None: - json_body, data_body = get_request_body(json=None, data={"hello": "world"}, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data={"hello": "world"}, request_options=None, omit=None + ) assert data_body == {"hello": "world"} assert json_body is None json_body_extras, data_body_extras = get_request_body( - json=None, data={"goodbye": "world"}, request_options=get_request_options(), omit=None + json=None, + data={"goodbye": "world"}, + request_options=get_request_options(), + omit=None, ) assert data_body_extras == {"goodbye": "world", "see you": "later"} @@ -35,7 +45,9 @@ def test_get_files_request_body() -> None: def test_get_none_request_body() -> None: - json_body, data_body = get_request_body(json=None, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data=None, request_options=None, omit=None + ) assert data_body is None assert json_body is None diff --git a/seed/python-sdk/imdb/tests/utils/test_query_encoding.py b/seed/python-sdk/imdb/tests/utils/test_query_encoding.py index 247e1551b46..fbc8f402167 100644 --- a/seed/python-sdk/imdb/tests/utils/test_query_encoding.py +++ b/seed/python-sdk/imdb/tests/utils/test_query_encoding.py @@ -4,9 +4,15 @@ def test_query_encoding() -> None: - assert encode_query({"hello world": "hello world"}) == {"hello world": "hello world"} - assert encode_query({"hello_world": {"hello": "world"}}) == {"hello_world[hello]": "world"} - assert encode_query({"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"}) == { + assert encode_query({"hello world": "hello world"}) == { + "hello world": "hello world" + } + assert encode_query({"hello_world": {"hello": "world"}}) == { + "hello_world[hello]": "world" + } + assert encode_query( + {"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"} + ) == { "hello_world[hello][world]": "today", "hello_world[test]": "this", "hi": "there", diff --git a/seed/python-sdk/imdb/tests/utils/test_serialization.py b/seed/python-sdk/imdb/tests/utils/test_serialization.py index 58b1ed66e6d..5ca956916dd 100644 --- a/seed/python-sdk/imdb/tests/utils/test_serialization.py +++ b/seed/python-sdk/imdb/tests/utils/test_serialization.py @@ -1,10 +1,12 @@ # This file was auto-generated by Fern from our API Definition. -from typing import Any, List +from typing import List, Any -from seed.core.serialization import convert_and_respect_annotation_metadata +from seed.core.serialization import ( + convert_and_respect_annotation_metadata, +) +from .assets.models import ShapeParams, ObjectWithOptionalFieldParams -from .assets.models import ObjectWithOptionalFieldParams, ShapeParams UNION_TEST: ShapeParams = {"radius_measurement": 1.0, "shape_type": "circle", "id": "1"} UNION_TEST_CONVERTED = {"shapeType": "circle", "radiusMeasurement": 1.0, "id": "1"} @@ -18,20 +20,54 @@ def test_convert_and_respect_annotation_metadata() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) - assert converted == {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"} + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) + assert converted == { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + } def test_convert_and_respect_annotation_metadata_in_list() -> None: data: List[ObjectWithOptionalFieldParams] = [ - {"string": "string", "long_": 12345, "bool_": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long_": 67890, "list_": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long_": 12345, + "bool_": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long_": 67890, + "list_": [], + "literal": "lit_one", + "any": "any", + }, ] - converted = convert_and_respect_annotation_metadata(object_=data, annotation=List[ObjectWithOptionalFieldParams]) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=List[ObjectWithOptionalFieldParams] + ) assert converted == [ - {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long": 67890, "list": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long": 67890, + "list": [], + "literal": "lit_one", + "any": "any", + }, ] @@ -43,7 +79,9 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) assert converted == { "string": "string", @@ -55,12 +93,16 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: def test_convert_and_respect_annotation_metadata_in_union() -> None: - converted = convert_and_respect_annotation_metadata(object_=UNION_TEST, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=UNION_TEST, annotation=ShapeParams + ) assert converted == UNION_TEST_CONVERTED def test_convert_and_respect_annotation_metadata_with_empty_object() -> None: data: Any = {} - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ShapeParams + ) assert converted == data diff --git a/seed/python-sdk/literal/no-custom-config/pyproject.toml b/seed/python-sdk/literal/no-custom-config/pyproject.toml index 594ee777a56..0f51dabd03c 100644 --- a/seed/python-sdk/literal/no-custom-config/pyproject.toml +++ b/seed/python-sdk/literal/no-custom-config/pyproject.toml @@ -43,6 +43,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/python-sdk/literal/no-custom-config/src/seed/client.py b/seed/python-sdk/literal/no-custom-config/src/seed/client.py index 65036f6a25e..205ad56a526 100644 --- a/seed/python-sdk/literal/no-custom-config/src/seed/client.py +++ b/seed/python-sdk/literal/no-custom-config/src/seed/client.py @@ -1,15 +1,19 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from .headers.client import AsyncHeadersClient, HeadersClient -from .inlined.client import AsyncInlinedClient, InlinedClient -from .path.client import AsyncPathClient, PathClient -from .query.client import AsyncQueryClient, QueryClient -from .reference.client import AsyncReferenceClient, ReferenceClient +from .core.client_wrapper import SyncClientWrapper +from .headers.client import HeadersClient +from .inlined.client import InlinedClient +from .path.client import PathClient +from .query.client import QueryClient +from .reference.client import ReferenceClient +from .core.client_wrapper import AsyncClientWrapper +from .headers.client import AsyncHeadersClient +from .inlined.client import AsyncInlinedClient +from .path.client import AsyncPathClient +from .query.client import AsyncQueryClient +from .reference.client import AsyncReferenceClient class SeedLiteral: @@ -45,14 +49,18 @@ def __init__( base_url: str, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.Client] = None + httpx_client: typing.Optional[httpx.Client] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = SyncClientWrapper( base_url=base_url, httpx_client=httpx_client if httpx_client is not None - else httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.Client( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.Client(timeout=_defaulted_timeout), timeout=_defaulted_timeout, @@ -97,14 +105,18 @@ def __init__( base_url: str, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.AsyncClient] = None + httpx_client: typing.Optional[httpx.AsyncClient] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = AsyncClientWrapper( base_url=base_url, httpx_client=httpx_client if httpx_client is not None - else httpx.AsyncClient(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.AsyncClient( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.AsyncClient(timeout=_defaulted_timeout), timeout=_defaulted_timeout, diff --git a/seed/python-sdk/literal/no-custom-config/src/seed/core/api_error.py b/seed/python-sdk/literal/no-custom-config/src/seed/core/api_error.py index 2e9fc5431cd..da734b58068 100644 --- a/seed/python-sdk/literal/no-custom-config/src/seed/core/api_error.py +++ b/seed/python-sdk/literal/no-custom-config/src/seed/core/api_error.py @@ -7,7 +7,9 @@ class ApiError(Exception): status_code: typing.Optional[int] body: typing.Any - def __init__(self, *, status_code: typing.Optional[int] = None, body: typing.Any = None): + def __init__( + self, *, status_code: typing.Optional[int] = None, body: typing.Any = None + ): self.status_code = status_code self.body = body diff --git a/seed/python-sdk/literal/no-custom-config/src/seed/core/client_wrapper.py b/seed/python-sdk/literal/no-custom-config/src/seed/core/client_wrapper.py index 296afedfe49..3012779d99e 100644 --- a/seed/python-sdk/literal/no-custom-config/src/seed/core/client_wrapper.py +++ b/seed/python-sdk/literal/no-custom-config/src/seed/core/client_wrapper.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .http_client import AsyncHttpClient, HttpClient +from .http_client import HttpClient +from .http_client import AsyncHttpClient class BaseClientWrapper: @@ -30,7 +29,13 @@ def get_timeout(self) -> typing.Optional[float]: class SyncClientWrapper(BaseClientWrapper): - def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, httpx_client: httpx.Client): + def __init__( + self, + *, + base_url: str, + timeout: typing.Optional[float] = None, + httpx_client: httpx.Client, + ): super().__init__(base_url=base_url, timeout=timeout) self.httpx_client = HttpClient( httpx_client=httpx_client, @@ -41,7 +46,13 @@ def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, htt class AsyncClientWrapper(BaseClientWrapper): - def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, httpx_client: httpx.AsyncClient): + def __init__( + self, + *, + base_url: str, + timeout: typing.Optional[float] = None, + httpx_client: httpx.AsyncClient, + ): super().__init__(base_url=base_url, timeout=timeout) self.httpx_client = AsyncHttpClient( httpx_client=httpx_client, diff --git a/seed/python-sdk/literal/no-custom-config/src/seed/core/datetime_utils.py b/seed/python-sdk/literal/no-custom-config/src/seed/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/python-sdk/literal/no-custom-config/src/seed/core/datetime_utils.py +++ b/seed/python-sdk/literal/no-custom-config/src/seed/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/python-sdk/literal/no-custom-config/src/seed/core/file.py b/seed/python-sdk/literal/no-custom-config/src/seed/core/file.py index cb0d40bbbf3..6e0f92bfcb1 100644 --- a/seed/python-sdk/literal/no-custom-config/src/seed/core/file.py +++ b/seed/python-sdk/literal/no-custom-config/src/seed/core/file.py @@ -13,12 +13,17 @@ # (filename, file (or bytes), content_type) typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str]], # (filename, file (or bytes), content_type, headers) - typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str], typing.Mapping[str, str]], + typing.Tuple[ + typing.Optional[str], + FileContent, + typing.Optional[str], + typing.Mapping[str, str], + ], ] def convert_file_dict_to_httpx_tuples( - d: typing.Dict[str, typing.Union[File, typing.List[File]]] + d: typing.Dict[str, typing.Union[File, typing.List[File]]], ) -> typing.List[typing.Tuple[str, File]]: """ The format we use is a list of tuples, where the first element is the diff --git a/seed/python-sdk/literal/no-custom-config/src/seed/core/http_client.py b/seed/python-sdk/literal/no-custom-config/src/seed/core/http_client.py index 9333d8a7f15..091f71bc185 100644 --- a/seed/python-sdk/literal/no-custom-config/src/seed/core/http_client.py +++ b/seed/python-sdk/literal/no-custom-config/src/seed/core/http_client.py @@ -77,7 +77,9 @@ def _retry_timeout(response: httpx.Response, retries: int) -> float: return retry_after # Apply exponential backoff, capped at MAX_RETRY_DELAY_SECONDS. - retry_delay = min(INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS) + retry_delay = min( + INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS + ) # Add a randomness / jitter to the retry delay to avoid overwhelming the server with retries. timeout = retry_delay * (1 - 0.25 * random()) @@ -90,7 +92,8 @@ def _should_retry(response: httpx.Response) -> bool: def remove_omit_from_dict( - original: typing.Dict[str, typing.Optional[typing.Any]], omit: typing.Optional[typing.Any] + original: typing.Dict[str, typing.Optional[typing.Any]], + omit: typing.Optional[typing.Any], ) -> typing.Dict[str, typing.Any]: if omit is None: return original @@ -108,7 +111,8 @@ def maybe_filter_request_body( ) -> typing.Optional[typing.Any]: if data is None: return ( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else None ) @@ -118,7 +122,8 @@ def maybe_filter_request_body( data_content = { **(jsonable_encoder(remove_omit_from_dict(data, omit))), # type: ignore **( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else {} ), @@ -162,7 +167,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url def request( @@ -174,8 +181,12 @@ def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -184,11 +195,14 @@ def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) response = self.httpx_client.request( method=method, @@ -198,7 +212,11 @@ def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -209,7 +227,10 @@ def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -222,11 +243,15 @@ def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: time.sleep(_retry_timeout(response=response, retries=retries)) @@ -256,8 +281,12 @@ def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -266,11 +295,14 @@ def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) with self.httpx_client.stream( method=method, @@ -280,7 +312,11 @@ def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -291,7 +327,9 @@ def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -304,7 +342,9 @@ def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream @@ -327,7 +367,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url async def request( @@ -339,8 +381,12 @@ async def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -349,11 +395,14 @@ async def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) # Add the input to each of these and do None-safety checks response = await self.httpx_client.request( @@ -364,7 +413,11 @@ async def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -375,7 +428,10 @@ async def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -388,11 +444,15 @@ async def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: await asyncio.sleep(_retry_timeout(response=response, retries=retries)) @@ -421,8 +481,12 @@ async def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -431,11 +495,14 @@ async def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) async with self.httpx_client.stream( method=method, @@ -445,7 +512,11 @@ async def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -456,7 +527,9 @@ async def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -469,7 +542,9 @@ async def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream diff --git a/seed/python-sdk/literal/no-custom-config/src/seed/core/jsonable_encoder.py b/seed/python-sdk/literal/no-custom-config/src/seed/core/jsonable_encoder.py index d3fd328fd41..12a8b52fc22 100644 --- a/seed/python-sdk/literal/no-custom-config/src/seed/core/jsonable_encoder.py +++ b/seed/python-sdk/literal/no-custom-config/src/seed/core/jsonable_encoder.py @@ -19,13 +19,19 @@ import pydantic from .datetime_utils import serialize_datetime -from .pydantic_utilities import IS_PYDANTIC_V2, encode_by_type, to_jsonable_with_fallback +from .pydantic_utilities import ( + IS_PYDANTIC_V2, + encode_by_type, + to_jsonable_with_fallback, +) SetIntStr = Set[Union[int, str]] DictIntStrAny = Dict[Union[int, str], Any] -def jsonable_encoder(obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None) -> Any: +def jsonable_encoder( + obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None +) -> Any: custom_encoder = custom_encoder or {} if custom_encoder: if type(obj) in custom_encoder: diff --git a/seed/python-sdk/literal/no-custom-config/src/seed/core/pydantic_utilities.py b/seed/python-sdk/literal/no-custom-config/src/seed/core/pydantic_utilities.py index 170a563d6eb..c63935c32a2 100644 --- a/seed/python-sdk/literal/no-custom-config/src/seed/core/pydantic_utilities.py +++ b/seed/python-sdk/literal/no-custom-config/src/seed/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) # type: ignore # Pydantic v1 diff --git a/seed/python-sdk/literal/no-custom-config/src/seed/core/query_encoder.py b/seed/python-sdk/literal/no-custom-config/src/seed/core/query_encoder.py index 24076d72ee9..7cb98f52cd7 100644 --- a/seed/python-sdk/literal/no-custom-config/src/seed/core/query_encoder.py +++ b/seed/python-sdk/literal/no-custom-config/src/seed/core/query_encoder.py @@ -7,7 +7,9 @@ # Flattens dicts to be of the form {"key[subkey][subkey2]": value} where value is not a dict -def traverse_query_dict(dict_flat: Dict[str, Any], key_prefix: Optional[str] = None) -> Dict[str, Any]: +def traverse_query_dict( + dict_flat: Dict[str, Any], key_prefix: Optional[str] = None +) -> Dict[str, Any]: result = {} for k, v in dict_flat.items(): key = f"{key_prefix}[{k}]" if key_prefix is not None else k @@ -30,4 +32,8 @@ def single_query_encoder(query_key: str, query_value: Any) -> Dict[str, Any]: def encode_query(query: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: - return dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) if query is not None else None + return ( + dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) + if query is not None + else None + ) diff --git a/seed/python-sdk/literal/no-custom-config/src/seed/core/serialization.py b/seed/python-sdk/literal/no-custom-config/src/seed/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/python-sdk/literal/no-custom-config/src/seed/core/serialization.py +++ b/seed/python-sdk/literal/no-custom-config/src/seed/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/python-sdk/literal/no-custom-config/src/seed/headers/client.py b/seed/python-sdk/literal/no-custom-config/src/seed/headers/client.py index 190172e0bb8..57bf9dc122c 100644 --- a/seed/python-sdk/literal/no-custom-config/src/seed/headers/client.py +++ b/seed/python-sdk/literal/no-custom-config/src/seed/headers/client.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. import typing -from json.decoder import JSONDecodeError - -from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.pydantic_utilities import parse_obj_as +from ..core.client_wrapper import SyncClientWrapper from ..core.request_options import RequestOptions from ..types.send_response import SendResponse +from ..core.pydantic_utilities import parse_obj_as +from json.decoder import JSONDecodeError +from ..core.api_error import ApiError +from ..core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -17,7 +17,9 @@ class HeadersClient: def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper - def send(self, *, query: str, request_options: typing.Optional[RequestOptions] = None) -> SendResponse: + def send( + self, *, query: str, request_options: typing.Optional[RequestOptions] = None + ) -> SendResponse: """ Parameters ---------- @@ -44,14 +46,22 @@ def send(self, *, query: str, request_options: typing.Optional[RequestOptions] = _response = self._client_wrapper.httpx_client.request( "headers", method="POST", - json={"query": query}, - headers={"X-Endpoint-Version": "02-12-2024", "X-Async": "true"}, + json={ + "query": query, + }, + headers={ + "X-Endpoint-Version": "02-12-2024", + "X-Async": "true", + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(SendResponse, parse_obj_as(type_=SendResponse, object_=_response.json())) # type: ignore + return typing.cast( + SendResponse, + parse_obj_as(type_=SendResponse, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -62,7 +72,9 @@ class AsyncHeadersClient: def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper - async def send(self, *, query: str, request_options: typing.Optional[RequestOptions] = None) -> SendResponse: + async def send( + self, *, query: str, request_options: typing.Optional[RequestOptions] = None + ) -> SendResponse: """ Parameters ---------- @@ -97,14 +109,22 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( "headers", method="POST", - json={"query": query}, - headers={"X-Endpoint-Version": "02-12-2024", "X-Async": "true"}, + json={ + "query": query, + }, + headers={ + "X-Endpoint-Version": "02-12-2024", + "X-Async": "true", + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(SendResponse, parse_obj_as(type_=SendResponse, object_=_response.json())) # type: ignore + return typing.cast( + SendResponse, + parse_obj_as(type_=SendResponse, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/literal/no-custom-config/src/seed/inlined/client.py b/seed/python-sdk/literal/no-custom-config/src/seed/inlined/client.py index 2a467bce880..41a9d215bc2 100644 --- a/seed/python-sdk/literal/no-custom-config/src/seed/inlined/client.py +++ b/seed/python-sdk/literal/no-custom-config/src/seed/inlined/client.py @@ -1,14 +1,14 @@ # This file was auto-generated by Fern from our API Definition. import typing -from json.decoder import JSONDecodeError - -from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.pydantic_utilities import parse_obj_as +from ..core.client_wrapper import SyncClientWrapper +from .types.some_aliased_literal import SomeAliasedLiteral from ..core.request_options import RequestOptions from ..types.send_response import SendResponse -from .types.some_aliased_literal import SomeAliasedLiteral +from ..core.pydantic_utilities import parse_obj_as +from json.decoder import JSONDecodeError +from ..core.api_error import ApiError +from ..core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -25,7 +25,7 @@ def send( context: typing.Optional[typing.Literal["You're super wise"]] = OMIT, temperature: typing.Optional[float] = OMIT, maybe_context: typing.Optional[SomeAliasedLiteral] = OMIT, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> SendResponse: """ Parameters @@ -76,7 +76,10 @@ def send( ) try: if 200 <= _response.status_code < 300: - return typing.cast(SendResponse, parse_obj_as(type_=SendResponse, object_=_response.json())) # type: ignore + return typing.cast( + SendResponse, + parse_obj_as(type_=SendResponse, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -94,7 +97,7 @@ async def send( context: typing.Optional[typing.Literal["You're super wise"]] = OMIT, temperature: typing.Optional[float] = OMIT, maybe_context: typing.Optional[SomeAliasedLiteral] = OMIT, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> SendResponse: """ Parameters @@ -153,7 +156,10 @@ async def main() -> None: ) try: if 200 <= _response.status_code < 300: - return typing.cast(SendResponse, parse_obj_as(type_=SendResponse, object_=_response.json())) # type: ignore + return typing.cast( + SendResponse, + parse_obj_as(type_=SendResponse, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/literal/no-custom-config/src/seed/path/client.py b/seed/python-sdk/literal/no-custom-config/src/seed/path/client.py index 25af982550e..9fb92030ea3 100644 --- a/seed/python-sdk/literal/no-custom-config/src/seed/path/client.py +++ b/seed/python-sdk/literal/no-custom-config/src/seed/path/client.py @@ -1,20 +1,22 @@ # This file was auto-generated by Fern from our API Definition. +from ..core.client_wrapper import SyncClientWrapper import typing -from json.decoder import JSONDecodeError - -from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.pydantic_utilities import parse_obj_as from ..core.request_options import RequestOptions from ..types.send_response import SendResponse +from ..core.pydantic_utilities import parse_obj_as +from json.decoder import JSONDecodeError +from ..core.api_error import ApiError +from ..core.client_wrapper import AsyncClientWrapper class PathClient: def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper - def send(self, *, request_options: typing.Optional[RequestOptions] = None) -> SendResponse: + def send( + self, *, request_options: typing.Optional[RequestOptions] = None + ) -> SendResponse: """ Parameters ---------- @@ -35,11 +37,16 @@ def send(self, *, request_options: typing.Optional[RequestOptions] = None) -> Se client.path.send() """ _response = self._client_wrapper.httpx_client.request( - f"path/123", method="POST", request_options=request_options + f"path/123", + method="POST", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(SendResponse, parse_obj_as(type_=SendResponse, object_=_response.json())) # type: ignore + return typing.cast( + SendResponse, + parse_obj_as(type_=SendResponse, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -50,7 +57,9 @@ class AsyncPathClient: def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper - async def send(self, *, request_options: typing.Optional[RequestOptions] = None) -> SendResponse: + async def send( + self, *, request_options: typing.Optional[RequestOptions] = None + ) -> SendResponse: """ Parameters ---------- @@ -79,11 +88,16 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - f"path/123", method="POST", request_options=request_options + f"path/123", + method="POST", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(SendResponse, parse_obj_as(type_=SendResponse, object_=_response.json())) # type: ignore + return typing.cast( + SendResponse, + parse_obj_as(type_=SendResponse, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/literal/no-custom-config/src/seed/query/client.py b/seed/python-sdk/literal/no-custom-config/src/seed/query/client.py index 1ace903b1e0..0ff321b1029 100644 --- a/seed/python-sdk/literal/no-custom-config/src/seed/query/client.py +++ b/seed/python-sdk/literal/no-custom-config/src/seed/query/client.py @@ -1,20 +1,22 @@ # This file was auto-generated by Fern from our API Definition. +from ..core.client_wrapper import SyncClientWrapper import typing -from json.decoder import JSONDecodeError - -from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.pydantic_utilities import parse_obj_as from ..core.request_options import RequestOptions from ..types.send_response import SendResponse +from ..core.pydantic_utilities import parse_obj_as +from json.decoder import JSONDecodeError +from ..core.api_error import ApiError +from ..core.client_wrapper import AsyncClientWrapper class QueryClient: def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper - def send(self, *, query: str, request_options: typing.Optional[RequestOptions] = None) -> SendResponse: + def send( + self, *, query: str, request_options: typing.Optional[RequestOptions] = None + ) -> SendResponse: """ Parameters ---------- @@ -41,12 +43,19 @@ def send(self, *, query: str, request_options: typing.Optional[RequestOptions] = _response = self._client_wrapper.httpx_client.request( "query", method="POST", - params={"prompt": "You are a helpful assistant", "query": query, "stream": False}, + params={ + "prompt": "You are a helpful assistant", + "query": query, + "stream": False, + }, request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(SendResponse, parse_obj_as(type_=SendResponse, object_=_response.json())) # type: ignore + return typing.cast( + SendResponse, + parse_obj_as(type_=SendResponse, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -57,7 +66,9 @@ class AsyncQueryClient: def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper - async def send(self, *, query: str, request_options: typing.Optional[RequestOptions] = None) -> SendResponse: + async def send( + self, *, query: str, request_options: typing.Optional[RequestOptions] = None + ) -> SendResponse: """ Parameters ---------- @@ -92,12 +103,19 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( "query", method="POST", - params={"prompt": "You are a helpful assistant", "query": query, "stream": False}, + params={ + "prompt": "You are a helpful assistant", + "query": query, + "stream": False, + }, request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(SendResponse, parse_obj_as(type_=SendResponse, object_=_response.json())) # type: ignore + return typing.cast( + SendResponse, + parse_obj_as(type_=SendResponse, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/literal/no-custom-config/src/seed/reference/client.py b/seed/python-sdk/literal/no-custom-config/src/seed/reference/client.py index 2bf78090067..55074065bc6 100644 --- a/seed/python-sdk/literal/no-custom-config/src/seed/reference/client.py +++ b/seed/python-sdk/literal/no-custom-config/src/seed/reference/client.py @@ -1,14 +1,14 @@ # This file was auto-generated by Fern from our API Definition. import typing -from json.decoder import JSONDecodeError - -from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.pydantic_utilities import parse_obj_as +from ..core.client_wrapper import SyncClientWrapper +from .types.some_literal import SomeLiteral from ..core.request_options import RequestOptions from ..types.send_response import SendResponse -from .types.some_literal import SomeLiteral +from ..core.pydantic_utilities import parse_obj_as +from json.decoder import JSONDecodeError +from ..core.api_error import ApiError +from ..core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -23,7 +23,7 @@ def send( *, query: str, maybe_context: typing.Optional[SomeLiteral] = OMIT, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> SendResponse: """ Parameters @@ -65,7 +65,10 @@ def send( ) try: if 200 <= _response.status_code < 300: - return typing.cast(SendResponse, parse_obj_as(type_=SendResponse, object_=_response.json())) # type: ignore + return typing.cast( + SendResponse, + parse_obj_as(type_=SendResponse, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -81,7 +84,7 @@ async def send( *, query: str, maybe_context: typing.Optional[SomeLiteral] = OMIT, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> SendResponse: """ Parameters @@ -131,7 +134,10 @@ async def main() -> None: ) try: if 200 <= _response.status_code < 300: - return typing.cast(SendResponse, parse_obj_as(type_=SendResponse, object_=_response.json())) # type: ignore + return typing.cast( + SendResponse, + parse_obj_as(type_=SendResponse, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/literal/no-custom-config/src/seed/reference/types/send_request.py b/seed/python-sdk/literal/no-custom-config/src/seed/reference/types/send_request.py index 008ec105e31..ca54eb6bca1 100644 --- a/seed/python-sdk/literal/no-custom-config/src/seed/reference/types/send_request.py +++ b/seed/python-sdk/literal/no-custom-config/src/seed/reference/types/send_request.py @@ -1,22 +1,27 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .some_literal import SomeLiteral +import pydantic +from ...core.pydantic_utilities import IS_PYDANTIC_V2 class SendRequest(UniversalBaseModel): - prompt: typing.Literal["You are a helpful assistant"] = "You are a helpful assistant" + prompt: typing.Literal["You are a helpful assistant"] = ( + "You are a helpful assistant" + ) query: str stream: typing.Literal[False] = False context: SomeLiteral = "You're super wise" - maybe_context: typing.Optional[SomeLiteral] = pydantic.Field(alias="maybeContext", default=None) + maybe_context: typing.Optional[SomeLiteral] = pydantic.Field( + alias="maybeContext", default=None + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/literal/no-custom-config/src/seed/types/send_response.py b/seed/python-sdk/literal/no-custom-config/src/seed/types/send_response.py index 1db6b0e34de..6fdab63cac9 100644 --- a/seed/python-sdk/literal/no-custom-config/src/seed/types/send_response.py +++ b/seed/python-sdk/literal/no-custom-config/src/seed/types/send_response.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from ..core.pydantic_utilities import UniversalBaseModel import typing - +from ..core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class SendResponse(UniversalBaseModel): message: str @@ -13,7 +12,9 @@ class SendResponse(UniversalBaseModel): success: typing.Literal[True] = True if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/literal/no-custom-config/src/seed/version.py b/seed/python-sdk/literal/no-custom-config/src/seed/version.py index 1857ce2c069..476e813c9f3 100644 --- a/seed/python-sdk/literal/no-custom-config/src/seed/version.py +++ b/seed/python-sdk/literal/no-custom-config/src/seed/version.py @@ -1,4 +1,3 @@ - from importlib import metadata __version__ = metadata.version("fern_literal") diff --git a/seed/python-sdk/literal/no-custom-config/tests/conftest.py b/seed/python-sdk/literal/no-custom-config/tests/conftest.py index 1394c81144f..d0a97cf0652 100644 --- a/seed/python-sdk/literal/no-custom-config/tests/conftest.py +++ b/seed/python-sdk/literal/no-custom-config/tests/conftest.py @@ -1,9 +1,9 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedLiteral import os - import pytest -from seed import AsyncSeedLiteral, SeedLiteral +from seed import AsyncSeedLiteral @pytest.fixture diff --git a/seed/python-sdk/literal/no-custom-config/tests/custom/test_client.py b/seed/python-sdk/literal/no-custom-config/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/python-sdk/literal/no-custom-config/tests/custom/test_client.py +++ b/seed/python-sdk/literal/no-custom-config/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/python-sdk/literal/no-custom-config/tests/test_headers.py b/seed/python-sdk/literal/no-custom-config/tests/test_headers.py index d712980b74c..51861ae4d40 100644 --- a/seed/python-sdk/literal/no-custom-config/tests/test_headers.py +++ b/seed/python-sdk/literal/no-custom-config/tests/test_headers.py @@ -1,14 +1,17 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedLiteral +from seed import AsyncSeedLiteral import typing - -from seed import AsyncSeedLiteral, SeedLiteral - from .utilities import validate_response async def test_send(client: SeedLiteral, async_client: AsyncSeedLiteral) -> None: - expected_response: typing.Any = {"message": "The weather is sunny", "status": 200, "success": True} + expected_response: typing.Any = { + "message": "The weather is sunny", + "status": 200, + "success": True, + } expected_types: typing.Any = {"message": None, "status": "integer", "success": None} response = client.headers.send(query="What is the weather today") validate_response(response, expected_response, expected_types) diff --git a/seed/python-sdk/literal/no-custom-config/tests/test_inlined.py b/seed/python-sdk/literal/no-custom-config/tests/test_inlined.py index 47004f21dc0..e9457ef4acf 100644 --- a/seed/python-sdk/literal/no-custom-config/tests/test_inlined.py +++ b/seed/python-sdk/literal/no-custom-config/tests/test_inlined.py @@ -1,14 +1,17 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedLiteral +from seed import AsyncSeedLiteral import typing - -from seed import AsyncSeedLiteral, SeedLiteral - from .utilities import validate_response async def test_send(client: SeedLiteral, async_client: AsyncSeedLiteral) -> None: - expected_response: typing.Any = {"message": "The weather is sunny", "status": 200, "success": True} + expected_response: typing.Any = { + "message": "The weather is sunny", + "status": 200, + "success": True, + } expected_types: typing.Any = {"message": None, "status": "integer", "success": None} response = client.inlined.send( temperature=10.1, diff --git a/seed/python-sdk/literal/no-custom-config/tests/test_path.py b/seed/python-sdk/literal/no-custom-config/tests/test_path.py index 319940b6223..46ee07f53cc 100644 --- a/seed/python-sdk/literal/no-custom-config/tests/test_path.py +++ b/seed/python-sdk/literal/no-custom-config/tests/test_path.py @@ -1,14 +1,17 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedLiteral +from seed import AsyncSeedLiteral import typing - -from seed import AsyncSeedLiteral, SeedLiteral - from .utilities import validate_response async def test_send(client: SeedLiteral, async_client: AsyncSeedLiteral) -> None: - expected_response: typing.Any = {"message": "The weather is sunny", "status": 200, "success": True} + expected_response: typing.Any = { + "message": "The weather is sunny", + "status": 200, + "success": True, + } expected_types: typing.Any = {"message": None, "status": "integer", "success": None} response = client.path.send() validate_response(response, expected_response, expected_types) diff --git a/seed/python-sdk/literal/no-custom-config/tests/test_query.py b/seed/python-sdk/literal/no-custom-config/tests/test_query.py index 01431e45052..8997f23a10e 100644 --- a/seed/python-sdk/literal/no-custom-config/tests/test_query.py +++ b/seed/python-sdk/literal/no-custom-config/tests/test_query.py @@ -1,14 +1,17 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedLiteral +from seed import AsyncSeedLiteral import typing - -from seed import AsyncSeedLiteral, SeedLiteral - from .utilities import validate_response async def test_send(client: SeedLiteral, async_client: AsyncSeedLiteral) -> None: - expected_response: typing.Any = {"message": "The weather is sunny", "status": 200, "success": True} + expected_response: typing.Any = { + "message": "The weather is sunny", + "status": 200, + "success": True, + } expected_types: typing.Any = {"message": None, "status": "integer", "success": None} response = client.query.send(query="What is the weather today") validate_response(response, expected_response, expected_types) diff --git a/seed/python-sdk/literal/no-custom-config/tests/test_reference.py b/seed/python-sdk/literal/no-custom-config/tests/test_reference.py index ece749256d7..b74465ce828 100644 --- a/seed/python-sdk/literal/no-custom-config/tests/test_reference.py +++ b/seed/python-sdk/literal/no-custom-config/tests/test_reference.py @@ -1,17 +1,22 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedLiteral +from seed import AsyncSeedLiteral import typing - -from seed import AsyncSeedLiteral, SeedLiteral - from .utilities import validate_response async def test_send(client: SeedLiteral, async_client: AsyncSeedLiteral) -> None: - expected_response: typing.Any = {"message": "The weather is sunny", "status": 200, "success": True} + expected_response: typing.Any = { + "message": "The weather is sunny", + "status": 200, + "success": True, + } expected_types: typing.Any = {"message": None, "status": "integer", "success": None} response = client.reference.send(query="What is the weather today") validate_response(response, expected_response, expected_types) - async_response = await async_client.reference.send(query="What is the weather today") + async_response = await async_client.reference.send( + query="What is the weather today" + ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/literal/no-custom-config/tests/utilities.py b/seed/python-sdk/literal/no-custom-config/tests/utilities.py index 13da208eb3a..e8f4472564c 100644 --- a/seed/python-sdk/literal/no-custom-config/tests/utilities.py +++ b/seed/python-sdk/literal/no-custom-config/tests/utilities.py @@ -3,11 +3,14 @@ import typing import uuid -import pydantic from dateutil import parser +import pydantic + -def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> typing.Any: +def cast_field( + json_expectation: typing.Any, type_expectation: typing.Any +) -> typing.Any: # Cast these specific types which come through as string and expect our # models to cast to the correct type. if type_expectation == "uuid": @@ -25,7 +28,9 @@ def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> ty return json_expectation -def validate_field(response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any) -> None: +def validate_field( + response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectation == "no_validate": return @@ -44,7 +49,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(entry_expectation, dict): is_container_of_complex_type = True validate_response( - response=response[idx], json_expectation=ex, type_expectations=entry_expectation + response=response[idx], + json_expectation=ex, + type_expectations=entry_expectation, ) else: cast_json_expectation.append(cast_field(ex, entry_expectation)) @@ -56,7 +63,10 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # if any of the values of the set have a type_expectation of a dict, we're assuming it's a pydantic # model and keeping it a list. if container_expectation != "set" or not any( - map(lambda value: isinstance(value, dict), list(contents_expectation.values())) + map( + lambda value: isinstance(value, dict), + list(contents_expectation.values()), + ) ): json_expectation = cast_field(json_expectation, container_expectation) elif isinstance(type_expectation, tuple): @@ -65,9 +75,15 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(contents_expectation, dict): json_expectation = { cast_field( - key, contents_expectation.get(idx)[0] if contents_expectation.get(idx) is not None else None # type: ignore + key, + contents_expectation.get(idx)[0] + if contents_expectation.get(idx) is not None + else None, # type: ignore ): cast_field( - value, contents_expectation.get(idx)[1] if contents_expectation.get(idx) is not None else None # type: ignore + value, + contents_expectation.get(idx)[1] + if contents_expectation.get(idx) is not None + else None, # type: ignore ) for idx, (key, value) in enumerate(json_expectation.items()) } @@ -86,7 +102,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # Arg type_expectations is a deeply nested structure that matches the response, but with the values replaced with the expected types -def validate_response(response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any) -> None: +def validate_response( + response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectations == "no_validate": return @@ -96,11 +114,17 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e and not isinstance(response, dict) and not issubclass(type(response), pydantic.BaseModel) ): - validate_field(response=response, json_expectation=json_expectation, type_expectation=type_expectations) + validate_field( + response=response, + json_expectation=json_expectation, + type_expectation=type_expectations, + ) return if isinstance(response, list): - assert len(response) == len(json_expectation), "Length mismatch, expected: {0}, Actual: {1}".format( + assert len(response) == len( + json_expectation + ), "Length mismatch, expected: {0}, Actual: {1}".format( len(response), len(json_expectation) ) content_expectation = type_expectations @@ -108,7 +132,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e content_expectation = type_expectations[1] for idx, item in enumerate(response): validate_response( - response=item, json_expectation=json_expectation[idx], type_expectations=content_expectation[idx] + response=item, + json_expectation=json_expectation[idx], + type_expectations=content_expectation[idx], ) else: response_json = response @@ -116,7 +142,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e response_json = response.dict(by_alias=True) for key, value in json_expectation.items(): - assert key in response_json, "Field {0} not found within the response object: {1}".format( + assert ( + key in response_json + ), "Field {0} not found within the response object: {1}".format( key, response_json ) @@ -128,11 +156,19 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e # Otherwise, we're just validating a single field that's a pydantic model. if isinstance(value, dict) and not isinstance(type_expectation, tuple): validate_response( - response=response_json[key], json_expectation=value, type_expectations=type_expectation + response=response_json[key], + json_expectation=value, + type_expectations=type_expectation, ) else: - validate_field(response=response_json[key], json_expectation=value, type_expectation=type_expectation) + validate_field( + response=response_json[key], + json_expectation=value, + type_expectation=type_expectation, + ) # Ensure there are no additional fields here either del response_json[key] - assert len(response_json) == 0, "Additional fields found, expected None: {0}".format(response_json) + assert ( + len(response_json) == 0 + ), "Additional fields found, expected None: {0}".format(response_json) diff --git a/seed/python-sdk/literal/no-custom-config/tests/utils/assets/models/__init__.py b/seed/python-sdk/literal/no-custom-config/tests/utils/assets/models/__init__.py index 2cf01263529..3a1c852e71e 100644 --- a/seed/python-sdk/literal/no-custom-config/tests/utils/assets/models/__init__.py +++ b/seed/python-sdk/literal/no-custom-config/tests/utils/assets/models/__init__.py @@ -5,7 +5,7 @@ from .circle import CircleParams from .object_with_defaults import ObjectWithDefaultsParams from .object_with_optional_field import ObjectWithOptionalFieldParams -from .shape import Shape_CircleParams, Shape_SquareParams, ShapeParams +from .shape import ShapeParams, Shape_CircleParams, Shape_SquareParams from .square import SquareParams from .undiscriminated_shape import UndiscriminatedShapeParams diff --git a/seed/python-sdk/literal/no-custom-config/tests/utils/assets/models/circle.py b/seed/python-sdk/literal/no-custom-config/tests/utils/assets/models/circle.py index af7a1bf8a8e..253f12d38b3 100644 --- a/seed/python-sdk/literal/no-custom-config/tests/utils/assets/models/circle.py +++ b/seed/python-sdk/literal/no-custom-config/tests/utils/assets/models/circle.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class CircleParams(typing_extensions.TypedDict): - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] diff --git a/seed/python-sdk/literal/no-custom-config/tests/utils/assets/models/object_with_optional_field.py b/seed/python-sdk/literal/no-custom-config/tests/utils/assets/models/object_with_optional_field.py index 3ad93d5f305..ebe7dc80547 100644 --- a/seed/python-sdk/literal/no-custom-config/tests/utils/assets/models/object_with_optional_field.py +++ b/seed/python-sdk/literal/no-custom-config/tests/utils/assets/models/object_with_optional_field.py @@ -7,8 +7,8 @@ import uuid import typing_extensions -from seed.core.serialization import FieldMetadata +from seed.core.serialization import FieldMetadata from .color import Color from .shape import ShapeParams from .undiscriminated_shape import UndiscriminatedShapeParams @@ -18,16 +18,30 @@ class ObjectWithOptionalFieldParams(typing_extensions.TypedDict): literal: typing.Literal["lit_one"] string: typing_extensions.NotRequired[str] integer: typing_extensions.NotRequired[int] - long_: typing_extensions.NotRequired[typing_extensions.Annotated[int, FieldMetadata(alias="long")]] + long_: typing_extensions.NotRequired[ + typing_extensions.Annotated[int, FieldMetadata(alias="long")] + ] double: typing_extensions.NotRequired[float] - bool_: typing_extensions.NotRequired[typing_extensions.Annotated[bool, FieldMetadata(alias="bool")]] + bool_: typing_extensions.NotRequired[ + typing_extensions.Annotated[bool, FieldMetadata(alias="bool")] + ] datetime: typing_extensions.NotRequired[dt.datetime] date: typing_extensions.NotRequired[dt.date] - uuid_: typing_extensions.NotRequired[typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")]] - base_64: typing_extensions.NotRequired[typing_extensions.Annotated[str, FieldMetadata(alias="base64")]] - list_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")]] - set_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")]] - map_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")]] + uuid_: typing_extensions.NotRequired[ + typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")] + ] + base_64: typing_extensions.NotRequired[ + typing_extensions.Annotated[str, FieldMetadata(alias="base64")] + ] + list_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")] + ] + set_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")] + ] + map_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")] + ] enum: typing_extensions.NotRequired[Color] union: typing_extensions.NotRequired[ShapeParams] second_union: typing_extensions.NotRequired[ShapeParams] diff --git a/seed/python-sdk/literal/no-custom-config/tests/utils/assets/models/shape.py b/seed/python-sdk/literal/no-custom-config/tests/utils/assets/models/shape.py index 2c33c877951..816ffc51bdc 100644 --- a/seed/python-sdk/literal/no-custom-config/tests/utils/assets/models/shape.py +++ b/seed/python-sdk/literal/no-custom-config/tests/utils/assets/models/shape.py @@ -7,6 +7,7 @@ import typing import typing_extensions + from seed.core.serialization import FieldMetadata @@ -15,13 +16,21 @@ class Base(typing_extensions.TypedDict): class Shape_CircleParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["circle"], FieldMetadata(alias="shapeType")] - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["circle"], FieldMetadata(alias="shapeType") + ] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] class Shape_SquareParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["square"], FieldMetadata(alias="shapeType")] - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["square"], FieldMetadata(alias="shapeType") + ] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] ShapeParams = typing.Union[Shape_CircleParams, Shape_SquareParams] diff --git a/seed/python-sdk/literal/no-custom-config/tests/utils/assets/models/square.py b/seed/python-sdk/literal/no-custom-config/tests/utils/assets/models/square.py index b9b7dd319bc..bcf08a723c5 100644 --- a/seed/python-sdk/literal/no-custom-config/tests/utils/assets/models/square.py +++ b/seed/python-sdk/literal/no-custom-config/tests/utils/assets/models/square.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class SquareParams(typing_extensions.TypedDict): - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] diff --git a/seed/python-sdk/literal/no-custom-config/tests/utils/test_http_client.py b/seed/python-sdk/literal/no-custom-config/tests/utils/test_http_client.py index edd11ca7afb..f5a874a75f3 100644 --- a/seed/python-sdk/literal/no-custom-config/tests/utils/test_http_client.py +++ b/seed/python-sdk/literal/no-custom-config/tests/utils/test_http_client.py @@ -9,12 +9,17 @@ def get_request_options() -> RequestOptions: def test_get_json_request_body() -> None: - json_body, data_body = get_request_body(json={"hello": "world"}, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json={"hello": "world"}, data=None, request_options=None, omit=None + ) assert json_body == {"hello": "world"} assert data_body is None json_body_extras, data_body_extras = get_request_body( - json={"goodbye": "world"}, data=None, request_options=get_request_options(), omit=None + json={"goodbye": "world"}, + data=None, + request_options=get_request_options(), + omit=None, ) assert json_body_extras == {"goodbye": "world", "see you": "later"} @@ -22,12 +27,17 @@ def test_get_json_request_body() -> None: def test_get_files_request_body() -> None: - json_body, data_body = get_request_body(json=None, data={"hello": "world"}, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data={"hello": "world"}, request_options=None, omit=None + ) assert data_body == {"hello": "world"} assert json_body is None json_body_extras, data_body_extras = get_request_body( - json=None, data={"goodbye": "world"}, request_options=get_request_options(), omit=None + json=None, + data={"goodbye": "world"}, + request_options=get_request_options(), + omit=None, ) assert data_body_extras == {"goodbye": "world", "see you": "later"} @@ -35,7 +45,9 @@ def test_get_files_request_body() -> None: def test_get_none_request_body() -> None: - json_body, data_body = get_request_body(json=None, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data=None, request_options=None, omit=None + ) assert data_body is None assert json_body is None diff --git a/seed/python-sdk/literal/no-custom-config/tests/utils/test_query_encoding.py b/seed/python-sdk/literal/no-custom-config/tests/utils/test_query_encoding.py index 247e1551b46..fbc8f402167 100644 --- a/seed/python-sdk/literal/no-custom-config/tests/utils/test_query_encoding.py +++ b/seed/python-sdk/literal/no-custom-config/tests/utils/test_query_encoding.py @@ -4,9 +4,15 @@ def test_query_encoding() -> None: - assert encode_query({"hello world": "hello world"}) == {"hello world": "hello world"} - assert encode_query({"hello_world": {"hello": "world"}}) == {"hello_world[hello]": "world"} - assert encode_query({"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"}) == { + assert encode_query({"hello world": "hello world"}) == { + "hello world": "hello world" + } + assert encode_query({"hello_world": {"hello": "world"}}) == { + "hello_world[hello]": "world" + } + assert encode_query( + {"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"} + ) == { "hello_world[hello][world]": "today", "hello_world[test]": "this", "hi": "there", diff --git a/seed/python-sdk/literal/no-custom-config/tests/utils/test_serialization.py b/seed/python-sdk/literal/no-custom-config/tests/utils/test_serialization.py index 58b1ed66e6d..5ca956916dd 100644 --- a/seed/python-sdk/literal/no-custom-config/tests/utils/test_serialization.py +++ b/seed/python-sdk/literal/no-custom-config/tests/utils/test_serialization.py @@ -1,10 +1,12 @@ # This file was auto-generated by Fern from our API Definition. -from typing import Any, List +from typing import List, Any -from seed.core.serialization import convert_and_respect_annotation_metadata +from seed.core.serialization import ( + convert_and_respect_annotation_metadata, +) +from .assets.models import ShapeParams, ObjectWithOptionalFieldParams -from .assets.models import ObjectWithOptionalFieldParams, ShapeParams UNION_TEST: ShapeParams = {"radius_measurement": 1.0, "shape_type": "circle", "id": "1"} UNION_TEST_CONVERTED = {"shapeType": "circle", "radiusMeasurement": 1.0, "id": "1"} @@ -18,20 +20,54 @@ def test_convert_and_respect_annotation_metadata() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) - assert converted == {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"} + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) + assert converted == { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + } def test_convert_and_respect_annotation_metadata_in_list() -> None: data: List[ObjectWithOptionalFieldParams] = [ - {"string": "string", "long_": 12345, "bool_": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long_": 67890, "list_": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long_": 12345, + "bool_": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long_": 67890, + "list_": [], + "literal": "lit_one", + "any": "any", + }, ] - converted = convert_and_respect_annotation_metadata(object_=data, annotation=List[ObjectWithOptionalFieldParams]) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=List[ObjectWithOptionalFieldParams] + ) assert converted == [ - {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long": 67890, "list": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long": 67890, + "list": [], + "literal": "lit_one", + "any": "any", + }, ] @@ -43,7 +79,9 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) assert converted == { "string": "string", @@ -55,12 +93,16 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: def test_convert_and_respect_annotation_metadata_in_union() -> None: - converted = convert_and_respect_annotation_metadata(object_=UNION_TEST, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=UNION_TEST, annotation=ShapeParams + ) assert converted == UNION_TEST_CONVERTED def test_convert_and_respect_annotation_metadata_with_empty_object() -> None: data: Any = {} - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ShapeParams + ) assert converted == data diff --git a/seed/python-sdk/literal/use_typeddict_requests/pyproject.toml b/seed/python-sdk/literal/use_typeddict_requests/pyproject.toml index 594ee777a56..0f51dabd03c 100644 --- a/seed/python-sdk/literal/use_typeddict_requests/pyproject.toml +++ b/seed/python-sdk/literal/use_typeddict_requests/pyproject.toml @@ -43,6 +43,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/python-sdk/literal/use_typeddict_requests/src/seed/client.py b/seed/python-sdk/literal/use_typeddict_requests/src/seed/client.py index 65036f6a25e..205ad56a526 100644 --- a/seed/python-sdk/literal/use_typeddict_requests/src/seed/client.py +++ b/seed/python-sdk/literal/use_typeddict_requests/src/seed/client.py @@ -1,15 +1,19 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from .headers.client import AsyncHeadersClient, HeadersClient -from .inlined.client import AsyncInlinedClient, InlinedClient -from .path.client import AsyncPathClient, PathClient -from .query.client import AsyncQueryClient, QueryClient -from .reference.client import AsyncReferenceClient, ReferenceClient +from .core.client_wrapper import SyncClientWrapper +from .headers.client import HeadersClient +from .inlined.client import InlinedClient +from .path.client import PathClient +from .query.client import QueryClient +from .reference.client import ReferenceClient +from .core.client_wrapper import AsyncClientWrapper +from .headers.client import AsyncHeadersClient +from .inlined.client import AsyncInlinedClient +from .path.client import AsyncPathClient +from .query.client import AsyncQueryClient +from .reference.client import AsyncReferenceClient class SeedLiteral: @@ -45,14 +49,18 @@ def __init__( base_url: str, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.Client] = None + httpx_client: typing.Optional[httpx.Client] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = SyncClientWrapper( base_url=base_url, httpx_client=httpx_client if httpx_client is not None - else httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.Client( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.Client(timeout=_defaulted_timeout), timeout=_defaulted_timeout, @@ -97,14 +105,18 @@ def __init__( base_url: str, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.AsyncClient] = None + httpx_client: typing.Optional[httpx.AsyncClient] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = AsyncClientWrapper( base_url=base_url, httpx_client=httpx_client if httpx_client is not None - else httpx.AsyncClient(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.AsyncClient( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.AsyncClient(timeout=_defaulted_timeout), timeout=_defaulted_timeout, diff --git a/seed/python-sdk/literal/use_typeddict_requests/src/seed/core/api_error.py b/seed/python-sdk/literal/use_typeddict_requests/src/seed/core/api_error.py index 2e9fc5431cd..da734b58068 100644 --- a/seed/python-sdk/literal/use_typeddict_requests/src/seed/core/api_error.py +++ b/seed/python-sdk/literal/use_typeddict_requests/src/seed/core/api_error.py @@ -7,7 +7,9 @@ class ApiError(Exception): status_code: typing.Optional[int] body: typing.Any - def __init__(self, *, status_code: typing.Optional[int] = None, body: typing.Any = None): + def __init__( + self, *, status_code: typing.Optional[int] = None, body: typing.Any = None + ): self.status_code = status_code self.body = body diff --git a/seed/python-sdk/literal/use_typeddict_requests/src/seed/core/client_wrapper.py b/seed/python-sdk/literal/use_typeddict_requests/src/seed/core/client_wrapper.py index 296afedfe49..3012779d99e 100644 --- a/seed/python-sdk/literal/use_typeddict_requests/src/seed/core/client_wrapper.py +++ b/seed/python-sdk/literal/use_typeddict_requests/src/seed/core/client_wrapper.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .http_client import AsyncHttpClient, HttpClient +from .http_client import HttpClient +from .http_client import AsyncHttpClient class BaseClientWrapper: @@ -30,7 +29,13 @@ def get_timeout(self) -> typing.Optional[float]: class SyncClientWrapper(BaseClientWrapper): - def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, httpx_client: httpx.Client): + def __init__( + self, + *, + base_url: str, + timeout: typing.Optional[float] = None, + httpx_client: httpx.Client, + ): super().__init__(base_url=base_url, timeout=timeout) self.httpx_client = HttpClient( httpx_client=httpx_client, @@ -41,7 +46,13 @@ def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, htt class AsyncClientWrapper(BaseClientWrapper): - def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, httpx_client: httpx.AsyncClient): + def __init__( + self, + *, + base_url: str, + timeout: typing.Optional[float] = None, + httpx_client: httpx.AsyncClient, + ): super().__init__(base_url=base_url, timeout=timeout) self.httpx_client = AsyncHttpClient( httpx_client=httpx_client, diff --git a/seed/python-sdk/literal/use_typeddict_requests/src/seed/core/datetime_utils.py b/seed/python-sdk/literal/use_typeddict_requests/src/seed/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/python-sdk/literal/use_typeddict_requests/src/seed/core/datetime_utils.py +++ b/seed/python-sdk/literal/use_typeddict_requests/src/seed/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/python-sdk/literal/use_typeddict_requests/src/seed/core/file.py b/seed/python-sdk/literal/use_typeddict_requests/src/seed/core/file.py index cb0d40bbbf3..6e0f92bfcb1 100644 --- a/seed/python-sdk/literal/use_typeddict_requests/src/seed/core/file.py +++ b/seed/python-sdk/literal/use_typeddict_requests/src/seed/core/file.py @@ -13,12 +13,17 @@ # (filename, file (or bytes), content_type) typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str]], # (filename, file (or bytes), content_type, headers) - typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str], typing.Mapping[str, str]], + typing.Tuple[ + typing.Optional[str], + FileContent, + typing.Optional[str], + typing.Mapping[str, str], + ], ] def convert_file_dict_to_httpx_tuples( - d: typing.Dict[str, typing.Union[File, typing.List[File]]] + d: typing.Dict[str, typing.Union[File, typing.List[File]]], ) -> typing.List[typing.Tuple[str, File]]: """ The format we use is a list of tuples, where the first element is the diff --git a/seed/python-sdk/literal/use_typeddict_requests/src/seed/core/http_client.py b/seed/python-sdk/literal/use_typeddict_requests/src/seed/core/http_client.py index 9333d8a7f15..091f71bc185 100644 --- a/seed/python-sdk/literal/use_typeddict_requests/src/seed/core/http_client.py +++ b/seed/python-sdk/literal/use_typeddict_requests/src/seed/core/http_client.py @@ -77,7 +77,9 @@ def _retry_timeout(response: httpx.Response, retries: int) -> float: return retry_after # Apply exponential backoff, capped at MAX_RETRY_DELAY_SECONDS. - retry_delay = min(INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS) + retry_delay = min( + INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS + ) # Add a randomness / jitter to the retry delay to avoid overwhelming the server with retries. timeout = retry_delay * (1 - 0.25 * random()) @@ -90,7 +92,8 @@ def _should_retry(response: httpx.Response) -> bool: def remove_omit_from_dict( - original: typing.Dict[str, typing.Optional[typing.Any]], omit: typing.Optional[typing.Any] + original: typing.Dict[str, typing.Optional[typing.Any]], + omit: typing.Optional[typing.Any], ) -> typing.Dict[str, typing.Any]: if omit is None: return original @@ -108,7 +111,8 @@ def maybe_filter_request_body( ) -> typing.Optional[typing.Any]: if data is None: return ( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else None ) @@ -118,7 +122,8 @@ def maybe_filter_request_body( data_content = { **(jsonable_encoder(remove_omit_from_dict(data, omit))), # type: ignore **( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else {} ), @@ -162,7 +167,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url def request( @@ -174,8 +181,12 @@ def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -184,11 +195,14 @@ def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) response = self.httpx_client.request( method=method, @@ -198,7 +212,11 @@ def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -209,7 +227,10 @@ def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -222,11 +243,15 @@ def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: time.sleep(_retry_timeout(response=response, retries=retries)) @@ -256,8 +281,12 @@ def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -266,11 +295,14 @@ def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) with self.httpx_client.stream( method=method, @@ -280,7 +312,11 @@ def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -291,7 +327,9 @@ def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -304,7 +342,9 @@ def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream @@ -327,7 +367,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url async def request( @@ -339,8 +381,12 @@ async def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -349,11 +395,14 @@ async def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) # Add the input to each of these and do None-safety checks response = await self.httpx_client.request( @@ -364,7 +413,11 @@ async def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -375,7 +428,10 @@ async def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -388,11 +444,15 @@ async def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: await asyncio.sleep(_retry_timeout(response=response, retries=retries)) @@ -421,8 +481,12 @@ async def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -431,11 +495,14 @@ async def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) async with self.httpx_client.stream( method=method, @@ -445,7 +512,11 @@ async def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -456,7 +527,9 @@ async def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -469,7 +542,9 @@ async def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream diff --git a/seed/python-sdk/literal/use_typeddict_requests/src/seed/core/jsonable_encoder.py b/seed/python-sdk/literal/use_typeddict_requests/src/seed/core/jsonable_encoder.py index d3fd328fd41..12a8b52fc22 100644 --- a/seed/python-sdk/literal/use_typeddict_requests/src/seed/core/jsonable_encoder.py +++ b/seed/python-sdk/literal/use_typeddict_requests/src/seed/core/jsonable_encoder.py @@ -19,13 +19,19 @@ import pydantic from .datetime_utils import serialize_datetime -from .pydantic_utilities import IS_PYDANTIC_V2, encode_by_type, to_jsonable_with_fallback +from .pydantic_utilities import ( + IS_PYDANTIC_V2, + encode_by_type, + to_jsonable_with_fallback, +) SetIntStr = Set[Union[int, str]] DictIntStrAny = Dict[Union[int, str], Any] -def jsonable_encoder(obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None) -> Any: +def jsonable_encoder( + obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None +) -> Any: custom_encoder = custom_encoder or {} if custom_encoder: if type(obj) in custom_encoder: diff --git a/seed/python-sdk/literal/use_typeddict_requests/src/seed/core/pydantic_utilities.py b/seed/python-sdk/literal/use_typeddict_requests/src/seed/core/pydantic_utilities.py index 170a563d6eb..c63935c32a2 100644 --- a/seed/python-sdk/literal/use_typeddict_requests/src/seed/core/pydantic_utilities.py +++ b/seed/python-sdk/literal/use_typeddict_requests/src/seed/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) # type: ignore # Pydantic v1 diff --git a/seed/python-sdk/literal/use_typeddict_requests/src/seed/core/query_encoder.py b/seed/python-sdk/literal/use_typeddict_requests/src/seed/core/query_encoder.py index 24076d72ee9..7cb98f52cd7 100644 --- a/seed/python-sdk/literal/use_typeddict_requests/src/seed/core/query_encoder.py +++ b/seed/python-sdk/literal/use_typeddict_requests/src/seed/core/query_encoder.py @@ -7,7 +7,9 @@ # Flattens dicts to be of the form {"key[subkey][subkey2]": value} where value is not a dict -def traverse_query_dict(dict_flat: Dict[str, Any], key_prefix: Optional[str] = None) -> Dict[str, Any]: +def traverse_query_dict( + dict_flat: Dict[str, Any], key_prefix: Optional[str] = None +) -> Dict[str, Any]: result = {} for k, v in dict_flat.items(): key = f"{key_prefix}[{k}]" if key_prefix is not None else k @@ -30,4 +32,8 @@ def single_query_encoder(query_key: str, query_value: Any) -> Dict[str, Any]: def encode_query(query: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: - return dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) if query is not None else None + return ( + dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) + if query is not None + else None + ) diff --git a/seed/python-sdk/literal/use_typeddict_requests/src/seed/core/serialization.py b/seed/python-sdk/literal/use_typeddict_requests/src/seed/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/python-sdk/literal/use_typeddict_requests/src/seed/core/serialization.py +++ b/seed/python-sdk/literal/use_typeddict_requests/src/seed/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/python-sdk/literal/use_typeddict_requests/src/seed/headers/client.py b/seed/python-sdk/literal/use_typeddict_requests/src/seed/headers/client.py index 190172e0bb8..57bf9dc122c 100644 --- a/seed/python-sdk/literal/use_typeddict_requests/src/seed/headers/client.py +++ b/seed/python-sdk/literal/use_typeddict_requests/src/seed/headers/client.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. import typing -from json.decoder import JSONDecodeError - -from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.pydantic_utilities import parse_obj_as +from ..core.client_wrapper import SyncClientWrapper from ..core.request_options import RequestOptions from ..types.send_response import SendResponse +from ..core.pydantic_utilities import parse_obj_as +from json.decoder import JSONDecodeError +from ..core.api_error import ApiError +from ..core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -17,7 +17,9 @@ class HeadersClient: def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper - def send(self, *, query: str, request_options: typing.Optional[RequestOptions] = None) -> SendResponse: + def send( + self, *, query: str, request_options: typing.Optional[RequestOptions] = None + ) -> SendResponse: """ Parameters ---------- @@ -44,14 +46,22 @@ def send(self, *, query: str, request_options: typing.Optional[RequestOptions] = _response = self._client_wrapper.httpx_client.request( "headers", method="POST", - json={"query": query}, - headers={"X-Endpoint-Version": "02-12-2024", "X-Async": "true"}, + json={ + "query": query, + }, + headers={ + "X-Endpoint-Version": "02-12-2024", + "X-Async": "true", + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(SendResponse, parse_obj_as(type_=SendResponse, object_=_response.json())) # type: ignore + return typing.cast( + SendResponse, + parse_obj_as(type_=SendResponse, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -62,7 +72,9 @@ class AsyncHeadersClient: def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper - async def send(self, *, query: str, request_options: typing.Optional[RequestOptions] = None) -> SendResponse: + async def send( + self, *, query: str, request_options: typing.Optional[RequestOptions] = None + ) -> SendResponse: """ Parameters ---------- @@ -97,14 +109,22 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( "headers", method="POST", - json={"query": query}, - headers={"X-Endpoint-Version": "02-12-2024", "X-Async": "true"}, + json={ + "query": query, + }, + headers={ + "X-Endpoint-Version": "02-12-2024", + "X-Async": "true", + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(SendResponse, parse_obj_as(type_=SendResponse, object_=_response.json())) # type: ignore + return typing.cast( + SendResponse, + parse_obj_as(type_=SendResponse, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/literal/use_typeddict_requests/src/seed/inlined/client.py b/seed/python-sdk/literal/use_typeddict_requests/src/seed/inlined/client.py index 2a467bce880..41a9d215bc2 100644 --- a/seed/python-sdk/literal/use_typeddict_requests/src/seed/inlined/client.py +++ b/seed/python-sdk/literal/use_typeddict_requests/src/seed/inlined/client.py @@ -1,14 +1,14 @@ # This file was auto-generated by Fern from our API Definition. import typing -from json.decoder import JSONDecodeError - -from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.pydantic_utilities import parse_obj_as +from ..core.client_wrapper import SyncClientWrapper +from .types.some_aliased_literal import SomeAliasedLiteral from ..core.request_options import RequestOptions from ..types.send_response import SendResponse -from .types.some_aliased_literal import SomeAliasedLiteral +from ..core.pydantic_utilities import parse_obj_as +from json.decoder import JSONDecodeError +from ..core.api_error import ApiError +from ..core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -25,7 +25,7 @@ def send( context: typing.Optional[typing.Literal["You're super wise"]] = OMIT, temperature: typing.Optional[float] = OMIT, maybe_context: typing.Optional[SomeAliasedLiteral] = OMIT, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> SendResponse: """ Parameters @@ -76,7 +76,10 @@ def send( ) try: if 200 <= _response.status_code < 300: - return typing.cast(SendResponse, parse_obj_as(type_=SendResponse, object_=_response.json())) # type: ignore + return typing.cast( + SendResponse, + parse_obj_as(type_=SendResponse, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -94,7 +97,7 @@ async def send( context: typing.Optional[typing.Literal["You're super wise"]] = OMIT, temperature: typing.Optional[float] = OMIT, maybe_context: typing.Optional[SomeAliasedLiteral] = OMIT, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> SendResponse: """ Parameters @@ -153,7 +156,10 @@ async def main() -> None: ) try: if 200 <= _response.status_code < 300: - return typing.cast(SendResponse, parse_obj_as(type_=SendResponse, object_=_response.json())) # type: ignore + return typing.cast( + SendResponse, + parse_obj_as(type_=SendResponse, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/literal/use_typeddict_requests/src/seed/path/client.py b/seed/python-sdk/literal/use_typeddict_requests/src/seed/path/client.py index 25af982550e..9fb92030ea3 100644 --- a/seed/python-sdk/literal/use_typeddict_requests/src/seed/path/client.py +++ b/seed/python-sdk/literal/use_typeddict_requests/src/seed/path/client.py @@ -1,20 +1,22 @@ # This file was auto-generated by Fern from our API Definition. +from ..core.client_wrapper import SyncClientWrapper import typing -from json.decoder import JSONDecodeError - -from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.pydantic_utilities import parse_obj_as from ..core.request_options import RequestOptions from ..types.send_response import SendResponse +from ..core.pydantic_utilities import parse_obj_as +from json.decoder import JSONDecodeError +from ..core.api_error import ApiError +from ..core.client_wrapper import AsyncClientWrapper class PathClient: def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper - def send(self, *, request_options: typing.Optional[RequestOptions] = None) -> SendResponse: + def send( + self, *, request_options: typing.Optional[RequestOptions] = None + ) -> SendResponse: """ Parameters ---------- @@ -35,11 +37,16 @@ def send(self, *, request_options: typing.Optional[RequestOptions] = None) -> Se client.path.send() """ _response = self._client_wrapper.httpx_client.request( - f"path/123", method="POST", request_options=request_options + f"path/123", + method="POST", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(SendResponse, parse_obj_as(type_=SendResponse, object_=_response.json())) # type: ignore + return typing.cast( + SendResponse, + parse_obj_as(type_=SendResponse, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -50,7 +57,9 @@ class AsyncPathClient: def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper - async def send(self, *, request_options: typing.Optional[RequestOptions] = None) -> SendResponse: + async def send( + self, *, request_options: typing.Optional[RequestOptions] = None + ) -> SendResponse: """ Parameters ---------- @@ -79,11 +88,16 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - f"path/123", method="POST", request_options=request_options + f"path/123", + method="POST", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(SendResponse, parse_obj_as(type_=SendResponse, object_=_response.json())) # type: ignore + return typing.cast( + SendResponse, + parse_obj_as(type_=SendResponse, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/literal/use_typeddict_requests/src/seed/query/client.py b/seed/python-sdk/literal/use_typeddict_requests/src/seed/query/client.py index 1ace903b1e0..0ff321b1029 100644 --- a/seed/python-sdk/literal/use_typeddict_requests/src/seed/query/client.py +++ b/seed/python-sdk/literal/use_typeddict_requests/src/seed/query/client.py @@ -1,20 +1,22 @@ # This file was auto-generated by Fern from our API Definition. +from ..core.client_wrapper import SyncClientWrapper import typing -from json.decoder import JSONDecodeError - -from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.pydantic_utilities import parse_obj_as from ..core.request_options import RequestOptions from ..types.send_response import SendResponse +from ..core.pydantic_utilities import parse_obj_as +from json.decoder import JSONDecodeError +from ..core.api_error import ApiError +from ..core.client_wrapper import AsyncClientWrapper class QueryClient: def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper - def send(self, *, query: str, request_options: typing.Optional[RequestOptions] = None) -> SendResponse: + def send( + self, *, query: str, request_options: typing.Optional[RequestOptions] = None + ) -> SendResponse: """ Parameters ---------- @@ -41,12 +43,19 @@ def send(self, *, query: str, request_options: typing.Optional[RequestOptions] = _response = self._client_wrapper.httpx_client.request( "query", method="POST", - params={"prompt": "You are a helpful assistant", "query": query, "stream": False}, + params={ + "prompt": "You are a helpful assistant", + "query": query, + "stream": False, + }, request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(SendResponse, parse_obj_as(type_=SendResponse, object_=_response.json())) # type: ignore + return typing.cast( + SendResponse, + parse_obj_as(type_=SendResponse, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -57,7 +66,9 @@ class AsyncQueryClient: def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper - async def send(self, *, query: str, request_options: typing.Optional[RequestOptions] = None) -> SendResponse: + async def send( + self, *, query: str, request_options: typing.Optional[RequestOptions] = None + ) -> SendResponse: """ Parameters ---------- @@ -92,12 +103,19 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( "query", method="POST", - params={"prompt": "You are a helpful assistant", "query": query, "stream": False}, + params={ + "prompt": "You are a helpful assistant", + "query": query, + "stream": False, + }, request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(SendResponse, parse_obj_as(type_=SendResponse, object_=_response.json())) # type: ignore + return typing.cast( + SendResponse, + parse_obj_as(type_=SendResponse, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/literal/use_typeddict_requests/src/seed/reference/client.py b/seed/python-sdk/literal/use_typeddict_requests/src/seed/reference/client.py index 2bf78090067..55074065bc6 100644 --- a/seed/python-sdk/literal/use_typeddict_requests/src/seed/reference/client.py +++ b/seed/python-sdk/literal/use_typeddict_requests/src/seed/reference/client.py @@ -1,14 +1,14 @@ # This file was auto-generated by Fern from our API Definition. import typing -from json.decoder import JSONDecodeError - -from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.pydantic_utilities import parse_obj_as +from ..core.client_wrapper import SyncClientWrapper +from .types.some_literal import SomeLiteral from ..core.request_options import RequestOptions from ..types.send_response import SendResponse -from .types.some_literal import SomeLiteral +from ..core.pydantic_utilities import parse_obj_as +from json.decoder import JSONDecodeError +from ..core.api_error import ApiError +from ..core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -23,7 +23,7 @@ def send( *, query: str, maybe_context: typing.Optional[SomeLiteral] = OMIT, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> SendResponse: """ Parameters @@ -65,7 +65,10 @@ def send( ) try: if 200 <= _response.status_code < 300: - return typing.cast(SendResponse, parse_obj_as(type_=SendResponse, object_=_response.json())) # type: ignore + return typing.cast( + SendResponse, + parse_obj_as(type_=SendResponse, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -81,7 +84,7 @@ async def send( *, query: str, maybe_context: typing.Optional[SomeLiteral] = OMIT, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> SendResponse: """ Parameters @@ -131,7 +134,10 @@ async def main() -> None: ) try: if 200 <= _response.status_code < 300: - return typing.cast(SendResponse, parse_obj_as(type_=SendResponse, object_=_response.json())) # type: ignore + return typing.cast( + SendResponse, + parse_obj_as(type_=SendResponse, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/literal/use_typeddict_requests/src/seed/reference/requests/send_request.py b/seed/python-sdk/literal/use_typeddict_requests/src/seed/reference/requests/send_request.py index a0690112471..66db996c744 100644 --- a/seed/python-sdk/literal/use_typeddict_requests/src/seed/reference/requests/send_request.py +++ b/seed/python-sdk/literal/use_typeddict_requests/src/seed/reference/requests/send_request.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +import typing_extensions import typing - +from ..types.some_literal import SomeLiteral import typing_extensions - from ...core.serialization import FieldMetadata -from ..types.some_literal import SomeLiteral class SendRequestParams(typing_extensions.TypedDict): diff --git a/seed/python-sdk/literal/use_typeddict_requests/src/seed/reference/types/send_request.py b/seed/python-sdk/literal/use_typeddict_requests/src/seed/reference/types/send_request.py index 008ec105e31..ca54eb6bca1 100644 --- a/seed/python-sdk/literal/use_typeddict_requests/src/seed/reference/types/send_request.py +++ b/seed/python-sdk/literal/use_typeddict_requests/src/seed/reference/types/send_request.py @@ -1,22 +1,27 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .some_literal import SomeLiteral +import pydantic +from ...core.pydantic_utilities import IS_PYDANTIC_V2 class SendRequest(UniversalBaseModel): - prompt: typing.Literal["You are a helpful assistant"] = "You are a helpful assistant" + prompt: typing.Literal["You are a helpful assistant"] = ( + "You are a helpful assistant" + ) query: str stream: typing.Literal[False] = False context: SomeLiteral = "You're super wise" - maybe_context: typing.Optional[SomeLiteral] = pydantic.Field(alias="maybeContext", default=None) + maybe_context: typing.Optional[SomeLiteral] = pydantic.Field( + alias="maybeContext", default=None + ) if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/literal/use_typeddict_requests/src/seed/requests/send_response.py b/seed/python-sdk/literal/use_typeddict_requests/src/seed/requests/send_response.py index 0580389d6fb..6ddd0cb4f94 100644 --- a/seed/python-sdk/literal/use_typeddict_requests/src/seed/requests/send_response.py +++ b/seed/python-sdk/literal/use_typeddict_requests/src/seed/requests/send_response.py @@ -1,8 +1,7 @@ # This file was auto-generated by Fern from our API Definition. -import typing - import typing_extensions +import typing class SendResponseParams(typing_extensions.TypedDict): diff --git a/seed/python-sdk/literal/use_typeddict_requests/src/seed/types/send_response.py b/seed/python-sdk/literal/use_typeddict_requests/src/seed/types/send_response.py index 1db6b0e34de..6fdab63cac9 100644 --- a/seed/python-sdk/literal/use_typeddict_requests/src/seed/types/send_response.py +++ b/seed/python-sdk/literal/use_typeddict_requests/src/seed/types/send_response.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from ..core.pydantic_utilities import UniversalBaseModel import typing - +from ..core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class SendResponse(UniversalBaseModel): message: str @@ -13,7 +12,9 @@ class SendResponse(UniversalBaseModel): success: typing.Literal[True] = True if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/literal/use_typeddict_requests/src/seed/version.py b/seed/python-sdk/literal/use_typeddict_requests/src/seed/version.py index 1857ce2c069..476e813c9f3 100644 --- a/seed/python-sdk/literal/use_typeddict_requests/src/seed/version.py +++ b/seed/python-sdk/literal/use_typeddict_requests/src/seed/version.py @@ -1,4 +1,3 @@ - from importlib import metadata __version__ = metadata.version("fern_literal") diff --git a/seed/python-sdk/literal/use_typeddict_requests/tests/conftest.py b/seed/python-sdk/literal/use_typeddict_requests/tests/conftest.py index 1394c81144f..d0a97cf0652 100644 --- a/seed/python-sdk/literal/use_typeddict_requests/tests/conftest.py +++ b/seed/python-sdk/literal/use_typeddict_requests/tests/conftest.py @@ -1,9 +1,9 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedLiteral import os - import pytest -from seed import AsyncSeedLiteral, SeedLiteral +from seed import AsyncSeedLiteral @pytest.fixture diff --git a/seed/python-sdk/literal/use_typeddict_requests/tests/custom/test_client.py b/seed/python-sdk/literal/use_typeddict_requests/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/python-sdk/literal/use_typeddict_requests/tests/custom/test_client.py +++ b/seed/python-sdk/literal/use_typeddict_requests/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/python-sdk/literal/use_typeddict_requests/tests/test_headers.py b/seed/python-sdk/literal/use_typeddict_requests/tests/test_headers.py index d712980b74c..51861ae4d40 100644 --- a/seed/python-sdk/literal/use_typeddict_requests/tests/test_headers.py +++ b/seed/python-sdk/literal/use_typeddict_requests/tests/test_headers.py @@ -1,14 +1,17 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedLiteral +from seed import AsyncSeedLiteral import typing - -from seed import AsyncSeedLiteral, SeedLiteral - from .utilities import validate_response async def test_send(client: SeedLiteral, async_client: AsyncSeedLiteral) -> None: - expected_response: typing.Any = {"message": "The weather is sunny", "status": 200, "success": True} + expected_response: typing.Any = { + "message": "The weather is sunny", + "status": 200, + "success": True, + } expected_types: typing.Any = {"message": None, "status": "integer", "success": None} response = client.headers.send(query="What is the weather today") validate_response(response, expected_response, expected_types) diff --git a/seed/python-sdk/literal/use_typeddict_requests/tests/test_inlined.py b/seed/python-sdk/literal/use_typeddict_requests/tests/test_inlined.py index 47004f21dc0..e9457ef4acf 100644 --- a/seed/python-sdk/literal/use_typeddict_requests/tests/test_inlined.py +++ b/seed/python-sdk/literal/use_typeddict_requests/tests/test_inlined.py @@ -1,14 +1,17 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedLiteral +from seed import AsyncSeedLiteral import typing - -from seed import AsyncSeedLiteral, SeedLiteral - from .utilities import validate_response async def test_send(client: SeedLiteral, async_client: AsyncSeedLiteral) -> None: - expected_response: typing.Any = {"message": "The weather is sunny", "status": 200, "success": True} + expected_response: typing.Any = { + "message": "The weather is sunny", + "status": 200, + "success": True, + } expected_types: typing.Any = {"message": None, "status": "integer", "success": None} response = client.inlined.send( temperature=10.1, diff --git a/seed/python-sdk/literal/use_typeddict_requests/tests/test_path.py b/seed/python-sdk/literal/use_typeddict_requests/tests/test_path.py index 319940b6223..46ee07f53cc 100644 --- a/seed/python-sdk/literal/use_typeddict_requests/tests/test_path.py +++ b/seed/python-sdk/literal/use_typeddict_requests/tests/test_path.py @@ -1,14 +1,17 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedLiteral +from seed import AsyncSeedLiteral import typing - -from seed import AsyncSeedLiteral, SeedLiteral - from .utilities import validate_response async def test_send(client: SeedLiteral, async_client: AsyncSeedLiteral) -> None: - expected_response: typing.Any = {"message": "The weather is sunny", "status": 200, "success": True} + expected_response: typing.Any = { + "message": "The weather is sunny", + "status": 200, + "success": True, + } expected_types: typing.Any = {"message": None, "status": "integer", "success": None} response = client.path.send() validate_response(response, expected_response, expected_types) diff --git a/seed/python-sdk/literal/use_typeddict_requests/tests/test_query.py b/seed/python-sdk/literal/use_typeddict_requests/tests/test_query.py index 01431e45052..8997f23a10e 100644 --- a/seed/python-sdk/literal/use_typeddict_requests/tests/test_query.py +++ b/seed/python-sdk/literal/use_typeddict_requests/tests/test_query.py @@ -1,14 +1,17 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedLiteral +from seed import AsyncSeedLiteral import typing - -from seed import AsyncSeedLiteral, SeedLiteral - from .utilities import validate_response async def test_send(client: SeedLiteral, async_client: AsyncSeedLiteral) -> None: - expected_response: typing.Any = {"message": "The weather is sunny", "status": 200, "success": True} + expected_response: typing.Any = { + "message": "The weather is sunny", + "status": 200, + "success": True, + } expected_types: typing.Any = {"message": None, "status": "integer", "success": None} response = client.query.send(query="What is the weather today") validate_response(response, expected_response, expected_types) diff --git a/seed/python-sdk/literal/use_typeddict_requests/tests/test_reference.py b/seed/python-sdk/literal/use_typeddict_requests/tests/test_reference.py index ece749256d7..b74465ce828 100644 --- a/seed/python-sdk/literal/use_typeddict_requests/tests/test_reference.py +++ b/seed/python-sdk/literal/use_typeddict_requests/tests/test_reference.py @@ -1,17 +1,22 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedLiteral +from seed import AsyncSeedLiteral import typing - -from seed import AsyncSeedLiteral, SeedLiteral - from .utilities import validate_response async def test_send(client: SeedLiteral, async_client: AsyncSeedLiteral) -> None: - expected_response: typing.Any = {"message": "The weather is sunny", "status": 200, "success": True} + expected_response: typing.Any = { + "message": "The weather is sunny", + "status": 200, + "success": True, + } expected_types: typing.Any = {"message": None, "status": "integer", "success": None} response = client.reference.send(query="What is the weather today") validate_response(response, expected_response, expected_types) - async_response = await async_client.reference.send(query="What is the weather today") + async_response = await async_client.reference.send( + query="What is the weather today" + ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/literal/use_typeddict_requests/tests/utilities.py b/seed/python-sdk/literal/use_typeddict_requests/tests/utilities.py index 13da208eb3a..e8f4472564c 100644 --- a/seed/python-sdk/literal/use_typeddict_requests/tests/utilities.py +++ b/seed/python-sdk/literal/use_typeddict_requests/tests/utilities.py @@ -3,11 +3,14 @@ import typing import uuid -import pydantic from dateutil import parser +import pydantic + -def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> typing.Any: +def cast_field( + json_expectation: typing.Any, type_expectation: typing.Any +) -> typing.Any: # Cast these specific types which come through as string and expect our # models to cast to the correct type. if type_expectation == "uuid": @@ -25,7 +28,9 @@ def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> ty return json_expectation -def validate_field(response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any) -> None: +def validate_field( + response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectation == "no_validate": return @@ -44,7 +49,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(entry_expectation, dict): is_container_of_complex_type = True validate_response( - response=response[idx], json_expectation=ex, type_expectations=entry_expectation + response=response[idx], + json_expectation=ex, + type_expectations=entry_expectation, ) else: cast_json_expectation.append(cast_field(ex, entry_expectation)) @@ -56,7 +63,10 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # if any of the values of the set have a type_expectation of a dict, we're assuming it's a pydantic # model and keeping it a list. if container_expectation != "set" or not any( - map(lambda value: isinstance(value, dict), list(contents_expectation.values())) + map( + lambda value: isinstance(value, dict), + list(contents_expectation.values()), + ) ): json_expectation = cast_field(json_expectation, container_expectation) elif isinstance(type_expectation, tuple): @@ -65,9 +75,15 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(contents_expectation, dict): json_expectation = { cast_field( - key, contents_expectation.get(idx)[0] if contents_expectation.get(idx) is not None else None # type: ignore + key, + contents_expectation.get(idx)[0] + if contents_expectation.get(idx) is not None + else None, # type: ignore ): cast_field( - value, contents_expectation.get(idx)[1] if contents_expectation.get(idx) is not None else None # type: ignore + value, + contents_expectation.get(idx)[1] + if contents_expectation.get(idx) is not None + else None, # type: ignore ) for idx, (key, value) in enumerate(json_expectation.items()) } @@ -86,7 +102,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # Arg type_expectations is a deeply nested structure that matches the response, but with the values replaced with the expected types -def validate_response(response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any) -> None: +def validate_response( + response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectations == "no_validate": return @@ -96,11 +114,17 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e and not isinstance(response, dict) and not issubclass(type(response), pydantic.BaseModel) ): - validate_field(response=response, json_expectation=json_expectation, type_expectation=type_expectations) + validate_field( + response=response, + json_expectation=json_expectation, + type_expectation=type_expectations, + ) return if isinstance(response, list): - assert len(response) == len(json_expectation), "Length mismatch, expected: {0}, Actual: {1}".format( + assert len(response) == len( + json_expectation + ), "Length mismatch, expected: {0}, Actual: {1}".format( len(response), len(json_expectation) ) content_expectation = type_expectations @@ -108,7 +132,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e content_expectation = type_expectations[1] for idx, item in enumerate(response): validate_response( - response=item, json_expectation=json_expectation[idx], type_expectations=content_expectation[idx] + response=item, + json_expectation=json_expectation[idx], + type_expectations=content_expectation[idx], ) else: response_json = response @@ -116,7 +142,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e response_json = response.dict(by_alias=True) for key, value in json_expectation.items(): - assert key in response_json, "Field {0} not found within the response object: {1}".format( + assert ( + key in response_json + ), "Field {0} not found within the response object: {1}".format( key, response_json ) @@ -128,11 +156,19 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e # Otherwise, we're just validating a single field that's a pydantic model. if isinstance(value, dict) and not isinstance(type_expectation, tuple): validate_response( - response=response_json[key], json_expectation=value, type_expectations=type_expectation + response=response_json[key], + json_expectation=value, + type_expectations=type_expectation, ) else: - validate_field(response=response_json[key], json_expectation=value, type_expectation=type_expectation) + validate_field( + response=response_json[key], + json_expectation=value, + type_expectation=type_expectation, + ) # Ensure there are no additional fields here either del response_json[key] - assert len(response_json) == 0, "Additional fields found, expected None: {0}".format(response_json) + assert ( + len(response_json) == 0 + ), "Additional fields found, expected None: {0}".format(response_json) diff --git a/seed/python-sdk/literal/use_typeddict_requests/tests/utils/assets/models/__init__.py b/seed/python-sdk/literal/use_typeddict_requests/tests/utils/assets/models/__init__.py index 2cf01263529..3a1c852e71e 100644 --- a/seed/python-sdk/literal/use_typeddict_requests/tests/utils/assets/models/__init__.py +++ b/seed/python-sdk/literal/use_typeddict_requests/tests/utils/assets/models/__init__.py @@ -5,7 +5,7 @@ from .circle import CircleParams from .object_with_defaults import ObjectWithDefaultsParams from .object_with_optional_field import ObjectWithOptionalFieldParams -from .shape import Shape_CircleParams, Shape_SquareParams, ShapeParams +from .shape import ShapeParams, Shape_CircleParams, Shape_SquareParams from .square import SquareParams from .undiscriminated_shape import UndiscriminatedShapeParams diff --git a/seed/python-sdk/literal/use_typeddict_requests/tests/utils/assets/models/circle.py b/seed/python-sdk/literal/use_typeddict_requests/tests/utils/assets/models/circle.py index af7a1bf8a8e..253f12d38b3 100644 --- a/seed/python-sdk/literal/use_typeddict_requests/tests/utils/assets/models/circle.py +++ b/seed/python-sdk/literal/use_typeddict_requests/tests/utils/assets/models/circle.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class CircleParams(typing_extensions.TypedDict): - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] diff --git a/seed/python-sdk/literal/use_typeddict_requests/tests/utils/assets/models/object_with_optional_field.py b/seed/python-sdk/literal/use_typeddict_requests/tests/utils/assets/models/object_with_optional_field.py index 3ad93d5f305..ebe7dc80547 100644 --- a/seed/python-sdk/literal/use_typeddict_requests/tests/utils/assets/models/object_with_optional_field.py +++ b/seed/python-sdk/literal/use_typeddict_requests/tests/utils/assets/models/object_with_optional_field.py @@ -7,8 +7,8 @@ import uuid import typing_extensions -from seed.core.serialization import FieldMetadata +from seed.core.serialization import FieldMetadata from .color import Color from .shape import ShapeParams from .undiscriminated_shape import UndiscriminatedShapeParams @@ -18,16 +18,30 @@ class ObjectWithOptionalFieldParams(typing_extensions.TypedDict): literal: typing.Literal["lit_one"] string: typing_extensions.NotRequired[str] integer: typing_extensions.NotRequired[int] - long_: typing_extensions.NotRequired[typing_extensions.Annotated[int, FieldMetadata(alias="long")]] + long_: typing_extensions.NotRequired[ + typing_extensions.Annotated[int, FieldMetadata(alias="long")] + ] double: typing_extensions.NotRequired[float] - bool_: typing_extensions.NotRequired[typing_extensions.Annotated[bool, FieldMetadata(alias="bool")]] + bool_: typing_extensions.NotRequired[ + typing_extensions.Annotated[bool, FieldMetadata(alias="bool")] + ] datetime: typing_extensions.NotRequired[dt.datetime] date: typing_extensions.NotRequired[dt.date] - uuid_: typing_extensions.NotRequired[typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")]] - base_64: typing_extensions.NotRequired[typing_extensions.Annotated[str, FieldMetadata(alias="base64")]] - list_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")]] - set_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")]] - map_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")]] + uuid_: typing_extensions.NotRequired[ + typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")] + ] + base_64: typing_extensions.NotRequired[ + typing_extensions.Annotated[str, FieldMetadata(alias="base64")] + ] + list_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")] + ] + set_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")] + ] + map_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")] + ] enum: typing_extensions.NotRequired[Color] union: typing_extensions.NotRequired[ShapeParams] second_union: typing_extensions.NotRequired[ShapeParams] diff --git a/seed/python-sdk/literal/use_typeddict_requests/tests/utils/assets/models/shape.py b/seed/python-sdk/literal/use_typeddict_requests/tests/utils/assets/models/shape.py index 2c33c877951..816ffc51bdc 100644 --- a/seed/python-sdk/literal/use_typeddict_requests/tests/utils/assets/models/shape.py +++ b/seed/python-sdk/literal/use_typeddict_requests/tests/utils/assets/models/shape.py @@ -7,6 +7,7 @@ import typing import typing_extensions + from seed.core.serialization import FieldMetadata @@ -15,13 +16,21 @@ class Base(typing_extensions.TypedDict): class Shape_CircleParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["circle"], FieldMetadata(alias="shapeType")] - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["circle"], FieldMetadata(alias="shapeType") + ] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] class Shape_SquareParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["square"], FieldMetadata(alias="shapeType")] - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["square"], FieldMetadata(alias="shapeType") + ] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] ShapeParams = typing.Union[Shape_CircleParams, Shape_SquareParams] diff --git a/seed/python-sdk/literal/use_typeddict_requests/tests/utils/assets/models/square.py b/seed/python-sdk/literal/use_typeddict_requests/tests/utils/assets/models/square.py index b9b7dd319bc..bcf08a723c5 100644 --- a/seed/python-sdk/literal/use_typeddict_requests/tests/utils/assets/models/square.py +++ b/seed/python-sdk/literal/use_typeddict_requests/tests/utils/assets/models/square.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class SquareParams(typing_extensions.TypedDict): - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] diff --git a/seed/python-sdk/literal/use_typeddict_requests/tests/utils/test_http_client.py b/seed/python-sdk/literal/use_typeddict_requests/tests/utils/test_http_client.py index edd11ca7afb..f5a874a75f3 100644 --- a/seed/python-sdk/literal/use_typeddict_requests/tests/utils/test_http_client.py +++ b/seed/python-sdk/literal/use_typeddict_requests/tests/utils/test_http_client.py @@ -9,12 +9,17 @@ def get_request_options() -> RequestOptions: def test_get_json_request_body() -> None: - json_body, data_body = get_request_body(json={"hello": "world"}, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json={"hello": "world"}, data=None, request_options=None, omit=None + ) assert json_body == {"hello": "world"} assert data_body is None json_body_extras, data_body_extras = get_request_body( - json={"goodbye": "world"}, data=None, request_options=get_request_options(), omit=None + json={"goodbye": "world"}, + data=None, + request_options=get_request_options(), + omit=None, ) assert json_body_extras == {"goodbye": "world", "see you": "later"} @@ -22,12 +27,17 @@ def test_get_json_request_body() -> None: def test_get_files_request_body() -> None: - json_body, data_body = get_request_body(json=None, data={"hello": "world"}, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data={"hello": "world"}, request_options=None, omit=None + ) assert data_body == {"hello": "world"} assert json_body is None json_body_extras, data_body_extras = get_request_body( - json=None, data={"goodbye": "world"}, request_options=get_request_options(), omit=None + json=None, + data={"goodbye": "world"}, + request_options=get_request_options(), + omit=None, ) assert data_body_extras == {"goodbye": "world", "see you": "later"} @@ -35,7 +45,9 @@ def test_get_files_request_body() -> None: def test_get_none_request_body() -> None: - json_body, data_body = get_request_body(json=None, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data=None, request_options=None, omit=None + ) assert data_body is None assert json_body is None diff --git a/seed/python-sdk/literal/use_typeddict_requests/tests/utils/test_query_encoding.py b/seed/python-sdk/literal/use_typeddict_requests/tests/utils/test_query_encoding.py index 247e1551b46..fbc8f402167 100644 --- a/seed/python-sdk/literal/use_typeddict_requests/tests/utils/test_query_encoding.py +++ b/seed/python-sdk/literal/use_typeddict_requests/tests/utils/test_query_encoding.py @@ -4,9 +4,15 @@ def test_query_encoding() -> None: - assert encode_query({"hello world": "hello world"}) == {"hello world": "hello world"} - assert encode_query({"hello_world": {"hello": "world"}}) == {"hello_world[hello]": "world"} - assert encode_query({"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"}) == { + assert encode_query({"hello world": "hello world"}) == { + "hello world": "hello world" + } + assert encode_query({"hello_world": {"hello": "world"}}) == { + "hello_world[hello]": "world" + } + assert encode_query( + {"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"} + ) == { "hello_world[hello][world]": "today", "hello_world[test]": "this", "hi": "there", diff --git a/seed/python-sdk/literal/use_typeddict_requests/tests/utils/test_serialization.py b/seed/python-sdk/literal/use_typeddict_requests/tests/utils/test_serialization.py index 58b1ed66e6d..5ca956916dd 100644 --- a/seed/python-sdk/literal/use_typeddict_requests/tests/utils/test_serialization.py +++ b/seed/python-sdk/literal/use_typeddict_requests/tests/utils/test_serialization.py @@ -1,10 +1,12 @@ # This file was auto-generated by Fern from our API Definition. -from typing import Any, List +from typing import List, Any -from seed.core.serialization import convert_and_respect_annotation_metadata +from seed.core.serialization import ( + convert_and_respect_annotation_metadata, +) +from .assets.models import ShapeParams, ObjectWithOptionalFieldParams -from .assets.models import ObjectWithOptionalFieldParams, ShapeParams UNION_TEST: ShapeParams = {"radius_measurement": 1.0, "shape_type": "circle", "id": "1"} UNION_TEST_CONVERTED = {"shapeType": "circle", "radiusMeasurement": 1.0, "id": "1"} @@ -18,20 +20,54 @@ def test_convert_and_respect_annotation_metadata() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) - assert converted == {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"} + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) + assert converted == { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + } def test_convert_and_respect_annotation_metadata_in_list() -> None: data: List[ObjectWithOptionalFieldParams] = [ - {"string": "string", "long_": 12345, "bool_": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long_": 67890, "list_": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long_": 12345, + "bool_": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long_": 67890, + "list_": [], + "literal": "lit_one", + "any": "any", + }, ] - converted = convert_and_respect_annotation_metadata(object_=data, annotation=List[ObjectWithOptionalFieldParams]) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=List[ObjectWithOptionalFieldParams] + ) assert converted == [ - {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long": 67890, "list": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long": 67890, + "list": [], + "literal": "lit_one", + "any": "any", + }, ] @@ -43,7 +79,9 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) assert converted == { "string": "string", @@ -55,12 +93,16 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: def test_convert_and_respect_annotation_metadata_in_union() -> None: - converted = convert_and_respect_annotation_metadata(object_=UNION_TEST, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=UNION_TEST, annotation=ShapeParams + ) assert converted == UNION_TEST_CONVERTED def test_convert_and_respect_annotation_metadata_with_empty_object() -> None: data: Any = {} - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ShapeParams + ) assert converted == data diff --git a/seed/python-sdk/mixed-case/pyproject.toml b/seed/python-sdk/mixed-case/pyproject.toml index 499a9ba7c69..febcd7d3216 100644 --- a/seed/python-sdk/mixed-case/pyproject.toml +++ b/seed/python-sdk/mixed-case/pyproject.toml @@ -43,6 +43,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/python-sdk/mixed-case/src/seed/__init__.py b/seed/python-sdk/mixed-case/src/seed/__init__.py index f3774837d7f..b8e65637759 100644 --- a/seed/python-sdk/mixed-case/src/seed/__init__.py +++ b/seed/python-sdk/mixed-case/src/seed/__init__.py @@ -2,7 +2,15 @@ from . import service from .client import AsyncSeedMixedCase, SeedMixedCase -from .service import NestedUser, Organization, Resource, ResourceStatus, Resource_Organization, Resource_User, User +from .service import ( + NestedUser, + Organization, + Resource, + ResourceStatus, + Resource_Organization, + Resource_User, + User, +) from .version import __version__ __all__ = [ diff --git a/seed/python-sdk/mixed-case/src/seed/client.py b/seed/python-sdk/mixed-case/src/seed/client.py index 3701b1fe024..d301b5ddfb0 100644 --- a/seed/python-sdk/mixed-case/src/seed/client.py +++ b/seed/python-sdk/mixed-case/src/seed/client.py @@ -1,11 +1,11 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from .service.client import AsyncServiceClient, ServiceClient +from .core.client_wrapper import SyncClientWrapper +from .service.client import ServiceClient +from .core.client_wrapper import AsyncClientWrapper +from .service.client import AsyncServiceClient class SeedMixedCase: @@ -41,14 +41,18 @@ def __init__( base_url: str, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.Client] = None + httpx_client: typing.Optional[httpx.Client] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = SyncClientWrapper( base_url=base_url, httpx_client=httpx_client if httpx_client is not None - else httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.Client( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.Client(timeout=_defaulted_timeout), timeout=_defaulted_timeout, @@ -89,14 +93,18 @@ def __init__( base_url: str, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.AsyncClient] = None + httpx_client: typing.Optional[httpx.AsyncClient] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = AsyncClientWrapper( base_url=base_url, httpx_client=httpx_client if httpx_client is not None - else httpx.AsyncClient(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.AsyncClient( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.AsyncClient(timeout=_defaulted_timeout), timeout=_defaulted_timeout, diff --git a/seed/python-sdk/mixed-case/src/seed/core/api_error.py b/seed/python-sdk/mixed-case/src/seed/core/api_error.py index 2e9fc5431cd..da734b58068 100644 --- a/seed/python-sdk/mixed-case/src/seed/core/api_error.py +++ b/seed/python-sdk/mixed-case/src/seed/core/api_error.py @@ -7,7 +7,9 @@ class ApiError(Exception): status_code: typing.Optional[int] body: typing.Any - def __init__(self, *, status_code: typing.Optional[int] = None, body: typing.Any = None): + def __init__( + self, *, status_code: typing.Optional[int] = None, body: typing.Any = None + ): self.status_code = status_code self.body = body diff --git a/seed/python-sdk/mixed-case/src/seed/core/client_wrapper.py b/seed/python-sdk/mixed-case/src/seed/core/client_wrapper.py index d8fe9ab628a..6c0bdb8beac 100644 --- a/seed/python-sdk/mixed-case/src/seed/core/client_wrapper.py +++ b/seed/python-sdk/mixed-case/src/seed/core/client_wrapper.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .http_client import AsyncHttpClient, HttpClient +from .http_client import HttpClient +from .http_client import AsyncHttpClient class BaseClientWrapper: @@ -28,7 +27,13 @@ def get_timeout(self) -> typing.Optional[float]: class SyncClientWrapper(BaseClientWrapper): - def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, httpx_client: httpx.Client): + def __init__( + self, + *, + base_url: str, + timeout: typing.Optional[float] = None, + httpx_client: httpx.Client, + ): super().__init__(base_url=base_url, timeout=timeout) self.httpx_client = HttpClient( httpx_client=httpx_client, @@ -39,7 +44,13 @@ def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, htt class AsyncClientWrapper(BaseClientWrapper): - def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, httpx_client: httpx.AsyncClient): + def __init__( + self, + *, + base_url: str, + timeout: typing.Optional[float] = None, + httpx_client: httpx.AsyncClient, + ): super().__init__(base_url=base_url, timeout=timeout) self.httpx_client = AsyncHttpClient( httpx_client=httpx_client, diff --git a/seed/python-sdk/mixed-case/src/seed/core/datetime_utils.py b/seed/python-sdk/mixed-case/src/seed/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/python-sdk/mixed-case/src/seed/core/datetime_utils.py +++ b/seed/python-sdk/mixed-case/src/seed/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/python-sdk/mixed-case/src/seed/core/file.py b/seed/python-sdk/mixed-case/src/seed/core/file.py index cb0d40bbbf3..6e0f92bfcb1 100644 --- a/seed/python-sdk/mixed-case/src/seed/core/file.py +++ b/seed/python-sdk/mixed-case/src/seed/core/file.py @@ -13,12 +13,17 @@ # (filename, file (or bytes), content_type) typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str]], # (filename, file (or bytes), content_type, headers) - typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str], typing.Mapping[str, str]], + typing.Tuple[ + typing.Optional[str], + FileContent, + typing.Optional[str], + typing.Mapping[str, str], + ], ] def convert_file_dict_to_httpx_tuples( - d: typing.Dict[str, typing.Union[File, typing.List[File]]] + d: typing.Dict[str, typing.Union[File, typing.List[File]]], ) -> typing.List[typing.Tuple[str, File]]: """ The format we use is a list of tuples, where the first element is the diff --git a/seed/python-sdk/mixed-case/src/seed/core/http_client.py b/seed/python-sdk/mixed-case/src/seed/core/http_client.py index 9333d8a7f15..091f71bc185 100644 --- a/seed/python-sdk/mixed-case/src/seed/core/http_client.py +++ b/seed/python-sdk/mixed-case/src/seed/core/http_client.py @@ -77,7 +77,9 @@ def _retry_timeout(response: httpx.Response, retries: int) -> float: return retry_after # Apply exponential backoff, capped at MAX_RETRY_DELAY_SECONDS. - retry_delay = min(INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS) + retry_delay = min( + INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS + ) # Add a randomness / jitter to the retry delay to avoid overwhelming the server with retries. timeout = retry_delay * (1 - 0.25 * random()) @@ -90,7 +92,8 @@ def _should_retry(response: httpx.Response) -> bool: def remove_omit_from_dict( - original: typing.Dict[str, typing.Optional[typing.Any]], omit: typing.Optional[typing.Any] + original: typing.Dict[str, typing.Optional[typing.Any]], + omit: typing.Optional[typing.Any], ) -> typing.Dict[str, typing.Any]: if omit is None: return original @@ -108,7 +111,8 @@ def maybe_filter_request_body( ) -> typing.Optional[typing.Any]: if data is None: return ( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else None ) @@ -118,7 +122,8 @@ def maybe_filter_request_body( data_content = { **(jsonable_encoder(remove_omit_from_dict(data, omit))), # type: ignore **( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else {} ), @@ -162,7 +167,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url def request( @@ -174,8 +181,12 @@ def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -184,11 +195,14 @@ def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) response = self.httpx_client.request( method=method, @@ -198,7 +212,11 @@ def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -209,7 +227,10 @@ def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -222,11 +243,15 @@ def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: time.sleep(_retry_timeout(response=response, retries=retries)) @@ -256,8 +281,12 @@ def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -266,11 +295,14 @@ def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) with self.httpx_client.stream( method=method, @@ -280,7 +312,11 @@ def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -291,7 +327,9 @@ def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -304,7 +342,9 @@ def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream @@ -327,7 +367,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url async def request( @@ -339,8 +381,12 @@ async def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -349,11 +395,14 @@ async def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) # Add the input to each of these and do None-safety checks response = await self.httpx_client.request( @@ -364,7 +413,11 @@ async def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -375,7 +428,10 @@ async def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -388,11 +444,15 @@ async def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: await asyncio.sleep(_retry_timeout(response=response, retries=retries)) @@ -421,8 +481,12 @@ async def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -431,11 +495,14 @@ async def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) async with self.httpx_client.stream( method=method, @@ -445,7 +512,11 @@ async def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -456,7 +527,9 @@ async def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -469,7 +542,9 @@ async def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream diff --git a/seed/python-sdk/mixed-case/src/seed/core/jsonable_encoder.py b/seed/python-sdk/mixed-case/src/seed/core/jsonable_encoder.py index d3fd328fd41..12a8b52fc22 100644 --- a/seed/python-sdk/mixed-case/src/seed/core/jsonable_encoder.py +++ b/seed/python-sdk/mixed-case/src/seed/core/jsonable_encoder.py @@ -19,13 +19,19 @@ import pydantic from .datetime_utils import serialize_datetime -from .pydantic_utilities import IS_PYDANTIC_V2, encode_by_type, to_jsonable_with_fallback +from .pydantic_utilities import ( + IS_PYDANTIC_V2, + encode_by_type, + to_jsonable_with_fallback, +) SetIntStr = Set[Union[int, str]] DictIntStrAny = Dict[Union[int, str], Any] -def jsonable_encoder(obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None) -> Any: +def jsonable_encoder( + obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None +) -> Any: custom_encoder = custom_encoder or {} if custom_encoder: if type(obj) in custom_encoder: diff --git a/seed/python-sdk/mixed-case/src/seed/core/pydantic_utilities.py b/seed/python-sdk/mixed-case/src/seed/core/pydantic_utilities.py index 170a563d6eb..c63935c32a2 100644 --- a/seed/python-sdk/mixed-case/src/seed/core/pydantic_utilities.py +++ b/seed/python-sdk/mixed-case/src/seed/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) # type: ignore # Pydantic v1 diff --git a/seed/python-sdk/mixed-case/src/seed/core/query_encoder.py b/seed/python-sdk/mixed-case/src/seed/core/query_encoder.py index 24076d72ee9..7cb98f52cd7 100644 --- a/seed/python-sdk/mixed-case/src/seed/core/query_encoder.py +++ b/seed/python-sdk/mixed-case/src/seed/core/query_encoder.py @@ -7,7 +7,9 @@ # Flattens dicts to be of the form {"key[subkey][subkey2]": value} where value is not a dict -def traverse_query_dict(dict_flat: Dict[str, Any], key_prefix: Optional[str] = None) -> Dict[str, Any]: +def traverse_query_dict( + dict_flat: Dict[str, Any], key_prefix: Optional[str] = None +) -> Dict[str, Any]: result = {} for k, v in dict_flat.items(): key = f"{key_prefix}[{k}]" if key_prefix is not None else k @@ -30,4 +32,8 @@ def single_query_encoder(query_key: str, query_value: Any) -> Dict[str, Any]: def encode_query(query: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: - return dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) if query is not None else None + return ( + dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) + if query is not None + else None + ) diff --git a/seed/python-sdk/mixed-case/src/seed/core/serialization.py b/seed/python-sdk/mixed-case/src/seed/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/python-sdk/mixed-case/src/seed/core/serialization.py +++ b/seed/python-sdk/mixed-case/src/seed/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/python-sdk/mixed-case/src/seed/service/__init__.py b/seed/python-sdk/mixed-case/src/seed/service/__init__.py index 28b4887b589..d11a6d81b0c 100644 --- a/seed/python-sdk/mixed-case/src/seed/service/__init__.py +++ b/seed/python-sdk/mixed-case/src/seed/service/__init__.py @@ -1,5 +1,21 @@ # This file was auto-generated by Fern from our API Definition. -from .types import NestedUser, Organization, Resource, ResourceStatus, Resource_Organization, Resource_User, User +from .types import ( + NestedUser, + Organization, + Resource, + ResourceStatus, + Resource_Organization, + Resource_User, + User, +) -__all__ = ["NestedUser", "Organization", "Resource", "ResourceStatus", "Resource_Organization", "Resource_User", "User"] +__all__ = [ + "NestedUser", + "Organization", + "Resource", + "ResourceStatus", + "Resource_Organization", + "Resource_User", + "User", +] diff --git a/seed/python-sdk/mixed-case/src/seed/service/client.py b/seed/python-sdk/mixed-case/src/seed/service/client.py index b6475af3e93..13cd4cf67b4 100644 --- a/seed/python-sdk/mixed-case/src/seed/service/client.py +++ b/seed/python-sdk/mixed-case/src/seed/service/client.py @@ -1,22 +1,27 @@ # This file was auto-generated by Fern from our API Definition. -import datetime as dt +from ..core.client_wrapper import SyncClientWrapper import typing -from json.decoder import JSONDecodeError - -from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.jsonable_encoder import jsonable_encoder -from ..core.pydantic_utilities import parse_obj_as from ..core.request_options import RequestOptions from .types.resource import Resource +from ..core.jsonable_encoder import jsonable_encoder +from ..core.pydantic_utilities import parse_obj_as +from json.decoder import JSONDecodeError +from ..core.api_error import ApiError +import datetime as dt +from ..core.client_wrapper import AsyncClientWrapper class ServiceClient: def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper - def get_resource(self, resource_id: str, *, request_options: typing.Optional[RequestOptions] = None) -> Resource: + def get_resource( + self, + resource_id: str, + *, + request_options: typing.Optional[RequestOptions] = None, + ) -> Resource: """ Parameters ---------- @@ -41,18 +46,26 @@ def get_resource(self, resource_id: str, *, request_options: typing.Optional[Req ) """ _response = self._client_wrapper.httpx_client.request( - f"resource/{jsonable_encoder(resource_id)}", method="GET", request_options=request_options + f"resource/{jsonable_encoder(resource_id)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(Resource, parse_obj_as(type_=Resource, object_=_response.json())) # type: ignore + return typing.cast( + Resource, parse_obj_as(type_=Resource, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def list_resources( - self, *, page_limit: int, before_date: dt.date, request_options: typing.Optional[RequestOptions] = None + self, + *, + page_limit: int, + before_date: dt.date, + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[Resource]: """ Parameters @@ -87,12 +100,18 @@ def list_resources( _response = self._client_wrapper.httpx_client.request( "resource", method="GET", - params={"page_limit": page_limit, "beforeDate": str(before_date)}, + params={ + "page_limit": page_limit, + "beforeDate": str(before_date), + }, request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.List[Resource], parse_obj_as(type_=typing.List[Resource], object_=_response.json())) # type: ignore + return typing.cast( + typing.List[Resource], + parse_obj_as(type_=typing.List[Resource], object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -104,7 +123,10 @@ def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper async def get_resource( - self, resource_id: str, *, request_options: typing.Optional[RequestOptions] = None + self, + resource_id: str, + *, + request_options: typing.Optional[RequestOptions] = None, ) -> Resource: """ Parameters @@ -138,18 +160,26 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - f"resource/{jsonable_encoder(resource_id)}", method="GET", request_options=request_options + f"resource/{jsonable_encoder(resource_id)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(Resource, parse_obj_as(type_=Resource, object_=_response.json())) # type: ignore + return typing.cast( + Resource, parse_obj_as(type_=Resource, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def list_resources( - self, *, page_limit: int, before_date: dt.date, request_options: typing.Optional[RequestOptions] = None + self, + *, + page_limit: int, + before_date: dt.date, + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[Resource]: """ Parameters @@ -191,12 +221,18 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( "resource", method="GET", - params={"page_limit": page_limit, "beforeDate": str(before_date)}, + params={ + "page_limit": page_limit, + "beforeDate": str(before_date), + }, request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.List[Resource], parse_obj_as(type_=typing.List[Resource], object_=_response.json())) # type: ignore + return typing.cast( + typing.List[Resource], + parse_obj_as(type_=typing.List[Resource], object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/mixed-case/src/seed/service/types/__init__.py b/seed/python-sdk/mixed-case/src/seed/service/types/__init__.py index b6b435da5c1..c1d7d34969d 100644 --- a/seed/python-sdk/mixed-case/src/seed/service/types/__init__.py +++ b/seed/python-sdk/mixed-case/src/seed/service/types/__init__.py @@ -6,4 +6,12 @@ from .resource_status import ResourceStatus from .user import User -__all__ = ["NestedUser", "Organization", "Resource", "ResourceStatus", "Resource_Organization", "Resource_User", "User"] +__all__ = [ + "NestedUser", + "Organization", + "Resource", + "ResourceStatus", + "Resource_Organization", + "Resource_User", + "User", +] diff --git a/seed/python-sdk/mixed-case/src/seed/service/types/nested_user.py b/seed/python-sdk/mixed-case/src/seed/service/types/nested_user.py index 76028a48f59..8302f2a8e58 100644 --- a/seed/python-sdk/mixed-case/src/seed/service/types/nested_user.py +++ b/seed/python-sdk/mixed-case/src/seed/service/types/nested_user.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ...core.pydantic_utilities import UniversalBaseModel import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .user import User +from ...core.pydantic_utilities import IS_PYDANTIC_V2 +import typing class NestedUser(UniversalBaseModel): @@ -28,7 +27,9 @@ class NestedUser(UniversalBaseModel): nested_user: User = pydantic.Field(alias="NestedUser") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/mixed-case/src/seed/service/types/organization.py b/seed/python-sdk/mixed-case/src/seed/service/types/organization.py index 108bc2dd3c3..7f87b7c9686 100644 --- a/seed/python-sdk/mixed-case/src/seed/service/types/organization.py +++ b/seed/python-sdk/mixed-case/src/seed/service/types/organization.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class Organization(UniversalBaseModel): """ @@ -21,7 +20,9 @@ class Organization(UniversalBaseModel): name: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/mixed-case/src/seed/service/types/resource.py b/seed/python-sdk/mixed-case/src/seed/service/types/resource.py index dff1a09902b..b8f43980ec2 100644 --- a/seed/python-sdk/mixed-case/src/seed/service/types/resource.py +++ b/seed/python-sdk/mixed-case/src/seed/service/types/resource.py @@ -1,14 +1,12 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ...core.pydantic_utilities import UniversalBaseModel +from .resource_status import ResourceStatus +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .resource_status import ResourceStatus - class Base(UniversalBaseModel): """ @@ -26,7 +24,9 @@ class Base(UniversalBaseModel): status: ResourceStatus if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: @@ -54,7 +54,9 @@ class Resource_User(Base): extra_properties: typing.Dict[str, str] = pydantic.Field(alias="EXTRA_PROPERTIES") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: @@ -80,7 +82,9 @@ class Resource_Organization(Base): name: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/mixed-case/src/seed/service/types/user.py b/seed/python-sdk/mixed-case/src/seed/service/types/user.py index b2680726791..3334315f533 100644 --- a/seed/python-sdk/mixed-case/src/seed/service/types/user.py +++ b/seed/python-sdk/mixed-case/src/seed/service/types/user.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ...core.pydantic_utilities import UniversalBaseModel import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +import typing +from ...core.pydantic_utilities import IS_PYDANTIC_V2 class User(UniversalBaseModel): @@ -25,7 +24,9 @@ class User(UniversalBaseModel): extra_properties: typing.Dict[str, str] = pydantic.Field(alias="EXTRA_PROPERTIES") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/mixed-case/src/seed/version.py b/seed/python-sdk/mixed-case/src/seed/version.py index b74f13a6a30..069273f59bf 100644 --- a/seed/python-sdk/mixed-case/src/seed/version.py +++ b/seed/python-sdk/mixed-case/src/seed/version.py @@ -1,4 +1,3 @@ - from importlib import metadata __version__ = metadata.version("fern_mixed-case") diff --git a/seed/python-sdk/mixed-case/tests/conftest.py b/seed/python-sdk/mixed-case/tests/conftest.py index d6dd0d67094..8df2f6fc765 100644 --- a/seed/python-sdk/mixed-case/tests/conftest.py +++ b/seed/python-sdk/mixed-case/tests/conftest.py @@ -1,9 +1,9 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedMixedCase import os - import pytest -from seed import AsyncSeedMixedCase, SeedMixedCase +from seed import AsyncSeedMixedCase @pytest.fixture diff --git a/seed/python-sdk/mixed-case/tests/custom/test_client.py b/seed/python-sdk/mixed-case/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/python-sdk/mixed-case/tests/custom/test_client.py +++ b/seed/python-sdk/mixed-case/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/python-sdk/mixed-case/tests/test_service.py b/seed/python-sdk/mixed-case/tests/test_service.py index 4d7d071bb85..50edfe74b99 100644 --- a/seed/python-sdk/mixed-case/tests/test_service.py +++ b/seed/python-sdk/mixed-case/tests/test_service.py @@ -1,14 +1,15 @@ # This file was auto-generated by Fern from our API Definition. -import datetime +from seed import SeedMixedCase +from seed import AsyncSeedMixedCase import typing - -from seed import AsyncSeedMixedCase, SeedMixedCase - from .utilities import validate_response +import datetime -async def test_get_resource(client: SeedMixedCase, async_client: AsyncSeedMixedCase) -> None: +async def test_get_resource( + client: SeedMixedCase, async_client: AsyncSeedMixedCase +) -> None: expected_response: typing.Any = { "resource_type": "user", "userName": "username", @@ -23,7 +24,9 @@ async def test_get_resource(client: SeedMixedCase, async_client: AsyncSeedMixedC validate_response(async_response, expected_response, expected_types) -async def test_list_resources(client: SeedMixedCase, async_client: AsyncSeedMixedCase) -> None: +async def test_list_resources( + client: SeedMixedCase, async_client: AsyncSeedMixedCase +) -> None: expected_response: typing.Any = [ { "resource_type": "user", @@ -33,7 +36,9 @@ async def test_list_resources(client: SeedMixedCase, async_client: AsyncSeedMixe } ] expected_types: typing.Tuple[typing.Any, typing.Any] = ("list", {0: "no_validate"}) - response = client.service.list_resources(page_limit=10, before_date=datetime.date.fromisoformat("2023-01-01")) + response = client.service.list_resources( + page_limit=10, before_date=datetime.date.fromisoformat("2023-01-01") + ) validate_response(response, expected_response, expected_types) async_response = await async_client.service.list_resources( diff --git a/seed/python-sdk/mixed-case/tests/utilities.py b/seed/python-sdk/mixed-case/tests/utilities.py index 13da208eb3a..e8f4472564c 100644 --- a/seed/python-sdk/mixed-case/tests/utilities.py +++ b/seed/python-sdk/mixed-case/tests/utilities.py @@ -3,11 +3,14 @@ import typing import uuid -import pydantic from dateutil import parser +import pydantic + -def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> typing.Any: +def cast_field( + json_expectation: typing.Any, type_expectation: typing.Any +) -> typing.Any: # Cast these specific types which come through as string and expect our # models to cast to the correct type. if type_expectation == "uuid": @@ -25,7 +28,9 @@ def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> ty return json_expectation -def validate_field(response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any) -> None: +def validate_field( + response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectation == "no_validate": return @@ -44,7 +49,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(entry_expectation, dict): is_container_of_complex_type = True validate_response( - response=response[idx], json_expectation=ex, type_expectations=entry_expectation + response=response[idx], + json_expectation=ex, + type_expectations=entry_expectation, ) else: cast_json_expectation.append(cast_field(ex, entry_expectation)) @@ -56,7 +63,10 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # if any of the values of the set have a type_expectation of a dict, we're assuming it's a pydantic # model and keeping it a list. if container_expectation != "set" or not any( - map(lambda value: isinstance(value, dict), list(contents_expectation.values())) + map( + lambda value: isinstance(value, dict), + list(contents_expectation.values()), + ) ): json_expectation = cast_field(json_expectation, container_expectation) elif isinstance(type_expectation, tuple): @@ -65,9 +75,15 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(contents_expectation, dict): json_expectation = { cast_field( - key, contents_expectation.get(idx)[0] if contents_expectation.get(idx) is not None else None # type: ignore + key, + contents_expectation.get(idx)[0] + if contents_expectation.get(idx) is not None + else None, # type: ignore ): cast_field( - value, contents_expectation.get(idx)[1] if contents_expectation.get(idx) is not None else None # type: ignore + value, + contents_expectation.get(idx)[1] + if contents_expectation.get(idx) is not None + else None, # type: ignore ) for idx, (key, value) in enumerate(json_expectation.items()) } @@ -86,7 +102,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # Arg type_expectations is a deeply nested structure that matches the response, but with the values replaced with the expected types -def validate_response(response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any) -> None: +def validate_response( + response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectations == "no_validate": return @@ -96,11 +114,17 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e and not isinstance(response, dict) and not issubclass(type(response), pydantic.BaseModel) ): - validate_field(response=response, json_expectation=json_expectation, type_expectation=type_expectations) + validate_field( + response=response, + json_expectation=json_expectation, + type_expectation=type_expectations, + ) return if isinstance(response, list): - assert len(response) == len(json_expectation), "Length mismatch, expected: {0}, Actual: {1}".format( + assert len(response) == len( + json_expectation + ), "Length mismatch, expected: {0}, Actual: {1}".format( len(response), len(json_expectation) ) content_expectation = type_expectations @@ -108,7 +132,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e content_expectation = type_expectations[1] for idx, item in enumerate(response): validate_response( - response=item, json_expectation=json_expectation[idx], type_expectations=content_expectation[idx] + response=item, + json_expectation=json_expectation[idx], + type_expectations=content_expectation[idx], ) else: response_json = response @@ -116,7 +142,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e response_json = response.dict(by_alias=True) for key, value in json_expectation.items(): - assert key in response_json, "Field {0} not found within the response object: {1}".format( + assert ( + key in response_json + ), "Field {0} not found within the response object: {1}".format( key, response_json ) @@ -128,11 +156,19 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e # Otherwise, we're just validating a single field that's a pydantic model. if isinstance(value, dict) and not isinstance(type_expectation, tuple): validate_response( - response=response_json[key], json_expectation=value, type_expectations=type_expectation + response=response_json[key], + json_expectation=value, + type_expectations=type_expectation, ) else: - validate_field(response=response_json[key], json_expectation=value, type_expectation=type_expectation) + validate_field( + response=response_json[key], + json_expectation=value, + type_expectation=type_expectation, + ) # Ensure there are no additional fields here either del response_json[key] - assert len(response_json) == 0, "Additional fields found, expected None: {0}".format(response_json) + assert ( + len(response_json) == 0 + ), "Additional fields found, expected None: {0}".format(response_json) diff --git a/seed/python-sdk/mixed-case/tests/utils/assets/models/__init__.py b/seed/python-sdk/mixed-case/tests/utils/assets/models/__init__.py index 2cf01263529..3a1c852e71e 100644 --- a/seed/python-sdk/mixed-case/tests/utils/assets/models/__init__.py +++ b/seed/python-sdk/mixed-case/tests/utils/assets/models/__init__.py @@ -5,7 +5,7 @@ from .circle import CircleParams from .object_with_defaults import ObjectWithDefaultsParams from .object_with_optional_field import ObjectWithOptionalFieldParams -from .shape import Shape_CircleParams, Shape_SquareParams, ShapeParams +from .shape import ShapeParams, Shape_CircleParams, Shape_SquareParams from .square import SquareParams from .undiscriminated_shape import UndiscriminatedShapeParams diff --git a/seed/python-sdk/mixed-case/tests/utils/assets/models/circle.py b/seed/python-sdk/mixed-case/tests/utils/assets/models/circle.py index af7a1bf8a8e..253f12d38b3 100644 --- a/seed/python-sdk/mixed-case/tests/utils/assets/models/circle.py +++ b/seed/python-sdk/mixed-case/tests/utils/assets/models/circle.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class CircleParams(typing_extensions.TypedDict): - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] diff --git a/seed/python-sdk/mixed-case/tests/utils/assets/models/object_with_optional_field.py b/seed/python-sdk/mixed-case/tests/utils/assets/models/object_with_optional_field.py index 3ad93d5f305..ebe7dc80547 100644 --- a/seed/python-sdk/mixed-case/tests/utils/assets/models/object_with_optional_field.py +++ b/seed/python-sdk/mixed-case/tests/utils/assets/models/object_with_optional_field.py @@ -7,8 +7,8 @@ import uuid import typing_extensions -from seed.core.serialization import FieldMetadata +from seed.core.serialization import FieldMetadata from .color import Color from .shape import ShapeParams from .undiscriminated_shape import UndiscriminatedShapeParams @@ -18,16 +18,30 @@ class ObjectWithOptionalFieldParams(typing_extensions.TypedDict): literal: typing.Literal["lit_one"] string: typing_extensions.NotRequired[str] integer: typing_extensions.NotRequired[int] - long_: typing_extensions.NotRequired[typing_extensions.Annotated[int, FieldMetadata(alias="long")]] + long_: typing_extensions.NotRequired[ + typing_extensions.Annotated[int, FieldMetadata(alias="long")] + ] double: typing_extensions.NotRequired[float] - bool_: typing_extensions.NotRequired[typing_extensions.Annotated[bool, FieldMetadata(alias="bool")]] + bool_: typing_extensions.NotRequired[ + typing_extensions.Annotated[bool, FieldMetadata(alias="bool")] + ] datetime: typing_extensions.NotRequired[dt.datetime] date: typing_extensions.NotRequired[dt.date] - uuid_: typing_extensions.NotRequired[typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")]] - base_64: typing_extensions.NotRequired[typing_extensions.Annotated[str, FieldMetadata(alias="base64")]] - list_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")]] - set_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")]] - map_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")]] + uuid_: typing_extensions.NotRequired[ + typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")] + ] + base_64: typing_extensions.NotRequired[ + typing_extensions.Annotated[str, FieldMetadata(alias="base64")] + ] + list_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")] + ] + set_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")] + ] + map_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")] + ] enum: typing_extensions.NotRequired[Color] union: typing_extensions.NotRequired[ShapeParams] second_union: typing_extensions.NotRequired[ShapeParams] diff --git a/seed/python-sdk/mixed-case/tests/utils/assets/models/shape.py b/seed/python-sdk/mixed-case/tests/utils/assets/models/shape.py index 2c33c877951..816ffc51bdc 100644 --- a/seed/python-sdk/mixed-case/tests/utils/assets/models/shape.py +++ b/seed/python-sdk/mixed-case/tests/utils/assets/models/shape.py @@ -7,6 +7,7 @@ import typing import typing_extensions + from seed.core.serialization import FieldMetadata @@ -15,13 +16,21 @@ class Base(typing_extensions.TypedDict): class Shape_CircleParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["circle"], FieldMetadata(alias="shapeType")] - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["circle"], FieldMetadata(alias="shapeType") + ] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] class Shape_SquareParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["square"], FieldMetadata(alias="shapeType")] - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["square"], FieldMetadata(alias="shapeType") + ] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] ShapeParams = typing.Union[Shape_CircleParams, Shape_SquareParams] diff --git a/seed/python-sdk/mixed-case/tests/utils/assets/models/square.py b/seed/python-sdk/mixed-case/tests/utils/assets/models/square.py index b9b7dd319bc..bcf08a723c5 100644 --- a/seed/python-sdk/mixed-case/tests/utils/assets/models/square.py +++ b/seed/python-sdk/mixed-case/tests/utils/assets/models/square.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class SquareParams(typing_extensions.TypedDict): - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] diff --git a/seed/python-sdk/mixed-case/tests/utils/test_http_client.py b/seed/python-sdk/mixed-case/tests/utils/test_http_client.py index edd11ca7afb..f5a874a75f3 100644 --- a/seed/python-sdk/mixed-case/tests/utils/test_http_client.py +++ b/seed/python-sdk/mixed-case/tests/utils/test_http_client.py @@ -9,12 +9,17 @@ def get_request_options() -> RequestOptions: def test_get_json_request_body() -> None: - json_body, data_body = get_request_body(json={"hello": "world"}, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json={"hello": "world"}, data=None, request_options=None, omit=None + ) assert json_body == {"hello": "world"} assert data_body is None json_body_extras, data_body_extras = get_request_body( - json={"goodbye": "world"}, data=None, request_options=get_request_options(), omit=None + json={"goodbye": "world"}, + data=None, + request_options=get_request_options(), + omit=None, ) assert json_body_extras == {"goodbye": "world", "see you": "later"} @@ -22,12 +27,17 @@ def test_get_json_request_body() -> None: def test_get_files_request_body() -> None: - json_body, data_body = get_request_body(json=None, data={"hello": "world"}, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data={"hello": "world"}, request_options=None, omit=None + ) assert data_body == {"hello": "world"} assert json_body is None json_body_extras, data_body_extras = get_request_body( - json=None, data={"goodbye": "world"}, request_options=get_request_options(), omit=None + json=None, + data={"goodbye": "world"}, + request_options=get_request_options(), + omit=None, ) assert data_body_extras == {"goodbye": "world", "see you": "later"} @@ -35,7 +45,9 @@ def test_get_files_request_body() -> None: def test_get_none_request_body() -> None: - json_body, data_body = get_request_body(json=None, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data=None, request_options=None, omit=None + ) assert data_body is None assert json_body is None diff --git a/seed/python-sdk/mixed-case/tests/utils/test_query_encoding.py b/seed/python-sdk/mixed-case/tests/utils/test_query_encoding.py index 247e1551b46..fbc8f402167 100644 --- a/seed/python-sdk/mixed-case/tests/utils/test_query_encoding.py +++ b/seed/python-sdk/mixed-case/tests/utils/test_query_encoding.py @@ -4,9 +4,15 @@ def test_query_encoding() -> None: - assert encode_query({"hello world": "hello world"}) == {"hello world": "hello world"} - assert encode_query({"hello_world": {"hello": "world"}}) == {"hello_world[hello]": "world"} - assert encode_query({"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"}) == { + assert encode_query({"hello world": "hello world"}) == { + "hello world": "hello world" + } + assert encode_query({"hello_world": {"hello": "world"}}) == { + "hello_world[hello]": "world" + } + assert encode_query( + {"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"} + ) == { "hello_world[hello][world]": "today", "hello_world[test]": "this", "hi": "there", diff --git a/seed/python-sdk/mixed-case/tests/utils/test_serialization.py b/seed/python-sdk/mixed-case/tests/utils/test_serialization.py index 58b1ed66e6d..5ca956916dd 100644 --- a/seed/python-sdk/mixed-case/tests/utils/test_serialization.py +++ b/seed/python-sdk/mixed-case/tests/utils/test_serialization.py @@ -1,10 +1,12 @@ # This file was auto-generated by Fern from our API Definition. -from typing import Any, List +from typing import List, Any -from seed.core.serialization import convert_and_respect_annotation_metadata +from seed.core.serialization import ( + convert_and_respect_annotation_metadata, +) +from .assets.models import ShapeParams, ObjectWithOptionalFieldParams -from .assets.models import ObjectWithOptionalFieldParams, ShapeParams UNION_TEST: ShapeParams = {"radius_measurement": 1.0, "shape_type": "circle", "id": "1"} UNION_TEST_CONVERTED = {"shapeType": "circle", "radiusMeasurement": 1.0, "id": "1"} @@ -18,20 +20,54 @@ def test_convert_and_respect_annotation_metadata() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) - assert converted == {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"} + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) + assert converted == { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + } def test_convert_and_respect_annotation_metadata_in_list() -> None: data: List[ObjectWithOptionalFieldParams] = [ - {"string": "string", "long_": 12345, "bool_": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long_": 67890, "list_": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long_": 12345, + "bool_": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long_": 67890, + "list_": [], + "literal": "lit_one", + "any": "any", + }, ] - converted = convert_and_respect_annotation_metadata(object_=data, annotation=List[ObjectWithOptionalFieldParams]) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=List[ObjectWithOptionalFieldParams] + ) assert converted == [ - {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long": 67890, "list": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long": 67890, + "list": [], + "literal": "lit_one", + "any": "any", + }, ] @@ -43,7 +79,9 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) assert converted == { "string": "string", @@ -55,12 +93,16 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: def test_convert_and_respect_annotation_metadata_in_union() -> None: - converted = convert_and_respect_annotation_metadata(object_=UNION_TEST, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=UNION_TEST, annotation=ShapeParams + ) assert converted == UNION_TEST_CONVERTED def test_convert_and_respect_annotation_metadata_with_empty_object() -> None: data: Any = {} - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ShapeParams + ) assert converted == data diff --git a/seed/python-sdk/multi-line-docs/pyproject.toml b/seed/python-sdk/multi-line-docs/pyproject.toml index 27ab0cc7c61..cfa2eed2a95 100644 --- a/seed/python-sdk/multi-line-docs/pyproject.toml +++ b/seed/python-sdk/multi-line-docs/pyproject.toml @@ -43,6 +43,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/python-sdk/multi-line-docs/src/seed/__init__.py b/seed/python-sdk/multi-line-docs/src/seed/__init__.py index 94ee1386a9b..a12dafce2b3 100644 --- a/seed/python-sdk/multi-line-docs/src/seed/__init__.py +++ b/seed/python-sdk/multi-line-docs/src/seed/__init__.py @@ -6,4 +6,11 @@ from .user import User from .version import __version__ -__all__ = ["AsyncSeedMultiLineDocs", "Operand", "SeedMultiLineDocs", "User", "__version__", "user"] +__all__ = [ + "AsyncSeedMultiLineDocs", + "Operand", + "SeedMultiLineDocs", + "User", + "__version__", + "user", +] diff --git a/seed/python-sdk/multi-line-docs/src/seed/client.py b/seed/python-sdk/multi-line-docs/src/seed/client.py index b966aa2c908..6fb61b59443 100644 --- a/seed/python-sdk/multi-line-docs/src/seed/client.py +++ b/seed/python-sdk/multi-line-docs/src/seed/client.py @@ -1,11 +1,11 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from .user.client import AsyncUserClient, UserClient +from .core.client_wrapper import SyncClientWrapper +from .user.client import UserClient +from .core.client_wrapper import AsyncClientWrapper +from .user.client import AsyncUserClient class SeedMultiLineDocs: @@ -41,14 +41,18 @@ def __init__( base_url: str, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.Client] = None + httpx_client: typing.Optional[httpx.Client] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = SyncClientWrapper( base_url=base_url, httpx_client=httpx_client if httpx_client is not None - else httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.Client( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.Client(timeout=_defaulted_timeout), timeout=_defaulted_timeout, @@ -89,14 +93,18 @@ def __init__( base_url: str, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.AsyncClient] = None + httpx_client: typing.Optional[httpx.AsyncClient] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = AsyncClientWrapper( base_url=base_url, httpx_client=httpx_client if httpx_client is not None - else httpx.AsyncClient(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.AsyncClient( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.AsyncClient(timeout=_defaulted_timeout), timeout=_defaulted_timeout, diff --git a/seed/python-sdk/multi-line-docs/src/seed/core/api_error.py b/seed/python-sdk/multi-line-docs/src/seed/core/api_error.py index 2e9fc5431cd..da734b58068 100644 --- a/seed/python-sdk/multi-line-docs/src/seed/core/api_error.py +++ b/seed/python-sdk/multi-line-docs/src/seed/core/api_error.py @@ -7,7 +7,9 @@ class ApiError(Exception): status_code: typing.Optional[int] body: typing.Any - def __init__(self, *, status_code: typing.Optional[int] = None, body: typing.Any = None): + def __init__( + self, *, status_code: typing.Optional[int] = None, body: typing.Any = None + ): self.status_code = status_code self.body = body diff --git a/seed/python-sdk/multi-line-docs/src/seed/core/client_wrapper.py b/seed/python-sdk/multi-line-docs/src/seed/core/client_wrapper.py index ed66db48b7f..8dc95ae3014 100644 --- a/seed/python-sdk/multi-line-docs/src/seed/core/client_wrapper.py +++ b/seed/python-sdk/multi-line-docs/src/seed/core/client_wrapper.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .http_client import AsyncHttpClient, HttpClient +from .http_client import HttpClient +from .http_client import AsyncHttpClient class BaseClientWrapper: @@ -28,7 +27,13 @@ def get_timeout(self) -> typing.Optional[float]: class SyncClientWrapper(BaseClientWrapper): - def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, httpx_client: httpx.Client): + def __init__( + self, + *, + base_url: str, + timeout: typing.Optional[float] = None, + httpx_client: httpx.Client, + ): super().__init__(base_url=base_url, timeout=timeout) self.httpx_client = HttpClient( httpx_client=httpx_client, @@ -39,7 +44,13 @@ def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, htt class AsyncClientWrapper(BaseClientWrapper): - def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, httpx_client: httpx.AsyncClient): + def __init__( + self, + *, + base_url: str, + timeout: typing.Optional[float] = None, + httpx_client: httpx.AsyncClient, + ): super().__init__(base_url=base_url, timeout=timeout) self.httpx_client = AsyncHttpClient( httpx_client=httpx_client, diff --git a/seed/python-sdk/multi-line-docs/src/seed/core/datetime_utils.py b/seed/python-sdk/multi-line-docs/src/seed/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/python-sdk/multi-line-docs/src/seed/core/datetime_utils.py +++ b/seed/python-sdk/multi-line-docs/src/seed/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/python-sdk/multi-line-docs/src/seed/core/file.py b/seed/python-sdk/multi-line-docs/src/seed/core/file.py index cb0d40bbbf3..6e0f92bfcb1 100644 --- a/seed/python-sdk/multi-line-docs/src/seed/core/file.py +++ b/seed/python-sdk/multi-line-docs/src/seed/core/file.py @@ -13,12 +13,17 @@ # (filename, file (or bytes), content_type) typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str]], # (filename, file (or bytes), content_type, headers) - typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str], typing.Mapping[str, str]], + typing.Tuple[ + typing.Optional[str], + FileContent, + typing.Optional[str], + typing.Mapping[str, str], + ], ] def convert_file_dict_to_httpx_tuples( - d: typing.Dict[str, typing.Union[File, typing.List[File]]] + d: typing.Dict[str, typing.Union[File, typing.List[File]]], ) -> typing.List[typing.Tuple[str, File]]: """ The format we use is a list of tuples, where the first element is the diff --git a/seed/python-sdk/multi-line-docs/src/seed/core/http_client.py b/seed/python-sdk/multi-line-docs/src/seed/core/http_client.py index 9333d8a7f15..091f71bc185 100644 --- a/seed/python-sdk/multi-line-docs/src/seed/core/http_client.py +++ b/seed/python-sdk/multi-line-docs/src/seed/core/http_client.py @@ -77,7 +77,9 @@ def _retry_timeout(response: httpx.Response, retries: int) -> float: return retry_after # Apply exponential backoff, capped at MAX_RETRY_DELAY_SECONDS. - retry_delay = min(INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS) + retry_delay = min( + INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS + ) # Add a randomness / jitter to the retry delay to avoid overwhelming the server with retries. timeout = retry_delay * (1 - 0.25 * random()) @@ -90,7 +92,8 @@ def _should_retry(response: httpx.Response) -> bool: def remove_omit_from_dict( - original: typing.Dict[str, typing.Optional[typing.Any]], omit: typing.Optional[typing.Any] + original: typing.Dict[str, typing.Optional[typing.Any]], + omit: typing.Optional[typing.Any], ) -> typing.Dict[str, typing.Any]: if omit is None: return original @@ -108,7 +111,8 @@ def maybe_filter_request_body( ) -> typing.Optional[typing.Any]: if data is None: return ( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else None ) @@ -118,7 +122,8 @@ def maybe_filter_request_body( data_content = { **(jsonable_encoder(remove_omit_from_dict(data, omit))), # type: ignore **( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else {} ), @@ -162,7 +167,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url def request( @@ -174,8 +181,12 @@ def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -184,11 +195,14 @@ def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) response = self.httpx_client.request( method=method, @@ -198,7 +212,11 @@ def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -209,7 +227,10 @@ def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -222,11 +243,15 @@ def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: time.sleep(_retry_timeout(response=response, retries=retries)) @@ -256,8 +281,12 @@ def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -266,11 +295,14 @@ def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) with self.httpx_client.stream( method=method, @@ -280,7 +312,11 @@ def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -291,7 +327,9 @@ def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -304,7 +342,9 @@ def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream @@ -327,7 +367,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url async def request( @@ -339,8 +381,12 @@ async def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -349,11 +395,14 @@ async def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) # Add the input to each of these and do None-safety checks response = await self.httpx_client.request( @@ -364,7 +413,11 @@ async def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -375,7 +428,10 @@ async def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -388,11 +444,15 @@ async def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: await asyncio.sleep(_retry_timeout(response=response, retries=retries)) @@ -421,8 +481,12 @@ async def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -431,11 +495,14 @@ async def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) async with self.httpx_client.stream( method=method, @@ -445,7 +512,11 @@ async def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -456,7 +527,9 @@ async def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -469,7 +542,9 @@ async def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream diff --git a/seed/python-sdk/multi-line-docs/src/seed/core/jsonable_encoder.py b/seed/python-sdk/multi-line-docs/src/seed/core/jsonable_encoder.py index d3fd328fd41..12a8b52fc22 100644 --- a/seed/python-sdk/multi-line-docs/src/seed/core/jsonable_encoder.py +++ b/seed/python-sdk/multi-line-docs/src/seed/core/jsonable_encoder.py @@ -19,13 +19,19 @@ import pydantic from .datetime_utils import serialize_datetime -from .pydantic_utilities import IS_PYDANTIC_V2, encode_by_type, to_jsonable_with_fallback +from .pydantic_utilities import ( + IS_PYDANTIC_V2, + encode_by_type, + to_jsonable_with_fallback, +) SetIntStr = Set[Union[int, str]] DictIntStrAny = Dict[Union[int, str], Any] -def jsonable_encoder(obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None) -> Any: +def jsonable_encoder( + obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None +) -> Any: custom_encoder = custom_encoder or {} if custom_encoder: if type(obj) in custom_encoder: diff --git a/seed/python-sdk/multi-line-docs/src/seed/core/pydantic_utilities.py b/seed/python-sdk/multi-line-docs/src/seed/core/pydantic_utilities.py index 170a563d6eb..c63935c32a2 100644 --- a/seed/python-sdk/multi-line-docs/src/seed/core/pydantic_utilities.py +++ b/seed/python-sdk/multi-line-docs/src/seed/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) # type: ignore # Pydantic v1 diff --git a/seed/python-sdk/multi-line-docs/src/seed/core/query_encoder.py b/seed/python-sdk/multi-line-docs/src/seed/core/query_encoder.py index 24076d72ee9..7cb98f52cd7 100644 --- a/seed/python-sdk/multi-line-docs/src/seed/core/query_encoder.py +++ b/seed/python-sdk/multi-line-docs/src/seed/core/query_encoder.py @@ -7,7 +7,9 @@ # Flattens dicts to be of the form {"key[subkey][subkey2]": value} where value is not a dict -def traverse_query_dict(dict_flat: Dict[str, Any], key_prefix: Optional[str] = None) -> Dict[str, Any]: +def traverse_query_dict( + dict_flat: Dict[str, Any], key_prefix: Optional[str] = None +) -> Dict[str, Any]: result = {} for k, v in dict_flat.items(): key = f"{key_prefix}[{k}]" if key_prefix is not None else k @@ -30,4 +32,8 @@ def single_query_encoder(query_key: str, query_value: Any) -> Dict[str, Any]: def encode_query(query: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: - return dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) if query is not None else None + return ( + dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) + if query is not None + else None + ) diff --git a/seed/python-sdk/multi-line-docs/src/seed/core/serialization.py b/seed/python-sdk/multi-line-docs/src/seed/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/python-sdk/multi-line-docs/src/seed/core/serialization.py +++ b/seed/python-sdk/multi-line-docs/src/seed/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/python-sdk/multi-line-docs/src/seed/user/client.py b/seed/python-sdk/multi-line-docs/src/seed/user/client.py index 8bb33fd560d..c08a303f4e5 100644 --- a/seed/python-sdk/multi-line-docs/src/seed/user/client.py +++ b/seed/python-sdk/multi-line-docs/src/seed/user/client.py @@ -1,14 +1,14 @@ # This file was auto-generated by Fern from our API Definition. import typing +from ..core.client_wrapper import SyncClientWrapper +from ..core.request_options import RequestOptions +from ..core.jsonable_encoder import jsonable_encoder from json.decoder import JSONDecodeError - from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.jsonable_encoder import jsonable_encoder -from ..core.pydantic_utilities import parse_obj_as -from ..core.request_options import RequestOptions from .types.user import User +from ..core.pydantic_utilities import parse_obj_as +from ..core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -18,7 +18,9 @@ class UserClient: def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper - def get_user(self, user_id: str, *, request_options: typing.Optional[RequestOptions] = None) -> None: + def get_user( + self, user_id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> None: """ Retrieve a user. This endpoint is used to retrieve a user. @@ -48,7 +50,9 @@ def get_user(self, user_id: str, *, request_options: typing.Optional[RequestOpti ) """ _response = self._client_wrapper.httpx_client.request( - f"users/{jsonable_encoder(user_id)}", method="GET", request_options=request_options + f"users/{jsonable_encoder(user_id)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: @@ -59,7 +63,11 @@ def get_user(self, user_id: str, *, request_options: typing.Optional[RequestOpti raise ApiError(status_code=_response.status_code, body=_response_json) def create_user( - self, *, name: str, age: typing.Optional[int] = OMIT, request_options: typing.Optional[RequestOptions] = None + self, + *, + name: str, + age: typing.Optional[int] = OMIT, + request_options: typing.Optional[RequestOptions] = None, ) -> User: """ Create a new user. @@ -97,11 +105,20 @@ def create_user( ) """ _response = self._client_wrapper.httpx_client.request( - "users", method="POST", json={"name": name, "age": age}, request_options=request_options, omit=OMIT + "users", + method="POST", + json={ + "name": name, + "age": age, + }, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(User, parse_obj_as(type_=User, object_=_response.json())) # type: ignore + return typing.cast( + User, parse_obj_as(type_=User, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -112,7 +129,9 @@ class AsyncUserClient: def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper - async def get_user(self, user_id: str, *, request_options: typing.Optional[RequestOptions] = None) -> None: + async def get_user( + self, user_id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> None: """ Retrieve a user. This endpoint is used to retrieve a user. @@ -150,7 +169,9 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - f"users/{jsonable_encoder(user_id)}", method="GET", request_options=request_options + f"users/{jsonable_encoder(user_id)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: @@ -161,7 +182,11 @@ async def main() -> None: raise ApiError(status_code=_response.status_code, body=_response_json) async def create_user( - self, *, name: str, age: typing.Optional[int] = OMIT, request_options: typing.Optional[RequestOptions] = None + self, + *, + name: str, + age: typing.Optional[int] = OMIT, + request_options: typing.Optional[RequestOptions] = None, ) -> User: """ Create a new user. @@ -207,11 +232,20 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "users", method="POST", json={"name": name, "age": age}, request_options=request_options, omit=OMIT + "users", + method="POST", + json={ + "name": name, + "age": age, + }, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(User, parse_obj_as(type_=User, object_=_response.json())) # type: ignore + return typing.cast( + User, parse_obj_as(type_=User, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/multi-line-docs/src/seed/user/types/user.py b/seed/python-sdk/multi-line-docs/src/seed/user/types/user.py index 0050a356fc0..8ed9e184bd4 100644 --- a/seed/python-sdk/multi-line-docs/src/seed/user/types/user.py +++ b/seed/python-sdk/multi-line-docs/src/seed/user/types/user.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ...core.pydantic_utilities import UniversalBaseModel import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +import typing +from ...core.pydantic_utilities import IS_PYDANTIC_V2 class User(UniversalBaseModel): @@ -31,7 +30,9 @@ class User(UniversalBaseModel): """ if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/multi-line-docs/src/seed/version.py b/seed/python-sdk/multi-line-docs/src/seed/version.py index 19203ca56bf..2b1591e3e1f 100644 --- a/seed/python-sdk/multi-line-docs/src/seed/version.py +++ b/seed/python-sdk/multi-line-docs/src/seed/version.py @@ -1,4 +1,3 @@ - from importlib import metadata __version__ = metadata.version("fern_multi-line-docs") diff --git a/seed/python-sdk/multi-line-docs/tests/conftest.py b/seed/python-sdk/multi-line-docs/tests/conftest.py index e5b874b2056..d2b08fd3651 100644 --- a/seed/python-sdk/multi-line-docs/tests/conftest.py +++ b/seed/python-sdk/multi-line-docs/tests/conftest.py @@ -1,9 +1,9 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedMultiLineDocs import os - import pytest -from seed import AsyncSeedMultiLineDocs, SeedMultiLineDocs +from seed import AsyncSeedMultiLineDocs @pytest.fixture diff --git a/seed/python-sdk/multi-line-docs/tests/custom/test_client.py b/seed/python-sdk/multi-line-docs/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/python-sdk/multi-line-docs/tests/custom/test_client.py +++ b/seed/python-sdk/multi-line-docs/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/python-sdk/multi-line-docs/tests/test_user.py b/seed/python-sdk/multi-line-docs/tests/test_user.py index 2e7b2dd5be8..0c229c5f09a 100644 --- a/seed/python-sdk/multi-line-docs/tests/test_user.py +++ b/seed/python-sdk/multi-line-docs/tests/test_user.py @@ -1,20 +1,23 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedMultiLineDocs +from seed import AsyncSeedMultiLineDocs import typing - -from seed import AsyncSeedMultiLineDocs, SeedMultiLineDocs - from .utilities import validate_response -async def test_get_user(client: SeedMultiLineDocs, async_client: AsyncSeedMultiLineDocs) -> None: +async def test_get_user( + client: SeedMultiLineDocs, async_client: AsyncSeedMultiLineDocs +) -> None: # Type ignore to avoid mypy complaining about the function not being meant to return a value assert client.user.get_user(user_id="string") is None # type: ignore[func-returns-value] assert await async_client.user.get_user(user_id="string") is None # type: ignore[func-returns-value] -async def test_create_user(client: SeedMultiLineDocs, async_client: AsyncSeedMultiLineDocs) -> None: +async def test_create_user( + client: SeedMultiLineDocs, async_client: AsyncSeedMultiLineDocs +) -> None: expected_response: typing.Any = {"id": "string", "name": "string", "age": 1} expected_types: typing.Any = {"id": None, "name": None, "age": "integer"} response = client.user.create_user(name="string", age=1) diff --git a/seed/python-sdk/multi-line-docs/tests/utilities.py b/seed/python-sdk/multi-line-docs/tests/utilities.py index 13da208eb3a..e8f4472564c 100644 --- a/seed/python-sdk/multi-line-docs/tests/utilities.py +++ b/seed/python-sdk/multi-line-docs/tests/utilities.py @@ -3,11 +3,14 @@ import typing import uuid -import pydantic from dateutil import parser +import pydantic + -def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> typing.Any: +def cast_field( + json_expectation: typing.Any, type_expectation: typing.Any +) -> typing.Any: # Cast these specific types which come through as string and expect our # models to cast to the correct type. if type_expectation == "uuid": @@ -25,7 +28,9 @@ def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> ty return json_expectation -def validate_field(response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any) -> None: +def validate_field( + response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectation == "no_validate": return @@ -44,7 +49,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(entry_expectation, dict): is_container_of_complex_type = True validate_response( - response=response[idx], json_expectation=ex, type_expectations=entry_expectation + response=response[idx], + json_expectation=ex, + type_expectations=entry_expectation, ) else: cast_json_expectation.append(cast_field(ex, entry_expectation)) @@ -56,7 +63,10 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # if any of the values of the set have a type_expectation of a dict, we're assuming it's a pydantic # model and keeping it a list. if container_expectation != "set" or not any( - map(lambda value: isinstance(value, dict), list(contents_expectation.values())) + map( + lambda value: isinstance(value, dict), + list(contents_expectation.values()), + ) ): json_expectation = cast_field(json_expectation, container_expectation) elif isinstance(type_expectation, tuple): @@ -65,9 +75,15 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(contents_expectation, dict): json_expectation = { cast_field( - key, contents_expectation.get(idx)[0] if contents_expectation.get(idx) is not None else None # type: ignore + key, + contents_expectation.get(idx)[0] + if contents_expectation.get(idx) is not None + else None, # type: ignore ): cast_field( - value, contents_expectation.get(idx)[1] if contents_expectation.get(idx) is not None else None # type: ignore + value, + contents_expectation.get(idx)[1] + if contents_expectation.get(idx) is not None + else None, # type: ignore ) for idx, (key, value) in enumerate(json_expectation.items()) } @@ -86,7 +102,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # Arg type_expectations is a deeply nested structure that matches the response, but with the values replaced with the expected types -def validate_response(response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any) -> None: +def validate_response( + response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectations == "no_validate": return @@ -96,11 +114,17 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e and not isinstance(response, dict) and not issubclass(type(response), pydantic.BaseModel) ): - validate_field(response=response, json_expectation=json_expectation, type_expectation=type_expectations) + validate_field( + response=response, + json_expectation=json_expectation, + type_expectation=type_expectations, + ) return if isinstance(response, list): - assert len(response) == len(json_expectation), "Length mismatch, expected: {0}, Actual: {1}".format( + assert len(response) == len( + json_expectation + ), "Length mismatch, expected: {0}, Actual: {1}".format( len(response), len(json_expectation) ) content_expectation = type_expectations @@ -108,7 +132,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e content_expectation = type_expectations[1] for idx, item in enumerate(response): validate_response( - response=item, json_expectation=json_expectation[idx], type_expectations=content_expectation[idx] + response=item, + json_expectation=json_expectation[idx], + type_expectations=content_expectation[idx], ) else: response_json = response @@ -116,7 +142,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e response_json = response.dict(by_alias=True) for key, value in json_expectation.items(): - assert key in response_json, "Field {0} not found within the response object: {1}".format( + assert ( + key in response_json + ), "Field {0} not found within the response object: {1}".format( key, response_json ) @@ -128,11 +156,19 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e # Otherwise, we're just validating a single field that's a pydantic model. if isinstance(value, dict) and not isinstance(type_expectation, tuple): validate_response( - response=response_json[key], json_expectation=value, type_expectations=type_expectation + response=response_json[key], + json_expectation=value, + type_expectations=type_expectation, ) else: - validate_field(response=response_json[key], json_expectation=value, type_expectation=type_expectation) + validate_field( + response=response_json[key], + json_expectation=value, + type_expectation=type_expectation, + ) # Ensure there are no additional fields here either del response_json[key] - assert len(response_json) == 0, "Additional fields found, expected None: {0}".format(response_json) + assert ( + len(response_json) == 0 + ), "Additional fields found, expected None: {0}".format(response_json) diff --git a/seed/python-sdk/multi-line-docs/tests/utils/assets/models/__init__.py b/seed/python-sdk/multi-line-docs/tests/utils/assets/models/__init__.py index 2cf01263529..3a1c852e71e 100644 --- a/seed/python-sdk/multi-line-docs/tests/utils/assets/models/__init__.py +++ b/seed/python-sdk/multi-line-docs/tests/utils/assets/models/__init__.py @@ -5,7 +5,7 @@ from .circle import CircleParams from .object_with_defaults import ObjectWithDefaultsParams from .object_with_optional_field import ObjectWithOptionalFieldParams -from .shape import Shape_CircleParams, Shape_SquareParams, ShapeParams +from .shape import ShapeParams, Shape_CircleParams, Shape_SquareParams from .square import SquareParams from .undiscriminated_shape import UndiscriminatedShapeParams diff --git a/seed/python-sdk/multi-line-docs/tests/utils/assets/models/circle.py b/seed/python-sdk/multi-line-docs/tests/utils/assets/models/circle.py index af7a1bf8a8e..253f12d38b3 100644 --- a/seed/python-sdk/multi-line-docs/tests/utils/assets/models/circle.py +++ b/seed/python-sdk/multi-line-docs/tests/utils/assets/models/circle.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class CircleParams(typing_extensions.TypedDict): - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] diff --git a/seed/python-sdk/multi-line-docs/tests/utils/assets/models/object_with_optional_field.py b/seed/python-sdk/multi-line-docs/tests/utils/assets/models/object_with_optional_field.py index 3ad93d5f305..ebe7dc80547 100644 --- a/seed/python-sdk/multi-line-docs/tests/utils/assets/models/object_with_optional_field.py +++ b/seed/python-sdk/multi-line-docs/tests/utils/assets/models/object_with_optional_field.py @@ -7,8 +7,8 @@ import uuid import typing_extensions -from seed.core.serialization import FieldMetadata +from seed.core.serialization import FieldMetadata from .color import Color from .shape import ShapeParams from .undiscriminated_shape import UndiscriminatedShapeParams @@ -18,16 +18,30 @@ class ObjectWithOptionalFieldParams(typing_extensions.TypedDict): literal: typing.Literal["lit_one"] string: typing_extensions.NotRequired[str] integer: typing_extensions.NotRequired[int] - long_: typing_extensions.NotRequired[typing_extensions.Annotated[int, FieldMetadata(alias="long")]] + long_: typing_extensions.NotRequired[ + typing_extensions.Annotated[int, FieldMetadata(alias="long")] + ] double: typing_extensions.NotRequired[float] - bool_: typing_extensions.NotRequired[typing_extensions.Annotated[bool, FieldMetadata(alias="bool")]] + bool_: typing_extensions.NotRequired[ + typing_extensions.Annotated[bool, FieldMetadata(alias="bool")] + ] datetime: typing_extensions.NotRequired[dt.datetime] date: typing_extensions.NotRequired[dt.date] - uuid_: typing_extensions.NotRequired[typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")]] - base_64: typing_extensions.NotRequired[typing_extensions.Annotated[str, FieldMetadata(alias="base64")]] - list_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")]] - set_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")]] - map_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")]] + uuid_: typing_extensions.NotRequired[ + typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")] + ] + base_64: typing_extensions.NotRequired[ + typing_extensions.Annotated[str, FieldMetadata(alias="base64")] + ] + list_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")] + ] + set_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")] + ] + map_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")] + ] enum: typing_extensions.NotRequired[Color] union: typing_extensions.NotRequired[ShapeParams] second_union: typing_extensions.NotRequired[ShapeParams] diff --git a/seed/python-sdk/multi-line-docs/tests/utils/assets/models/shape.py b/seed/python-sdk/multi-line-docs/tests/utils/assets/models/shape.py index 2c33c877951..816ffc51bdc 100644 --- a/seed/python-sdk/multi-line-docs/tests/utils/assets/models/shape.py +++ b/seed/python-sdk/multi-line-docs/tests/utils/assets/models/shape.py @@ -7,6 +7,7 @@ import typing import typing_extensions + from seed.core.serialization import FieldMetadata @@ -15,13 +16,21 @@ class Base(typing_extensions.TypedDict): class Shape_CircleParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["circle"], FieldMetadata(alias="shapeType")] - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["circle"], FieldMetadata(alias="shapeType") + ] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] class Shape_SquareParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["square"], FieldMetadata(alias="shapeType")] - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["square"], FieldMetadata(alias="shapeType") + ] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] ShapeParams = typing.Union[Shape_CircleParams, Shape_SquareParams] diff --git a/seed/python-sdk/multi-line-docs/tests/utils/assets/models/square.py b/seed/python-sdk/multi-line-docs/tests/utils/assets/models/square.py index b9b7dd319bc..bcf08a723c5 100644 --- a/seed/python-sdk/multi-line-docs/tests/utils/assets/models/square.py +++ b/seed/python-sdk/multi-line-docs/tests/utils/assets/models/square.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class SquareParams(typing_extensions.TypedDict): - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] diff --git a/seed/python-sdk/multi-line-docs/tests/utils/test_http_client.py b/seed/python-sdk/multi-line-docs/tests/utils/test_http_client.py index edd11ca7afb..f5a874a75f3 100644 --- a/seed/python-sdk/multi-line-docs/tests/utils/test_http_client.py +++ b/seed/python-sdk/multi-line-docs/tests/utils/test_http_client.py @@ -9,12 +9,17 @@ def get_request_options() -> RequestOptions: def test_get_json_request_body() -> None: - json_body, data_body = get_request_body(json={"hello": "world"}, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json={"hello": "world"}, data=None, request_options=None, omit=None + ) assert json_body == {"hello": "world"} assert data_body is None json_body_extras, data_body_extras = get_request_body( - json={"goodbye": "world"}, data=None, request_options=get_request_options(), omit=None + json={"goodbye": "world"}, + data=None, + request_options=get_request_options(), + omit=None, ) assert json_body_extras == {"goodbye": "world", "see you": "later"} @@ -22,12 +27,17 @@ def test_get_json_request_body() -> None: def test_get_files_request_body() -> None: - json_body, data_body = get_request_body(json=None, data={"hello": "world"}, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data={"hello": "world"}, request_options=None, omit=None + ) assert data_body == {"hello": "world"} assert json_body is None json_body_extras, data_body_extras = get_request_body( - json=None, data={"goodbye": "world"}, request_options=get_request_options(), omit=None + json=None, + data={"goodbye": "world"}, + request_options=get_request_options(), + omit=None, ) assert data_body_extras == {"goodbye": "world", "see you": "later"} @@ -35,7 +45,9 @@ def test_get_files_request_body() -> None: def test_get_none_request_body() -> None: - json_body, data_body = get_request_body(json=None, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data=None, request_options=None, omit=None + ) assert data_body is None assert json_body is None diff --git a/seed/python-sdk/multi-line-docs/tests/utils/test_query_encoding.py b/seed/python-sdk/multi-line-docs/tests/utils/test_query_encoding.py index 247e1551b46..fbc8f402167 100644 --- a/seed/python-sdk/multi-line-docs/tests/utils/test_query_encoding.py +++ b/seed/python-sdk/multi-line-docs/tests/utils/test_query_encoding.py @@ -4,9 +4,15 @@ def test_query_encoding() -> None: - assert encode_query({"hello world": "hello world"}) == {"hello world": "hello world"} - assert encode_query({"hello_world": {"hello": "world"}}) == {"hello_world[hello]": "world"} - assert encode_query({"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"}) == { + assert encode_query({"hello world": "hello world"}) == { + "hello world": "hello world" + } + assert encode_query({"hello_world": {"hello": "world"}}) == { + "hello_world[hello]": "world" + } + assert encode_query( + {"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"} + ) == { "hello_world[hello][world]": "today", "hello_world[test]": "this", "hi": "there", diff --git a/seed/python-sdk/multi-line-docs/tests/utils/test_serialization.py b/seed/python-sdk/multi-line-docs/tests/utils/test_serialization.py index 58b1ed66e6d..5ca956916dd 100644 --- a/seed/python-sdk/multi-line-docs/tests/utils/test_serialization.py +++ b/seed/python-sdk/multi-line-docs/tests/utils/test_serialization.py @@ -1,10 +1,12 @@ # This file was auto-generated by Fern from our API Definition. -from typing import Any, List +from typing import List, Any -from seed.core.serialization import convert_and_respect_annotation_metadata +from seed.core.serialization import ( + convert_and_respect_annotation_metadata, +) +from .assets.models import ShapeParams, ObjectWithOptionalFieldParams -from .assets.models import ObjectWithOptionalFieldParams, ShapeParams UNION_TEST: ShapeParams = {"radius_measurement": 1.0, "shape_type": "circle", "id": "1"} UNION_TEST_CONVERTED = {"shapeType": "circle", "radiusMeasurement": 1.0, "id": "1"} @@ -18,20 +20,54 @@ def test_convert_and_respect_annotation_metadata() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) - assert converted == {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"} + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) + assert converted == { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + } def test_convert_and_respect_annotation_metadata_in_list() -> None: data: List[ObjectWithOptionalFieldParams] = [ - {"string": "string", "long_": 12345, "bool_": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long_": 67890, "list_": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long_": 12345, + "bool_": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long_": 67890, + "list_": [], + "literal": "lit_one", + "any": "any", + }, ] - converted = convert_and_respect_annotation_metadata(object_=data, annotation=List[ObjectWithOptionalFieldParams]) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=List[ObjectWithOptionalFieldParams] + ) assert converted == [ - {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long": 67890, "list": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long": 67890, + "list": [], + "literal": "lit_one", + "any": "any", + }, ] @@ -43,7 +79,9 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) assert converted == { "string": "string", @@ -55,12 +93,16 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: def test_convert_and_respect_annotation_metadata_in_union() -> None: - converted = convert_and_respect_annotation_metadata(object_=UNION_TEST, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=UNION_TEST, annotation=ShapeParams + ) assert converted == UNION_TEST_CONVERTED def test_convert_and_respect_annotation_metadata_with_empty_object() -> None: data: Any = {} - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ShapeParams + ) assert converted == data diff --git a/seed/python-sdk/multi-url-environment-no-default/pyproject.toml b/seed/python-sdk/multi-url-environment-no-default/pyproject.toml index 39d43645ba5..0a602de202f 100644 --- a/seed/python-sdk/multi-url-environment-no-default/pyproject.toml +++ b/seed/python-sdk/multi-url-environment-no-default/pyproject.toml @@ -43,6 +43,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/python-sdk/multi-url-environment-no-default/src/seed/__init__.py b/seed/python-sdk/multi-url-environment-no-default/src/seed/__init__.py index f37a887fc11..89f4ca6be36 100644 --- a/seed/python-sdk/multi-url-environment-no-default/src/seed/__init__.py +++ b/seed/python-sdk/multi-url-environment-no-default/src/seed/__init__.py @@ -1,7 +1,10 @@ # This file was auto-generated by Fern from our API Definition. from . import ec_2, s_3 -from .client import AsyncSeedMultiUrlEnvironmentNoDefault, SeedMultiUrlEnvironmentNoDefault +from .client import ( + AsyncSeedMultiUrlEnvironmentNoDefault, + SeedMultiUrlEnvironmentNoDefault, +) from .environment import SeedMultiUrlEnvironmentNoDefaultEnvironment from .version import __version__ diff --git a/seed/python-sdk/multi-url-environment-no-default/src/seed/client.py b/seed/python-sdk/multi-url-environment-no-default/src/seed/client.py index 89bc0a93321..ccff93bee75 100644 --- a/seed/python-sdk/multi-url-environment-no-default/src/seed/client.py +++ b/seed/python-sdk/multi-url-environment-no-default/src/seed/client.py @@ -1,13 +1,14 @@ # This file was auto-generated by Fern from our API Definition. +from .environment import SeedMultiUrlEnvironmentNoDefaultEnvironment import typing - import httpx - -from .core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from .ec_2.client import AsyncEc2Client, Ec2Client -from .environment import SeedMultiUrlEnvironmentNoDefaultEnvironment -from .s_3.client import AsyncS3Client, S3Client +from .core.client_wrapper import SyncClientWrapper +from .ec_2.client import Ec2Client +from .s_3.client import S3Client +from .core.client_wrapper import AsyncClientWrapper +from .ec_2.client import AsyncEc2Client +from .s_3.client import AsyncS3Client class SeedMultiUrlEnvironmentNoDefault: @@ -47,15 +48,19 @@ def __init__( token: typing.Union[str, typing.Callable[[], str]], timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.Client] = None + httpx_client: typing.Optional[httpx.Client] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = SyncClientWrapper( environment=environment, token=token, httpx_client=httpx_client if httpx_client is not None - else httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.Client( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.Client(timeout=_defaulted_timeout), timeout=_defaulted_timeout, @@ -101,15 +106,19 @@ def __init__( token: typing.Union[str, typing.Callable[[], str]], timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.AsyncClient] = None + httpx_client: typing.Optional[httpx.AsyncClient] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = AsyncClientWrapper( environment=environment, token=token, httpx_client=httpx_client if httpx_client is not None - else httpx.AsyncClient(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.AsyncClient( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.AsyncClient(timeout=_defaulted_timeout), timeout=_defaulted_timeout, diff --git a/seed/python-sdk/multi-url-environment-no-default/src/seed/core/api_error.py b/seed/python-sdk/multi-url-environment-no-default/src/seed/core/api_error.py index 2e9fc5431cd..da734b58068 100644 --- a/seed/python-sdk/multi-url-environment-no-default/src/seed/core/api_error.py +++ b/seed/python-sdk/multi-url-environment-no-default/src/seed/core/api_error.py @@ -7,7 +7,9 @@ class ApiError(Exception): status_code: typing.Optional[int] body: typing.Any - def __init__(self, *, status_code: typing.Optional[int] = None, body: typing.Any = None): + def __init__( + self, *, status_code: typing.Optional[int] = None, body: typing.Any = None + ): self.status_code = status_code self.body = body diff --git a/seed/python-sdk/multi-url-environment-no-default/src/seed/core/client_wrapper.py b/seed/python-sdk/multi-url-environment-no-default/src/seed/core/client_wrapper.py index f6966c5b45b..099f567d712 100644 --- a/seed/python-sdk/multi-url-environment-no-default/src/seed/core/client_wrapper.py +++ b/seed/python-sdk/multi-url-environment-no-default/src/seed/core/client_wrapper.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. import typing - -import httpx - from ..environment import SeedMultiUrlEnvironmentNoDefaultEnvironment -from .http_client import AsyncHttpClient, HttpClient +import httpx +from .http_client import HttpClient +from .http_client import AsyncHttpClient class BaseClientWrapper: @@ -53,7 +52,9 @@ def __init__( ): super().__init__(token=token, environment=environment, timeout=timeout) self.httpx_client = HttpClient( - httpx_client=httpx_client, base_headers=self.get_headers(), base_timeout=self.get_timeout() + httpx_client=httpx_client, + base_headers=self.get_headers(), + base_timeout=self.get_timeout(), ) @@ -68,5 +69,7 @@ def __init__( ): super().__init__(token=token, environment=environment, timeout=timeout) self.httpx_client = AsyncHttpClient( - httpx_client=httpx_client, base_headers=self.get_headers(), base_timeout=self.get_timeout() + httpx_client=httpx_client, + base_headers=self.get_headers(), + base_timeout=self.get_timeout(), ) diff --git a/seed/python-sdk/multi-url-environment-no-default/src/seed/core/datetime_utils.py b/seed/python-sdk/multi-url-environment-no-default/src/seed/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/python-sdk/multi-url-environment-no-default/src/seed/core/datetime_utils.py +++ b/seed/python-sdk/multi-url-environment-no-default/src/seed/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/python-sdk/multi-url-environment-no-default/src/seed/core/file.py b/seed/python-sdk/multi-url-environment-no-default/src/seed/core/file.py index cb0d40bbbf3..6e0f92bfcb1 100644 --- a/seed/python-sdk/multi-url-environment-no-default/src/seed/core/file.py +++ b/seed/python-sdk/multi-url-environment-no-default/src/seed/core/file.py @@ -13,12 +13,17 @@ # (filename, file (or bytes), content_type) typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str]], # (filename, file (or bytes), content_type, headers) - typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str], typing.Mapping[str, str]], + typing.Tuple[ + typing.Optional[str], + FileContent, + typing.Optional[str], + typing.Mapping[str, str], + ], ] def convert_file_dict_to_httpx_tuples( - d: typing.Dict[str, typing.Union[File, typing.List[File]]] + d: typing.Dict[str, typing.Union[File, typing.List[File]]], ) -> typing.List[typing.Tuple[str, File]]: """ The format we use is a list of tuples, where the first element is the diff --git a/seed/python-sdk/multi-url-environment-no-default/src/seed/core/http_client.py b/seed/python-sdk/multi-url-environment-no-default/src/seed/core/http_client.py index 9333d8a7f15..091f71bc185 100644 --- a/seed/python-sdk/multi-url-environment-no-default/src/seed/core/http_client.py +++ b/seed/python-sdk/multi-url-environment-no-default/src/seed/core/http_client.py @@ -77,7 +77,9 @@ def _retry_timeout(response: httpx.Response, retries: int) -> float: return retry_after # Apply exponential backoff, capped at MAX_RETRY_DELAY_SECONDS. - retry_delay = min(INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS) + retry_delay = min( + INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS + ) # Add a randomness / jitter to the retry delay to avoid overwhelming the server with retries. timeout = retry_delay * (1 - 0.25 * random()) @@ -90,7 +92,8 @@ def _should_retry(response: httpx.Response) -> bool: def remove_omit_from_dict( - original: typing.Dict[str, typing.Optional[typing.Any]], omit: typing.Optional[typing.Any] + original: typing.Dict[str, typing.Optional[typing.Any]], + omit: typing.Optional[typing.Any], ) -> typing.Dict[str, typing.Any]: if omit is None: return original @@ -108,7 +111,8 @@ def maybe_filter_request_body( ) -> typing.Optional[typing.Any]: if data is None: return ( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else None ) @@ -118,7 +122,8 @@ def maybe_filter_request_body( data_content = { **(jsonable_encoder(remove_omit_from_dict(data, omit))), # type: ignore **( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else {} ), @@ -162,7 +167,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url def request( @@ -174,8 +181,12 @@ def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -184,11 +195,14 @@ def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) response = self.httpx_client.request( method=method, @@ -198,7 +212,11 @@ def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -209,7 +227,10 @@ def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -222,11 +243,15 @@ def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: time.sleep(_retry_timeout(response=response, retries=retries)) @@ -256,8 +281,12 @@ def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -266,11 +295,14 @@ def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) with self.httpx_client.stream( method=method, @@ -280,7 +312,11 @@ def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -291,7 +327,9 @@ def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -304,7 +342,9 @@ def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream @@ -327,7 +367,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url async def request( @@ -339,8 +381,12 @@ async def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -349,11 +395,14 @@ async def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) # Add the input to each of these and do None-safety checks response = await self.httpx_client.request( @@ -364,7 +413,11 @@ async def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -375,7 +428,10 @@ async def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -388,11 +444,15 @@ async def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: await asyncio.sleep(_retry_timeout(response=response, retries=retries)) @@ -421,8 +481,12 @@ async def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -431,11 +495,14 @@ async def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) async with self.httpx_client.stream( method=method, @@ -445,7 +512,11 @@ async def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -456,7 +527,9 @@ async def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -469,7 +542,9 @@ async def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream diff --git a/seed/python-sdk/multi-url-environment-no-default/src/seed/core/jsonable_encoder.py b/seed/python-sdk/multi-url-environment-no-default/src/seed/core/jsonable_encoder.py index d3fd328fd41..12a8b52fc22 100644 --- a/seed/python-sdk/multi-url-environment-no-default/src/seed/core/jsonable_encoder.py +++ b/seed/python-sdk/multi-url-environment-no-default/src/seed/core/jsonable_encoder.py @@ -19,13 +19,19 @@ import pydantic from .datetime_utils import serialize_datetime -from .pydantic_utilities import IS_PYDANTIC_V2, encode_by_type, to_jsonable_with_fallback +from .pydantic_utilities import ( + IS_PYDANTIC_V2, + encode_by_type, + to_jsonable_with_fallback, +) SetIntStr = Set[Union[int, str]] DictIntStrAny = Dict[Union[int, str], Any] -def jsonable_encoder(obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None) -> Any: +def jsonable_encoder( + obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None +) -> Any: custom_encoder = custom_encoder or {} if custom_encoder: if type(obj) in custom_encoder: diff --git a/seed/python-sdk/multi-url-environment-no-default/src/seed/core/pydantic_utilities.py b/seed/python-sdk/multi-url-environment-no-default/src/seed/core/pydantic_utilities.py index 170a563d6eb..c63935c32a2 100644 --- a/seed/python-sdk/multi-url-environment-no-default/src/seed/core/pydantic_utilities.py +++ b/seed/python-sdk/multi-url-environment-no-default/src/seed/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) # type: ignore # Pydantic v1 diff --git a/seed/python-sdk/multi-url-environment-no-default/src/seed/core/query_encoder.py b/seed/python-sdk/multi-url-environment-no-default/src/seed/core/query_encoder.py index 24076d72ee9..7cb98f52cd7 100644 --- a/seed/python-sdk/multi-url-environment-no-default/src/seed/core/query_encoder.py +++ b/seed/python-sdk/multi-url-environment-no-default/src/seed/core/query_encoder.py @@ -7,7 +7,9 @@ # Flattens dicts to be of the form {"key[subkey][subkey2]": value} where value is not a dict -def traverse_query_dict(dict_flat: Dict[str, Any], key_prefix: Optional[str] = None) -> Dict[str, Any]: +def traverse_query_dict( + dict_flat: Dict[str, Any], key_prefix: Optional[str] = None +) -> Dict[str, Any]: result = {} for k, v in dict_flat.items(): key = f"{key_prefix}[{k}]" if key_prefix is not None else k @@ -30,4 +32,8 @@ def single_query_encoder(query_key: str, query_value: Any) -> Dict[str, Any]: def encode_query(query: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: - return dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) if query is not None else None + return ( + dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) + if query is not None + else None + ) diff --git a/seed/python-sdk/multi-url-environment-no-default/src/seed/core/serialization.py b/seed/python-sdk/multi-url-environment-no-default/src/seed/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/python-sdk/multi-url-environment-no-default/src/seed/core/serialization.py +++ b/seed/python-sdk/multi-url-environment-no-default/src/seed/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/python-sdk/multi-url-environment-no-default/src/seed/ec_2/client.py b/seed/python-sdk/multi-url-environment-no-default/src/seed/ec_2/client.py index 7180e1ce28b..828b812535d 100644 --- a/seed/python-sdk/multi-url-environment-no-default/src/seed/ec_2/client.py +++ b/seed/python-sdk/multi-url-environment-no-default/src/seed/ec_2/client.py @@ -1,11 +1,11 @@ # This file was auto-generated by Fern from our API Definition. import typing +from ..core.client_wrapper import SyncClientWrapper +from ..core.request_options import RequestOptions from json.decoder import JSONDecodeError - from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.request_options import RequestOptions +from ..core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -15,7 +15,9 @@ class Ec2Client: def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper - def boot_instance(self, *, size: str, request_options: typing.Optional[RequestOptions] = None) -> None: + def boot_instance( + self, *, size: str, request_options: typing.Optional[RequestOptions] = None + ) -> None: """ Parameters ---------- @@ -45,7 +47,9 @@ def boot_instance(self, *, size: str, request_options: typing.Optional[RequestOp "ec2/boot", base_url=self._client_wrapper.get_environment().ec_2, method="POST", - json={"size": size}, + json={ + "size": size, + }, request_options=request_options, omit=OMIT, ) @@ -62,7 +66,9 @@ class AsyncEc2Client: def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper - async def boot_instance(self, *, size: str, request_options: typing.Optional[RequestOptions] = None) -> None: + async def boot_instance( + self, *, size: str, request_options: typing.Optional[RequestOptions] = None + ) -> None: """ Parameters ---------- @@ -100,7 +106,9 @@ async def main() -> None: "ec2/boot", base_url=self._client_wrapper.get_environment().ec_2, method="POST", - json={"size": size}, + json={ + "size": size, + }, request_options=request_options, omit=OMIT, ) diff --git a/seed/python-sdk/multi-url-environment-no-default/src/seed/environment.py b/seed/python-sdk/multi-url-environment-no-default/src/seed/environment.py index fa4388d5b20..f44c3bd027e 100644 --- a/seed/python-sdk/multi-url-environment-no-default/src/seed/environment.py +++ b/seed/python-sdk/multi-url-environment-no-default/src/seed/environment.py @@ -12,9 +12,13 @@ def __init__(self, *, ec_2: str, s_3: str): self.s_3 = s_3 -SeedMultiUrlEnvironmentNoDefaultEnvironment.PRODUCTION = SeedMultiUrlEnvironmentNoDefaultEnvironment( - ec_2="https://ec2.aws.com", s_3="https://s3.aws.com" +SeedMultiUrlEnvironmentNoDefaultEnvironment.PRODUCTION = ( + SeedMultiUrlEnvironmentNoDefaultEnvironment( + ec_2="https://ec2.aws.com", s_3="https://s3.aws.com" + ) ) -SeedMultiUrlEnvironmentNoDefaultEnvironment.STAGING = SeedMultiUrlEnvironmentNoDefaultEnvironment( - ec_2="https://staging.ec2.aws.com", s_3="https://staging.s3.aws.com" +SeedMultiUrlEnvironmentNoDefaultEnvironment.STAGING = ( + SeedMultiUrlEnvironmentNoDefaultEnvironment( + ec_2="https://staging.ec2.aws.com", s_3="https://staging.s3.aws.com" + ) ) diff --git a/seed/python-sdk/multi-url-environment-no-default/src/seed/s_3/client.py b/seed/python-sdk/multi-url-environment-no-default/src/seed/s_3/client.py index fa481757e00..302c915a879 100644 --- a/seed/python-sdk/multi-url-environment-no-default/src/seed/s_3/client.py +++ b/seed/python-sdk/multi-url-environment-no-default/src/seed/s_3/client.py @@ -1,12 +1,12 @@ # This file was auto-generated by Fern from our API Definition. import typing +from ..core.client_wrapper import SyncClientWrapper +from ..core.request_options import RequestOptions +from ..core.pydantic_utilities import parse_obj_as from json.decoder import JSONDecodeError - from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.pydantic_utilities import parse_obj_as -from ..core.request_options import RequestOptions +from ..core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -16,7 +16,9 @@ class S3Client: def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper - def get_presigned_url(self, *, s_3_key: str, request_options: typing.Optional[RequestOptions] = None) -> str: + def get_presigned_url( + self, *, s_3_key: str, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -46,13 +48,17 @@ def get_presigned_url(self, *, s_3_key: str, request_options: typing.Optional[Re "s3/presigned-url", base_url=self._client_wrapper.get_environment().s_3, method="POST", - json={"s3Key": s_3_key}, + json={ + "s3Key": s_3_key, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -63,7 +69,9 @@ class AsyncS3Client: def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper - async def get_presigned_url(self, *, s_3_key: str, request_options: typing.Optional[RequestOptions] = None) -> str: + async def get_presigned_url( + self, *, s_3_key: str, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -101,13 +109,17 @@ async def main() -> None: "s3/presigned-url", base_url=self._client_wrapper.get_environment().s_3, method="POST", - json={"s3Key": s_3_key}, + json={ + "s3Key": s_3_key, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/multi-url-environment-no-default/src/seed/version.py b/seed/python-sdk/multi-url-environment-no-default/src/seed/version.py index df7e8175f82..951bd1de01c 100644 --- a/seed/python-sdk/multi-url-environment-no-default/src/seed/version.py +++ b/seed/python-sdk/multi-url-environment-no-default/src/seed/version.py @@ -1,4 +1,3 @@ - from importlib import metadata __version__ = metadata.version("fern_multi-url-environment-no-default") diff --git a/seed/python-sdk/multi-url-environment-no-default/tests/conftest.py b/seed/python-sdk/multi-url-environment-no-default/tests/conftest.py index 80dfbd87bed..38c6d59f2c8 100644 --- a/seed/python-sdk/multi-url-environment-no-default/tests/conftest.py +++ b/seed/python-sdk/multi-url-environment-no-default/tests/conftest.py @@ -1,10 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedMultiUrlEnvironmentNoDefault import os - -import pytest -from seed import AsyncSeedMultiUrlEnvironmentNoDefault, SeedMultiUrlEnvironmentNoDefault from seed.environment import SeedMultiUrlEnvironmentNoDefaultEnvironment +import pytest +from seed import AsyncSeedMultiUrlEnvironmentNoDefault @pytest.fixture @@ -12,7 +12,8 @@ def client() -> SeedMultiUrlEnvironmentNoDefault: return SeedMultiUrlEnvironmentNoDefault( token=os.getenv("ENV_TOKEN", "token"), environment=SeedMultiUrlEnvironmentNoDefaultEnvironment( - ec_2=os.getenv("TESTS_BASE_URL", "base_url"), s_3=os.getenv("TESTS_BASE_URL", "base_url") + ec_2=os.getenv("TESTS_BASE_URL", "base_url"), + s_3=os.getenv("TESTS_BASE_URL", "base_url"), ), ) @@ -22,6 +23,7 @@ def async_client() -> AsyncSeedMultiUrlEnvironmentNoDefault: return AsyncSeedMultiUrlEnvironmentNoDefault( token=os.getenv("ENV_TOKEN", "token"), environment=SeedMultiUrlEnvironmentNoDefaultEnvironment( - ec_2=os.getenv("TESTS_BASE_URL", "base_url"), s_3=os.getenv("TESTS_BASE_URL", "base_url") + ec_2=os.getenv("TESTS_BASE_URL", "base_url"), + s_3=os.getenv("TESTS_BASE_URL", "base_url"), ), ) diff --git a/seed/python-sdk/multi-url-environment-no-default/tests/custom/test_client.py b/seed/python-sdk/multi-url-environment-no-default/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/python-sdk/multi-url-environment-no-default/tests/custom/test_client.py +++ b/seed/python-sdk/multi-url-environment-no-default/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/python-sdk/multi-url-environment-no-default/tests/test_ec_2.py b/seed/python-sdk/multi-url-environment-no-default/tests/test_ec_2.py index 43d620a07c8..ff3f99d3574 100644 --- a/seed/python-sdk/multi-url-environment-no-default/tests/test_ec_2.py +++ b/seed/python-sdk/multi-url-environment-no-default/tests/test_ec_2.py @@ -1,10 +1,12 @@ # This file was auto-generated by Fern from our API Definition. -from seed import AsyncSeedMultiUrlEnvironmentNoDefault, SeedMultiUrlEnvironmentNoDefault +from seed import SeedMultiUrlEnvironmentNoDefault +from seed import AsyncSeedMultiUrlEnvironmentNoDefault async def test_boot_instance( - client: SeedMultiUrlEnvironmentNoDefault, async_client: AsyncSeedMultiUrlEnvironmentNoDefault + client: SeedMultiUrlEnvironmentNoDefault, + async_client: AsyncSeedMultiUrlEnvironmentNoDefault, ) -> None: # Type ignore to avoid mypy complaining about the function not being meant to return a value assert client.ec_2.boot_instance(size="string") is None # type: ignore[func-returns-value] diff --git a/seed/python-sdk/multi-url-environment-no-default/tests/test_s_3.py b/seed/python-sdk/multi-url-environment-no-default/tests/test_s_3.py index d204807883f..cf2d0c6061a 100644 --- a/seed/python-sdk/multi-url-environment-no-default/tests/test_s_3.py +++ b/seed/python-sdk/multi-url-environment-no-default/tests/test_s_3.py @@ -1,14 +1,14 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedMultiUrlEnvironmentNoDefault +from seed import AsyncSeedMultiUrlEnvironmentNoDefault import typing - -from seed import AsyncSeedMultiUrlEnvironmentNoDefault, SeedMultiUrlEnvironmentNoDefault - from .utilities import validate_response async def test_get_presigned_url( - client: SeedMultiUrlEnvironmentNoDefault, async_client: AsyncSeedMultiUrlEnvironmentNoDefault + client: SeedMultiUrlEnvironmentNoDefault, + async_client: AsyncSeedMultiUrlEnvironmentNoDefault, ) -> None: expected_response: typing.Any = "string" expected_types: typing.Any = None diff --git a/seed/python-sdk/multi-url-environment-no-default/tests/utilities.py b/seed/python-sdk/multi-url-environment-no-default/tests/utilities.py index 13da208eb3a..e8f4472564c 100644 --- a/seed/python-sdk/multi-url-environment-no-default/tests/utilities.py +++ b/seed/python-sdk/multi-url-environment-no-default/tests/utilities.py @@ -3,11 +3,14 @@ import typing import uuid -import pydantic from dateutil import parser +import pydantic + -def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> typing.Any: +def cast_field( + json_expectation: typing.Any, type_expectation: typing.Any +) -> typing.Any: # Cast these specific types which come through as string and expect our # models to cast to the correct type. if type_expectation == "uuid": @@ -25,7 +28,9 @@ def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> ty return json_expectation -def validate_field(response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any) -> None: +def validate_field( + response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectation == "no_validate": return @@ -44,7 +49,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(entry_expectation, dict): is_container_of_complex_type = True validate_response( - response=response[idx], json_expectation=ex, type_expectations=entry_expectation + response=response[idx], + json_expectation=ex, + type_expectations=entry_expectation, ) else: cast_json_expectation.append(cast_field(ex, entry_expectation)) @@ -56,7 +63,10 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # if any of the values of the set have a type_expectation of a dict, we're assuming it's a pydantic # model and keeping it a list. if container_expectation != "set" or not any( - map(lambda value: isinstance(value, dict), list(contents_expectation.values())) + map( + lambda value: isinstance(value, dict), + list(contents_expectation.values()), + ) ): json_expectation = cast_field(json_expectation, container_expectation) elif isinstance(type_expectation, tuple): @@ -65,9 +75,15 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(contents_expectation, dict): json_expectation = { cast_field( - key, contents_expectation.get(idx)[0] if contents_expectation.get(idx) is not None else None # type: ignore + key, + contents_expectation.get(idx)[0] + if contents_expectation.get(idx) is not None + else None, # type: ignore ): cast_field( - value, contents_expectation.get(idx)[1] if contents_expectation.get(idx) is not None else None # type: ignore + value, + contents_expectation.get(idx)[1] + if contents_expectation.get(idx) is not None + else None, # type: ignore ) for idx, (key, value) in enumerate(json_expectation.items()) } @@ -86,7 +102,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # Arg type_expectations is a deeply nested structure that matches the response, but with the values replaced with the expected types -def validate_response(response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any) -> None: +def validate_response( + response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectations == "no_validate": return @@ -96,11 +114,17 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e and not isinstance(response, dict) and not issubclass(type(response), pydantic.BaseModel) ): - validate_field(response=response, json_expectation=json_expectation, type_expectation=type_expectations) + validate_field( + response=response, + json_expectation=json_expectation, + type_expectation=type_expectations, + ) return if isinstance(response, list): - assert len(response) == len(json_expectation), "Length mismatch, expected: {0}, Actual: {1}".format( + assert len(response) == len( + json_expectation + ), "Length mismatch, expected: {0}, Actual: {1}".format( len(response), len(json_expectation) ) content_expectation = type_expectations @@ -108,7 +132,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e content_expectation = type_expectations[1] for idx, item in enumerate(response): validate_response( - response=item, json_expectation=json_expectation[idx], type_expectations=content_expectation[idx] + response=item, + json_expectation=json_expectation[idx], + type_expectations=content_expectation[idx], ) else: response_json = response @@ -116,7 +142,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e response_json = response.dict(by_alias=True) for key, value in json_expectation.items(): - assert key in response_json, "Field {0} not found within the response object: {1}".format( + assert ( + key in response_json + ), "Field {0} not found within the response object: {1}".format( key, response_json ) @@ -128,11 +156,19 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e # Otherwise, we're just validating a single field that's a pydantic model. if isinstance(value, dict) and not isinstance(type_expectation, tuple): validate_response( - response=response_json[key], json_expectation=value, type_expectations=type_expectation + response=response_json[key], + json_expectation=value, + type_expectations=type_expectation, ) else: - validate_field(response=response_json[key], json_expectation=value, type_expectation=type_expectation) + validate_field( + response=response_json[key], + json_expectation=value, + type_expectation=type_expectation, + ) # Ensure there are no additional fields here either del response_json[key] - assert len(response_json) == 0, "Additional fields found, expected None: {0}".format(response_json) + assert ( + len(response_json) == 0 + ), "Additional fields found, expected None: {0}".format(response_json) diff --git a/seed/python-sdk/multi-url-environment-no-default/tests/utils/assets/models/__init__.py b/seed/python-sdk/multi-url-environment-no-default/tests/utils/assets/models/__init__.py index 2cf01263529..3a1c852e71e 100644 --- a/seed/python-sdk/multi-url-environment-no-default/tests/utils/assets/models/__init__.py +++ b/seed/python-sdk/multi-url-environment-no-default/tests/utils/assets/models/__init__.py @@ -5,7 +5,7 @@ from .circle import CircleParams from .object_with_defaults import ObjectWithDefaultsParams from .object_with_optional_field import ObjectWithOptionalFieldParams -from .shape import Shape_CircleParams, Shape_SquareParams, ShapeParams +from .shape import ShapeParams, Shape_CircleParams, Shape_SquareParams from .square import SquareParams from .undiscriminated_shape import UndiscriminatedShapeParams diff --git a/seed/python-sdk/multi-url-environment-no-default/tests/utils/assets/models/circle.py b/seed/python-sdk/multi-url-environment-no-default/tests/utils/assets/models/circle.py index af7a1bf8a8e..253f12d38b3 100644 --- a/seed/python-sdk/multi-url-environment-no-default/tests/utils/assets/models/circle.py +++ b/seed/python-sdk/multi-url-environment-no-default/tests/utils/assets/models/circle.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class CircleParams(typing_extensions.TypedDict): - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] diff --git a/seed/python-sdk/multi-url-environment-no-default/tests/utils/assets/models/object_with_optional_field.py b/seed/python-sdk/multi-url-environment-no-default/tests/utils/assets/models/object_with_optional_field.py index 3ad93d5f305..ebe7dc80547 100644 --- a/seed/python-sdk/multi-url-environment-no-default/tests/utils/assets/models/object_with_optional_field.py +++ b/seed/python-sdk/multi-url-environment-no-default/tests/utils/assets/models/object_with_optional_field.py @@ -7,8 +7,8 @@ import uuid import typing_extensions -from seed.core.serialization import FieldMetadata +from seed.core.serialization import FieldMetadata from .color import Color from .shape import ShapeParams from .undiscriminated_shape import UndiscriminatedShapeParams @@ -18,16 +18,30 @@ class ObjectWithOptionalFieldParams(typing_extensions.TypedDict): literal: typing.Literal["lit_one"] string: typing_extensions.NotRequired[str] integer: typing_extensions.NotRequired[int] - long_: typing_extensions.NotRequired[typing_extensions.Annotated[int, FieldMetadata(alias="long")]] + long_: typing_extensions.NotRequired[ + typing_extensions.Annotated[int, FieldMetadata(alias="long")] + ] double: typing_extensions.NotRequired[float] - bool_: typing_extensions.NotRequired[typing_extensions.Annotated[bool, FieldMetadata(alias="bool")]] + bool_: typing_extensions.NotRequired[ + typing_extensions.Annotated[bool, FieldMetadata(alias="bool")] + ] datetime: typing_extensions.NotRequired[dt.datetime] date: typing_extensions.NotRequired[dt.date] - uuid_: typing_extensions.NotRequired[typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")]] - base_64: typing_extensions.NotRequired[typing_extensions.Annotated[str, FieldMetadata(alias="base64")]] - list_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")]] - set_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")]] - map_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")]] + uuid_: typing_extensions.NotRequired[ + typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")] + ] + base_64: typing_extensions.NotRequired[ + typing_extensions.Annotated[str, FieldMetadata(alias="base64")] + ] + list_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")] + ] + set_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")] + ] + map_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")] + ] enum: typing_extensions.NotRequired[Color] union: typing_extensions.NotRequired[ShapeParams] second_union: typing_extensions.NotRequired[ShapeParams] diff --git a/seed/python-sdk/multi-url-environment-no-default/tests/utils/assets/models/shape.py b/seed/python-sdk/multi-url-environment-no-default/tests/utils/assets/models/shape.py index 2c33c877951..816ffc51bdc 100644 --- a/seed/python-sdk/multi-url-environment-no-default/tests/utils/assets/models/shape.py +++ b/seed/python-sdk/multi-url-environment-no-default/tests/utils/assets/models/shape.py @@ -7,6 +7,7 @@ import typing import typing_extensions + from seed.core.serialization import FieldMetadata @@ -15,13 +16,21 @@ class Base(typing_extensions.TypedDict): class Shape_CircleParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["circle"], FieldMetadata(alias="shapeType")] - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["circle"], FieldMetadata(alias="shapeType") + ] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] class Shape_SquareParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["square"], FieldMetadata(alias="shapeType")] - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["square"], FieldMetadata(alias="shapeType") + ] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] ShapeParams = typing.Union[Shape_CircleParams, Shape_SquareParams] diff --git a/seed/python-sdk/multi-url-environment-no-default/tests/utils/assets/models/square.py b/seed/python-sdk/multi-url-environment-no-default/tests/utils/assets/models/square.py index b9b7dd319bc..bcf08a723c5 100644 --- a/seed/python-sdk/multi-url-environment-no-default/tests/utils/assets/models/square.py +++ b/seed/python-sdk/multi-url-environment-no-default/tests/utils/assets/models/square.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class SquareParams(typing_extensions.TypedDict): - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] diff --git a/seed/python-sdk/multi-url-environment-no-default/tests/utils/test_http_client.py b/seed/python-sdk/multi-url-environment-no-default/tests/utils/test_http_client.py index edd11ca7afb..f5a874a75f3 100644 --- a/seed/python-sdk/multi-url-environment-no-default/tests/utils/test_http_client.py +++ b/seed/python-sdk/multi-url-environment-no-default/tests/utils/test_http_client.py @@ -9,12 +9,17 @@ def get_request_options() -> RequestOptions: def test_get_json_request_body() -> None: - json_body, data_body = get_request_body(json={"hello": "world"}, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json={"hello": "world"}, data=None, request_options=None, omit=None + ) assert json_body == {"hello": "world"} assert data_body is None json_body_extras, data_body_extras = get_request_body( - json={"goodbye": "world"}, data=None, request_options=get_request_options(), omit=None + json={"goodbye": "world"}, + data=None, + request_options=get_request_options(), + omit=None, ) assert json_body_extras == {"goodbye": "world", "see you": "later"} @@ -22,12 +27,17 @@ def test_get_json_request_body() -> None: def test_get_files_request_body() -> None: - json_body, data_body = get_request_body(json=None, data={"hello": "world"}, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data={"hello": "world"}, request_options=None, omit=None + ) assert data_body == {"hello": "world"} assert json_body is None json_body_extras, data_body_extras = get_request_body( - json=None, data={"goodbye": "world"}, request_options=get_request_options(), omit=None + json=None, + data={"goodbye": "world"}, + request_options=get_request_options(), + omit=None, ) assert data_body_extras == {"goodbye": "world", "see you": "later"} @@ -35,7 +45,9 @@ def test_get_files_request_body() -> None: def test_get_none_request_body() -> None: - json_body, data_body = get_request_body(json=None, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data=None, request_options=None, omit=None + ) assert data_body is None assert json_body is None diff --git a/seed/python-sdk/multi-url-environment-no-default/tests/utils/test_query_encoding.py b/seed/python-sdk/multi-url-environment-no-default/tests/utils/test_query_encoding.py index 247e1551b46..fbc8f402167 100644 --- a/seed/python-sdk/multi-url-environment-no-default/tests/utils/test_query_encoding.py +++ b/seed/python-sdk/multi-url-environment-no-default/tests/utils/test_query_encoding.py @@ -4,9 +4,15 @@ def test_query_encoding() -> None: - assert encode_query({"hello world": "hello world"}) == {"hello world": "hello world"} - assert encode_query({"hello_world": {"hello": "world"}}) == {"hello_world[hello]": "world"} - assert encode_query({"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"}) == { + assert encode_query({"hello world": "hello world"}) == { + "hello world": "hello world" + } + assert encode_query({"hello_world": {"hello": "world"}}) == { + "hello_world[hello]": "world" + } + assert encode_query( + {"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"} + ) == { "hello_world[hello][world]": "today", "hello_world[test]": "this", "hi": "there", diff --git a/seed/python-sdk/multi-url-environment-no-default/tests/utils/test_serialization.py b/seed/python-sdk/multi-url-environment-no-default/tests/utils/test_serialization.py index 58b1ed66e6d..5ca956916dd 100644 --- a/seed/python-sdk/multi-url-environment-no-default/tests/utils/test_serialization.py +++ b/seed/python-sdk/multi-url-environment-no-default/tests/utils/test_serialization.py @@ -1,10 +1,12 @@ # This file was auto-generated by Fern from our API Definition. -from typing import Any, List +from typing import List, Any -from seed.core.serialization import convert_and_respect_annotation_metadata +from seed.core.serialization import ( + convert_and_respect_annotation_metadata, +) +from .assets.models import ShapeParams, ObjectWithOptionalFieldParams -from .assets.models import ObjectWithOptionalFieldParams, ShapeParams UNION_TEST: ShapeParams = {"radius_measurement": 1.0, "shape_type": "circle", "id": "1"} UNION_TEST_CONVERTED = {"shapeType": "circle", "radiusMeasurement": 1.0, "id": "1"} @@ -18,20 +20,54 @@ def test_convert_and_respect_annotation_metadata() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) - assert converted == {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"} + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) + assert converted == { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + } def test_convert_and_respect_annotation_metadata_in_list() -> None: data: List[ObjectWithOptionalFieldParams] = [ - {"string": "string", "long_": 12345, "bool_": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long_": 67890, "list_": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long_": 12345, + "bool_": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long_": 67890, + "list_": [], + "literal": "lit_one", + "any": "any", + }, ] - converted = convert_and_respect_annotation_metadata(object_=data, annotation=List[ObjectWithOptionalFieldParams]) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=List[ObjectWithOptionalFieldParams] + ) assert converted == [ - {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long": 67890, "list": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long": 67890, + "list": [], + "literal": "lit_one", + "any": "any", + }, ] @@ -43,7 +79,9 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) assert converted == { "string": "string", @@ -55,12 +93,16 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: def test_convert_and_respect_annotation_metadata_in_union() -> None: - converted = convert_and_respect_annotation_metadata(object_=UNION_TEST, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=UNION_TEST, annotation=ShapeParams + ) assert converted == UNION_TEST_CONVERTED def test_convert_and_respect_annotation_metadata_with_empty_object() -> None: data: Any = {} - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ShapeParams + ) assert converted == data diff --git a/seed/python-sdk/multi-url-environment/pyproject.toml b/seed/python-sdk/multi-url-environment/pyproject.toml index 7721c8ed7c1..f09fc721c31 100644 --- a/seed/python-sdk/multi-url-environment/pyproject.toml +++ b/seed/python-sdk/multi-url-environment/pyproject.toml @@ -43,6 +43,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/python-sdk/multi-url-environment/src/seed/client.py b/seed/python-sdk/multi-url-environment/src/seed/client.py index ed8b3f522d9..b62eb7f288c 100644 --- a/seed/python-sdk/multi-url-environment/src/seed/client.py +++ b/seed/python-sdk/multi-url-environment/src/seed/client.py @@ -1,13 +1,14 @@ # This file was auto-generated by Fern from our API Definition. +from .environment import SeedMultiUrlEnvironmentEnvironment import typing - import httpx - -from .core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from .ec_2.client import AsyncEc2Client, Ec2Client -from .environment import SeedMultiUrlEnvironmentEnvironment -from .s_3.client import AsyncS3Client, S3Client +from .core.client_wrapper import SyncClientWrapper +from .ec_2.client import Ec2Client +from .s_3.client import S3Client +from .core.client_wrapper import AsyncClientWrapper +from .ec_2.client import AsyncEc2Client +from .s_3.client import AsyncS3Client class SeedMultiUrlEnvironment: @@ -19,8 +20,6 @@ class SeedMultiUrlEnvironment: environment : SeedMultiUrlEnvironmentEnvironment The environment to use for requests from the client. from .environment import SeedMultiUrlEnvironmentEnvironment - - Defaults to SeedMultiUrlEnvironmentEnvironment.PRODUCTION @@ -51,15 +50,19 @@ def __init__( token: typing.Union[str, typing.Callable[[], str]], timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.Client] = None + httpx_client: typing.Optional[httpx.Client] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = SyncClientWrapper( environment=environment, token=token, httpx_client=httpx_client if httpx_client is not None - else httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.Client( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.Client(timeout=_defaulted_timeout), timeout=_defaulted_timeout, @@ -77,8 +80,6 @@ class AsyncSeedMultiUrlEnvironment: environment : SeedMultiUrlEnvironmentEnvironment The environment to use for requests from the client. from .environment import SeedMultiUrlEnvironmentEnvironment - - Defaults to SeedMultiUrlEnvironmentEnvironment.PRODUCTION @@ -109,15 +110,19 @@ def __init__( token: typing.Union[str, typing.Callable[[], str]], timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.AsyncClient] = None + httpx_client: typing.Optional[httpx.AsyncClient] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = AsyncClientWrapper( environment=environment, token=token, httpx_client=httpx_client if httpx_client is not None - else httpx.AsyncClient(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.AsyncClient( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.AsyncClient(timeout=_defaulted_timeout), timeout=_defaulted_timeout, diff --git a/seed/python-sdk/multi-url-environment/src/seed/core/api_error.py b/seed/python-sdk/multi-url-environment/src/seed/core/api_error.py index 2e9fc5431cd..da734b58068 100644 --- a/seed/python-sdk/multi-url-environment/src/seed/core/api_error.py +++ b/seed/python-sdk/multi-url-environment/src/seed/core/api_error.py @@ -7,7 +7,9 @@ class ApiError(Exception): status_code: typing.Optional[int] body: typing.Any - def __init__(self, *, status_code: typing.Optional[int] = None, body: typing.Any = None): + def __init__( + self, *, status_code: typing.Optional[int] = None, body: typing.Any = None + ): self.status_code = status_code self.body = body diff --git a/seed/python-sdk/multi-url-environment/src/seed/core/client_wrapper.py b/seed/python-sdk/multi-url-environment/src/seed/core/client_wrapper.py index 5668f943302..a960cdf4ff3 100644 --- a/seed/python-sdk/multi-url-environment/src/seed/core/client_wrapper.py +++ b/seed/python-sdk/multi-url-environment/src/seed/core/client_wrapper.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. import typing - -import httpx - from ..environment import SeedMultiUrlEnvironmentEnvironment -from .http_client import AsyncHttpClient, HttpClient +import httpx +from .http_client import HttpClient +from .http_client import AsyncHttpClient class BaseClientWrapper: @@ -53,7 +52,9 @@ def __init__( ): super().__init__(token=token, environment=environment, timeout=timeout) self.httpx_client = HttpClient( - httpx_client=httpx_client, base_headers=self.get_headers(), base_timeout=self.get_timeout() + httpx_client=httpx_client, + base_headers=self.get_headers(), + base_timeout=self.get_timeout(), ) @@ -68,5 +69,7 @@ def __init__( ): super().__init__(token=token, environment=environment, timeout=timeout) self.httpx_client = AsyncHttpClient( - httpx_client=httpx_client, base_headers=self.get_headers(), base_timeout=self.get_timeout() + httpx_client=httpx_client, + base_headers=self.get_headers(), + base_timeout=self.get_timeout(), ) diff --git a/seed/python-sdk/multi-url-environment/src/seed/core/datetime_utils.py b/seed/python-sdk/multi-url-environment/src/seed/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/python-sdk/multi-url-environment/src/seed/core/datetime_utils.py +++ b/seed/python-sdk/multi-url-environment/src/seed/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/python-sdk/multi-url-environment/src/seed/core/file.py b/seed/python-sdk/multi-url-environment/src/seed/core/file.py index cb0d40bbbf3..6e0f92bfcb1 100644 --- a/seed/python-sdk/multi-url-environment/src/seed/core/file.py +++ b/seed/python-sdk/multi-url-environment/src/seed/core/file.py @@ -13,12 +13,17 @@ # (filename, file (or bytes), content_type) typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str]], # (filename, file (or bytes), content_type, headers) - typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str], typing.Mapping[str, str]], + typing.Tuple[ + typing.Optional[str], + FileContent, + typing.Optional[str], + typing.Mapping[str, str], + ], ] def convert_file_dict_to_httpx_tuples( - d: typing.Dict[str, typing.Union[File, typing.List[File]]] + d: typing.Dict[str, typing.Union[File, typing.List[File]]], ) -> typing.List[typing.Tuple[str, File]]: """ The format we use is a list of tuples, where the first element is the diff --git a/seed/python-sdk/multi-url-environment/src/seed/core/http_client.py b/seed/python-sdk/multi-url-environment/src/seed/core/http_client.py index 9333d8a7f15..091f71bc185 100644 --- a/seed/python-sdk/multi-url-environment/src/seed/core/http_client.py +++ b/seed/python-sdk/multi-url-environment/src/seed/core/http_client.py @@ -77,7 +77,9 @@ def _retry_timeout(response: httpx.Response, retries: int) -> float: return retry_after # Apply exponential backoff, capped at MAX_RETRY_DELAY_SECONDS. - retry_delay = min(INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS) + retry_delay = min( + INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS + ) # Add a randomness / jitter to the retry delay to avoid overwhelming the server with retries. timeout = retry_delay * (1 - 0.25 * random()) @@ -90,7 +92,8 @@ def _should_retry(response: httpx.Response) -> bool: def remove_omit_from_dict( - original: typing.Dict[str, typing.Optional[typing.Any]], omit: typing.Optional[typing.Any] + original: typing.Dict[str, typing.Optional[typing.Any]], + omit: typing.Optional[typing.Any], ) -> typing.Dict[str, typing.Any]: if omit is None: return original @@ -108,7 +111,8 @@ def maybe_filter_request_body( ) -> typing.Optional[typing.Any]: if data is None: return ( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else None ) @@ -118,7 +122,8 @@ def maybe_filter_request_body( data_content = { **(jsonable_encoder(remove_omit_from_dict(data, omit))), # type: ignore **( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else {} ), @@ -162,7 +167,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url def request( @@ -174,8 +181,12 @@ def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -184,11 +195,14 @@ def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) response = self.httpx_client.request( method=method, @@ -198,7 +212,11 @@ def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -209,7 +227,10 @@ def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -222,11 +243,15 @@ def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: time.sleep(_retry_timeout(response=response, retries=retries)) @@ -256,8 +281,12 @@ def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -266,11 +295,14 @@ def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) with self.httpx_client.stream( method=method, @@ -280,7 +312,11 @@ def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -291,7 +327,9 @@ def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -304,7 +342,9 @@ def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream @@ -327,7 +367,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url async def request( @@ -339,8 +381,12 @@ async def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -349,11 +395,14 @@ async def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) # Add the input to each of these and do None-safety checks response = await self.httpx_client.request( @@ -364,7 +413,11 @@ async def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -375,7 +428,10 @@ async def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -388,11 +444,15 @@ async def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: await asyncio.sleep(_retry_timeout(response=response, retries=retries)) @@ -421,8 +481,12 @@ async def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -431,11 +495,14 @@ async def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) async with self.httpx_client.stream( method=method, @@ -445,7 +512,11 @@ async def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -456,7 +527,9 @@ async def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -469,7 +542,9 @@ async def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream diff --git a/seed/python-sdk/multi-url-environment/src/seed/core/jsonable_encoder.py b/seed/python-sdk/multi-url-environment/src/seed/core/jsonable_encoder.py index d3fd328fd41..12a8b52fc22 100644 --- a/seed/python-sdk/multi-url-environment/src/seed/core/jsonable_encoder.py +++ b/seed/python-sdk/multi-url-environment/src/seed/core/jsonable_encoder.py @@ -19,13 +19,19 @@ import pydantic from .datetime_utils import serialize_datetime -from .pydantic_utilities import IS_PYDANTIC_V2, encode_by_type, to_jsonable_with_fallback +from .pydantic_utilities import ( + IS_PYDANTIC_V2, + encode_by_type, + to_jsonable_with_fallback, +) SetIntStr = Set[Union[int, str]] DictIntStrAny = Dict[Union[int, str], Any] -def jsonable_encoder(obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None) -> Any: +def jsonable_encoder( + obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None +) -> Any: custom_encoder = custom_encoder or {} if custom_encoder: if type(obj) in custom_encoder: diff --git a/seed/python-sdk/multi-url-environment/src/seed/core/pydantic_utilities.py b/seed/python-sdk/multi-url-environment/src/seed/core/pydantic_utilities.py index 170a563d6eb..c63935c32a2 100644 --- a/seed/python-sdk/multi-url-environment/src/seed/core/pydantic_utilities.py +++ b/seed/python-sdk/multi-url-environment/src/seed/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) # type: ignore # Pydantic v1 diff --git a/seed/python-sdk/multi-url-environment/src/seed/core/query_encoder.py b/seed/python-sdk/multi-url-environment/src/seed/core/query_encoder.py index 24076d72ee9..7cb98f52cd7 100644 --- a/seed/python-sdk/multi-url-environment/src/seed/core/query_encoder.py +++ b/seed/python-sdk/multi-url-environment/src/seed/core/query_encoder.py @@ -7,7 +7,9 @@ # Flattens dicts to be of the form {"key[subkey][subkey2]": value} where value is not a dict -def traverse_query_dict(dict_flat: Dict[str, Any], key_prefix: Optional[str] = None) -> Dict[str, Any]: +def traverse_query_dict( + dict_flat: Dict[str, Any], key_prefix: Optional[str] = None +) -> Dict[str, Any]: result = {} for k, v in dict_flat.items(): key = f"{key_prefix}[{k}]" if key_prefix is not None else k @@ -30,4 +32,8 @@ def single_query_encoder(query_key: str, query_value: Any) -> Dict[str, Any]: def encode_query(query: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: - return dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) if query is not None else None + return ( + dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) + if query is not None + else None + ) diff --git a/seed/python-sdk/multi-url-environment/src/seed/core/serialization.py b/seed/python-sdk/multi-url-environment/src/seed/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/python-sdk/multi-url-environment/src/seed/core/serialization.py +++ b/seed/python-sdk/multi-url-environment/src/seed/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/python-sdk/multi-url-environment/src/seed/ec_2/client.py b/seed/python-sdk/multi-url-environment/src/seed/ec_2/client.py index 4f208370769..1c686476bf0 100644 --- a/seed/python-sdk/multi-url-environment/src/seed/ec_2/client.py +++ b/seed/python-sdk/multi-url-environment/src/seed/ec_2/client.py @@ -1,11 +1,11 @@ # This file was auto-generated by Fern from our API Definition. import typing +from ..core.client_wrapper import SyncClientWrapper +from ..core.request_options import RequestOptions from json.decoder import JSONDecodeError - from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.request_options import RequestOptions +from ..core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -15,7 +15,9 @@ class Ec2Client: def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper - def boot_instance(self, *, size: str, request_options: typing.Optional[RequestOptions] = None) -> None: + def boot_instance( + self, *, size: str, request_options: typing.Optional[RequestOptions] = None + ) -> None: """ Parameters ---------- @@ -43,7 +45,9 @@ def boot_instance(self, *, size: str, request_options: typing.Optional[RequestOp "ec2/boot", base_url=self._client_wrapper.get_environment().ec_2, method="POST", - json={"size": size}, + json={ + "size": size, + }, request_options=request_options, omit=OMIT, ) @@ -60,7 +64,9 @@ class AsyncEc2Client: def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper - async def boot_instance(self, *, size: str, request_options: typing.Optional[RequestOptions] = None) -> None: + async def boot_instance( + self, *, size: str, request_options: typing.Optional[RequestOptions] = None + ) -> None: """ Parameters ---------- @@ -96,7 +102,9 @@ async def main() -> None: "ec2/boot", base_url=self._client_wrapper.get_environment().ec_2, method="POST", - json={"size": size}, + json={ + "size": size, + }, request_options=request_options, omit=OMIT, ) diff --git a/seed/python-sdk/multi-url-environment/src/seed/s_3/client.py b/seed/python-sdk/multi-url-environment/src/seed/s_3/client.py index 562b84e94bd..e7f5fea8963 100644 --- a/seed/python-sdk/multi-url-environment/src/seed/s_3/client.py +++ b/seed/python-sdk/multi-url-environment/src/seed/s_3/client.py @@ -1,12 +1,12 @@ # This file was auto-generated by Fern from our API Definition. import typing +from ..core.client_wrapper import SyncClientWrapper +from ..core.request_options import RequestOptions +from ..core.pydantic_utilities import parse_obj_as from json.decoder import JSONDecodeError - from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.pydantic_utilities import parse_obj_as -from ..core.request_options import RequestOptions +from ..core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -16,7 +16,9 @@ class S3Client: def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper - def get_presigned_url(self, *, s_3_key: str, request_options: typing.Optional[RequestOptions] = None) -> str: + def get_presigned_url( + self, *, s_3_key: str, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -44,13 +46,17 @@ def get_presigned_url(self, *, s_3_key: str, request_options: typing.Optional[Re "s3/presigned-url", base_url=self._client_wrapper.get_environment().s_3, method="POST", - json={"s3Key": s_3_key}, + json={ + "s3Key": s_3_key, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -61,7 +67,9 @@ class AsyncS3Client: def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper - async def get_presigned_url(self, *, s_3_key: str, request_options: typing.Optional[RequestOptions] = None) -> str: + async def get_presigned_url( + self, *, s_3_key: str, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -97,13 +105,17 @@ async def main() -> None: "s3/presigned-url", base_url=self._client_wrapper.get_environment().s_3, method="POST", - json={"s3Key": s_3_key}, + json={ + "s3Key": s_3_key, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/multi-url-environment/src/seed/version.py b/seed/python-sdk/multi-url-environment/src/seed/version.py index 855019ef296..0d55b34746e 100644 --- a/seed/python-sdk/multi-url-environment/src/seed/version.py +++ b/seed/python-sdk/multi-url-environment/src/seed/version.py @@ -1,4 +1,3 @@ - from importlib import metadata __version__ = metadata.version("fern_multi-url-environment") diff --git a/seed/python-sdk/multi-url-environment/tests/conftest.py b/seed/python-sdk/multi-url-environment/tests/conftest.py index b34b85ba272..5de5fa65e6c 100644 --- a/seed/python-sdk/multi-url-environment/tests/conftest.py +++ b/seed/python-sdk/multi-url-environment/tests/conftest.py @@ -1,10 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedMultiUrlEnvironment import os - -import pytest -from seed import AsyncSeedMultiUrlEnvironment, SeedMultiUrlEnvironment from seed.environment import SeedMultiUrlEnvironmentEnvironment +import pytest +from seed import AsyncSeedMultiUrlEnvironment @pytest.fixture @@ -12,7 +12,8 @@ def client() -> SeedMultiUrlEnvironment: return SeedMultiUrlEnvironment( token=os.getenv("ENV_TOKEN", "token"), environment=SeedMultiUrlEnvironmentEnvironment( - ec_2=os.getenv("TESTS_BASE_URL", "base_url"), s_3=os.getenv("TESTS_BASE_URL", "base_url") + ec_2=os.getenv("TESTS_BASE_URL", "base_url"), + s_3=os.getenv("TESTS_BASE_URL", "base_url"), ), ) @@ -22,6 +23,7 @@ def async_client() -> AsyncSeedMultiUrlEnvironment: return AsyncSeedMultiUrlEnvironment( token=os.getenv("ENV_TOKEN", "token"), environment=SeedMultiUrlEnvironmentEnvironment( - ec_2=os.getenv("TESTS_BASE_URL", "base_url"), s_3=os.getenv("TESTS_BASE_URL", "base_url") + ec_2=os.getenv("TESTS_BASE_URL", "base_url"), + s_3=os.getenv("TESTS_BASE_URL", "base_url"), ), ) diff --git a/seed/python-sdk/multi-url-environment/tests/custom/test_client.py b/seed/python-sdk/multi-url-environment/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/python-sdk/multi-url-environment/tests/custom/test_client.py +++ b/seed/python-sdk/multi-url-environment/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/python-sdk/multi-url-environment/tests/test_ec_2.py b/seed/python-sdk/multi-url-environment/tests/test_ec_2.py index 16cefda9603..68252ca316a 100644 --- a/seed/python-sdk/multi-url-environment/tests/test_ec_2.py +++ b/seed/python-sdk/multi-url-environment/tests/test_ec_2.py @@ -1,9 +1,12 @@ # This file was auto-generated by Fern from our API Definition. -from seed import AsyncSeedMultiUrlEnvironment, SeedMultiUrlEnvironment +from seed import SeedMultiUrlEnvironment +from seed import AsyncSeedMultiUrlEnvironment -async def test_boot_instance(client: SeedMultiUrlEnvironment, async_client: AsyncSeedMultiUrlEnvironment) -> None: +async def test_boot_instance( + client: SeedMultiUrlEnvironment, async_client: AsyncSeedMultiUrlEnvironment +) -> None: # Type ignore to avoid mypy complaining about the function not being meant to return a value assert client.ec_2.boot_instance(size="string") is None # type: ignore[func-returns-value] diff --git a/seed/python-sdk/multi-url-environment/tests/test_s_3.py b/seed/python-sdk/multi-url-environment/tests/test_s_3.py index d31488e9d80..f4e5aade7a9 100644 --- a/seed/python-sdk/multi-url-environment/tests/test_s_3.py +++ b/seed/python-sdk/multi-url-environment/tests/test_s_3.py @@ -1,13 +1,14 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedMultiUrlEnvironment +from seed import AsyncSeedMultiUrlEnvironment import typing - -from seed import AsyncSeedMultiUrlEnvironment, SeedMultiUrlEnvironment - from .utilities import validate_response -async def test_get_presigned_url(client: SeedMultiUrlEnvironment, async_client: AsyncSeedMultiUrlEnvironment) -> None: +async def test_get_presigned_url( + client: SeedMultiUrlEnvironment, async_client: AsyncSeedMultiUrlEnvironment +) -> None: expected_response: typing.Any = "string" expected_types: typing.Any = None response = client.s_3.get_presigned_url(s_3_key="string") diff --git a/seed/python-sdk/multi-url-environment/tests/utilities.py b/seed/python-sdk/multi-url-environment/tests/utilities.py index 13da208eb3a..e8f4472564c 100644 --- a/seed/python-sdk/multi-url-environment/tests/utilities.py +++ b/seed/python-sdk/multi-url-environment/tests/utilities.py @@ -3,11 +3,14 @@ import typing import uuid -import pydantic from dateutil import parser +import pydantic + -def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> typing.Any: +def cast_field( + json_expectation: typing.Any, type_expectation: typing.Any +) -> typing.Any: # Cast these specific types which come through as string and expect our # models to cast to the correct type. if type_expectation == "uuid": @@ -25,7 +28,9 @@ def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> ty return json_expectation -def validate_field(response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any) -> None: +def validate_field( + response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectation == "no_validate": return @@ -44,7 +49,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(entry_expectation, dict): is_container_of_complex_type = True validate_response( - response=response[idx], json_expectation=ex, type_expectations=entry_expectation + response=response[idx], + json_expectation=ex, + type_expectations=entry_expectation, ) else: cast_json_expectation.append(cast_field(ex, entry_expectation)) @@ -56,7 +63,10 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # if any of the values of the set have a type_expectation of a dict, we're assuming it's a pydantic # model and keeping it a list. if container_expectation != "set" or not any( - map(lambda value: isinstance(value, dict), list(contents_expectation.values())) + map( + lambda value: isinstance(value, dict), + list(contents_expectation.values()), + ) ): json_expectation = cast_field(json_expectation, container_expectation) elif isinstance(type_expectation, tuple): @@ -65,9 +75,15 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(contents_expectation, dict): json_expectation = { cast_field( - key, contents_expectation.get(idx)[0] if contents_expectation.get(idx) is not None else None # type: ignore + key, + contents_expectation.get(idx)[0] + if contents_expectation.get(idx) is not None + else None, # type: ignore ): cast_field( - value, contents_expectation.get(idx)[1] if contents_expectation.get(idx) is not None else None # type: ignore + value, + contents_expectation.get(idx)[1] + if contents_expectation.get(idx) is not None + else None, # type: ignore ) for idx, (key, value) in enumerate(json_expectation.items()) } @@ -86,7 +102,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # Arg type_expectations is a deeply nested structure that matches the response, but with the values replaced with the expected types -def validate_response(response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any) -> None: +def validate_response( + response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectations == "no_validate": return @@ -96,11 +114,17 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e and not isinstance(response, dict) and not issubclass(type(response), pydantic.BaseModel) ): - validate_field(response=response, json_expectation=json_expectation, type_expectation=type_expectations) + validate_field( + response=response, + json_expectation=json_expectation, + type_expectation=type_expectations, + ) return if isinstance(response, list): - assert len(response) == len(json_expectation), "Length mismatch, expected: {0}, Actual: {1}".format( + assert len(response) == len( + json_expectation + ), "Length mismatch, expected: {0}, Actual: {1}".format( len(response), len(json_expectation) ) content_expectation = type_expectations @@ -108,7 +132,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e content_expectation = type_expectations[1] for idx, item in enumerate(response): validate_response( - response=item, json_expectation=json_expectation[idx], type_expectations=content_expectation[idx] + response=item, + json_expectation=json_expectation[idx], + type_expectations=content_expectation[idx], ) else: response_json = response @@ -116,7 +142,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e response_json = response.dict(by_alias=True) for key, value in json_expectation.items(): - assert key in response_json, "Field {0} not found within the response object: {1}".format( + assert ( + key in response_json + ), "Field {0} not found within the response object: {1}".format( key, response_json ) @@ -128,11 +156,19 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e # Otherwise, we're just validating a single field that's a pydantic model. if isinstance(value, dict) and not isinstance(type_expectation, tuple): validate_response( - response=response_json[key], json_expectation=value, type_expectations=type_expectation + response=response_json[key], + json_expectation=value, + type_expectations=type_expectation, ) else: - validate_field(response=response_json[key], json_expectation=value, type_expectation=type_expectation) + validate_field( + response=response_json[key], + json_expectation=value, + type_expectation=type_expectation, + ) # Ensure there are no additional fields here either del response_json[key] - assert len(response_json) == 0, "Additional fields found, expected None: {0}".format(response_json) + assert ( + len(response_json) == 0 + ), "Additional fields found, expected None: {0}".format(response_json) diff --git a/seed/python-sdk/multi-url-environment/tests/utils/assets/models/__init__.py b/seed/python-sdk/multi-url-environment/tests/utils/assets/models/__init__.py index 2cf01263529..3a1c852e71e 100644 --- a/seed/python-sdk/multi-url-environment/tests/utils/assets/models/__init__.py +++ b/seed/python-sdk/multi-url-environment/tests/utils/assets/models/__init__.py @@ -5,7 +5,7 @@ from .circle import CircleParams from .object_with_defaults import ObjectWithDefaultsParams from .object_with_optional_field import ObjectWithOptionalFieldParams -from .shape import Shape_CircleParams, Shape_SquareParams, ShapeParams +from .shape import ShapeParams, Shape_CircleParams, Shape_SquareParams from .square import SquareParams from .undiscriminated_shape import UndiscriminatedShapeParams diff --git a/seed/python-sdk/multi-url-environment/tests/utils/assets/models/circle.py b/seed/python-sdk/multi-url-environment/tests/utils/assets/models/circle.py index af7a1bf8a8e..253f12d38b3 100644 --- a/seed/python-sdk/multi-url-environment/tests/utils/assets/models/circle.py +++ b/seed/python-sdk/multi-url-environment/tests/utils/assets/models/circle.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class CircleParams(typing_extensions.TypedDict): - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] diff --git a/seed/python-sdk/multi-url-environment/tests/utils/assets/models/object_with_optional_field.py b/seed/python-sdk/multi-url-environment/tests/utils/assets/models/object_with_optional_field.py index 3ad93d5f305..ebe7dc80547 100644 --- a/seed/python-sdk/multi-url-environment/tests/utils/assets/models/object_with_optional_field.py +++ b/seed/python-sdk/multi-url-environment/tests/utils/assets/models/object_with_optional_field.py @@ -7,8 +7,8 @@ import uuid import typing_extensions -from seed.core.serialization import FieldMetadata +from seed.core.serialization import FieldMetadata from .color import Color from .shape import ShapeParams from .undiscriminated_shape import UndiscriminatedShapeParams @@ -18,16 +18,30 @@ class ObjectWithOptionalFieldParams(typing_extensions.TypedDict): literal: typing.Literal["lit_one"] string: typing_extensions.NotRequired[str] integer: typing_extensions.NotRequired[int] - long_: typing_extensions.NotRequired[typing_extensions.Annotated[int, FieldMetadata(alias="long")]] + long_: typing_extensions.NotRequired[ + typing_extensions.Annotated[int, FieldMetadata(alias="long")] + ] double: typing_extensions.NotRequired[float] - bool_: typing_extensions.NotRequired[typing_extensions.Annotated[bool, FieldMetadata(alias="bool")]] + bool_: typing_extensions.NotRequired[ + typing_extensions.Annotated[bool, FieldMetadata(alias="bool")] + ] datetime: typing_extensions.NotRequired[dt.datetime] date: typing_extensions.NotRequired[dt.date] - uuid_: typing_extensions.NotRequired[typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")]] - base_64: typing_extensions.NotRequired[typing_extensions.Annotated[str, FieldMetadata(alias="base64")]] - list_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")]] - set_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")]] - map_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")]] + uuid_: typing_extensions.NotRequired[ + typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")] + ] + base_64: typing_extensions.NotRequired[ + typing_extensions.Annotated[str, FieldMetadata(alias="base64")] + ] + list_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")] + ] + set_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")] + ] + map_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")] + ] enum: typing_extensions.NotRequired[Color] union: typing_extensions.NotRequired[ShapeParams] second_union: typing_extensions.NotRequired[ShapeParams] diff --git a/seed/python-sdk/multi-url-environment/tests/utils/assets/models/shape.py b/seed/python-sdk/multi-url-environment/tests/utils/assets/models/shape.py index 2c33c877951..816ffc51bdc 100644 --- a/seed/python-sdk/multi-url-environment/tests/utils/assets/models/shape.py +++ b/seed/python-sdk/multi-url-environment/tests/utils/assets/models/shape.py @@ -7,6 +7,7 @@ import typing import typing_extensions + from seed.core.serialization import FieldMetadata @@ -15,13 +16,21 @@ class Base(typing_extensions.TypedDict): class Shape_CircleParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["circle"], FieldMetadata(alias="shapeType")] - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["circle"], FieldMetadata(alias="shapeType") + ] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] class Shape_SquareParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["square"], FieldMetadata(alias="shapeType")] - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["square"], FieldMetadata(alias="shapeType") + ] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] ShapeParams = typing.Union[Shape_CircleParams, Shape_SquareParams] diff --git a/seed/python-sdk/multi-url-environment/tests/utils/assets/models/square.py b/seed/python-sdk/multi-url-environment/tests/utils/assets/models/square.py index b9b7dd319bc..bcf08a723c5 100644 --- a/seed/python-sdk/multi-url-environment/tests/utils/assets/models/square.py +++ b/seed/python-sdk/multi-url-environment/tests/utils/assets/models/square.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class SquareParams(typing_extensions.TypedDict): - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] diff --git a/seed/python-sdk/multi-url-environment/tests/utils/test_http_client.py b/seed/python-sdk/multi-url-environment/tests/utils/test_http_client.py index edd11ca7afb..f5a874a75f3 100644 --- a/seed/python-sdk/multi-url-environment/tests/utils/test_http_client.py +++ b/seed/python-sdk/multi-url-environment/tests/utils/test_http_client.py @@ -9,12 +9,17 @@ def get_request_options() -> RequestOptions: def test_get_json_request_body() -> None: - json_body, data_body = get_request_body(json={"hello": "world"}, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json={"hello": "world"}, data=None, request_options=None, omit=None + ) assert json_body == {"hello": "world"} assert data_body is None json_body_extras, data_body_extras = get_request_body( - json={"goodbye": "world"}, data=None, request_options=get_request_options(), omit=None + json={"goodbye": "world"}, + data=None, + request_options=get_request_options(), + omit=None, ) assert json_body_extras == {"goodbye": "world", "see you": "later"} @@ -22,12 +27,17 @@ def test_get_json_request_body() -> None: def test_get_files_request_body() -> None: - json_body, data_body = get_request_body(json=None, data={"hello": "world"}, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data={"hello": "world"}, request_options=None, omit=None + ) assert data_body == {"hello": "world"} assert json_body is None json_body_extras, data_body_extras = get_request_body( - json=None, data={"goodbye": "world"}, request_options=get_request_options(), omit=None + json=None, + data={"goodbye": "world"}, + request_options=get_request_options(), + omit=None, ) assert data_body_extras == {"goodbye": "world", "see you": "later"} @@ -35,7 +45,9 @@ def test_get_files_request_body() -> None: def test_get_none_request_body() -> None: - json_body, data_body = get_request_body(json=None, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data=None, request_options=None, omit=None + ) assert data_body is None assert json_body is None diff --git a/seed/python-sdk/multi-url-environment/tests/utils/test_query_encoding.py b/seed/python-sdk/multi-url-environment/tests/utils/test_query_encoding.py index 247e1551b46..fbc8f402167 100644 --- a/seed/python-sdk/multi-url-environment/tests/utils/test_query_encoding.py +++ b/seed/python-sdk/multi-url-environment/tests/utils/test_query_encoding.py @@ -4,9 +4,15 @@ def test_query_encoding() -> None: - assert encode_query({"hello world": "hello world"}) == {"hello world": "hello world"} - assert encode_query({"hello_world": {"hello": "world"}}) == {"hello_world[hello]": "world"} - assert encode_query({"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"}) == { + assert encode_query({"hello world": "hello world"}) == { + "hello world": "hello world" + } + assert encode_query({"hello_world": {"hello": "world"}}) == { + "hello_world[hello]": "world" + } + assert encode_query( + {"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"} + ) == { "hello_world[hello][world]": "today", "hello_world[test]": "this", "hi": "there", diff --git a/seed/python-sdk/multi-url-environment/tests/utils/test_serialization.py b/seed/python-sdk/multi-url-environment/tests/utils/test_serialization.py index 58b1ed66e6d..5ca956916dd 100644 --- a/seed/python-sdk/multi-url-environment/tests/utils/test_serialization.py +++ b/seed/python-sdk/multi-url-environment/tests/utils/test_serialization.py @@ -1,10 +1,12 @@ # This file was auto-generated by Fern from our API Definition. -from typing import Any, List +from typing import List, Any -from seed.core.serialization import convert_and_respect_annotation_metadata +from seed.core.serialization import ( + convert_and_respect_annotation_metadata, +) +from .assets.models import ShapeParams, ObjectWithOptionalFieldParams -from .assets.models import ObjectWithOptionalFieldParams, ShapeParams UNION_TEST: ShapeParams = {"radius_measurement": 1.0, "shape_type": "circle", "id": "1"} UNION_TEST_CONVERTED = {"shapeType": "circle", "radiusMeasurement": 1.0, "id": "1"} @@ -18,20 +20,54 @@ def test_convert_and_respect_annotation_metadata() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) - assert converted == {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"} + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) + assert converted == { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + } def test_convert_and_respect_annotation_metadata_in_list() -> None: data: List[ObjectWithOptionalFieldParams] = [ - {"string": "string", "long_": 12345, "bool_": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long_": 67890, "list_": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long_": 12345, + "bool_": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long_": 67890, + "list_": [], + "literal": "lit_one", + "any": "any", + }, ] - converted = convert_and_respect_annotation_metadata(object_=data, annotation=List[ObjectWithOptionalFieldParams]) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=List[ObjectWithOptionalFieldParams] + ) assert converted == [ - {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long": 67890, "list": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long": 67890, + "list": [], + "literal": "lit_one", + "any": "any", + }, ] @@ -43,7 +79,9 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) assert converted == { "string": "string", @@ -55,12 +93,16 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: def test_convert_and_respect_annotation_metadata_in_union() -> None: - converted = convert_and_respect_annotation_metadata(object_=UNION_TEST, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=UNION_TEST, annotation=ShapeParams + ) assert converted == UNION_TEST_CONVERTED def test_convert_and_respect_annotation_metadata_with_empty_object() -> None: data: Any = {} - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ShapeParams + ) assert converted == data diff --git a/seed/python-sdk/no-environment/pyproject.toml b/seed/python-sdk/no-environment/pyproject.toml index 912fea4d91c..af1259a0440 100644 --- a/seed/python-sdk/no-environment/pyproject.toml +++ b/seed/python-sdk/no-environment/pyproject.toml @@ -43,6 +43,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/python-sdk/no-environment/src/seed/client.py b/seed/python-sdk/no-environment/src/seed/client.py index 36de2cbff5a..7a2377938f9 100644 --- a/seed/python-sdk/no-environment/src/seed/client.py +++ b/seed/python-sdk/no-environment/src/seed/client.py @@ -1,11 +1,11 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from .dummy.client import AsyncDummyClient, DummyClient +from .core.client_wrapper import SyncClientWrapper +from .dummy.client import DummyClient +from .core.client_wrapper import AsyncClientWrapper +from .dummy.client import AsyncDummyClient class SeedNoEnvironment: @@ -44,15 +44,19 @@ def __init__( token: typing.Union[str, typing.Callable[[], str]], timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.Client] = None + httpx_client: typing.Optional[httpx.Client] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = SyncClientWrapper( base_url=base_url, token=token, httpx_client=httpx_client if httpx_client is not None - else httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.Client( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.Client(timeout=_defaulted_timeout), timeout=_defaulted_timeout, @@ -96,15 +100,19 @@ def __init__( token: typing.Union[str, typing.Callable[[], str]], timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.AsyncClient] = None + httpx_client: typing.Optional[httpx.AsyncClient] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = AsyncClientWrapper( base_url=base_url, token=token, httpx_client=httpx_client if httpx_client is not None - else httpx.AsyncClient(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.AsyncClient( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.AsyncClient(timeout=_defaulted_timeout), timeout=_defaulted_timeout, diff --git a/seed/python-sdk/no-environment/src/seed/core/api_error.py b/seed/python-sdk/no-environment/src/seed/core/api_error.py index 2e9fc5431cd..da734b58068 100644 --- a/seed/python-sdk/no-environment/src/seed/core/api_error.py +++ b/seed/python-sdk/no-environment/src/seed/core/api_error.py @@ -7,7 +7,9 @@ class ApiError(Exception): status_code: typing.Optional[int] body: typing.Any - def __init__(self, *, status_code: typing.Optional[int] = None, body: typing.Any = None): + def __init__( + self, *, status_code: typing.Optional[int] = None, body: typing.Any = None + ): self.status_code = status_code self.body = body diff --git a/seed/python-sdk/no-environment/src/seed/core/client_wrapper.py b/seed/python-sdk/no-environment/src/seed/core/client_wrapper.py index 1c4f8de0630..41c7e516b45 100644 --- a/seed/python-sdk/no-environment/src/seed/core/client_wrapper.py +++ b/seed/python-sdk/no-environment/src/seed/core/client_wrapper.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .http_client import AsyncHttpClient, HttpClient +from .http_client import HttpClient +from .http_client import AsyncHttpClient class BaseClientWrapper: diff --git a/seed/python-sdk/no-environment/src/seed/core/datetime_utils.py b/seed/python-sdk/no-environment/src/seed/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/python-sdk/no-environment/src/seed/core/datetime_utils.py +++ b/seed/python-sdk/no-environment/src/seed/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/python-sdk/no-environment/src/seed/core/file.py b/seed/python-sdk/no-environment/src/seed/core/file.py index cb0d40bbbf3..6e0f92bfcb1 100644 --- a/seed/python-sdk/no-environment/src/seed/core/file.py +++ b/seed/python-sdk/no-environment/src/seed/core/file.py @@ -13,12 +13,17 @@ # (filename, file (or bytes), content_type) typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str]], # (filename, file (or bytes), content_type, headers) - typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str], typing.Mapping[str, str]], + typing.Tuple[ + typing.Optional[str], + FileContent, + typing.Optional[str], + typing.Mapping[str, str], + ], ] def convert_file_dict_to_httpx_tuples( - d: typing.Dict[str, typing.Union[File, typing.List[File]]] + d: typing.Dict[str, typing.Union[File, typing.List[File]]], ) -> typing.List[typing.Tuple[str, File]]: """ The format we use is a list of tuples, where the first element is the diff --git a/seed/python-sdk/no-environment/src/seed/core/http_client.py b/seed/python-sdk/no-environment/src/seed/core/http_client.py index 9333d8a7f15..091f71bc185 100644 --- a/seed/python-sdk/no-environment/src/seed/core/http_client.py +++ b/seed/python-sdk/no-environment/src/seed/core/http_client.py @@ -77,7 +77,9 @@ def _retry_timeout(response: httpx.Response, retries: int) -> float: return retry_after # Apply exponential backoff, capped at MAX_RETRY_DELAY_SECONDS. - retry_delay = min(INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS) + retry_delay = min( + INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS + ) # Add a randomness / jitter to the retry delay to avoid overwhelming the server with retries. timeout = retry_delay * (1 - 0.25 * random()) @@ -90,7 +92,8 @@ def _should_retry(response: httpx.Response) -> bool: def remove_omit_from_dict( - original: typing.Dict[str, typing.Optional[typing.Any]], omit: typing.Optional[typing.Any] + original: typing.Dict[str, typing.Optional[typing.Any]], + omit: typing.Optional[typing.Any], ) -> typing.Dict[str, typing.Any]: if omit is None: return original @@ -108,7 +111,8 @@ def maybe_filter_request_body( ) -> typing.Optional[typing.Any]: if data is None: return ( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else None ) @@ -118,7 +122,8 @@ def maybe_filter_request_body( data_content = { **(jsonable_encoder(remove_omit_from_dict(data, omit))), # type: ignore **( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else {} ), @@ -162,7 +167,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url def request( @@ -174,8 +181,12 @@ def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -184,11 +195,14 @@ def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) response = self.httpx_client.request( method=method, @@ -198,7 +212,11 @@ def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -209,7 +227,10 @@ def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -222,11 +243,15 @@ def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: time.sleep(_retry_timeout(response=response, retries=retries)) @@ -256,8 +281,12 @@ def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -266,11 +295,14 @@ def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) with self.httpx_client.stream( method=method, @@ -280,7 +312,11 @@ def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -291,7 +327,9 @@ def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -304,7 +342,9 @@ def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream @@ -327,7 +367,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url async def request( @@ -339,8 +381,12 @@ async def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -349,11 +395,14 @@ async def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) # Add the input to each of these and do None-safety checks response = await self.httpx_client.request( @@ -364,7 +413,11 @@ async def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -375,7 +428,10 @@ async def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -388,11 +444,15 @@ async def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: await asyncio.sleep(_retry_timeout(response=response, retries=retries)) @@ -421,8 +481,12 @@ async def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -431,11 +495,14 @@ async def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) async with self.httpx_client.stream( method=method, @@ -445,7 +512,11 @@ async def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -456,7 +527,9 @@ async def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -469,7 +542,9 @@ async def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream diff --git a/seed/python-sdk/no-environment/src/seed/core/jsonable_encoder.py b/seed/python-sdk/no-environment/src/seed/core/jsonable_encoder.py index d3fd328fd41..12a8b52fc22 100644 --- a/seed/python-sdk/no-environment/src/seed/core/jsonable_encoder.py +++ b/seed/python-sdk/no-environment/src/seed/core/jsonable_encoder.py @@ -19,13 +19,19 @@ import pydantic from .datetime_utils import serialize_datetime -from .pydantic_utilities import IS_PYDANTIC_V2, encode_by_type, to_jsonable_with_fallback +from .pydantic_utilities import ( + IS_PYDANTIC_V2, + encode_by_type, + to_jsonable_with_fallback, +) SetIntStr = Set[Union[int, str]] DictIntStrAny = Dict[Union[int, str], Any] -def jsonable_encoder(obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None) -> Any: +def jsonable_encoder( + obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None +) -> Any: custom_encoder = custom_encoder or {} if custom_encoder: if type(obj) in custom_encoder: diff --git a/seed/python-sdk/no-environment/src/seed/core/pydantic_utilities.py b/seed/python-sdk/no-environment/src/seed/core/pydantic_utilities.py index 170a563d6eb..c63935c32a2 100644 --- a/seed/python-sdk/no-environment/src/seed/core/pydantic_utilities.py +++ b/seed/python-sdk/no-environment/src/seed/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) # type: ignore # Pydantic v1 diff --git a/seed/python-sdk/no-environment/src/seed/core/query_encoder.py b/seed/python-sdk/no-environment/src/seed/core/query_encoder.py index 24076d72ee9..7cb98f52cd7 100644 --- a/seed/python-sdk/no-environment/src/seed/core/query_encoder.py +++ b/seed/python-sdk/no-environment/src/seed/core/query_encoder.py @@ -7,7 +7,9 @@ # Flattens dicts to be of the form {"key[subkey][subkey2]": value} where value is not a dict -def traverse_query_dict(dict_flat: Dict[str, Any], key_prefix: Optional[str] = None) -> Dict[str, Any]: +def traverse_query_dict( + dict_flat: Dict[str, Any], key_prefix: Optional[str] = None +) -> Dict[str, Any]: result = {} for k, v in dict_flat.items(): key = f"{key_prefix}[{k}]" if key_prefix is not None else k @@ -30,4 +32,8 @@ def single_query_encoder(query_key: str, query_value: Any) -> Dict[str, Any]: def encode_query(query: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: - return dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) if query is not None else None + return ( + dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) + if query is not None + else None + ) diff --git a/seed/python-sdk/no-environment/src/seed/core/serialization.py b/seed/python-sdk/no-environment/src/seed/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/python-sdk/no-environment/src/seed/core/serialization.py +++ b/seed/python-sdk/no-environment/src/seed/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/python-sdk/no-environment/src/seed/dummy/client.py b/seed/python-sdk/no-environment/src/seed/dummy/client.py index 22125c9b248..411de706bff 100644 --- a/seed/python-sdk/no-environment/src/seed/dummy/client.py +++ b/seed/python-sdk/no-environment/src/seed/dummy/client.py @@ -1,19 +1,21 @@ # This file was auto-generated by Fern from our API Definition. +from ..core.client_wrapper import SyncClientWrapper import typing +from ..core.request_options import RequestOptions +from ..core.pydantic_utilities import parse_obj_as from json.decoder import JSONDecodeError - from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.pydantic_utilities import parse_obj_as -from ..core.request_options import RequestOptions +from ..core.client_wrapper import AsyncClientWrapper class DummyClient: def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper - def get_dummy(self, *, request_options: typing.Optional[RequestOptions] = None) -> str: + def get_dummy( + self, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -34,10 +36,16 @@ def get_dummy(self, *, request_options: typing.Optional[RequestOptions] = None) ) client.dummy.get_dummy() """ - _response = self._client_wrapper.httpx_client.request("dummy", method="GET", request_options=request_options) + _response = self._client_wrapper.httpx_client.request( + "dummy", + method="GET", + request_options=request_options, + ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -48,7 +56,9 @@ class AsyncDummyClient: def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper - async def get_dummy(self, *, request_options: typing.Optional[RequestOptions] = None) -> str: + async def get_dummy( + self, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -78,11 +88,15 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "dummy", method="GET", request_options=request_options + "dummy", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/no-environment/src/seed/version.py b/seed/python-sdk/no-environment/src/seed/version.py index 96d53412db3..9dced00fc3c 100644 --- a/seed/python-sdk/no-environment/src/seed/version.py +++ b/seed/python-sdk/no-environment/src/seed/version.py @@ -1,4 +1,3 @@ - from importlib import metadata __version__ = metadata.version("fern_no-environment") diff --git a/seed/python-sdk/no-environment/tests/conftest.py b/seed/python-sdk/no-environment/tests/conftest.py index c6074d70403..f1155087e0e 100644 --- a/seed/python-sdk/no-environment/tests/conftest.py +++ b/seed/python-sdk/no-environment/tests/conftest.py @@ -1,18 +1,22 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedNoEnvironment import os - import pytest -from seed import AsyncSeedNoEnvironment, SeedNoEnvironment +from seed import AsyncSeedNoEnvironment @pytest.fixture def client() -> SeedNoEnvironment: - return SeedNoEnvironment(token=os.getenv("ENV_TOKEN", "token"), base_url=os.getenv("TESTS_BASE_URL", "base_url")) + return SeedNoEnvironment( + token=os.getenv("ENV_TOKEN", "token"), + base_url=os.getenv("TESTS_BASE_URL", "base_url"), + ) @pytest.fixture def async_client() -> AsyncSeedNoEnvironment: return AsyncSeedNoEnvironment( - token=os.getenv("ENV_TOKEN", "token"), base_url=os.getenv("TESTS_BASE_URL", "base_url") + token=os.getenv("ENV_TOKEN", "token"), + base_url=os.getenv("TESTS_BASE_URL", "base_url"), ) diff --git a/seed/python-sdk/no-environment/tests/custom/test_client.py b/seed/python-sdk/no-environment/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/python-sdk/no-environment/tests/custom/test_client.py +++ b/seed/python-sdk/no-environment/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/python-sdk/no-environment/tests/test_dummy.py b/seed/python-sdk/no-environment/tests/test_dummy.py index eb36b83d5c6..96bfe7b3d5e 100644 --- a/seed/python-sdk/no-environment/tests/test_dummy.py +++ b/seed/python-sdk/no-environment/tests/test_dummy.py @@ -1,13 +1,14 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedNoEnvironment +from seed import AsyncSeedNoEnvironment import typing - -from seed import AsyncSeedNoEnvironment, SeedNoEnvironment - from .utilities import validate_response -async def test_get_dummy(client: SeedNoEnvironment, async_client: AsyncSeedNoEnvironment) -> None: +async def test_get_dummy( + client: SeedNoEnvironment, async_client: AsyncSeedNoEnvironment +) -> None: expected_response: typing.Any = "string" expected_types: typing.Any = None response = client.dummy.get_dummy() diff --git a/seed/python-sdk/no-environment/tests/utilities.py b/seed/python-sdk/no-environment/tests/utilities.py index 13da208eb3a..e8f4472564c 100644 --- a/seed/python-sdk/no-environment/tests/utilities.py +++ b/seed/python-sdk/no-environment/tests/utilities.py @@ -3,11 +3,14 @@ import typing import uuid -import pydantic from dateutil import parser +import pydantic + -def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> typing.Any: +def cast_field( + json_expectation: typing.Any, type_expectation: typing.Any +) -> typing.Any: # Cast these specific types which come through as string and expect our # models to cast to the correct type. if type_expectation == "uuid": @@ -25,7 +28,9 @@ def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> ty return json_expectation -def validate_field(response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any) -> None: +def validate_field( + response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectation == "no_validate": return @@ -44,7 +49,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(entry_expectation, dict): is_container_of_complex_type = True validate_response( - response=response[idx], json_expectation=ex, type_expectations=entry_expectation + response=response[idx], + json_expectation=ex, + type_expectations=entry_expectation, ) else: cast_json_expectation.append(cast_field(ex, entry_expectation)) @@ -56,7 +63,10 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # if any of the values of the set have a type_expectation of a dict, we're assuming it's a pydantic # model and keeping it a list. if container_expectation != "set" or not any( - map(lambda value: isinstance(value, dict), list(contents_expectation.values())) + map( + lambda value: isinstance(value, dict), + list(contents_expectation.values()), + ) ): json_expectation = cast_field(json_expectation, container_expectation) elif isinstance(type_expectation, tuple): @@ -65,9 +75,15 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(contents_expectation, dict): json_expectation = { cast_field( - key, contents_expectation.get(idx)[0] if contents_expectation.get(idx) is not None else None # type: ignore + key, + contents_expectation.get(idx)[0] + if contents_expectation.get(idx) is not None + else None, # type: ignore ): cast_field( - value, contents_expectation.get(idx)[1] if contents_expectation.get(idx) is not None else None # type: ignore + value, + contents_expectation.get(idx)[1] + if contents_expectation.get(idx) is not None + else None, # type: ignore ) for idx, (key, value) in enumerate(json_expectation.items()) } @@ -86,7 +102,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # Arg type_expectations is a deeply nested structure that matches the response, but with the values replaced with the expected types -def validate_response(response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any) -> None: +def validate_response( + response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectations == "no_validate": return @@ -96,11 +114,17 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e and not isinstance(response, dict) and not issubclass(type(response), pydantic.BaseModel) ): - validate_field(response=response, json_expectation=json_expectation, type_expectation=type_expectations) + validate_field( + response=response, + json_expectation=json_expectation, + type_expectation=type_expectations, + ) return if isinstance(response, list): - assert len(response) == len(json_expectation), "Length mismatch, expected: {0}, Actual: {1}".format( + assert len(response) == len( + json_expectation + ), "Length mismatch, expected: {0}, Actual: {1}".format( len(response), len(json_expectation) ) content_expectation = type_expectations @@ -108,7 +132,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e content_expectation = type_expectations[1] for idx, item in enumerate(response): validate_response( - response=item, json_expectation=json_expectation[idx], type_expectations=content_expectation[idx] + response=item, + json_expectation=json_expectation[idx], + type_expectations=content_expectation[idx], ) else: response_json = response @@ -116,7 +142,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e response_json = response.dict(by_alias=True) for key, value in json_expectation.items(): - assert key in response_json, "Field {0} not found within the response object: {1}".format( + assert ( + key in response_json + ), "Field {0} not found within the response object: {1}".format( key, response_json ) @@ -128,11 +156,19 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e # Otherwise, we're just validating a single field that's a pydantic model. if isinstance(value, dict) and not isinstance(type_expectation, tuple): validate_response( - response=response_json[key], json_expectation=value, type_expectations=type_expectation + response=response_json[key], + json_expectation=value, + type_expectations=type_expectation, ) else: - validate_field(response=response_json[key], json_expectation=value, type_expectation=type_expectation) + validate_field( + response=response_json[key], + json_expectation=value, + type_expectation=type_expectation, + ) # Ensure there are no additional fields here either del response_json[key] - assert len(response_json) == 0, "Additional fields found, expected None: {0}".format(response_json) + assert ( + len(response_json) == 0 + ), "Additional fields found, expected None: {0}".format(response_json) diff --git a/seed/python-sdk/no-environment/tests/utils/assets/models/__init__.py b/seed/python-sdk/no-environment/tests/utils/assets/models/__init__.py index 2cf01263529..3a1c852e71e 100644 --- a/seed/python-sdk/no-environment/tests/utils/assets/models/__init__.py +++ b/seed/python-sdk/no-environment/tests/utils/assets/models/__init__.py @@ -5,7 +5,7 @@ from .circle import CircleParams from .object_with_defaults import ObjectWithDefaultsParams from .object_with_optional_field import ObjectWithOptionalFieldParams -from .shape import Shape_CircleParams, Shape_SquareParams, ShapeParams +from .shape import ShapeParams, Shape_CircleParams, Shape_SquareParams from .square import SquareParams from .undiscriminated_shape import UndiscriminatedShapeParams diff --git a/seed/python-sdk/no-environment/tests/utils/assets/models/circle.py b/seed/python-sdk/no-environment/tests/utils/assets/models/circle.py index af7a1bf8a8e..253f12d38b3 100644 --- a/seed/python-sdk/no-environment/tests/utils/assets/models/circle.py +++ b/seed/python-sdk/no-environment/tests/utils/assets/models/circle.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class CircleParams(typing_extensions.TypedDict): - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] diff --git a/seed/python-sdk/no-environment/tests/utils/assets/models/object_with_optional_field.py b/seed/python-sdk/no-environment/tests/utils/assets/models/object_with_optional_field.py index 3ad93d5f305..ebe7dc80547 100644 --- a/seed/python-sdk/no-environment/tests/utils/assets/models/object_with_optional_field.py +++ b/seed/python-sdk/no-environment/tests/utils/assets/models/object_with_optional_field.py @@ -7,8 +7,8 @@ import uuid import typing_extensions -from seed.core.serialization import FieldMetadata +from seed.core.serialization import FieldMetadata from .color import Color from .shape import ShapeParams from .undiscriminated_shape import UndiscriminatedShapeParams @@ -18,16 +18,30 @@ class ObjectWithOptionalFieldParams(typing_extensions.TypedDict): literal: typing.Literal["lit_one"] string: typing_extensions.NotRequired[str] integer: typing_extensions.NotRequired[int] - long_: typing_extensions.NotRequired[typing_extensions.Annotated[int, FieldMetadata(alias="long")]] + long_: typing_extensions.NotRequired[ + typing_extensions.Annotated[int, FieldMetadata(alias="long")] + ] double: typing_extensions.NotRequired[float] - bool_: typing_extensions.NotRequired[typing_extensions.Annotated[bool, FieldMetadata(alias="bool")]] + bool_: typing_extensions.NotRequired[ + typing_extensions.Annotated[bool, FieldMetadata(alias="bool")] + ] datetime: typing_extensions.NotRequired[dt.datetime] date: typing_extensions.NotRequired[dt.date] - uuid_: typing_extensions.NotRequired[typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")]] - base_64: typing_extensions.NotRequired[typing_extensions.Annotated[str, FieldMetadata(alias="base64")]] - list_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")]] - set_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")]] - map_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")]] + uuid_: typing_extensions.NotRequired[ + typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")] + ] + base_64: typing_extensions.NotRequired[ + typing_extensions.Annotated[str, FieldMetadata(alias="base64")] + ] + list_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")] + ] + set_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")] + ] + map_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")] + ] enum: typing_extensions.NotRequired[Color] union: typing_extensions.NotRequired[ShapeParams] second_union: typing_extensions.NotRequired[ShapeParams] diff --git a/seed/python-sdk/no-environment/tests/utils/assets/models/shape.py b/seed/python-sdk/no-environment/tests/utils/assets/models/shape.py index 2c33c877951..816ffc51bdc 100644 --- a/seed/python-sdk/no-environment/tests/utils/assets/models/shape.py +++ b/seed/python-sdk/no-environment/tests/utils/assets/models/shape.py @@ -7,6 +7,7 @@ import typing import typing_extensions + from seed.core.serialization import FieldMetadata @@ -15,13 +16,21 @@ class Base(typing_extensions.TypedDict): class Shape_CircleParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["circle"], FieldMetadata(alias="shapeType")] - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["circle"], FieldMetadata(alias="shapeType") + ] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] class Shape_SquareParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["square"], FieldMetadata(alias="shapeType")] - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["square"], FieldMetadata(alias="shapeType") + ] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] ShapeParams = typing.Union[Shape_CircleParams, Shape_SquareParams] diff --git a/seed/python-sdk/no-environment/tests/utils/assets/models/square.py b/seed/python-sdk/no-environment/tests/utils/assets/models/square.py index b9b7dd319bc..bcf08a723c5 100644 --- a/seed/python-sdk/no-environment/tests/utils/assets/models/square.py +++ b/seed/python-sdk/no-environment/tests/utils/assets/models/square.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class SquareParams(typing_extensions.TypedDict): - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] diff --git a/seed/python-sdk/no-environment/tests/utils/test_http_client.py b/seed/python-sdk/no-environment/tests/utils/test_http_client.py index edd11ca7afb..f5a874a75f3 100644 --- a/seed/python-sdk/no-environment/tests/utils/test_http_client.py +++ b/seed/python-sdk/no-environment/tests/utils/test_http_client.py @@ -9,12 +9,17 @@ def get_request_options() -> RequestOptions: def test_get_json_request_body() -> None: - json_body, data_body = get_request_body(json={"hello": "world"}, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json={"hello": "world"}, data=None, request_options=None, omit=None + ) assert json_body == {"hello": "world"} assert data_body is None json_body_extras, data_body_extras = get_request_body( - json={"goodbye": "world"}, data=None, request_options=get_request_options(), omit=None + json={"goodbye": "world"}, + data=None, + request_options=get_request_options(), + omit=None, ) assert json_body_extras == {"goodbye": "world", "see you": "later"} @@ -22,12 +27,17 @@ def test_get_json_request_body() -> None: def test_get_files_request_body() -> None: - json_body, data_body = get_request_body(json=None, data={"hello": "world"}, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data={"hello": "world"}, request_options=None, omit=None + ) assert data_body == {"hello": "world"} assert json_body is None json_body_extras, data_body_extras = get_request_body( - json=None, data={"goodbye": "world"}, request_options=get_request_options(), omit=None + json=None, + data={"goodbye": "world"}, + request_options=get_request_options(), + omit=None, ) assert data_body_extras == {"goodbye": "world", "see you": "later"} @@ -35,7 +45,9 @@ def test_get_files_request_body() -> None: def test_get_none_request_body() -> None: - json_body, data_body = get_request_body(json=None, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data=None, request_options=None, omit=None + ) assert data_body is None assert json_body is None diff --git a/seed/python-sdk/no-environment/tests/utils/test_query_encoding.py b/seed/python-sdk/no-environment/tests/utils/test_query_encoding.py index 247e1551b46..fbc8f402167 100644 --- a/seed/python-sdk/no-environment/tests/utils/test_query_encoding.py +++ b/seed/python-sdk/no-environment/tests/utils/test_query_encoding.py @@ -4,9 +4,15 @@ def test_query_encoding() -> None: - assert encode_query({"hello world": "hello world"}) == {"hello world": "hello world"} - assert encode_query({"hello_world": {"hello": "world"}}) == {"hello_world[hello]": "world"} - assert encode_query({"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"}) == { + assert encode_query({"hello world": "hello world"}) == { + "hello world": "hello world" + } + assert encode_query({"hello_world": {"hello": "world"}}) == { + "hello_world[hello]": "world" + } + assert encode_query( + {"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"} + ) == { "hello_world[hello][world]": "today", "hello_world[test]": "this", "hi": "there", diff --git a/seed/python-sdk/no-environment/tests/utils/test_serialization.py b/seed/python-sdk/no-environment/tests/utils/test_serialization.py index 58b1ed66e6d..5ca956916dd 100644 --- a/seed/python-sdk/no-environment/tests/utils/test_serialization.py +++ b/seed/python-sdk/no-environment/tests/utils/test_serialization.py @@ -1,10 +1,12 @@ # This file was auto-generated by Fern from our API Definition. -from typing import Any, List +from typing import List, Any -from seed.core.serialization import convert_and_respect_annotation_metadata +from seed.core.serialization import ( + convert_and_respect_annotation_metadata, +) +from .assets.models import ShapeParams, ObjectWithOptionalFieldParams -from .assets.models import ObjectWithOptionalFieldParams, ShapeParams UNION_TEST: ShapeParams = {"radius_measurement": 1.0, "shape_type": "circle", "id": "1"} UNION_TEST_CONVERTED = {"shapeType": "circle", "radiusMeasurement": 1.0, "id": "1"} @@ -18,20 +20,54 @@ def test_convert_and_respect_annotation_metadata() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) - assert converted == {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"} + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) + assert converted == { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + } def test_convert_and_respect_annotation_metadata_in_list() -> None: data: List[ObjectWithOptionalFieldParams] = [ - {"string": "string", "long_": 12345, "bool_": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long_": 67890, "list_": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long_": 12345, + "bool_": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long_": 67890, + "list_": [], + "literal": "lit_one", + "any": "any", + }, ] - converted = convert_and_respect_annotation_metadata(object_=data, annotation=List[ObjectWithOptionalFieldParams]) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=List[ObjectWithOptionalFieldParams] + ) assert converted == [ - {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long": 67890, "list": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long": 67890, + "list": [], + "literal": "lit_one", + "any": "any", + }, ] @@ -43,7 +79,9 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) assert converted == { "string": "string", @@ -55,12 +93,16 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: def test_convert_and_respect_annotation_metadata_in_union() -> None: - converted = convert_and_respect_annotation_metadata(object_=UNION_TEST, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=UNION_TEST, annotation=ShapeParams + ) assert converted == UNION_TEST_CONVERTED def test_convert_and_respect_annotation_metadata_with_empty_object() -> None: data: Any = {} - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ShapeParams + ) assert converted == data diff --git a/seed/python-sdk/oauth-client-credentials-default/pyproject.toml b/seed/python-sdk/oauth-client-credentials-default/pyproject.toml index ecda3e2bf7a..1b1dee59905 100644 --- a/seed/python-sdk/oauth-client-credentials-default/pyproject.toml +++ b/seed/python-sdk/oauth-client-credentials-default/pyproject.toml @@ -43,6 +43,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/python-sdk/oauth-client-credentials-default/src/seed/__init__.py b/seed/python-sdk/oauth-client-credentials-default/src/seed/__init__.py index e59fc4163cd..a9842f9c84a 100644 --- a/seed/python-sdk/oauth-client-credentials-default/src/seed/__init__.py +++ b/seed/python-sdk/oauth-client-credentials-default/src/seed/__init__.py @@ -2,7 +2,10 @@ from . import auth from .auth import TokenResponse -from .client import AsyncSeedOauthClientCredentialsDefault, SeedOauthClientCredentialsDefault +from .client import ( + AsyncSeedOauthClientCredentialsDefault, + SeedOauthClientCredentialsDefault, +) from .version import __version__ __all__ = [ diff --git a/seed/python-sdk/oauth-client-credentials-default/src/seed/auth/client.py b/seed/python-sdk/oauth-client-credentials-default/src/seed/auth/client.py index c82733082bd..8dd08e95008 100644 --- a/seed/python-sdk/oauth-client-credentials-default/src/seed/auth/client.py +++ b/seed/python-sdk/oauth-client-credentials-default/src/seed/auth/client.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. import typing -from json.decoder import JSONDecodeError - -from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.pydantic_utilities import parse_obj_as +from ..core.client_wrapper import SyncClientWrapper from ..core.request_options import RequestOptions from .types.token_response import TokenResponse +from ..core.pydantic_utilities import parse_obj_as +from json.decoder import JSONDecodeError +from ..core.api_error import ApiError +from ..core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -18,7 +18,11 @@ def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper def get_token( - self, *, client_id: str, client_secret: str, request_options: typing.Optional[RequestOptions] = None + self, + *, + client_id: str, + client_secret: str, + request_options: typing.Optional[RequestOptions] = None, ) -> TokenResponse: """ Parameters @@ -51,13 +55,20 @@ def get_token( _response = self._client_wrapper.httpx_client.request( "token", method="POST", - json={"client_id": client_id, "client_secret": client_secret, "grant_type": "client_credentials"}, + json={ + "client_id": client_id, + "client_secret": client_secret, + "grant_type": "client_credentials", + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(TokenResponse, parse_obj_as(type_=TokenResponse, object_=_response.json())) # type: ignore + return typing.cast( + TokenResponse, + parse_obj_as(type_=TokenResponse, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -69,7 +80,11 @@ def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper async def get_token( - self, *, client_id: str, client_secret: str, request_options: typing.Optional[RequestOptions] = None + self, + *, + client_id: str, + client_secret: str, + request_options: typing.Optional[RequestOptions] = None, ) -> TokenResponse: """ Parameters @@ -110,13 +125,20 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( "token", method="POST", - json={"client_id": client_id, "client_secret": client_secret, "grant_type": "client_credentials"}, + json={ + "client_id": client_id, + "client_secret": client_secret, + "grant_type": "client_credentials", + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(TokenResponse, parse_obj_as(type_=TokenResponse, object_=_response.json())) # type: ignore + return typing.cast( + TokenResponse, + parse_obj_as(type_=TokenResponse, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/oauth-client-credentials-default/src/seed/auth/types/token_response.py b/seed/python-sdk/oauth-client-credentials-default/src/seed/auth/types/token_response.py index d6107461e8b..c0f15e61321 100644 --- a/seed/python-sdk/oauth-client-credentials-default/src/seed/auth/types/token_response.py +++ b/seed/python-sdk/oauth-client-credentials-default/src/seed/auth/types/token_response.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class TokenResponse(UniversalBaseModel): """ @@ -16,7 +15,9 @@ class TokenResponse(UniversalBaseModel): expires_in: int if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/oauth-client-credentials-default/src/seed/client.py b/seed/python-sdk/oauth-client-credentials-default/src/seed/client.py index f74fcd8faa0..2ab51feead7 100644 --- a/seed/python-sdk/oauth-client-credentials-default/src/seed/client.py +++ b/seed/python-sdk/oauth-client-credentials-default/src/seed/client.py @@ -1,12 +1,12 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .auth.client import AsyncAuthClient, AuthClient -from .core.client_wrapper import AsyncClientWrapper, SyncClientWrapper from .core.oauth_token_provider import OAuthTokenProvider +from .core.client_wrapper import SyncClientWrapper +from .auth.client import AuthClient +from .core.client_wrapper import AsyncClientWrapper +from .auth.client import AsyncAuthClient class SeedOauthClientCredentialsDefault: @@ -50,15 +50,19 @@ def __init__( _token_getter_override: typing.Optional[typing.Callable[[], str]] = None, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.Client] = None + httpx_client: typing.Optional[httpx.Client] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) oauth_token_provider = OAuthTokenProvider( client_id=client_id, client_secret=client_secret, client_wrapper=SyncClientWrapper( base_url=base_url, - httpx_client=httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + httpx_client=httpx.Client( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.Client(timeout=_defaulted_timeout), timeout=_defaulted_timeout, @@ -66,10 +70,14 @@ def __init__( ) self._client_wrapper = SyncClientWrapper( base_url=base_url, - token=_token_getter_override if _token_getter_override is not None else oauth_token_provider.get_token, + token=_token_getter_override + if _token_getter_override is not None + else oauth_token_provider.get_token, httpx_client=httpx_client if httpx_client is not None - else httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.Client( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.Client(timeout=_defaulted_timeout), timeout=_defaulted_timeout, @@ -118,15 +126,19 @@ def __init__( _token_getter_override: typing.Optional[typing.Callable[[], str]] = None, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.AsyncClient] = None + httpx_client: typing.Optional[httpx.AsyncClient] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) oauth_token_provider = OAuthTokenProvider( client_id=client_id, client_secret=client_secret, client_wrapper=SyncClientWrapper( base_url=base_url, - httpx_client=httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + httpx_client=httpx.Client( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.Client(timeout=_defaulted_timeout), timeout=_defaulted_timeout, @@ -134,10 +146,14 @@ def __init__( ) self._client_wrapper = AsyncClientWrapper( base_url=base_url, - token=_token_getter_override if _token_getter_override is not None else oauth_token_provider.get_token, + token=_token_getter_override + if _token_getter_override is not None + else oauth_token_provider.get_token, httpx_client=httpx_client if httpx_client is not None - else httpx.AsyncClient(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.AsyncClient( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.AsyncClient(timeout=_defaulted_timeout), timeout=_defaulted_timeout, diff --git a/seed/python-sdk/oauth-client-credentials-default/src/seed/core/api_error.py b/seed/python-sdk/oauth-client-credentials-default/src/seed/core/api_error.py index 2e9fc5431cd..da734b58068 100644 --- a/seed/python-sdk/oauth-client-credentials-default/src/seed/core/api_error.py +++ b/seed/python-sdk/oauth-client-credentials-default/src/seed/core/api_error.py @@ -7,7 +7,9 @@ class ApiError(Exception): status_code: typing.Optional[int] body: typing.Any - def __init__(self, *, status_code: typing.Optional[int] = None, body: typing.Any = None): + def __init__( + self, *, status_code: typing.Optional[int] = None, body: typing.Any = None + ): self.status_code = status_code self.body = body diff --git a/seed/python-sdk/oauth-client-credentials-default/src/seed/core/client_wrapper.py b/seed/python-sdk/oauth-client-credentials-default/src/seed/core/client_wrapper.py index aa6ef36d7b7..df11f2ac352 100644 --- a/seed/python-sdk/oauth-client-credentials-default/src/seed/core/client_wrapper.py +++ b/seed/python-sdk/oauth-client-credentials-default/src/seed/core/client_wrapper.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .http_client import AsyncHttpClient, HttpClient +from .http_client import HttpClient +from .http_client import AsyncHttpClient class BaseClientWrapper: diff --git a/seed/python-sdk/oauth-client-credentials-default/src/seed/core/datetime_utils.py b/seed/python-sdk/oauth-client-credentials-default/src/seed/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/python-sdk/oauth-client-credentials-default/src/seed/core/datetime_utils.py +++ b/seed/python-sdk/oauth-client-credentials-default/src/seed/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/python-sdk/oauth-client-credentials-default/src/seed/core/file.py b/seed/python-sdk/oauth-client-credentials-default/src/seed/core/file.py index cb0d40bbbf3..6e0f92bfcb1 100644 --- a/seed/python-sdk/oauth-client-credentials-default/src/seed/core/file.py +++ b/seed/python-sdk/oauth-client-credentials-default/src/seed/core/file.py @@ -13,12 +13,17 @@ # (filename, file (or bytes), content_type) typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str]], # (filename, file (or bytes), content_type, headers) - typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str], typing.Mapping[str, str]], + typing.Tuple[ + typing.Optional[str], + FileContent, + typing.Optional[str], + typing.Mapping[str, str], + ], ] def convert_file_dict_to_httpx_tuples( - d: typing.Dict[str, typing.Union[File, typing.List[File]]] + d: typing.Dict[str, typing.Union[File, typing.List[File]]], ) -> typing.List[typing.Tuple[str, File]]: """ The format we use is a list of tuples, where the first element is the diff --git a/seed/python-sdk/oauth-client-credentials-default/src/seed/core/http_client.py b/seed/python-sdk/oauth-client-credentials-default/src/seed/core/http_client.py index 9333d8a7f15..091f71bc185 100644 --- a/seed/python-sdk/oauth-client-credentials-default/src/seed/core/http_client.py +++ b/seed/python-sdk/oauth-client-credentials-default/src/seed/core/http_client.py @@ -77,7 +77,9 @@ def _retry_timeout(response: httpx.Response, retries: int) -> float: return retry_after # Apply exponential backoff, capped at MAX_RETRY_DELAY_SECONDS. - retry_delay = min(INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS) + retry_delay = min( + INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS + ) # Add a randomness / jitter to the retry delay to avoid overwhelming the server with retries. timeout = retry_delay * (1 - 0.25 * random()) @@ -90,7 +92,8 @@ def _should_retry(response: httpx.Response) -> bool: def remove_omit_from_dict( - original: typing.Dict[str, typing.Optional[typing.Any]], omit: typing.Optional[typing.Any] + original: typing.Dict[str, typing.Optional[typing.Any]], + omit: typing.Optional[typing.Any], ) -> typing.Dict[str, typing.Any]: if omit is None: return original @@ -108,7 +111,8 @@ def maybe_filter_request_body( ) -> typing.Optional[typing.Any]: if data is None: return ( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else None ) @@ -118,7 +122,8 @@ def maybe_filter_request_body( data_content = { **(jsonable_encoder(remove_omit_from_dict(data, omit))), # type: ignore **( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else {} ), @@ -162,7 +167,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url def request( @@ -174,8 +181,12 @@ def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -184,11 +195,14 @@ def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) response = self.httpx_client.request( method=method, @@ -198,7 +212,11 @@ def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -209,7 +227,10 @@ def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -222,11 +243,15 @@ def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: time.sleep(_retry_timeout(response=response, retries=retries)) @@ -256,8 +281,12 @@ def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -266,11 +295,14 @@ def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) with self.httpx_client.stream( method=method, @@ -280,7 +312,11 @@ def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -291,7 +327,9 @@ def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -304,7 +342,9 @@ def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream @@ -327,7 +367,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url async def request( @@ -339,8 +381,12 @@ async def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -349,11 +395,14 @@ async def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) # Add the input to each of these and do None-safety checks response = await self.httpx_client.request( @@ -364,7 +413,11 @@ async def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -375,7 +428,10 @@ async def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -388,11 +444,15 @@ async def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: await asyncio.sleep(_retry_timeout(response=response, retries=retries)) @@ -421,8 +481,12 @@ async def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -431,11 +495,14 @@ async def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) async with self.httpx_client.stream( method=method, @@ -445,7 +512,11 @@ async def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -456,7 +527,9 @@ async def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -469,7 +542,9 @@ async def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream diff --git a/seed/python-sdk/oauth-client-credentials-default/src/seed/core/jsonable_encoder.py b/seed/python-sdk/oauth-client-credentials-default/src/seed/core/jsonable_encoder.py index d3fd328fd41..12a8b52fc22 100644 --- a/seed/python-sdk/oauth-client-credentials-default/src/seed/core/jsonable_encoder.py +++ b/seed/python-sdk/oauth-client-credentials-default/src/seed/core/jsonable_encoder.py @@ -19,13 +19,19 @@ import pydantic from .datetime_utils import serialize_datetime -from .pydantic_utilities import IS_PYDANTIC_V2, encode_by_type, to_jsonable_with_fallback +from .pydantic_utilities import ( + IS_PYDANTIC_V2, + encode_by_type, + to_jsonable_with_fallback, +) SetIntStr = Set[Union[int, str]] DictIntStrAny = Dict[Union[int, str], Any] -def jsonable_encoder(obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None) -> Any: +def jsonable_encoder( + obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None +) -> Any: custom_encoder = custom_encoder or {} if custom_encoder: if type(obj) in custom_encoder: diff --git a/seed/python-sdk/oauth-client-credentials-default/src/seed/core/oauth_token_provider.py b/seed/python-sdk/oauth-client-credentials-default/src/seed/core/oauth_token_provider.py index 259eb12bb5e..8326d6f69f8 100644 --- a/seed/python-sdk/oauth-client-credentials-default/src/seed/core/oauth_token_provider.py +++ b/seed/python-sdk/oauth-client-credentials-default/src/seed/core/oauth_token_provider.py @@ -1,15 +1,16 @@ # This file was auto-generated by Fern from our API Definition. +from .client_wrapper import SyncClientWrapper import typing - from ..auth.client import AuthClient -from .client_wrapper import SyncClientWrapper class OAuthTokenProvider: BUFFER_IN_MINUTES = 2 - def __init__(self, *, client_id: str, client_secret: str, client_wrapper: SyncClientWrapper): + def __init__( + self, *, client_id: str, client_secret: str, client_wrapper: SyncClientWrapper + ): self._client_id = client_id self._client_secret = client_secret self._access_token: typing.Optional[str] = None @@ -21,6 +22,8 @@ def get_token(self) -> str: return self._refresh() def _refresh(self) -> str: - token_response = self._auth_client.get_token(client_id=self._client_id, client_secret=self._client_secret) + token_response = self._auth_client.get_token( + client_id=self._client_id, client_secret=self._client_secret + ) self._access_token = token_response.access_token return self._access_token diff --git a/seed/python-sdk/oauth-client-credentials-default/src/seed/core/pydantic_utilities.py b/seed/python-sdk/oauth-client-credentials-default/src/seed/core/pydantic_utilities.py index 170a563d6eb..c63935c32a2 100644 --- a/seed/python-sdk/oauth-client-credentials-default/src/seed/core/pydantic_utilities.py +++ b/seed/python-sdk/oauth-client-credentials-default/src/seed/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) # type: ignore # Pydantic v1 diff --git a/seed/python-sdk/oauth-client-credentials-default/src/seed/core/query_encoder.py b/seed/python-sdk/oauth-client-credentials-default/src/seed/core/query_encoder.py index 24076d72ee9..7cb98f52cd7 100644 --- a/seed/python-sdk/oauth-client-credentials-default/src/seed/core/query_encoder.py +++ b/seed/python-sdk/oauth-client-credentials-default/src/seed/core/query_encoder.py @@ -7,7 +7,9 @@ # Flattens dicts to be of the form {"key[subkey][subkey2]": value} where value is not a dict -def traverse_query_dict(dict_flat: Dict[str, Any], key_prefix: Optional[str] = None) -> Dict[str, Any]: +def traverse_query_dict( + dict_flat: Dict[str, Any], key_prefix: Optional[str] = None +) -> Dict[str, Any]: result = {} for k, v in dict_flat.items(): key = f"{key_prefix}[{k}]" if key_prefix is not None else k @@ -30,4 +32,8 @@ def single_query_encoder(query_key: str, query_value: Any) -> Dict[str, Any]: def encode_query(query: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: - return dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) if query is not None else None + return ( + dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) + if query is not None + else None + ) diff --git a/seed/python-sdk/oauth-client-credentials-default/src/seed/core/serialization.py b/seed/python-sdk/oauth-client-credentials-default/src/seed/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/python-sdk/oauth-client-credentials-default/src/seed/core/serialization.py +++ b/seed/python-sdk/oauth-client-credentials-default/src/seed/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/python-sdk/oauth-client-credentials-default/src/seed/version.py b/seed/python-sdk/oauth-client-credentials-default/src/seed/version.py index 42124c75b97..d21edde5cb2 100644 --- a/seed/python-sdk/oauth-client-credentials-default/src/seed/version.py +++ b/seed/python-sdk/oauth-client-credentials-default/src/seed/version.py @@ -1,4 +1,3 @@ - from importlib import metadata __version__ = metadata.version("fern_oauth-client-credentials-default") diff --git a/seed/python-sdk/oauth-client-credentials-default/tests/conftest.py b/seed/python-sdk/oauth-client-credentials-default/tests/conftest.py index 988b58944d0..1fd7d766628 100644 --- a/seed/python-sdk/oauth-client-credentials-default/tests/conftest.py +++ b/seed/python-sdk/oauth-client-credentials-default/tests/conftest.py @@ -1,9 +1,9 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedOauthClientCredentialsDefault import os - import pytest -from seed import AsyncSeedOauthClientCredentialsDefault, SeedOauthClientCredentialsDefault +from seed import AsyncSeedOauthClientCredentialsDefault @pytest.fixture diff --git a/seed/python-sdk/oauth-client-credentials-default/tests/custom/test_client.py b/seed/python-sdk/oauth-client-credentials-default/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/python-sdk/oauth-client-credentials-default/tests/custom/test_client.py +++ b/seed/python-sdk/oauth-client-credentials-default/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/python-sdk/oauth-client-credentials-default/tests/test_auth.py b/seed/python-sdk/oauth-client-credentials-default/tests/test_auth.py index a3f5c4cc3e7..3f2a24afad6 100644 --- a/seed/python-sdk/oauth-client-credentials-default/tests/test_auth.py +++ b/seed/python-sdk/oauth-client-credentials-default/tests/test_auth.py @@ -1,19 +1,21 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedOauthClientCredentialsDefault +from seed import AsyncSeedOauthClientCredentialsDefault import typing - -from seed import AsyncSeedOauthClientCredentialsDefault, SeedOauthClientCredentialsDefault - from .utilities import validate_response async def test_get_token( - client: SeedOauthClientCredentialsDefault, async_client: AsyncSeedOauthClientCredentialsDefault + client: SeedOauthClientCredentialsDefault, + async_client: AsyncSeedOauthClientCredentialsDefault, ) -> None: expected_response: typing.Any = {"access_token": "string", "expires_in": 1} expected_types: typing.Any = {"access_token": None, "expires_in": "integer"} response = client.auth.get_token(client_id="string", client_secret="string") validate_response(response, expected_response, expected_types) - async_response = await async_client.auth.get_token(client_id="string", client_secret="string") + async_response = await async_client.auth.get_token( + client_id="string", client_secret="string" + ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/oauth-client-credentials-default/tests/utilities.py b/seed/python-sdk/oauth-client-credentials-default/tests/utilities.py index 13da208eb3a..e8f4472564c 100644 --- a/seed/python-sdk/oauth-client-credentials-default/tests/utilities.py +++ b/seed/python-sdk/oauth-client-credentials-default/tests/utilities.py @@ -3,11 +3,14 @@ import typing import uuid -import pydantic from dateutil import parser +import pydantic + -def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> typing.Any: +def cast_field( + json_expectation: typing.Any, type_expectation: typing.Any +) -> typing.Any: # Cast these specific types which come through as string and expect our # models to cast to the correct type. if type_expectation == "uuid": @@ -25,7 +28,9 @@ def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> ty return json_expectation -def validate_field(response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any) -> None: +def validate_field( + response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectation == "no_validate": return @@ -44,7 +49,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(entry_expectation, dict): is_container_of_complex_type = True validate_response( - response=response[idx], json_expectation=ex, type_expectations=entry_expectation + response=response[idx], + json_expectation=ex, + type_expectations=entry_expectation, ) else: cast_json_expectation.append(cast_field(ex, entry_expectation)) @@ -56,7 +63,10 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # if any of the values of the set have a type_expectation of a dict, we're assuming it's a pydantic # model and keeping it a list. if container_expectation != "set" or not any( - map(lambda value: isinstance(value, dict), list(contents_expectation.values())) + map( + lambda value: isinstance(value, dict), + list(contents_expectation.values()), + ) ): json_expectation = cast_field(json_expectation, container_expectation) elif isinstance(type_expectation, tuple): @@ -65,9 +75,15 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(contents_expectation, dict): json_expectation = { cast_field( - key, contents_expectation.get(idx)[0] if contents_expectation.get(idx) is not None else None # type: ignore + key, + contents_expectation.get(idx)[0] + if contents_expectation.get(idx) is not None + else None, # type: ignore ): cast_field( - value, contents_expectation.get(idx)[1] if contents_expectation.get(idx) is not None else None # type: ignore + value, + contents_expectation.get(idx)[1] + if contents_expectation.get(idx) is not None + else None, # type: ignore ) for idx, (key, value) in enumerate(json_expectation.items()) } @@ -86,7 +102,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # Arg type_expectations is a deeply nested structure that matches the response, but with the values replaced with the expected types -def validate_response(response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any) -> None: +def validate_response( + response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectations == "no_validate": return @@ -96,11 +114,17 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e and not isinstance(response, dict) and not issubclass(type(response), pydantic.BaseModel) ): - validate_field(response=response, json_expectation=json_expectation, type_expectation=type_expectations) + validate_field( + response=response, + json_expectation=json_expectation, + type_expectation=type_expectations, + ) return if isinstance(response, list): - assert len(response) == len(json_expectation), "Length mismatch, expected: {0}, Actual: {1}".format( + assert len(response) == len( + json_expectation + ), "Length mismatch, expected: {0}, Actual: {1}".format( len(response), len(json_expectation) ) content_expectation = type_expectations @@ -108,7 +132,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e content_expectation = type_expectations[1] for idx, item in enumerate(response): validate_response( - response=item, json_expectation=json_expectation[idx], type_expectations=content_expectation[idx] + response=item, + json_expectation=json_expectation[idx], + type_expectations=content_expectation[idx], ) else: response_json = response @@ -116,7 +142,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e response_json = response.dict(by_alias=True) for key, value in json_expectation.items(): - assert key in response_json, "Field {0} not found within the response object: {1}".format( + assert ( + key in response_json + ), "Field {0} not found within the response object: {1}".format( key, response_json ) @@ -128,11 +156,19 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e # Otherwise, we're just validating a single field that's a pydantic model. if isinstance(value, dict) and not isinstance(type_expectation, tuple): validate_response( - response=response_json[key], json_expectation=value, type_expectations=type_expectation + response=response_json[key], + json_expectation=value, + type_expectations=type_expectation, ) else: - validate_field(response=response_json[key], json_expectation=value, type_expectation=type_expectation) + validate_field( + response=response_json[key], + json_expectation=value, + type_expectation=type_expectation, + ) # Ensure there are no additional fields here either del response_json[key] - assert len(response_json) == 0, "Additional fields found, expected None: {0}".format(response_json) + assert ( + len(response_json) == 0 + ), "Additional fields found, expected None: {0}".format(response_json) diff --git a/seed/python-sdk/oauth-client-credentials-default/tests/utils/assets/models/__init__.py b/seed/python-sdk/oauth-client-credentials-default/tests/utils/assets/models/__init__.py index 2cf01263529..3a1c852e71e 100644 --- a/seed/python-sdk/oauth-client-credentials-default/tests/utils/assets/models/__init__.py +++ b/seed/python-sdk/oauth-client-credentials-default/tests/utils/assets/models/__init__.py @@ -5,7 +5,7 @@ from .circle import CircleParams from .object_with_defaults import ObjectWithDefaultsParams from .object_with_optional_field import ObjectWithOptionalFieldParams -from .shape import Shape_CircleParams, Shape_SquareParams, ShapeParams +from .shape import ShapeParams, Shape_CircleParams, Shape_SquareParams from .square import SquareParams from .undiscriminated_shape import UndiscriminatedShapeParams diff --git a/seed/python-sdk/oauth-client-credentials-default/tests/utils/assets/models/circle.py b/seed/python-sdk/oauth-client-credentials-default/tests/utils/assets/models/circle.py index af7a1bf8a8e..253f12d38b3 100644 --- a/seed/python-sdk/oauth-client-credentials-default/tests/utils/assets/models/circle.py +++ b/seed/python-sdk/oauth-client-credentials-default/tests/utils/assets/models/circle.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class CircleParams(typing_extensions.TypedDict): - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] diff --git a/seed/python-sdk/oauth-client-credentials-default/tests/utils/assets/models/object_with_optional_field.py b/seed/python-sdk/oauth-client-credentials-default/tests/utils/assets/models/object_with_optional_field.py index 3ad93d5f305..ebe7dc80547 100644 --- a/seed/python-sdk/oauth-client-credentials-default/tests/utils/assets/models/object_with_optional_field.py +++ b/seed/python-sdk/oauth-client-credentials-default/tests/utils/assets/models/object_with_optional_field.py @@ -7,8 +7,8 @@ import uuid import typing_extensions -from seed.core.serialization import FieldMetadata +from seed.core.serialization import FieldMetadata from .color import Color from .shape import ShapeParams from .undiscriminated_shape import UndiscriminatedShapeParams @@ -18,16 +18,30 @@ class ObjectWithOptionalFieldParams(typing_extensions.TypedDict): literal: typing.Literal["lit_one"] string: typing_extensions.NotRequired[str] integer: typing_extensions.NotRequired[int] - long_: typing_extensions.NotRequired[typing_extensions.Annotated[int, FieldMetadata(alias="long")]] + long_: typing_extensions.NotRequired[ + typing_extensions.Annotated[int, FieldMetadata(alias="long")] + ] double: typing_extensions.NotRequired[float] - bool_: typing_extensions.NotRequired[typing_extensions.Annotated[bool, FieldMetadata(alias="bool")]] + bool_: typing_extensions.NotRequired[ + typing_extensions.Annotated[bool, FieldMetadata(alias="bool")] + ] datetime: typing_extensions.NotRequired[dt.datetime] date: typing_extensions.NotRequired[dt.date] - uuid_: typing_extensions.NotRequired[typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")]] - base_64: typing_extensions.NotRequired[typing_extensions.Annotated[str, FieldMetadata(alias="base64")]] - list_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")]] - set_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")]] - map_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")]] + uuid_: typing_extensions.NotRequired[ + typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")] + ] + base_64: typing_extensions.NotRequired[ + typing_extensions.Annotated[str, FieldMetadata(alias="base64")] + ] + list_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")] + ] + set_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")] + ] + map_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")] + ] enum: typing_extensions.NotRequired[Color] union: typing_extensions.NotRequired[ShapeParams] second_union: typing_extensions.NotRequired[ShapeParams] diff --git a/seed/python-sdk/oauth-client-credentials-default/tests/utils/assets/models/shape.py b/seed/python-sdk/oauth-client-credentials-default/tests/utils/assets/models/shape.py index 2c33c877951..816ffc51bdc 100644 --- a/seed/python-sdk/oauth-client-credentials-default/tests/utils/assets/models/shape.py +++ b/seed/python-sdk/oauth-client-credentials-default/tests/utils/assets/models/shape.py @@ -7,6 +7,7 @@ import typing import typing_extensions + from seed.core.serialization import FieldMetadata @@ -15,13 +16,21 @@ class Base(typing_extensions.TypedDict): class Shape_CircleParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["circle"], FieldMetadata(alias="shapeType")] - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["circle"], FieldMetadata(alias="shapeType") + ] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] class Shape_SquareParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["square"], FieldMetadata(alias="shapeType")] - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["square"], FieldMetadata(alias="shapeType") + ] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] ShapeParams = typing.Union[Shape_CircleParams, Shape_SquareParams] diff --git a/seed/python-sdk/oauth-client-credentials-default/tests/utils/assets/models/square.py b/seed/python-sdk/oauth-client-credentials-default/tests/utils/assets/models/square.py index b9b7dd319bc..bcf08a723c5 100644 --- a/seed/python-sdk/oauth-client-credentials-default/tests/utils/assets/models/square.py +++ b/seed/python-sdk/oauth-client-credentials-default/tests/utils/assets/models/square.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class SquareParams(typing_extensions.TypedDict): - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] diff --git a/seed/python-sdk/oauth-client-credentials-default/tests/utils/test_http_client.py b/seed/python-sdk/oauth-client-credentials-default/tests/utils/test_http_client.py index edd11ca7afb..f5a874a75f3 100644 --- a/seed/python-sdk/oauth-client-credentials-default/tests/utils/test_http_client.py +++ b/seed/python-sdk/oauth-client-credentials-default/tests/utils/test_http_client.py @@ -9,12 +9,17 @@ def get_request_options() -> RequestOptions: def test_get_json_request_body() -> None: - json_body, data_body = get_request_body(json={"hello": "world"}, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json={"hello": "world"}, data=None, request_options=None, omit=None + ) assert json_body == {"hello": "world"} assert data_body is None json_body_extras, data_body_extras = get_request_body( - json={"goodbye": "world"}, data=None, request_options=get_request_options(), omit=None + json={"goodbye": "world"}, + data=None, + request_options=get_request_options(), + omit=None, ) assert json_body_extras == {"goodbye": "world", "see you": "later"} @@ -22,12 +27,17 @@ def test_get_json_request_body() -> None: def test_get_files_request_body() -> None: - json_body, data_body = get_request_body(json=None, data={"hello": "world"}, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data={"hello": "world"}, request_options=None, omit=None + ) assert data_body == {"hello": "world"} assert json_body is None json_body_extras, data_body_extras = get_request_body( - json=None, data={"goodbye": "world"}, request_options=get_request_options(), omit=None + json=None, + data={"goodbye": "world"}, + request_options=get_request_options(), + omit=None, ) assert data_body_extras == {"goodbye": "world", "see you": "later"} @@ -35,7 +45,9 @@ def test_get_files_request_body() -> None: def test_get_none_request_body() -> None: - json_body, data_body = get_request_body(json=None, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data=None, request_options=None, omit=None + ) assert data_body is None assert json_body is None diff --git a/seed/python-sdk/oauth-client-credentials-default/tests/utils/test_query_encoding.py b/seed/python-sdk/oauth-client-credentials-default/tests/utils/test_query_encoding.py index 247e1551b46..fbc8f402167 100644 --- a/seed/python-sdk/oauth-client-credentials-default/tests/utils/test_query_encoding.py +++ b/seed/python-sdk/oauth-client-credentials-default/tests/utils/test_query_encoding.py @@ -4,9 +4,15 @@ def test_query_encoding() -> None: - assert encode_query({"hello world": "hello world"}) == {"hello world": "hello world"} - assert encode_query({"hello_world": {"hello": "world"}}) == {"hello_world[hello]": "world"} - assert encode_query({"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"}) == { + assert encode_query({"hello world": "hello world"}) == { + "hello world": "hello world" + } + assert encode_query({"hello_world": {"hello": "world"}}) == { + "hello_world[hello]": "world" + } + assert encode_query( + {"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"} + ) == { "hello_world[hello][world]": "today", "hello_world[test]": "this", "hi": "there", diff --git a/seed/python-sdk/oauth-client-credentials-default/tests/utils/test_serialization.py b/seed/python-sdk/oauth-client-credentials-default/tests/utils/test_serialization.py index 58b1ed66e6d..5ca956916dd 100644 --- a/seed/python-sdk/oauth-client-credentials-default/tests/utils/test_serialization.py +++ b/seed/python-sdk/oauth-client-credentials-default/tests/utils/test_serialization.py @@ -1,10 +1,12 @@ # This file was auto-generated by Fern from our API Definition. -from typing import Any, List +from typing import List, Any -from seed.core.serialization import convert_and_respect_annotation_metadata +from seed.core.serialization import ( + convert_and_respect_annotation_metadata, +) +from .assets.models import ShapeParams, ObjectWithOptionalFieldParams -from .assets.models import ObjectWithOptionalFieldParams, ShapeParams UNION_TEST: ShapeParams = {"radius_measurement": 1.0, "shape_type": "circle", "id": "1"} UNION_TEST_CONVERTED = {"shapeType": "circle", "radiusMeasurement": 1.0, "id": "1"} @@ -18,20 +20,54 @@ def test_convert_and_respect_annotation_metadata() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) - assert converted == {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"} + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) + assert converted == { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + } def test_convert_and_respect_annotation_metadata_in_list() -> None: data: List[ObjectWithOptionalFieldParams] = [ - {"string": "string", "long_": 12345, "bool_": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long_": 67890, "list_": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long_": 12345, + "bool_": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long_": 67890, + "list_": [], + "literal": "lit_one", + "any": "any", + }, ] - converted = convert_and_respect_annotation_metadata(object_=data, annotation=List[ObjectWithOptionalFieldParams]) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=List[ObjectWithOptionalFieldParams] + ) assert converted == [ - {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long": 67890, "list": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long": 67890, + "list": [], + "literal": "lit_one", + "any": "any", + }, ] @@ -43,7 +79,9 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) assert converted == { "string": "string", @@ -55,12 +93,16 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: def test_convert_and_respect_annotation_metadata_in_union() -> None: - converted = convert_and_respect_annotation_metadata(object_=UNION_TEST, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=UNION_TEST, annotation=ShapeParams + ) assert converted == UNION_TEST_CONVERTED def test_convert_and_respect_annotation_metadata_with_empty_object() -> None: data: Any = {} - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ShapeParams + ) assert converted == data diff --git a/seed/python-sdk/oauth-client-credentials-environment-variables/pyproject.toml b/seed/python-sdk/oauth-client-credentials-environment-variables/pyproject.toml index a50bd6e8dc0..b20268f8a25 100644 --- a/seed/python-sdk/oauth-client-credentials-environment-variables/pyproject.toml +++ b/seed/python-sdk/oauth-client-credentials-environment-variables/pyproject.toml @@ -43,6 +43,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/python-sdk/oauth-client-credentials-environment-variables/src/seed/__init__.py b/seed/python-sdk/oauth-client-credentials-environment-variables/src/seed/__init__.py index 5e5e67cf885..d47af570d2e 100644 --- a/seed/python-sdk/oauth-client-credentials-environment-variables/src/seed/__init__.py +++ b/seed/python-sdk/oauth-client-credentials-environment-variables/src/seed/__init__.py @@ -2,7 +2,10 @@ from . import auth from .auth import TokenResponse -from .client import AsyncSeedOauthClientCredentialsEnvironmentVariables, SeedOauthClientCredentialsEnvironmentVariables +from .client import ( + AsyncSeedOauthClientCredentialsEnvironmentVariables, + SeedOauthClientCredentialsEnvironmentVariables, +) from .version import __version__ __all__ = [ diff --git a/seed/python-sdk/oauth-client-credentials-environment-variables/src/seed/auth/client.py b/seed/python-sdk/oauth-client-credentials-environment-variables/src/seed/auth/client.py index 75807e33de6..d463022a124 100644 --- a/seed/python-sdk/oauth-client-credentials-environment-variables/src/seed/auth/client.py +++ b/seed/python-sdk/oauth-client-credentials-environment-variables/src/seed/auth/client.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. import typing -from json.decoder import JSONDecodeError - -from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.pydantic_utilities import parse_obj_as +from ..core.client_wrapper import SyncClientWrapper from ..core.request_options import RequestOptions from .types.token_response import TokenResponse +from ..core.pydantic_utilities import parse_obj_as +from json.decoder import JSONDecodeError +from ..core.api_error import ApiError +from ..core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -23,7 +23,7 @@ def get_token_with_client_credentials( client_id: str, client_secret: str, scope: typing.Optional[str] = OMIT, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> TokenResponse: """ Parameters @@ -71,7 +71,10 @@ def get_token_with_client_credentials( ) try: if 200 <= _response.status_code < 300: - return typing.cast(TokenResponse, parse_obj_as(type_=TokenResponse, object_=_response.json())) # type: ignore + return typing.cast( + TokenResponse, + parse_obj_as(type_=TokenResponse, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -84,7 +87,7 @@ def refresh_token( client_secret: str, refresh_token: str, scope: typing.Optional[str] = OMIT, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> TokenResponse: """ Parameters @@ -136,7 +139,10 @@ def refresh_token( ) try: if 200 <= _response.status_code < 300: - return typing.cast(TokenResponse, parse_obj_as(type_=TokenResponse, object_=_response.json())) # type: ignore + return typing.cast( + TokenResponse, + parse_obj_as(type_=TokenResponse, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -153,7 +159,7 @@ async def get_token_with_client_credentials( client_id: str, client_secret: str, scope: typing.Optional[str] = OMIT, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> TokenResponse: """ Parameters @@ -209,7 +215,10 @@ async def main() -> None: ) try: if 200 <= _response.status_code < 300: - return typing.cast(TokenResponse, parse_obj_as(type_=TokenResponse, object_=_response.json())) # type: ignore + return typing.cast( + TokenResponse, + parse_obj_as(type_=TokenResponse, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -222,7 +231,7 @@ async def refresh_token( client_secret: str, refresh_token: str, scope: typing.Optional[str] = OMIT, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> TokenResponse: """ Parameters @@ -282,7 +291,10 @@ async def main() -> None: ) try: if 200 <= _response.status_code < 300: - return typing.cast(TokenResponse, parse_obj_as(type_=TokenResponse, object_=_response.json())) # type: ignore + return typing.cast( + TokenResponse, + parse_obj_as(type_=TokenResponse, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/oauth-client-credentials-environment-variables/src/seed/auth/types/token_response.py b/seed/python-sdk/oauth-client-credentials-environment-variables/src/seed/auth/types/token_response.py index 44ac83f1a2b..3277d3fd341 100644 --- a/seed/python-sdk/oauth-client-credentials-environment-variables/src/seed/auth/types/token_response.py +++ b/seed/python-sdk/oauth-client-credentials-environment-variables/src/seed/auth/types/token_response.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel import typing - +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class TokenResponse(UniversalBaseModel): """ @@ -17,7 +16,9 @@ class TokenResponse(UniversalBaseModel): refresh_token: typing.Optional[str] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/oauth-client-credentials-environment-variables/src/seed/client.py b/seed/python-sdk/oauth-client-credentials-environment-variables/src/seed/client.py index 342baec50dc..9da43d127ac 100644 --- a/seed/python-sdk/oauth-client-credentials-environment-variables/src/seed/client.py +++ b/seed/python-sdk/oauth-client-credentials-environment-variables/src/seed/client.py @@ -1,14 +1,14 @@ # This file was auto-generated by Fern from our API Definition. -import os import typing - +import os import httpx - -from .auth.client import AsyncAuthClient, AuthClient from .core.api_error import ApiError -from .core.client_wrapper import AsyncClientWrapper, SyncClientWrapper from .core.oauth_token_provider import OAuthTokenProvider +from .core.client_wrapper import SyncClientWrapper +from .auth.client import AuthClient +from .core.client_wrapper import AsyncClientWrapper +from .auth.client import AsyncAuthClient class SeedOauthClientCredentialsEnvironmentVariables: @@ -52,11 +52,15 @@ def __init__( _token_getter_override: typing.Optional[typing.Callable[[], str]] = None, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.Client] = None + httpx_client: typing.Optional[httpx.Client] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) if client_id is None: - raise ApiError(body="The client must be instantiated be either passing in client_id or setting CLIENT_ID") + raise ApiError( + body="The client must be instantiated be either passing in client_id or setting CLIENT_ID" + ) if client_secret is None: raise ApiError( body="The client must be instantiated be either passing in client_secret or setting CLIENT_SECRET" @@ -66,7 +70,9 @@ def __init__( client_secret=client_secret, client_wrapper=SyncClientWrapper( base_url=base_url, - httpx_client=httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + httpx_client=httpx.Client( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.Client(timeout=_defaulted_timeout), timeout=_defaulted_timeout, @@ -74,10 +80,14 @@ def __init__( ) self._client_wrapper = SyncClientWrapper( base_url=base_url, - token=_token_getter_override if _token_getter_override is not None else oauth_token_provider.get_token, + token=_token_getter_override + if _token_getter_override is not None + else oauth_token_provider.get_token, httpx_client=httpx_client if httpx_client is not None - else httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.Client( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.Client(timeout=_defaulted_timeout), timeout=_defaulted_timeout, @@ -126,11 +136,15 @@ def __init__( _token_getter_override: typing.Optional[typing.Callable[[], str]] = None, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.AsyncClient] = None + httpx_client: typing.Optional[httpx.AsyncClient] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) if client_id is None: - raise ApiError(body="The client must be instantiated be either passing in client_id or setting CLIENT_ID") + raise ApiError( + body="The client must be instantiated be either passing in client_id or setting CLIENT_ID" + ) if client_secret is None: raise ApiError( body="The client must be instantiated be either passing in client_secret or setting CLIENT_SECRET" @@ -140,7 +154,9 @@ def __init__( client_secret=client_secret, client_wrapper=SyncClientWrapper( base_url=base_url, - httpx_client=httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + httpx_client=httpx.Client( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.Client(timeout=_defaulted_timeout), timeout=_defaulted_timeout, @@ -148,10 +164,14 @@ def __init__( ) self._client_wrapper = AsyncClientWrapper( base_url=base_url, - token=_token_getter_override if _token_getter_override is not None else oauth_token_provider.get_token, + token=_token_getter_override + if _token_getter_override is not None + else oauth_token_provider.get_token, httpx_client=httpx_client if httpx_client is not None - else httpx.AsyncClient(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.AsyncClient( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.AsyncClient(timeout=_defaulted_timeout), timeout=_defaulted_timeout, diff --git a/seed/python-sdk/oauth-client-credentials-environment-variables/src/seed/core/api_error.py b/seed/python-sdk/oauth-client-credentials-environment-variables/src/seed/core/api_error.py index 2e9fc5431cd..da734b58068 100644 --- a/seed/python-sdk/oauth-client-credentials-environment-variables/src/seed/core/api_error.py +++ b/seed/python-sdk/oauth-client-credentials-environment-variables/src/seed/core/api_error.py @@ -7,7 +7,9 @@ class ApiError(Exception): status_code: typing.Optional[int] body: typing.Any - def __init__(self, *, status_code: typing.Optional[int] = None, body: typing.Any = None): + def __init__( + self, *, status_code: typing.Optional[int] = None, body: typing.Any = None + ): self.status_code = status_code self.body = body diff --git a/seed/python-sdk/oauth-client-credentials-environment-variables/src/seed/core/client_wrapper.py b/seed/python-sdk/oauth-client-credentials-environment-variables/src/seed/core/client_wrapper.py index 22713e57f78..d64919dbcc9 100644 --- a/seed/python-sdk/oauth-client-credentials-environment-variables/src/seed/core/client_wrapper.py +++ b/seed/python-sdk/oauth-client-credentials-environment-variables/src/seed/core/client_wrapper.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .http_client import AsyncHttpClient, HttpClient +from .http_client import HttpClient +from .http_client import AsyncHttpClient class BaseClientWrapper: diff --git a/seed/python-sdk/oauth-client-credentials-environment-variables/src/seed/core/datetime_utils.py b/seed/python-sdk/oauth-client-credentials-environment-variables/src/seed/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/python-sdk/oauth-client-credentials-environment-variables/src/seed/core/datetime_utils.py +++ b/seed/python-sdk/oauth-client-credentials-environment-variables/src/seed/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/python-sdk/oauth-client-credentials-environment-variables/src/seed/core/file.py b/seed/python-sdk/oauth-client-credentials-environment-variables/src/seed/core/file.py index cb0d40bbbf3..6e0f92bfcb1 100644 --- a/seed/python-sdk/oauth-client-credentials-environment-variables/src/seed/core/file.py +++ b/seed/python-sdk/oauth-client-credentials-environment-variables/src/seed/core/file.py @@ -13,12 +13,17 @@ # (filename, file (or bytes), content_type) typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str]], # (filename, file (or bytes), content_type, headers) - typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str], typing.Mapping[str, str]], + typing.Tuple[ + typing.Optional[str], + FileContent, + typing.Optional[str], + typing.Mapping[str, str], + ], ] def convert_file_dict_to_httpx_tuples( - d: typing.Dict[str, typing.Union[File, typing.List[File]]] + d: typing.Dict[str, typing.Union[File, typing.List[File]]], ) -> typing.List[typing.Tuple[str, File]]: """ The format we use is a list of tuples, where the first element is the diff --git a/seed/python-sdk/oauth-client-credentials-environment-variables/src/seed/core/http_client.py b/seed/python-sdk/oauth-client-credentials-environment-variables/src/seed/core/http_client.py index 9333d8a7f15..091f71bc185 100644 --- a/seed/python-sdk/oauth-client-credentials-environment-variables/src/seed/core/http_client.py +++ b/seed/python-sdk/oauth-client-credentials-environment-variables/src/seed/core/http_client.py @@ -77,7 +77,9 @@ def _retry_timeout(response: httpx.Response, retries: int) -> float: return retry_after # Apply exponential backoff, capped at MAX_RETRY_DELAY_SECONDS. - retry_delay = min(INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS) + retry_delay = min( + INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS + ) # Add a randomness / jitter to the retry delay to avoid overwhelming the server with retries. timeout = retry_delay * (1 - 0.25 * random()) @@ -90,7 +92,8 @@ def _should_retry(response: httpx.Response) -> bool: def remove_omit_from_dict( - original: typing.Dict[str, typing.Optional[typing.Any]], omit: typing.Optional[typing.Any] + original: typing.Dict[str, typing.Optional[typing.Any]], + omit: typing.Optional[typing.Any], ) -> typing.Dict[str, typing.Any]: if omit is None: return original @@ -108,7 +111,8 @@ def maybe_filter_request_body( ) -> typing.Optional[typing.Any]: if data is None: return ( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else None ) @@ -118,7 +122,8 @@ def maybe_filter_request_body( data_content = { **(jsonable_encoder(remove_omit_from_dict(data, omit))), # type: ignore **( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else {} ), @@ -162,7 +167,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url def request( @@ -174,8 +181,12 @@ def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -184,11 +195,14 @@ def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) response = self.httpx_client.request( method=method, @@ -198,7 +212,11 @@ def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -209,7 +227,10 @@ def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -222,11 +243,15 @@ def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: time.sleep(_retry_timeout(response=response, retries=retries)) @@ -256,8 +281,12 @@ def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -266,11 +295,14 @@ def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) with self.httpx_client.stream( method=method, @@ -280,7 +312,11 @@ def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -291,7 +327,9 @@ def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -304,7 +342,9 @@ def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream @@ -327,7 +367,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url async def request( @@ -339,8 +381,12 @@ async def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -349,11 +395,14 @@ async def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) # Add the input to each of these and do None-safety checks response = await self.httpx_client.request( @@ -364,7 +413,11 @@ async def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -375,7 +428,10 @@ async def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -388,11 +444,15 @@ async def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: await asyncio.sleep(_retry_timeout(response=response, retries=retries)) @@ -421,8 +481,12 @@ async def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -431,11 +495,14 @@ async def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) async with self.httpx_client.stream( method=method, @@ -445,7 +512,11 @@ async def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -456,7 +527,9 @@ async def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -469,7 +542,9 @@ async def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream diff --git a/seed/python-sdk/oauth-client-credentials-environment-variables/src/seed/core/jsonable_encoder.py b/seed/python-sdk/oauth-client-credentials-environment-variables/src/seed/core/jsonable_encoder.py index d3fd328fd41..12a8b52fc22 100644 --- a/seed/python-sdk/oauth-client-credentials-environment-variables/src/seed/core/jsonable_encoder.py +++ b/seed/python-sdk/oauth-client-credentials-environment-variables/src/seed/core/jsonable_encoder.py @@ -19,13 +19,19 @@ import pydantic from .datetime_utils import serialize_datetime -from .pydantic_utilities import IS_PYDANTIC_V2, encode_by_type, to_jsonable_with_fallback +from .pydantic_utilities import ( + IS_PYDANTIC_V2, + encode_by_type, + to_jsonable_with_fallback, +) SetIntStr = Set[Union[int, str]] DictIntStrAny = Dict[Union[int, str], Any] -def jsonable_encoder(obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None) -> Any: +def jsonable_encoder( + obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None +) -> Any: custom_encoder = custom_encoder or {} if custom_encoder: if type(obj) in custom_encoder: diff --git a/seed/python-sdk/oauth-client-credentials-environment-variables/src/seed/core/oauth_token_provider.py b/seed/python-sdk/oauth-client-credentials-environment-variables/src/seed/core/oauth_token_provider.py index 1594d736901..cc68370f332 100644 --- a/seed/python-sdk/oauth-client-credentials-environment-variables/src/seed/core/oauth_token_provider.py +++ b/seed/python-sdk/oauth-client-credentials-environment-variables/src/seed/core/oauth_token_provider.py @@ -1,16 +1,17 @@ # This file was auto-generated by Fern from our API Definition. -import datetime as dt +from .client_wrapper import SyncClientWrapper import typing - +import datetime as dt from ..auth.client import AuthClient -from .client_wrapper import SyncClientWrapper class OAuthTokenProvider: BUFFER_IN_MINUTES = 2 - def __init__(self, *, client_id: str, client_secret: str, client_wrapper: SyncClientWrapper): + def __init__( + self, *, client_id: str, client_secret: str, client_wrapper: SyncClientWrapper + ): self._client_id = client_id self._client_secret = client_secret self._access_token: typing.Optional[str] = None @@ -28,9 +29,14 @@ def _refresh(self) -> str: ) self._access_token = token_response.access_token self._expires_at = self._get_expires_at( - expires_in_seconds=token_response.expires_in, buffer_in_minutes=self.BUFFER_IN_MINUTES + expires_in_seconds=token_response.expires_in, + buffer_in_minutes=self.BUFFER_IN_MINUTES, ) return self._access_token def _get_expires_at(self, *, expires_in_seconds: int, buffer_in_minutes: int): - return dt.datetime.now() + dt.timedelta(seconds=expires_in_seconds) - dt.timedelta(minutes=buffer_in_minutes) + return ( + dt.datetime.now() + + dt.timedelta(seconds=expires_in_seconds) + - dt.timedelta(minutes=buffer_in_minutes) + ) diff --git a/seed/python-sdk/oauth-client-credentials-environment-variables/src/seed/core/pydantic_utilities.py b/seed/python-sdk/oauth-client-credentials-environment-variables/src/seed/core/pydantic_utilities.py index 170a563d6eb..c63935c32a2 100644 --- a/seed/python-sdk/oauth-client-credentials-environment-variables/src/seed/core/pydantic_utilities.py +++ b/seed/python-sdk/oauth-client-credentials-environment-variables/src/seed/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) # type: ignore # Pydantic v1 diff --git a/seed/python-sdk/oauth-client-credentials-environment-variables/src/seed/core/query_encoder.py b/seed/python-sdk/oauth-client-credentials-environment-variables/src/seed/core/query_encoder.py index 24076d72ee9..7cb98f52cd7 100644 --- a/seed/python-sdk/oauth-client-credentials-environment-variables/src/seed/core/query_encoder.py +++ b/seed/python-sdk/oauth-client-credentials-environment-variables/src/seed/core/query_encoder.py @@ -7,7 +7,9 @@ # Flattens dicts to be of the form {"key[subkey][subkey2]": value} where value is not a dict -def traverse_query_dict(dict_flat: Dict[str, Any], key_prefix: Optional[str] = None) -> Dict[str, Any]: +def traverse_query_dict( + dict_flat: Dict[str, Any], key_prefix: Optional[str] = None +) -> Dict[str, Any]: result = {} for k, v in dict_flat.items(): key = f"{key_prefix}[{k}]" if key_prefix is not None else k @@ -30,4 +32,8 @@ def single_query_encoder(query_key: str, query_value: Any) -> Dict[str, Any]: def encode_query(query: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: - return dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) if query is not None else None + return ( + dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) + if query is not None + else None + ) diff --git a/seed/python-sdk/oauth-client-credentials-environment-variables/src/seed/core/serialization.py b/seed/python-sdk/oauth-client-credentials-environment-variables/src/seed/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/python-sdk/oauth-client-credentials-environment-variables/src/seed/core/serialization.py +++ b/seed/python-sdk/oauth-client-credentials-environment-variables/src/seed/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/python-sdk/oauth-client-credentials-environment-variables/src/seed/version.py b/seed/python-sdk/oauth-client-credentials-environment-variables/src/seed/version.py index 6d5d6390ac6..ccfee7d60c6 100644 --- a/seed/python-sdk/oauth-client-credentials-environment-variables/src/seed/version.py +++ b/seed/python-sdk/oauth-client-credentials-environment-variables/src/seed/version.py @@ -1,4 +1,3 @@ - from importlib import metadata __version__ = metadata.version("fern_oauth-client-credentials-environment-variables") diff --git a/seed/python-sdk/oauth-client-credentials-environment-variables/tests/conftest.py b/seed/python-sdk/oauth-client-credentials-environment-variables/tests/conftest.py index 2c062ddef86..7bfdc8dcc6e 100644 --- a/seed/python-sdk/oauth-client-credentials-environment-variables/tests/conftest.py +++ b/seed/python-sdk/oauth-client-credentials-environment-variables/tests/conftest.py @@ -1,9 +1,9 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedOauthClientCredentialsEnvironmentVariables import os - import pytest -from seed import AsyncSeedOauthClientCredentialsEnvironmentVariables, SeedOauthClientCredentialsEnvironmentVariables +from seed import AsyncSeedOauthClientCredentialsEnvironmentVariables @pytest.fixture diff --git a/seed/python-sdk/oauth-client-credentials-environment-variables/tests/custom/test_client.py b/seed/python-sdk/oauth-client-credentials-environment-variables/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/python-sdk/oauth-client-credentials-environment-variables/tests/custom/test_client.py +++ b/seed/python-sdk/oauth-client-credentials-environment-variables/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/python-sdk/oauth-client-credentials-environment-variables/tests/test_auth.py b/seed/python-sdk/oauth-client-credentials-environment-variables/tests/test_auth.py index 66d73729604..10a1fd66bc7 100644 --- a/seed/python-sdk/oauth-client-credentials-environment-variables/tests/test_auth.py +++ b/seed/python-sdk/oauth-client-credentials-environment-variables/tests/test_auth.py @@ -1,9 +1,8 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedOauthClientCredentialsEnvironmentVariables +from seed import AsyncSeedOauthClientCredentialsEnvironmentVariables import typing - -from seed import AsyncSeedOauthClientCredentialsEnvironmentVariables, SeedOauthClientCredentialsEnvironmentVariables - from .utilities import validate_response @@ -11,9 +10,19 @@ async def test_get_token_with_client_credentials( client: SeedOauthClientCredentialsEnvironmentVariables, async_client: AsyncSeedOauthClientCredentialsEnvironmentVariables, ) -> None: - expected_response: typing.Any = {"access_token": "string", "expires_in": 1, "refresh_token": "string"} - expected_types: typing.Any = {"access_token": None, "expires_in": "integer", "refresh_token": None} - response = client.auth.get_token_with_client_credentials(client_id="string", client_secret="string", scope="string") + expected_response: typing.Any = { + "access_token": "string", + "expires_in": 1, + "refresh_token": "string", + } + expected_types: typing.Any = { + "access_token": None, + "expires_in": "integer", + "refresh_token": None, + } + response = client.auth.get_token_with_client_credentials( + client_id="string", client_secret="string", scope="string" + ) validate_response(response, expected_response, expected_types) async_response = await async_client.auth.get_token_with_client_credentials( @@ -26,14 +35,28 @@ async def test_refresh_token( client: SeedOauthClientCredentialsEnvironmentVariables, async_client: AsyncSeedOauthClientCredentialsEnvironmentVariables, ) -> None: - expected_response: typing.Any = {"access_token": "string", "expires_in": 1, "refresh_token": "string"} - expected_types: typing.Any = {"access_token": None, "expires_in": "integer", "refresh_token": None} + expected_response: typing.Any = { + "access_token": "string", + "expires_in": 1, + "refresh_token": "string", + } + expected_types: typing.Any = { + "access_token": None, + "expires_in": "integer", + "refresh_token": None, + } response = client.auth.refresh_token( - client_id="string", client_secret="string", refresh_token="string", scope="string" + client_id="string", + client_secret="string", + refresh_token="string", + scope="string", ) validate_response(response, expected_response, expected_types) async_response = await async_client.auth.refresh_token( - client_id="string", client_secret="string", refresh_token="string", scope="string" + client_id="string", + client_secret="string", + refresh_token="string", + scope="string", ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/oauth-client-credentials-environment-variables/tests/utilities.py b/seed/python-sdk/oauth-client-credentials-environment-variables/tests/utilities.py index 13da208eb3a..e8f4472564c 100644 --- a/seed/python-sdk/oauth-client-credentials-environment-variables/tests/utilities.py +++ b/seed/python-sdk/oauth-client-credentials-environment-variables/tests/utilities.py @@ -3,11 +3,14 @@ import typing import uuid -import pydantic from dateutil import parser +import pydantic + -def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> typing.Any: +def cast_field( + json_expectation: typing.Any, type_expectation: typing.Any +) -> typing.Any: # Cast these specific types which come through as string and expect our # models to cast to the correct type. if type_expectation == "uuid": @@ -25,7 +28,9 @@ def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> ty return json_expectation -def validate_field(response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any) -> None: +def validate_field( + response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectation == "no_validate": return @@ -44,7 +49,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(entry_expectation, dict): is_container_of_complex_type = True validate_response( - response=response[idx], json_expectation=ex, type_expectations=entry_expectation + response=response[idx], + json_expectation=ex, + type_expectations=entry_expectation, ) else: cast_json_expectation.append(cast_field(ex, entry_expectation)) @@ -56,7 +63,10 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # if any of the values of the set have a type_expectation of a dict, we're assuming it's a pydantic # model and keeping it a list. if container_expectation != "set" or not any( - map(lambda value: isinstance(value, dict), list(contents_expectation.values())) + map( + lambda value: isinstance(value, dict), + list(contents_expectation.values()), + ) ): json_expectation = cast_field(json_expectation, container_expectation) elif isinstance(type_expectation, tuple): @@ -65,9 +75,15 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(contents_expectation, dict): json_expectation = { cast_field( - key, contents_expectation.get(idx)[0] if contents_expectation.get(idx) is not None else None # type: ignore + key, + contents_expectation.get(idx)[0] + if contents_expectation.get(idx) is not None + else None, # type: ignore ): cast_field( - value, contents_expectation.get(idx)[1] if contents_expectation.get(idx) is not None else None # type: ignore + value, + contents_expectation.get(idx)[1] + if contents_expectation.get(idx) is not None + else None, # type: ignore ) for idx, (key, value) in enumerate(json_expectation.items()) } @@ -86,7 +102,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # Arg type_expectations is a deeply nested structure that matches the response, but with the values replaced with the expected types -def validate_response(response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any) -> None: +def validate_response( + response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectations == "no_validate": return @@ -96,11 +114,17 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e and not isinstance(response, dict) and not issubclass(type(response), pydantic.BaseModel) ): - validate_field(response=response, json_expectation=json_expectation, type_expectation=type_expectations) + validate_field( + response=response, + json_expectation=json_expectation, + type_expectation=type_expectations, + ) return if isinstance(response, list): - assert len(response) == len(json_expectation), "Length mismatch, expected: {0}, Actual: {1}".format( + assert len(response) == len( + json_expectation + ), "Length mismatch, expected: {0}, Actual: {1}".format( len(response), len(json_expectation) ) content_expectation = type_expectations @@ -108,7 +132,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e content_expectation = type_expectations[1] for idx, item in enumerate(response): validate_response( - response=item, json_expectation=json_expectation[idx], type_expectations=content_expectation[idx] + response=item, + json_expectation=json_expectation[idx], + type_expectations=content_expectation[idx], ) else: response_json = response @@ -116,7 +142,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e response_json = response.dict(by_alias=True) for key, value in json_expectation.items(): - assert key in response_json, "Field {0} not found within the response object: {1}".format( + assert ( + key in response_json + ), "Field {0} not found within the response object: {1}".format( key, response_json ) @@ -128,11 +156,19 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e # Otherwise, we're just validating a single field that's a pydantic model. if isinstance(value, dict) and not isinstance(type_expectation, tuple): validate_response( - response=response_json[key], json_expectation=value, type_expectations=type_expectation + response=response_json[key], + json_expectation=value, + type_expectations=type_expectation, ) else: - validate_field(response=response_json[key], json_expectation=value, type_expectation=type_expectation) + validate_field( + response=response_json[key], + json_expectation=value, + type_expectation=type_expectation, + ) # Ensure there are no additional fields here either del response_json[key] - assert len(response_json) == 0, "Additional fields found, expected None: {0}".format(response_json) + assert ( + len(response_json) == 0 + ), "Additional fields found, expected None: {0}".format(response_json) diff --git a/seed/python-sdk/oauth-client-credentials-environment-variables/tests/utils/assets/models/__init__.py b/seed/python-sdk/oauth-client-credentials-environment-variables/tests/utils/assets/models/__init__.py index 2cf01263529..3a1c852e71e 100644 --- a/seed/python-sdk/oauth-client-credentials-environment-variables/tests/utils/assets/models/__init__.py +++ b/seed/python-sdk/oauth-client-credentials-environment-variables/tests/utils/assets/models/__init__.py @@ -5,7 +5,7 @@ from .circle import CircleParams from .object_with_defaults import ObjectWithDefaultsParams from .object_with_optional_field import ObjectWithOptionalFieldParams -from .shape import Shape_CircleParams, Shape_SquareParams, ShapeParams +from .shape import ShapeParams, Shape_CircleParams, Shape_SquareParams from .square import SquareParams from .undiscriminated_shape import UndiscriminatedShapeParams diff --git a/seed/python-sdk/oauth-client-credentials-environment-variables/tests/utils/assets/models/circle.py b/seed/python-sdk/oauth-client-credentials-environment-variables/tests/utils/assets/models/circle.py index af7a1bf8a8e..253f12d38b3 100644 --- a/seed/python-sdk/oauth-client-credentials-environment-variables/tests/utils/assets/models/circle.py +++ b/seed/python-sdk/oauth-client-credentials-environment-variables/tests/utils/assets/models/circle.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class CircleParams(typing_extensions.TypedDict): - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] diff --git a/seed/python-sdk/oauth-client-credentials-environment-variables/tests/utils/assets/models/object_with_optional_field.py b/seed/python-sdk/oauth-client-credentials-environment-variables/tests/utils/assets/models/object_with_optional_field.py index 3ad93d5f305..ebe7dc80547 100644 --- a/seed/python-sdk/oauth-client-credentials-environment-variables/tests/utils/assets/models/object_with_optional_field.py +++ b/seed/python-sdk/oauth-client-credentials-environment-variables/tests/utils/assets/models/object_with_optional_field.py @@ -7,8 +7,8 @@ import uuid import typing_extensions -from seed.core.serialization import FieldMetadata +from seed.core.serialization import FieldMetadata from .color import Color from .shape import ShapeParams from .undiscriminated_shape import UndiscriminatedShapeParams @@ -18,16 +18,30 @@ class ObjectWithOptionalFieldParams(typing_extensions.TypedDict): literal: typing.Literal["lit_one"] string: typing_extensions.NotRequired[str] integer: typing_extensions.NotRequired[int] - long_: typing_extensions.NotRequired[typing_extensions.Annotated[int, FieldMetadata(alias="long")]] + long_: typing_extensions.NotRequired[ + typing_extensions.Annotated[int, FieldMetadata(alias="long")] + ] double: typing_extensions.NotRequired[float] - bool_: typing_extensions.NotRequired[typing_extensions.Annotated[bool, FieldMetadata(alias="bool")]] + bool_: typing_extensions.NotRequired[ + typing_extensions.Annotated[bool, FieldMetadata(alias="bool")] + ] datetime: typing_extensions.NotRequired[dt.datetime] date: typing_extensions.NotRequired[dt.date] - uuid_: typing_extensions.NotRequired[typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")]] - base_64: typing_extensions.NotRequired[typing_extensions.Annotated[str, FieldMetadata(alias="base64")]] - list_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")]] - set_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")]] - map_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")]] + uuid_: typing_extensions.NotRequired[ + typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")] + ] + base_64: typing_extensions.NotRequired[ + typing_extensions.Annotated[str, FieldMetadata(alias="base64")] + ] + list_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")] + ] + set_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")] + ] + map_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")] + ] enum: typing_extensions.NotRequired[Color] union: typing_extensions.NotRequired[ShapeParams] second_union: typing_extensions.NotRequired[ShapeParams] diff --git a/seed/python-sdk/oauth-client-credentials-environment-variables/tests/utils/assets/models/shape.py b/seed/python-sdk/oauth-client-credentials-environment-variables/tests/utils/assets/models/shape.py index 2c33c877951..816ffc51bdc 100644 --- a/seed/python-sdk/oauth-client-credentials-environment-variables/tests/utils/assets/models/shape.py +++ b/seed/python-sdk/oauth-client-credentials-environment-variables/tests/utils/assets/models/shape.py @@ -7,6 +7,7 @@ import typing import typing_extensions + from seed.core.serialization import FieldMetadata @@ -15,13 +16,21 @@ class Base(typing_extensions.TypedDict): class Shape_CircleParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["circle"], FieldMetadata(alias="shapeType")] - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["circle"], FieldMetadata(alias="shapeType") + ] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] class Shape_SquareParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["square"], FieldMetadata(alias="shapeType")] - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["square"], FieldMetadata(alias="shapeType") + ] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] ShapeParams = typing.Union[Shape_CircleParams, Shape_SquareParams] diff --git a/seed/python-sdk/oauth-client-credentials-environment-variables/tests/utils/assets/models/square.py b/seed/python-sdk/oauth-client-credentials-environment-variables/tests/utils/assets/models/square.py index b9b7dd319bc..bcf08a723c5 100644 --- a/seed/python-sdk/oauth-client-credentials-environment-variables/tests/utils/assets/models/square.py +++ b/seed/python-sdk/oauth-client-credentials-environment-variables/tests/utils/assets/models/square.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class SquareParams(typing_extensions.TypedDict): - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] diff --git a/seed/python-sdk/oauth-client-credentials-environment-variables/tests/utils/test_http_client.py b/seed/python-sdk/oauth-client-credentials-environment-variables/tests/utils/test_http_client.py index edd11ca7afb..f5a874a75f3 100644 --- a/seed/python-sdk/oauth-client-credentials-environment-variables/tests/utils/test_http_client.py +++ b/seed/python-sdk/oauth-client-credentials-environment-variables/tests/utils/test_http_client.py @@ -9,12 +9,17 @@ def get_request_options() -> RequestOptions: def test_get_json_request_body() -> None: - json_body, data_body = get_request_body(json={"hello": "world"}, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json={"hello": "world"}, data=None, request_options=None, omit=None + ) assert json_body == {"hello": "world"} assert data_body is None json_body_extras, data_body_extras = get_request_body( - json={"goodbye": "world"}, data=None, request_options=get_request_options(), omit=None + json={"goodbye": "world"}, + data=None, + request_options=get_request_options(), + omit=None, ) assert json_body_extras == {"goodbye": "world", "see you": "later"} @@ -22,12 +27,17 @@ def test_get_json_request_body() -> None: def test_get_files_request_body() -> None: - json_body, data_body = get_request_body(json=None, data={"hello": "world"}, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data={"hello": "world"}, request_options=None, omit=None + ) assert data_body == {"hello": "world"} assert json_body is None json_body_extras, data_body_extras = get_request_body( - json=None, data={"goodbye": "world"}, request_options=get_request_options(), omit=None + json=None, + data={"goodbye": "world"}, + request_options=get_request_options(), + omit=None, ) assert data_body_extras == {"goodbye": "world", "see you": "later"} @@ -35,7 +45,9 @@ def test_get_files_request_body() -> None: def test_get_none_request_body() -> None: - json_body, data_body = get_request_body(json=None, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data=None, request_options=None, omit=None + ) assert data_body is None assert json_body is None diff --git a/seed/python-sdk/oauth-client-credentials-environment-variables/tests/utils/test_query_encoding.py b/seed/python-sdk/oauth-client-credentials-environment-variables/tests/utils/test_query_encoding.py index 247e1551b46..fbc8f402167 100644 --- a/seed/python-sdk/oauth-client-credentials-environment-variables/tests/utils/test_query_encoding.py +++ b/seed/python-sdk/oauth-client-credentials-environment-variables/tests/utils/test_query_encoding.py @@ -4,9 +4,15 @@ def test_query_encoding() -> None: - assert encode_query({"hello world": "hello world"}) == {"hello world": "hello world"} - assert encode_query({"hello_world": {"hello": "world"}}) == {"hello_world[hello]": "world"} - assert encode_query({"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"}) == { + assert encode_query({"hello world": "hello world"}) == { + "hello world": "hello world" + } + assert encode_query({"hello_world": {"hello": "world"}}) == { + "hello_world[hello]": "world" + } + assert encode_query( + {"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"} + ) == { "hello_world[hello][world]": "today", "hello_world[test]": "this", "hi": "there", diff --git a/seed/python-sdk/oauth-client-credentials-environment-variables/tests/utils/test_serialization.py b/seed/python-sdk/oauth-client-credentials-environment-variables/tests/utils/test_serialization.py index 58b1ed66e6d..5ca956916dd 100644 --- a/seed/python-sdk/oauth-client-credentials-environment-variables/tests/utils/test_serialization.py +++ b/seed/python-sdk/oauth-client-credentials-environment-variables/tests/utils/test_serialization.py @@ -1,10 +1,12 @@ # This file was auto-generated by Fern from our API Definition. -from typing import Any, List +from typing import List, Any -from seed.core.serialization import convert_and_respect_annotation_metadata +from seed.core.serialization import ( + convert_and_respect_annotation_metadata, +) +from .assets.models import ShapeParams, ObjectWithOptionalFieldParams -from .assets.models import ObjectWithOptionalFieldParams, ShapeParams UNION_TEST: ShapeParams = {"radius_measurement": 1.0, "shape_type": "circle", "id": "1"} UNION_TEST_CONVERTED = {"shapeType": "circle", "radiusMeasurement": 1.0, "id": "1"} @@ -18,20 +20,54 @@ def test_convert_and_respect_annotation_metadata() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) - assert converted == {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"} + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) + assert converted == { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + } def test_convert_and_respect_annotation_metadata_in_list() -> None: data: List[ObjectWithOptionalFieldParams] = [ - {"string": "string", "long_": 12345, "bool_": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long_": 67890, "list_": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long_": 12345, + "bool_": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long_": 67890, + "list_": [], + "literal": "lit_one", + "any": "any", + }, ] - converted = convert_and_respect_annotation_metadata(object_=data, annotation=List[ObjectWithOptionalFieldParams]) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=List[ObjectWithOptionalFieldParams] + ) assert converted == [ - {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long": 67890, "list": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long": 67890, + "list": [], + "literal": "lit_one", + "any": "any", + }, ] @@ -43,7 +79,9 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) assert converted == { "string": "string", @@ -55,12 +93,16 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: def test_convert_and_respect_annotation_metadata_in_union() -> None: - converted = convert_and_respect_annotation_metadata(object_=UNION_TEST, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=UNION_TEST, annotation=ShapeParams + ) assert converted == UNION_TEST_CONVERTED def test_convert_and_respect_annotation_metadata_with_empty_object() -> None: data: Any = {} - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ShapeParams + ) assert converted == data diff --git a/seed/python-sdk/oauth-client-credentials-nested-root/pyproject.toml b/seed/python-sdk/oauth-client-credentials-nested-root/pyproject.toml index 83edfd2d2fa..590993f35d2 100644 --- a/seed/python-sdk/oauth-client-credentials-nested-root/pyproject.toml +++ b/seed/python-sdk/oauth-client-credentials-nested-root/pyproject.toml @@ -43,6 +43,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/python-sdk/oauth-client-credentials-nested-root/src/seed/__init__.py b/seed/python-sdk/oauth-client-credentials-nested-root/src/seed/__init__.py index 69856793a8d..0a1210d8a8f 100644 --- a/seed/python-sdk/oauth-client-credentials-nested-root/src/seed/__init__.py +++ b/seed/python-sdk/oauth-client-credentials-nested-root/src/seed/__init__.py @@ -4,4 +4,9 @@ from .client import AsyncSeedOauthClientCredentials, SeedOauthClientCredentials from .version import __version__ -__all__ = ["AsyncSeedOauthClientCredentials", "SeedOauthClientCredentials", "__version__", "auth"] +__all__ = [ + "AsyncSeedOauthClientCredentials", + "SeedOauthClientCredentials", + "__version__", + "auth", +] diff --git a/seed/python-sdk/oauth-client-credentials-nested-root/src/seed/auth/client.py b/seed/python-sdk/oauth-client-credentials-nested-root/src/seed/auth/client.py index 670fc53520f..3a0ba998bac 100644 --- a/seed/python-sdk/oauth-client-credentials-nested-root/src/seed/auth/client.py +++ b/seed/python-sdk/oauth-client-credentials-nested-root/src/seed/auth/client.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. import typing -from json.decoder import JSONDecodeError - -from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.pydantic_utilities import parse_obj_as +from ..core.client_wrapper import SyncClientWrapper from ..core.request_options import RequestOptions from .types.token_response import TokenResponse +from ..core.pydantic_utilities import parse_obj_as +from json.decoder import JSONDecodeError +from ..core.api_error import ApiError +from ..core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -23,7 +23,7 @@ def get_token( client_id: str, client_secret: str, scope: typing.Optional[str] = OMIT, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> TokenResponse: """ Parameters @@ -71,7 +71,10 @@ def get_token( ) try: if 200 <= _response.status_code < 300: - return typing.cast(TokenResponse, parse_obj_as(type_=TokenResponse, object_=_response.json())) # type: ignore + return typing.cast( + TokenResponse, + parse_obj_as(type_=TokenResponse, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -88,7 +91,7 @@ async def get_token( client_id: str, client_secret: str, scope: typing.Optional[str] = OMIT, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> TokenResponse: """ Parameters @@ -144,7 +147,10 @@ async def main() -> None: ) try: if 200 <= _response.status_code < 300: - return typing.cast(TokenResponse, parse_obj_as(type_=TokenResponse, object_=_response.json())) # type: ignore + return typing.cast( + TokenResponse, + parse_obj_as(type_=TokenResponse, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/oauth-client-credentials-nested-root/src/seed/auth/types/token_response.py b/seed/python-sdk/oauth-client-credentials-nested-root/src/seed/auth/types/token_response.py index 44ac83f1a2b..3277d3fd341 100644 --- a/seed/python-sdk/oauth-client-credentials-nested-root/src/seed/auth/types/token_response.py +++ b/seed/python-sdk/oauth-client-credentials-nested-root/src/seed/auth/types/token_response.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel import typing - +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class TokenResponse(UniversalBaseModel): """ @@ -17,7 +16,9 @@ class TokenResponse(UniversalBaseModel): refresh_token: typing.Optional[str] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/oauth-client-credentials-nested-root/src/seed/client.py b/seed/python-sdk/oauth-client-credentials-nested-root/src/seed/client.py index 1d7db30adbb..afea747d55d 100644 --- a/seed/python-sdk/oauth-client-credentials-nested-root/src/seed/client.py +++ b/seed/python-sdk/oauth-client-credentials-nested-root/src/seed/client.py @@ -1,12 +1,12 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .auth.client import AsyncAuthClient, AuthClient -from .core.client_wrapper import AsyncClientWrapper, SyncClientWrapper from .core.oauth_token_provider import OAuthTokenProvider +from .core.client_wrapper import SyncClientWrapper +from .auth.client import AuthClient +from .core.client_wrapper import AsyncClientWrapper +from .auth.client import AsyncAuthClient class SeedOauthClientCredentials: @@ -50,15 +50,19 @@ def __init__( _token_getter_override: typing.Optional[typing.Callable[[], str]] = None, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.Client] = None + httpx_client: typing.Optional[httpx.Client] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) oauth_token_provider = OAuthTokenProvider( client_id=client_id, client_secret=client_secret, client_wrapper=SyncClientWrapper( base_url=base_url, - httpx_client=httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + httpx_client=httpx.Client( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.Client(timeout=_defaulted_timeout), timeout=_defaulted_timeout, @@ -66,10 +70,14 @@ def __init__( ) self._client_wrapper = SyncClientWrapper( base_url=base_url, - token=_token_getter_override if _token_getter_override is not None else oauth_token_provider.get_token, + token=_token_getter_override + if _token_getter_override is not None + else oauth_token_provider.get_token, httpx_client=httpx_client if httpx_client is not None - else httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.Client( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.Client(timeout=_defaulted_timeout), timeout=_defaulted_timeout, @@ -118,15 +126,19 @@ def __init__( _token_getter_override: typing.Optional[typing.Callable[[], str]] = None, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.AsyncClient] = None + httpx_client: typing.Optional[httpx.AsyncClient] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) oauth_token_provider = OAuthTokenProvider( client_id=client_id, client_secret=client_secret, client_wrapper=SyncClientWrapper( base_url=base_url, - httpx_client=httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + httpx_client=httpx.Client( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.Client(timeout=_defaulted_timeout), timeout=_defaulted_timeout, @@ -134,10 +146,14 @@ def __init__( ) self._client_wrapper = AsyncClientWrapper( base_url=base_url, - token=_token_getter_override if _token_getter_override is not None else oauth_token_provider.get_token, + token=_token_getter_override + if _token_getter_override is not None + else oauth_token_provider.get_token, httpx_client=httpx_client if httpx_client is not None - else httpx.AsyncClient(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.AsyncClient( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.AsyncClient(timeout=_defaulted_timeout), timeout=_defaulted_timeout, diff --git a/seed/python-sdk/oauth-client-credentials-nested-root/src/seed/core/api_error.py b/seed/python-sdk/oauth-client-credentials-nested-root/src/seed/core/api_error.py index 2e9fc5431cd..da734b58068 100644 --- a/seed/python-sdk/oauth-client-credentials-nested-root/src/seed/core/api_error.py +++ b/seed/python-sdk/oauth-client-credentials-nested-root/src/seed/core/api_error.py @@ -7,7 +7,9 @@ class ApiError(Exception): status_code: typing.Optional[int] body: typing.Any - def __init__(self, *, status_code: typing.Optional[int] = None, body: typing.Any = None): + def __init__( + self, *, status_code: typing.Optional[int] = None, body: typing.Any = None + ): self.status_code = status_code self.body = body diff --git a/seed/python-sdk/oauth-client-credentials-nested-root/src/seed/core/client_wrapper.py b/seed/python-sdk/oauth-client-credentials-nested-root/src/seed/core/client_wrapper.py index d3190064d99..155010692a0 100644 --- a/seed/python-sdk/oauth-client-credentials-nested-root/src/seed/core/client_wrapper.py +++ b/seed/python-sdk/oauth-client-credentials-nested-root/src/seed/core/client_wrapper.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .http_client import AsyncHttpClient, HttpClient +from .http_client import HttpClient +from .http_client import AsyncHttpClient class BaseClientWrapper: diff --git a/seed/python-sdk/oauth-client-credentials-nested-root/src/seed/core/datetime_utils.py b/seed/python-sdk/oauth-client-credentials-nested-root/src/seed/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/python-sdk/oauth-client-credentials-nested-root/src/seed/core/datetime_utils.py +++ b/seed/python-sdk/oauth-client-credentials-nested-root/src/seed/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/python-sdk/oauth-client-credentials-nested-root/src/seed/core/file.py b/seed/python-sdk/oauth-client-credentials-nested-root/src/seed/core/file.py index cb0d40bbbf3..6e0f92bfcb1 100644 --- a/seed/python-sdk/oauth-client-credentials-nested-root/src/seed/core/file.py +++ b/seed/python-sdk/oauth-client-credentials-nested-root/src/seed/core/file.py @@ -13,12 +13,17 @@ # (filename, file (or bytes), content_type) typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str]], # (filename, file (or bytes), content_type, headers) - typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str], typing.Mapping[str, str]], + typing.Tuple[ + typing.Optional[str], + FileContent, + typing.Optional[str], + typing.Mapping[str, str], + ], ] def convert_file_dict_to_httpx_tuples( - d: typing.Dict[str, typing.Union[File, typing.List[File]]] + d: typing.Dict[str, typing.Union[File, typing.List[File]]], ) -> typing.List[typing.Tuple[str, File]]: """ The format we use is a list of tuples, where the first element is the diff --git a/seed/python-sdk/oauth-client-credentials-nested-root/src/seed/core/http_client.py b/seed/python-sdk/oauth-client-credentials-nested-root/src/seed/core/http_client.py index 9333d8a7f15..091f71bc185 100644 --- a/seed/python-sdk/oauth-client-credentials-nested-root/src/seed/core/http_client.py +++ b/seed/python-sdk/oauth-client-credentials-nested-root/src/seed/core/http_client.py @@ -77,7 +77,9 @@ def _retry_timeout(response: httpx.Response, retries: int) -> float: return retry_after # Apply exponential backoff, capped at MAX_RETRY_DELAY_SECONDS. - retry_delay = min(INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS) + retry_delay = min( + INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS + ) # Add a randomness / jitter to the retry delay to avoid overwhelming the server with retries. timeout = retry_delay * (1 - 0.25 * random()) @@ -90,7 +92,8 @@ def _should_retry(response: httpx.Response) -> bool: def remove_omit_from_dict( - original: typing.Dict[str, typing.Optional[typing.Any]], omit: typing.Optional[typing.Any] + original: typing.Dict[str, typing.Optional[typing.Any]], + omit: typing.Optional[typing.Any], ) -> typing.Dict[str, typing.Any]: if omit is None: return original @@ -108,7 +111,8 @@ def maybe_filter_request_body( ) -> typing.Optional[typing.Any]: if data is None: return ( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else None ) @@ -118,7 +122,8 @@ def maybe_filter_request_body( data_content = { **(jsonable_encoder(remove_omit_from_dict(data, omit))), # type: ignore **( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else {} ), @@ -162,7 +167,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url def request( @@ -174,8 +181,12 @@ def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -184,11 +195,14 @@ def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) response = self.httpx_client.request( method=method, @@ -198,7 +212,11 @@ def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -209,7 +227,10 @@ def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -222,11 +243,15 @@ def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: time.sleep(_retry_timeout(response=response, retries=retries)) @@ -256,8 +281,12 @@ def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -266,11 +295,14 @@ def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) with self.httpx_client.stream( method=method, @@ -280,7 +312,11 @@ def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -291,7 +327,9 @@ def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -304,7 +342,9 @@ def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream @@ -327,7 +367,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url async def request( @@ -339,8 +381,12 @@ async def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -349,11 +395,14 @@ async def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) # Add the input to each of these and do None-safety checks response = await self.httpx_client.request( @@ -364,7 +413,11 @@ async def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -375,7 +428,10 @@ async def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -388,11 +444,15 @@ async def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: await asyncio.sleep(_retry_timeout(response=response, retries=retries)) @@ -421,8 +481,12 @@ async def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -431,11 +495,14 @@ async def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) async with self.httpx_client.stream( method=method, @@ -445,7 +512,11 @@ async def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -456,7 +527,9 @@ async def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -469,7 +542,9 @@ async def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream diff --git a/seed/python-sdk/oauth-client-credentials-nested-root/src/seed/core/jsonable_encoder.py b/seed/python-sdk/oauth-client-credentials-nested-root/src/seed/core/jsonable_encoder.py index d3fd328fd41..12a8b52fc22 100644 --- a/seed/python-sdk/oauth-client-credentials-nested-root/src/seed/core/jsonable_encoder.py +++ b/seed/python-sdk/oauth-client-credentials-nested-root/src/seed/core/jsonable_encoder.py @@ -19,13 +19,19 @@ import pydantic from .datetime_utils import serialize_datetime -from .pydantic_utilities import IS_PYDANTIC_V2, encode_by_type, to_jsonable_with_fallback +from .pydantic_utilities import ( + IS_PYDANTIC_V2, + encode_by_type, + to_jsonable_with_fallback, +) SetIntStr = Set[Union[int, str]] DictIntStrAny = Dict[Union[int, str], Any] -def jsonable_encoder(obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None) -> Any: +def jsonable_encoder( + obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None +) -> Any: custom_encoder = custom_encoder or {} if custom_encoder: if type(obj) in custom_encoder: diff --git a/seed/python-sdk/oauth-client-credentials-nested-root/src/seed/core/oauth_token_provider.py b/seed/python-sdk/oauth-client-credentials-nested-root/src/seed/core/oauth_token_provider.py index 25d22cd2b1e..6570df8dec7 100644 --- a/seed/python-sdk/oauth-client-credentials-nested-root/src/seed/core/oauth_token_provider.py +++ b/seed/python-sdk/oauth-client-credentials-nested-root/src/seed/core/oauth_token_provider.py @@ -1,16 +1,17 @@ # This file was auto-generated by Fern from our API Definition. -import datetime as dt +from .client_wrapper import SyncClientWrapper import typing - +import datetime as dt from ..auth.client import AuthClient -from .client_wrapper import SyncClientWrapper class OAuthTokenProvider: BUFFER_IN_MINUTES = 2 - def __init__(self, *, client_id: str, client_secret: str, client_wrapper: SyncClientWrapper): + def __init__( + self, *, client_id: str, client_secret: str, client_wrapper: SyncClientWrapper + ): self._client_id = client_id self._client_secret = client_secret self._access_token: typing.Optional[str] = None @@ -23,12 +24,19 @@ def get_token(self) -> str: return self._refresh() def _refresh(self) -> str: - token_response = self._auth_client.get_token(client_id=self._client_id, client_secret=self._client_secret) + token_response = self._auth_client.get_token( + client_id=self._client_id, client_secret=self._client_secret + ) self._access_token = token_response.access_token self._expires_at = self._get_expires_at( - expires_in_seconds=token_response.expires_in, buffer_in_minutes=self.BUFFER_IN_MINUTES + expires_in_seconds=token_response.expires_in, + buffer_in_minutes=self.BUFFER_IN_MINUTES, ) return self._access_token def _get_expires_at(self, *, expires_in_seconds: int, buffer_in_minutes: int): - return dt.datetime.now() + dt.timedelta(seconds=expires_in_seconds) - dt.timedelta(minutes=buffer_in_minutes) + return ( + dt.datetime.now() + + dt.timedelta(seconds=expires_in_seconds) + - dt.timedelta(minutes=buffer_in_minutes) + ) diff --git a/seed/python-sdk/oauth-client-credentials-nested-root/src/seed/core/pydantic_utilities.py b/seed/python-sdk/oauth-client-credentials-nested-root/src/seed/core/pydantic_utilities.py index 170a563d6eb..c63935c32a2 100644 --- a/seed/python-sdk/oauth-client-credentials-nested-root/src/seed/core/pydantic_utilities.py +++ b/seed/python-sdk/oauth-client-credentials-nested-root/src/seed/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) # type: ignore # Pydantic v1 diff --git a/seed/python-sdk/oauth-client-credentials-nested-root/src/seed/core/query_encoder.py b/seed/python-sdk/oauth-client-credentials-nested-root/src/seed/core/query_encoder.py index 24076d72ee9..7cb98f52cd7 100644 --- a/seed/python-sdk/oauth-client-credentials-nested-root/src/seed/core/query_encoder.py +++ b/seed/python-sdk/oauth-client-credentials-nested-root/src/seed/core/query_encoder.py @@ -7,7 +7,9 @@ # Flattens dicts to be of the form {"key[subkey][subkey2]": value} where value is not a dict -def traverse_query_dict(dict_flat: Dict[str, Any], key_prefix: Optional[str] = None) -> Dict[str, Any]: +def traverse_query_dict( + dict_flat: Dict[str, Any], key_prefix: Optional[str] = None +) -> Dict[str, Any]: result = {} for k, v in dict_flat.items(): key = f"{key_prefix}[{k}]" if key_prefix is not None else k @@ -30,4 +32,8 @@ def single_query_encoder(query_key: str, query_value: Any) -> Dict[str, Any]: def encode_query(query: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: - return dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) if query is not None else None + return ( + dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) + if query is not None + else None + ) diff --git a/seed/python-sdk/oauth-client-credentials-nested-root/src/seed/core/serialization.py b/seed/python-sdk/oauth-client-credentials-nested-root/src/seed/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/python-sdk/oauth-client-credentials-nested-root/src/seed/core/serialization.py +++ b/seed/python-sdk/oauth-client-credentials-nested-root/src/seed/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/python-sdk/oauth-client-credentials-nested-root/src/seed/version.py b/seed/python-sdk/oauth-client-credentials-nested-root/src/seed/version.py index ed05f091e6e..c9f332305a6 100644 --- a/seed/python-sdk/oauth-client-credentials-nested-root/src/seed/version.py +++ b/seed/python-sdk/oauth-client-credentials-nested-root/src/seed/version.py @@ -1,4 +1,3 @@ - from importlib import metadata __version__ = metadata.version("fern_oauth-client-credentials-nested-root") diff --git a/seed/python-sdk/oauth-client-credentials-nested-root/tests/auth/test_root.py b/seed/python-sdk/oauth-client-credentials-nested-root/tests/auth/test_root.py index 210845aa8c0..3748bf38a09 100644 --- a/seed/python-sdk/oauth-client-credentials-nested-root/tests/auth/test_root.py +++ b/seed/python-sdk/oauth-client-credentials-nested-root/tests/auth/test_root.py @@ -1,17 +1,30 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedOauthClientCredentials +from seed import AsyncSeedOauthClientCredentials import typing - -from seed import AsyncSeedOauthClientCredentials, SeedOauthClientCredentials - from ..utilities import validate_response -async def test_get_token(client: SeedOauthClientCredentials, async_client: AsyncSeedOauthClientCredentials) -> None: - expected_response: typing.Any = {"access_token": "string", "expires_in": 1, "refresh_token": "string"} - expected_types: typing.Any = {"access_token": None, "expires_in": "integer", "refresh_token": None} - response = client.auth.get_token(client_id="string", client_secret="string", scope="string") +async def test_get_token( + client: SeedOauthClientCredentials, async_client: AsyncSeedOauthClientCredentials +) -> None: + expected_response: typing.Any = { + "access_token": "string", + "expires_in": 1, + "refresh_token": "string", + } + expected_types: typing.Any = { + "access_token": None, + "expires_in": "integer", + "refresh_token": None, + } + response = client.auth.get_token( + client_id="string", client_secret="string", scope="string" + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.auth.get_token(client_id="string", client_secret="string", scope="string") + async_response = await async_client.auth.get_token( + client_id="string", client_secret="string", scope="string" + ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/oauth-client-credentials-nested-root/tests/conftest.py b/seed/python-sdk/oauth-client-credentials-nested-root/tests/conftest.py index 93bff0658ab..1168b370983 100644 --- a/seed/python-sdk/oauth-client-credentials-nested-root/tests/conftest.py +++ b/seed/python-sdk/oauth-client-credentials-nested-root/tests/conftest.py @@ -1,9 +1,9 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedOauthClientCredentials import os - import pytest -from seed import AsyncSeedOauthClientCredentials, SeedOauthClientCredentials +from seed import AsyncSeedOauthClientCredentials @pytest.fixture diff --git a/seed/python-sdk/oauth-client-credentials-nested-root/tests/custom/test_client.py b/seed/python-sdk/oauth-client-credentials-nested-root/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/python-sdk/oauth-client-credentials-nested-root/tests/custom/test_client.py +++ b/seed/python-sdk/oauth-client-credentials-nested-root/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/python-sdk/oauth-client-credentials-nested-root/tests/utilities.py b/seed/python-sdk/oauth-client-credentials-nested-root/tests/utilities.py index 13da208eb3a..e8f4472564c 100644 --- a/seed/python-sdk/oauth-client-credentials-nested-root/tests/utilities.py +++ b/seed/python-sdk/oauth-client-credentials-nested-root/tests/utilities.py @@ -3,11 +3,14 @@ import typing import uuid -import pydantic from dateutil import parser +import pydantic + -def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> typing.Any: +def cast_field( + json_expectation: typing.Any, type_expectation: typing.Any +) -> typing.Any: # Cast these specific types which come through as string and expect our # models to cast to the correct type. if type_expectation == "uuid": @@ -25,7 +28,9 @@ def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> ty return json_expectation -def validate_field(response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any) -> None: +def validate_field( + response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectation == "no_validate": return @@ -44,7 +49,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(entry_expectation, dict): is_container_of_complex_type = True validate_response( - response=response[idx], json_expectation=ex, type_expectations=entry_expectation + response=response[idx], + json_expectation=ex, + type_expectations=entry_expectation, ) else: cast_json_expectation.append(cast_field(ex, entry_expectation)) @@ -56,7 +63,10 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # if any of the values of the set have a type_expectation of a dict, we're assuming it's a pydantic # model and keeping it a list. if container_expectation != "set" or not any( - map(lambda value: isinstance(value, dict), list(contents_expectation.values())) + map( + lambda value: isinstance(value, dict), + list(contents_expectation.values()), + ) ): json_expectation = cast_field(json_expectation, container_expectation) elif isinstance(type_expectation, tuple): @@ -65,9 +75,15 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(contents_expectation, dict): json_expectation = { cast_field( - key, contents_expectation.get(idx)[0] if contents_expectation.get(idx) is not None else None # type: ignore + key, + contents_expectation.get(idx)[0] + if contents_expectation.get(idx) is not None + else None, # type: ignore ): cast_field( - value, contents_expectation.get(idx)[1] if contents_expectation.get(idx) is not None else None # type: ignore + value, + contents_expectation.get(idx)[1] + if contents_expectation.get(idx) is not None + else None, # type: ignore ) for idx, (key, value) in enumerate(json_expectation.items()) } @@ -86,7 +102,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # Arg type_expectations is a deeply nested structure that matches the response, but with the values replaced with the expected types -def validate_response(response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any) -> None: +def validate_response( + response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectations == "no_validate": return @@ -96,11 +114,17 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e and not isinstance(response, dict) and not issubclass(type(response), pydantic.BaseModel) ): - validate_field(response=response, json_expectation=json_expectation, type_expectation=type_expectations) + validate_field( + response=response, + json_expectation=json_expectation, + type_expectation=type_expectations, + ) return if isinstance(response, list): - assert len(response) == len(json_expectation), "Length mismatch, expected: {0}, Actual: {1}".format( + assert len(response) == len( + json_expectation + ), "Length mismatch, expected: {0}, Actual: {1}".format( len(response), len(json_expectation) ) content_expectation = type_expectations @@ -108,7 +132,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e content_expectation = type_expectations[1] for idx, item in enumerate(response): validate_response( - response=item, json_expectation=json_expectation[idx], type_expectations=content_expectation[idx] + response=item, + json_expectation=json_expectation[idx], + type_expectations=content_expectation[idx], ) else: response_json = response @@ -116,7 +142,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e response_json = response.dict(by_alias=True) for key, value in json_expectation.items(): - assert key in response_json, "Field {0} not found within the response object: {1}".format( + assert ( + key in response_json + ), "Field {0} not found within the response object: {1}".format( key, response_json ) @@ -128,11 +156,19 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e # Otherwise, we're just validating a single field that's a pydantic model. if isinstance(value, dict) and not isinstance(type_expectation, tuple): validate_response( - response=response_json[key], json_expectation=value, type_expectations=type_expectation + response=response_json[key], + json_expectation=value, + type_expectations=type_expectation, ) else: - validate_field(response=response_json[key], json_expectation=value, type_expectation=type_expectation) + validate_field( + response=response_json[key], + json_expectation=value, + type_expectation=type_expectation, + ) # Ensure there are no additional fields here either del response_json[key] - assert len(response_json) == 0, "Additional fields found, expected None: {0}".format(response_json) + assert ( + len(response_json) == 0 + ), "Additional fields found, expected None: {0}".format(response_json) diff --git a/seed/python-sdk/oauth-client-credentials-nested-root/tests/utils/assets/models/__init__.py b/seed/python-sdk/oauth-client-credentials-nested-root/tests/utils/assets/models/__init__.py index 2cf01263529..3a1c852e71e 100644 --- a/seed/python-sdk/oauth-client-credentials-nested-root/tests/utils/assets/models/__init__.py +++ b/seed/python-sdk/oauth-client-credentials-nested-root/tests/utils/assets/models/__init__.py @@ -5,7 +5,7 @@ from .circle import CircleParams from .object_with_defaults import ObjectWithDefaultsParams from .object_with_optional_field import ObjectWithOptionalFieldParams -from .shape import Shape_CircleParams, Shape_SquareParams, ShapeParams +from .shape import ShapeParams, Shape_CircleParams, Shape_SquareParams from .square import SquareParams from .undiscriminated_shape import UndiscriminatedShapeParams diff --git a/seed/python-sdk/oauth-client-credentials-nested-root/tests/utils/assets/models/circle.py b/seed/python-sdk/oauth-client-credentials-nested-root/tests/utils/assets/models/circle.py index af7a1bf8a8e..253f12d38b3 100644 --- a/seed/python-sdk/oauth-client-credentials-nested-root/tests/utils/assets/models/circle.py +++ b/seed/python-sdk/oauth-client-credentials-nested-root/tests/utils/assets/models/circle.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class CircleParams(typing_extensions.TypedDict): - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] diff --git a/seed/python-sdk/oauth-client-credentials-nested-root/tests/utils/assets/models/object_with_optional_field.py b/seed/python-sdk/oauth-client-credentials-nested-root/tests/utils/assets/models/object_with_optional_field.py index 3ad93d5f305..ebe7dc80547 100644 --- a/seed/python-sdk/oauth-client-credentials-nested-root/tests/utils/assets/models/object_with_optional_field.py +++ b/seed/python-sdk/oauth-client-credentials-nested-root/tests/utils/assets/models/object_with_optional_field.py @@ -7,8 +7,8 @@ import uuid import typing_extensions -from seed.core.serialization import FieldMetadata +from seed.core.serialization import FieldMetadata from .color import Color from .shape import ShapeParams from .undiscriminated_shape import UndiscriminatedShapeParams @@ -18,16 +18,30 @@ class ObjectWithOptionalFieldParams(typing_extensions.TypedDict): literal: typing.Literal["lit_one"] string: typing_extensions.NotRequired[str] integer: typing_extensions.NotRequired[int] - long_: typing_extensions.NotRequired[typing_extensions.Annotated[int, FieldMetadata(alias="long")]] + long_: typing_extensions.NotRequired[ + typing_extensions.Annotated[int, FieldMetadata(alias="long")] + ] double: typing_extensions.NotRequired[float] - bool_: typing_extensions.NotRequired[typing_extensions.Annotated[bool, FieldMetadata(alias="bool")]] + bool_: typing_extensions.NotRequired[ + typing_extensions.Annotated[bool, FieldMetadata(alias="bool")] + ] datetime: typing_extensions.NotRequired[dt.datetime] date: typing_extensions.NotRequired[dt.date] - uuid_: typing_extensions.NotRequired[typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")]] - base_64: typing_extensions.NotRequired[typing_extensions.Annotated[str, FieldMetadata(alias="base64")]] - list_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")]] - set_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")]] - map_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")]] + uuid_: typing_extensions.NotRequired[ + typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")] + ] + base_64: typing_extensions.NotRequired[ + typing_extensions.Annotated[str, FieldMetadata(alias="base64")] + ] + list_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")] + ] + set_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")] + ] + map_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")] + ] enum: typing_extensions.NotRequired[Color] union: typing_extensions.NotRequired[ShapeParams] second_union: typing_extensions.NotRequired[ShapeParams] diff --git a/seed/python-sdk/oauth-client-credentials-nested-root/tests/utils/assets/models/shape.py b/seed/python-sdk/oauth-client-credentials-nested-root/tests/utils/assets/models/shape.py index 2c33c877951..816ffc51bdc 100644 --- a/seed/python-sdk/oauth-client-credentials-nested-root/tests/utils/assets/models/shape.py +++ b/seed/python-sdk/oauth-client-credentials-nested-root/tests/utils/assets/models/shape.py @@ -7,6 +7,7 @@ import typing import typing_extensions + from seed.core.serialization import FieldMetadata @@ -15,13 +16,21 @@ class Base(typing_extensions.TypedDict): class Shape_CircleParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["circle"], FieldMetadata(alias="shapeType")] - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["circle"], FieldMetadata(alias="shapeType") + ] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] class Shape_SquareParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["square"], FieldMetadata(alias="shapeType")] - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["square"], FieldMetadata(alias="shapeType") + ] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] ShapeParams = typing.Union[Shape_CircleParams, Shape_SquareParams] diff --git a/seed/python-sdk/oauth-client-credentials-nested-root/tests/utils/assets/models/square.py b/seed/python-sdk/oauth-client-credentials-nested-root/tests/utils/assets/models/square.py index b9b7dd319bc..bcf08a723c5 100644 --- a/seed/python-sdk/oauth-client-credentials-nested-root/tests/utils/assets/models/square.py +++ b/seed/python-sdk/oauth-client-credentials-nested-root/tests/utils/assets/models/square.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class SquareParams(typing_extensions.TypedDict): - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] diff --git a/seed/python-sdk/oauth-client-credentials-nested-root/tests/utils/test_http_client.py b/seed/python-sdk/oauth-client-credentials-nested-root/tests/utils/test_http_client.py index edd11ca7afb..f5a874a75f3 100644 --- a/seed/python-sdk/oauth-client-credentials-nested-root/tests/utils/test_http_client.py +++ b/seed/python-sdk/oauth-client-credentials-nested-root/tests/utils/test_http_client.py @@ -9,12 +9,17 @@ def get_request_options() -> RequestOptions: def test_get_json_request_body() -> None: - json_body, data_body = get_request_body(json={"hello": "world"}, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json={"hello": "world"}, data=None, request_options=None, omit=None + ) assert json_body == {"hello": "world"} assert data_body is None json_body_extras, data_body_extras = get_request_body( - json={"goodbye": "world"}, data=None, request_options=get_request_options(), omit=None + json={"goodbye": "world"}, + data=None, + request_options=get_request_options(), + omit=None, ) assert json_body_extras == {"goodbye": "world", "see you": "later"} @@ -22,12 +27,17 @@ def test_get_json_request_body() -> None: def test_get_files_request_body() -> None: - json_body, data_body = get_request_body(json=None, data={"hello": "world"}, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data={"hello": "world"}, request_options=None, omit=None + ) assert data_body == {"hello": "world"} assert json_body is None json_body_extras, data_body_extras = get_request_body( - json=None, data={"goodbye": "world"}, request_options=get_request_options(), omit=None + json=None, + data={"goodbye": "world"}, + request_options=get_request_options(), + omit=None, ) assert data_body_extras == {"goodbye": "world", "see you": "later"} @@ -35,7 +45,9 @@ def test_get_files_request_body() -> None: def test_get_none_request_body() -> None: - json_body, data_body = get_request_body(json=None, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data=None, request_options=None, omit=None + ) assert data_body is None assert json_body is None diff --git a/seed/python-sdk/oauth-client-credentials-nested-root/tests/utils/test_query_encoding.py b/seed/python-sdk/oauth-client-credentials-nested-root/tests/utils/test_query_encoding.py index 247e1551b46..fbc8f402167 100644 --- a/seed/python-sdk/oauth-client-credentials-nested-root/tests/utils/test_query_encoding.py +++ b/seed/python-sdk/oauth-client-credentials-nested-root/tests/utils/test_query_encoding.py @@ -4,9 +4,15 @@ def test_query_encoding() -> None: - assert encode_query({"hello world": "hello world"}) == {"hello world": "hello world"} - assert encode_query({"hello_world": {"hello": "world"}}) == {"hello_world[hello]": "world"} - assert encode_query({"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"}) == { + assert encode_query({"hello world": "hello world"}) == { + "hello world": "hello world" + } + assert encode_query({"hello_world": {"hello": "world"}}) == { + "hello_world[hello]": "world" + } + assert encode_query( + {"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"} + ) == { "hello_world[hello][world]": "today", "hello_world[test]": "this", "hi": "there", diff --git a/seed/python-sdk/oauth-client-credentials-nested-root/tests/utils/test_serialization.py b/seed/python-sdk/oauth-client-credentials-nested-root/tests/utils/test_serialization.py index 58b1ed66e6d..5ca956916dd 100644 --- a/seed/python-sdk/oauth-client-credentials-nested-root/tests/utils/test_serialization.py +++ b/seed/python-sdk/oauth-client-credentials-nested-root/tests/utils/test_serialization.py @@ -1,10 +1,12 @@ # This file was auto-generated by Fern from our API Definition. -from typing import Any, List +from typing import List, Any -from seed.core.serialization import convert_and_respect_annotation_metadata +from seed.core.serialization import ( + convert_and_respect_annotation_metadata, +) +from .assets.models import ShapeParams, ObjectWithOptionalFieldParams -from .assets.models import ObjectWithOptionalFieldParams, ShapeParams UNION_TEST: ShapeParams = {"radius_measurement": 1.0, "shape_type": "circle", "id": "1"} UNION_TEST_CONVERTED = {"shapeType": "circle", "radiusMeasurement": 1.0, "id": "1"} @@ -18,20 +20,54 @@ def test_convert_and_respect_annotation_metadata() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) - assert converted == {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"} + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) + assert converted == { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + } def test_convert_and_respect_annotation_metadata_in_list() -> None: data: List[ObjectWithOptionalFieldParams] = [ - {"string": "string", "long_": 12345, "bool_": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long_": 67890, "list_": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long_": 12345, + "bool_": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long_": 67890, + "list_": [], + "literal": "lit_one", + "any": "any", + }, ] - converted = convert_and_respect_annotation_metadata(object_=data, annotation=List[ObjectWithOptionalFieldParams]) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=List[ObjectWithOptionalFieldParams] + ) assert converted == [ - {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long": 67890, "list": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long": 67890, + "list": [], + "literal": "lit_one", + "any": "any", + }, ] @@ -43,7 +79,9 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) assert converted == { "string": "string", @@ -55,12 +93,16 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: def test_convert_and_respect_annotation_metadata_in_union() -> None: - converted = convert_and_respect_annotation_metadata(object_=UNION_TEST, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=UNION_TEST, annotation=ShapeParams + ) assert converted == UNION_TEST_CONVERTED def test_convert_and_respect_annotation_metadata_with_empty_object() -> None: data: Any = {} - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ShapeParams + ) assert converted == data diff --git a/seed/python-sdk/oauth-client-credentials/pyproject.toml b/seed/python-sdk/oauth-client-credentials/pyproject.toml index d2b68a5ccfd..9d6605c1be0 100644 --- a/seed/python-sdk/oauth-client-credentials/pyproject.toml +++ b/seed/python-sdk/oauth-client-credentials/pyproject.toml @@ -43,6 +43,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/python-sdk/oauth-client-credentials/src/seed/__init__.py b/seed/python-sdk/oauth-client-credentials/src/seed/__init__.py index fd6712714a8..0904da20e2c 100644 --- a/seed/python-sdk/oauth-client-credentials/src/seed/__init__.py +++ b/seed/python-sdk/oauth-client-credentials/src/seed/__init__.py @@ -5,4 +5,10 @@ from .client import AsyncSeedOauthClientCredentials, SeedOauthClientCredentials from .version import __version__ -__all__ = ["AsyncSeedOauthClientCredentials", "SeedOauthClientCredentials", "TokenResponse", "__version__", "auth"] +__all__ = [ + "AsyncSeedOauthClientCredentials", + "SeedOauthClientCredentials", + "TokenResponse", + "__version__", + "auth", +] diff --git a/seed/python-sdk/oauth-client-credentials/src/seed/auth/client.py b/seed/python-sdk/oauth-client-credentials/src/seed/auth/client.py index 20486f7c838..f569b7e045d 100644 --- a/seed/python-sdk/oauth-client-credentials/src/seed/auth/client.py +++ b/seed/python-sdk/oauth-client-credentials/src/seed/auth/client.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. import typing -from json.decoder import JSONDecodeError - -from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.pydantic_utilities import parse_obj_as +from ..core.client_wrapper import SyncClientWrapper from ..core.request_options import RequestOptions from .types.token_response import TokenResponse +from ..core.pydantic_utilities import parse_obj_as +from json.decoder import JSONDecodeError +from ..core.api_error import ApiError +from ..core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -23,7 +23,7 @@ def get_token_with_client_credentials( client_id: str, client_secret: str, scope: typing.Optional[str] = OMIT, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> TokenResponse: """ Parameters @@ -71,7 +71,10 @@ def get_token_with_client_credentials( ) try: if 200 <= _response.status_code < 300: - return typing.cast(TokenResponse, parse_obj_as(type_=TokenResponse, object_=_response.json())) # type: ignore + return typing.cast( + TokenResponse, + parse_obj_as(type_=TokenResponse, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -84,7 +87,7 @@ def refresh_token( client_secret: str, refresh_token: str, scope: typing.Optional[str] = OMIT, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> TokenResponse: """ Parameters @@ -136,7 +139,10 @@ def refresh_token( ) try: if 200 <= _response.status_code < 300: - return typing.cast(TokenResponse, parse_obj_as(type_=TokenResponse, object_=_response.json())) # type: ignore + return typing.cast( + TokenResponse, + parse_obj_as(type_=TokenResponse, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -153,7 +159,7 @@ async def get_token_with_client_credentials( client_id: str, client_secret: str, scope: typing.Optional[str] = OMIT, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> TokenResponse: """ Parameters @@ -209,7 +215,10 @@ async def main() -> None: ) try: if 200 <= _response.status_code < 300: - return typing.cast(TokenResponse, parse_obj_as(type_=TokenResponse, object_=_response.json())) # type: ignore + return typing.cast( + TokenResponse, + parse_obj_as(type_=TokenResponse, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -222,7 +231,7 @@ async def refresh_token( client_secret: str, refresh_token: str, scope: typing.Optional[str] = OMIT, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> TokenResponse: """ Parameters @@ -282,7 +291,10 @@ async def main() -> None: ) try: if 200 <= _response.status_code < 300: - return typing.cast(TokenResponse, parse_obj_as(type_=TokenResponse, object_=_response.json())) # type: ignore + return typing.cast( + TokenResponse, + parse_obj_as(type_=TokenResponse, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/oauth-client-credentials/src/seed/auth/types/token_response.py b/seed/python-sdk/oauth-client-credentials/src/seed/auth/types/token_response.py index 44ac83f1a2b..3277d3fd341 100644 --- a/seed/python-sdk/oauth-client-credentials/src/seed/auth/types/token_response.py +++ b/seed/python-sdk/oauth-client-credentials/src/seed/auth/types/token_response.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel import typing - +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class TokenResponse(UniversalBaseModel): """ @@ -17,7 +16,9 @@ class TokenResponse(UniversalBaseModel): refresh_token: typing.Optional[str] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/oauth-client-credentials/src/seed/client.py b/seed/python-sdk/oauth-client-credentials/src/seed/client.py index 1d7db30adbb..afea747d55d 100644 --- a/seed/python-sdk/oauth-client-credentials/src/seed/client.py +++ b/seed/python-sdk/oauth-client-credentials/src/seed/client.py @@ -1,12 +1,12 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .auth.client import AsyncAuthClient, AuthClient -from .core.client_wrapper import AsyncClientWrapper, SyncClientWrapper from .core.oauth_token_provider import OAuthTokenProvider +from .core.client_wrapper import SyncClientWrapper +from .auth.client import AuthClient +from .core.client_wrapper import AsyncClientWrapper +from .auth.client import AsyncAuthClient class SeedOauthClientCredentials: @@ -50,15 +50,19 @@ def __init__( _token_getter_override: typing.Optional[typing.Callable[[], str]] = None, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.Client] = None + httpx_client: typing.Optional[httpx.Client] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) oauth_token_provider = OAuthTokenProvider( client_id=client_id, client_secret=client_secret, client_wrapper=SyncClientWrapper( base_url=base_url, - httpx_client=httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + httpx_client=httpx.Client( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.Client(timeout=_defaulted_timeout), timeout=_defaulted_timeout, @@ -66,10 +70,14 @@ def __init__( ) self._client_wrapper = SyncClientWrapper( base_url=base_url, - token=_token_getter_override if _token_getter_override is not None else oauth_token_provider.get_token, + token=_token_getter_override + if _token_getter_override is not None + else oauth_token_provider.get_token, httpx_client=httpx_client if httpx_client is not None - else httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.Client( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.Client(timeout=_defaulted_timeout), timeout=_defaulted_timeout, @@ -118,15 +126,19 @@ def __init__( _token_getter_override: typing.Optional[typing.Callable[[], str]] = None, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.AsyncClient] = None + httpx_client: typing.Optional[httpx.AsyncClient] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) oauth_token_provider = OAuthTokenProvider( client_id=client_id, client_secret=client_secret, client_wrapper=SyncClientWrapper( base_url=base_url, - httpx_client=httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + httpx_client=httpx.Client( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.Client(timeout=_defaulted_timeout), timeout=_defaulted_timeout, @@ -134,10 +146,14 @@ def __init__( ) self._client_wrapper = AsyncClientWrapper( base_url=base_url, - token=_token_getter_override if _token_getter_override is not None else oauth_token_provider.get_token, + token=_token_getter_override + if _token_getter_override is not None + else oauth_token_provider.get_token, httpx_client=httpx_client if httpx_client is not None - else httpx.AsyncClient(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.AsyncClient( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.AsyncClient(timeout=_defaulted_timeout), timeout=_defaulted_timeout, diff --git a/seed/python-sdk/oauth-client-credentials/src/seed/core/api_error.py b/seed/python-sdk/oauth-client-credentials/src/seed/core/api_error.py index 2e9fc5431cd..da734b58068 100644 --- a/seed/python-sdk/oauth-client-credentials/src/seed/core/api_error.py +++ b/seed/python-sdk/oauth-client-credentials/src/seed/core/api_error.py @@ -7,7 +7,9 @@ class ApiError(Exception): status_code: typing.Optional[int] body: typing.Any - def __init__(self, *, status_code: typing.Optional[int] = None, body: typing.Any = None): + def __init__( + self, *, status_code: typing.Optional[int] = None, body: typing.Any = None + ): self.status_code = status_code self.body = body diff --git a/seed/python-sdk/oauth-client-credentials/src/seed/core/client_wrapper.py b/seed/python-sdk/oauth-client-credentials/src/seed/core/client_wrapper.py index 611565d5835..58d770f7362 100644 --- a/seed/python-sdk/oauth-client-credentials/src/seed/core/client_wrapper.py +++ b/seed/python-sdk/oauth-client-credentials/src/seed/core/client_wrapper.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .http_client import AsyncHttpClient, HttpClient +from .http_client import HttpClient +from .http_client import AsyncHttpClient class BaseClientWrapper: diff --git a/seed/python-sdk/oauth-client-credentials/src/seed/core/datetime_utils.py b/seed/python-sdk/oauth-client-credentials/src/seed/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/python-sdk/oauth-client-credentials/src/seed/core/datetime_utils.py +++ b/seed/python-sdk/oauth-client-credentials/src/seed/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/python-sdk/oauth-client-credentials/src/seed/core/file.py b/seed/python-sdk/oauth-client-credentials/src/seed/core/file.py index cb0d40bbbf3..6e0f92bfcb1 100644 --- a/seed/python-sdk/oauth-client-credentials/src/seed/core/file.py +++ b/seed/python-sdk/oauth-client-credentials/src/seed/core/file.py @@ -13,12 +13,17 @@ # (filename, file (or bytes), content_type) typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str]], # (filename, file (or bytes), content_type, headers) - typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str], typing.Mapping[str, str]], + typing.Tuple[ + typing.Optional[str], + FileContent, + typing.Optional[str], + typing.Mapping[str, str], + ], ] def convert_file_dict_to_httpx_tuples( - d: typing.Dict[str, typing.Union[File, typing.List[File]]] + d: typing.Dict[str, typing.Union[File, typing.List[File]]], ) -> typing.List[typing.Tuple[str, File]]: """ The format we use is a list of tuples, where the first element is the diff --git a/seed/python-sdk/oauth-client-credentials/src/seed/core/http_client.py b/seed/python-sdk/oauth-client-credentials/src/seed/core/http_client.py index 9333d8a7f15..091f71bc185 100644 --- a/seed/python-sdk/oauth-client-credentials/src/seed/core/http_client.py +++ b/seed/python-sdk/oauth-client-credentials/src/seed/core/http_client.py @@ -77,7 +77,9 @@ def _retry_timeout(response: httpx.Response, retries: int) -> float: return retry_after # Apply exponential backoff, capped at MAX_RETRY_DELAY_SECONDS. - retry_delay = min(INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS) + retry_delay = min( + INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS + ) # Add a randomness / jitter to the retry delay to avoid overwhelming the server with retries. timeout = retry_delay * (1 - 0.25 * random()) @@ -90,7 +92,8 @@ def _should_retry(response: httpx.Response) -> bool: def remove_omit_from_dict( - original: typing.Dict[str, typing.Optional[typing.Any]], omit: typing.Optional[typing.Any] + original: typing.Dict[str, typing.Optional[typing.Any]], + omit: typing.Optional[typing.Any], ) -> typing.Dict[str, typing.Any]: if omit is None: return original @@ -108,7 +111,8 @@ def maybe_filter_request_body( ) -> typing.Optional[typing.Any]: if data is None: return ( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else None ) @@ -118,7 +122,8 @@ def maybe_filter_request_body( data_content = { **(jsonable_encoder(remove_omit_from_dict(data, omit))), # type: ignore **( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else {} ), @@ -162,7 +167,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url def request( @@ -174,8 +181,12 @@ def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -184,11 +195,14 @@ def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) response = self.httpx_client.request( method=method, @@ -198,7 +212,11 @@ def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -209,7 +227,10 @@ def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -222,11 +243,15 @@ def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: time.sleep(_retry_timeout(response=response, retries=retries)) @@ -256,8 +281,12 @@ def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -266,11 +295,14 @@ def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) with self.httpx_client.stream( method=method, @@ -280,7 +312,11 @@ def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -291,7 +327,9 @@ def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -304,7 +342,9 @@ def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream @@ -327,7 +367,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url async def request( @@ -339,8 +381,12 @@ async def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -349,11 +395,14 @@ async def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) # Add the input to each of these and do None-safety checks response = await self.httpx_client.request( @@ -364,7 +413,11 @@ async def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -375,7 +428,10 @@ async def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -388,11 +444,15 @@ async def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: await asyncio.sleep(_retry_timeout(response=response, retries=retries)) @@ -421,8 +481,12 @@ async def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -431,11 +495,14 @@ async def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) async with self.httpx_client.stream( method=method, @@ -445,7 +512,11 @@ async def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -456,7 +527,9 @@ async def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -469,7 +542,9 @@ async def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream diff --git a/seed/python-sdk/oauth-client-credentials/src/seed/core/jsonable_encoder.py b/seed/python-sdk/oauth-client-credentials/src/seed/core/jsonable_encoder.py index d3fd328fd41..12a8b52fc22 100644 --- a/seed/python-sdk/oauth-client-credentials/src/seed/core/jsonable_encoder.py +++ b/seed/python-sdk/oauth-client-credentials/src/seed/core/jsonable_encoder.py @@ -19,13 +19,19 @@ import pydantic from .datetime_utils import serialize_datetime -from .pydantic_utilities import IS_PYDANTIC_V2, encode_by_type, to_jsonable_with_fallback +from .pydantic_utilities import ( + IS_PYDANTIC_V2, + encode_by_type, + to_jsonable_with_fallback, +) SetIntStr = Set[Union[int, str]] DictIntStrAny = Dict[Union[int, str], Any] -def jsonable_encoder(obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None) -> Any: +def jsonable_encoder( + obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None +) -> Any: custom_encoder = custom_encoder or {} if custom_encoder: if type(obj) in custom_encoder: diff --git a/seed/python-sdk/oauth-client-credentials/src/seed/core/oauth_token_provider.py b/seed/python-sdk/oauth-client-credentials/src/seed/core/oauth_token_provider.py index 1594d736901..cc68370f332 100644 --- a/seed/python-sdk/oauth-client-credentials/src/seed/core/oauth_token_provider.py +++ b/seed/python-sdk/oauth-client-credentials/src/seed/core/oauth_token_provider.py @@ -1,16 +1,17 @@ # This file was auto-generated by Fern from our API Definition. -import datetime as dt +from .client_wrapper import SyncClientWrapper import typing - +import datetime as dt from ..auth.client import AuthClient -from .client_wrapper import SyncClientWrapper class OAuthTokenProvider: BUFFER_IN_MINUTES = 2 - def __init__(self, *, client_id: str, client_secret: str, client_wrapper: SyncClientWrapper): + def __init__( + self, *, client_id: str, client_secret: str, client_wrapper: SyncClientWrapper + ): self._client_id = client_id self._client_secret = client_secret self._access_token: typing.Optional[str] = None @@ -28,9 +29,14 @@ def _refresh(self) -> str: ) self._access_token = token_response.access_token self._expires_at = self._get_expires_at( - expires_in_seconds=token_response.expires_in, buffer_in_minutes=self.BUFFER_IN_MINUTES + expires_in_seconds=token_response.expires_in, + buffer_in_minutes=self.BUFFER_IN_MINUTES, ) return self._access_token def _get_expires_at(self, *, expires_in_seconds: int, buffer_in_minutes: int): - return dt.datetime.now() + dt.timedelta(seconds=expires_in_seconds) - dt.timedelta(minutes=buffer_in_minutes) + return ( + dt.datetime.now() + + dt.timedelta(seconds=expires_in_seconds) + - dt.timedelta(minutes=buffer_in_minutes) + ) diff --git a/seed/python-sdk/oauth-client-credentials/src/seed/core/pydantic_utilities.py b/seed/python-sdk/oauth-client-credentials/src/seed/core/pydantic_utilities.py index 170a563d6eb..c63935c32a2 100644 --- a/seed/python-sdk/oauth-client-credentials/src/seed/core/pydantic_utilities.py +++ b/seed/python-sdk/oauth-client-credentials/src/seed/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) # type: ignore # Pydantic v1 diff --git a/seed/python-sdk/oauth-client-credentials/src/seed/core/query_encoder.py b/seed/python-sdk/oauth-client-credentials/src/seed/core/query_encoder.py index 24076d72ee9..7cb98f52cd7 100644 --- a/seed/python-sdk/oauth-client-credentials/src/seed/core/query_encoder.py +++ b/seed/python-sdk/oauth-client-credentials/src/seed/core/query_encoder.py @@ -7,7 +7,9 @@ # Flattens dicts to be of the form {"key[subkey][subkey2]": value} where value is not a dict -def traverse_query_dict(dict_flat: Dict[str, Any], key_prefix: Optional[str] = None) -> Dict[str, Any]: +def traverse_query_dict( + dict_flat: Dict[str, Any], key_prefix: Optional[str] = None +) -> Dict[str, Any]: result = {} for k, v in dict_flat.items(): key = f"{key_prefix}[{k}]" if key_prefix is not None else k @@ -30,4 +32,8 @@ def single_query_encoder(query_key: str, query_value: Any) -> Dict[str, Any]: def encode_query(query: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: - return dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) if query is not None else None + return ( + dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) + if query is not None + else None + ) diff --git a/seed/python-sdk/oauth-client-credentials/src/seed/core/serialization.py b/seed/python-sdk/oauth-client-credentials/src/seed/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/python-sdk/oauth-client-credentials/src/seed/core/serialization.py +++ b/seed/python-sdk/oauth-client-credentials/src/seed/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/python-sdk/oauth-client-credentials/src/seed/version.py b/seed/python-sdk/oauth-client-credentials/src/seed/version.py index c2ab9374758..468e83737f8 100644 --- a/seed/python-sdk/oauth-client-credentials/src/seed/version.py +++ b/seed/python-sdk/oauth-client-credentials/src/seed/version.py @@ -1,4 +1,3 @@ - from importlib import metadata __version__ = metadata.version("fern_oauth-client-credentials") diff --git a/seed/python-sdk/oauth-client-credentials/tests/conftest.py b/seed/python-sdk/oauth-client-credentials/tests/conftest.py index 93bff0658ab..1168b370983 100644 --- a/seed/python-sdk/oauth-client-credentials/tests/conftest.py +++ b/seed/python-sdk/oauth-client-credentials/tests/conftest.py @@ -1,9 +1,9 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedOauthClientCredentials import os - import pytest -from seed import AsyncSeedOauthClientCredentials, SeedOauthClientCredentials +from seed import AsyncSeedOauthClientCredentials @pytest.fixture diff --git a/seed/python-sdk/oauth-client-credentials/tests/custom/test_client.py b/seed/python-sdk/oauth-client-credentials/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/python-sdk/oauth-client-credentials/tests/custom/test_client.py +++ b/seed/python-sdk/oauth-client-credentials/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/python-sdk/oauth-client-credentials/tests/test_auth.py b/seed/python-sdk/oauth-client-credentials/tests/test_auth.py index fe88a55033a..b738967458c 100644 --- a/seed/python-sdk/oauth-client-credentials/tests/test_auth.py +++ b/seed/python-sdk/oauth-client-credentials/tests/test_auth.py @@ -1,18 +1,27 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedOauthClientCredentials +from seed import AsyncSeedOauthClientCredentials import typing - -from seed import AsyncSeedOauthClientCredentials, SeedOauthClientCredentials - from .utilities import validate_response async def test_get_token_with_client_credentials( client: SeedOauthClientCredentials, async_client: AsyncSeedOauthClientCredentials ) -> None: - expected_response: typing.Any = {"access_token": "string", "expires_in": 1, "refresh_token": "string"} - expected_types: typing.Any = {"access_token": None, "expires_in": "integer", "refresh_token": None} - response = client.auth.get_token_with_client_credentials(client_id="string", client_secret="string", scope="string") + expected_response: typing.Any = { + "access_token": "string", + "expires_in": 1, + "refresh_token": "string", + } + expected_types: typing.Any = { + "access_token": None, + "expires_in": "integer", + "refresh_token": None, + } + response = client.auth.get_token_with_client_credentials( + client_id="string", client_secret="string", scope="string" + ) validate_response(response, expected_response, expected_types) async_response = await async_client.auth.get_token_with_client_credentials( @@ -21,15 +30,31 @@ async def test_get_token_with_client_credentials( validate_response(async_response, expected_response, expected_types) -async def test_refresh_token(client: SeedOauthClientCredentials, async_client: AsyncSeedOauthClientCredentials) -> None: - expected_response: typing.Any = {"access_token": "string", "expires_in": 1, "refresh_token": "string"} - expected_types: typing.Any = {"access_token": None, "expires_in": "integer", "refresh_token": None} +async def test_refresh_token( + client: SeedOauthClientCredentials, async_client: AsyncSeedOauthClientCredentials +) -> None: + expected_response: typing.Any = { + "access_token": "string", + "expires_in": 1, + "refresh_token": "string", + } + expected_types: typing.Any = { + "access_token": None, + "expires_in": "integer", + "refresh_token": None, + } response = client.auth.refresh_token( - client_id="string", client_secret="string", refresh_token="string", scope="string" + client_id="string", + client_secret="string", + refresh_token="string", + scope="string", ) validate_response(response, expected_response, expected_types) async_response = await async_client.auth.refresh_token( - client_id="string", client_secret="string", refresh_token="string", scope="string" + client_id="string", + client_secret="string", + refresh_token="string", + scope="string", ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/oauth-client-credentials/tests/utilities.py b/seed/python-sdk/oauth-client-credentials/tests/utilities.py index 13da208eb3a..e8f4472564c 100644 --- a/seed/python-sdk/oauth-client-credentials/tests/utilities.py +++ b/seed/python-sdk/oauth-client-credentials/tests/utilities.py @@ -3,11 +3,14 @@ import typing import uuid -import pydantic from dateutil import parser +import pydantic + -def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> typing.Any: +def cast_field( + json_expectation: typing.Any, type_expectation: typing.Any +) -> typing.Any: # Cast these specific types which come through as string and expect our # models to cast to the correct type. if type_expectation == "uuid": @@ -25,7 +28,9 @@ def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> ty return json_expectation -def validate_field(response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any) -> None: +def validate_field( + response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectation == "no_validate": return @@ -44,7 +49,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(entry_expectation, dict): is_container_of_complex_type = True validate_response( - response=response[idx], json_expectation=ex, type_expectations=entry_expectation + response=response[idx], + json_expectation=ex, + type_expectations=entry_expectation, ) else: cast_json_expectation.append(cast_field(ex, entry_expectation)) @@ -56,7 +63,10 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # if any of the values of the set have a type_expectation of a dict, we're assuming it's a pydantic # model and keeping it a list. if container_expectation != "set" or not any( - map(lambda value: isinstance(value, dict), list(contents_expectation.values())) + map( + lambda value: isinstance(value, dict), + list(contents_expectation.values()), + ) ): json_expectation = cast_field(json_expectation, container_expectation) elif isinstance(type_expectation, tuple): @@ -65,9 +75,15 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(contents_expectation, dict): json_expectation = { cast_field( - key, contents_expectation.get(idx)[0] if contents_expectation.get(idx) is not None else None # type: ignore + key, + contents_expectation.get(idx)[0] + if contents_expectation.get(idx) is not None + else None, # type: ignore ): cast_field( - value, contents_expectation.get(idx)[1] if contents_expectation.get(idx) is not None else None # type: ignore + value, + contents_expectation.get(idx)[1] + if contents_expectation.get(idx) is not None + else None, # type: ignore ) for idx, (key, value) in enumerate(json_expectation.items()) } @@ -86,7 +102,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # Arg type_expectations is a deeply nested structure that matches the response, but with the values replaced with the expected types -def validate_response(response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any) -> None: +def validate_response( + response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectations == "no_validate": return @@ -96,11 +114,17 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e and not isinstance(response, dict) and not issubclass(type(response), pydantic.BaseModel) ): - validate_field(response=response, json_expectation=json_expectation, type_expectation=type_expectations) + validate_field( + response=response, + json_expectation=json_expectation, + type_expectation=type_expectations, + ) return if isinstance(response, list): - assert len(response) == len(json_expectation), "Length mismatch, expected: {0}, Actual: {1}".format( + assert len(response) == len( + json_expectation + ), "Length mismatch, expected: {0}, Actual: {1}".format( len(response), len(json_expectation) ) content_expectation = type_expectations @@ -108,7 +132,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e content_expectation = type_expectations[1] for idx, item in enumerate(response): validate_response( - response=item, json_expectation=json_expectation[idx], type_expectations=content_expectation[idx] + response=item, + json_expectation=json_expectation[idx], + type_expectations=content_expectation[idx], ) else: response_json = response @@ -116,7 +142,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e response_json = response.dict(by_alias=True) for key, value in json_expectation.items(): - assert key in response_json, "Field {0} not found within the response object: {1}".format( + assert ( + key in response_json + ), "Field {0} not found within the response object: {1}".format( key, response_json ) @@ -128,11 +156,19 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e # Otherwise, we're just validating a single field that's a pydantic model. if isinstance(value, dict) and not isinstance(type_expectation, tuple): validate_response( - response=response_json[key], json_expectation=value, type_expectations=type_expectation + response=response_json[key], + json_expectation=value, + type_expectations=type_expectation, ) else: - validate_field(response=response_json[key], json_expectation=value, type_expectation=type_expectation) + validate_field( + response=response_json[key], + json_expectation=value, + type_expectation=type_expectation, + ) # Ensure there are no additional fields here either del response_json[key] - assert len(response_json) == 0, "Additional fields found, expected None: {0}".format(response_json) + assert ( + len(response_json) == 0 + ), "Additional fields found, expected None: {0}".format(response_json) diff --git a/seed/python-sdk/oauth-client-credentials/tests/utils/assets/models/__init__.py b/seed/python-sdk/oauth-client-credentials/tests/utils/assets/models/__init__.py index 2cf01263529..3a1c852e71e 100644 --- a/seed/python-sdk/oauth-client-credentials/tests/utils/assets/models/__init__.py +++ b/seed/python-sdk/oauth-client-credentials/tests/utils/assets/models/__init__.py @@ -5,7 +5,7 @@ from .circle import CircleParams from .object_with_defaults import ObjectWithDefaultsParams from .object_with_optional_field import ObjectWithOptionalFieldParams -from .shape import Shape_CircleParams, Shape_SquareParams, ShapeParams +from .shape import ShapeParams, Shape_CircleParams, Shape_SquareParams from .square import SquareParams from .undiscriminated_shape import UndiscriminatedShapeParams diff --git a/seed/python-sdk/oauth-client-credentials/tests/utils/assets/models/circle.py b/seed/python-sdk/oauth-client-credentials/tests/utils/assets/models/circle.py index af7a1bf8a8e..253f12d38b3 100644 --- a/seed/python-sdk/oauth-client-credentials/tests/utils/assets/models/circle.py +++ b/seed/python-sdk/oauth-client-credentials/tests/utils/assets/models/circle.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class CircleParams(typing_extensions.TypedDict): - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] diff --git a/seed/python-sdk/oauth-client-credentials/tests/utils/assets/models/object_with_optional_field.py b/seed/python-sdk/oauth-client-credentials/tests/utils/assets/models/object_with_optional_field.py index 3ad93d5f305..ebe7dc80547 100644 --- a/seed/python-sdk/oauth-client-credentials/tests/utils/assets/models/object_with_optional_field.py +++ b/seed/python-sdk/oauth-client-credentials/tests/utils/assets/models/object_with_optional_field.py @@ -7,8 +7,8 @@ import uuid import typing_extensions -from seed.core.serialization import FieldMetadata +from seed.core.serialization import FieldMetadata from .color import Color from .shape import ShapeParams from .undiscriminated_shape import UndiscriminatedShapeParams @@ -18,16 +18,30 @@ class ObjectWithOptionalFieldParams(typing_extensions.TypedDict): literal: typing.Literal["lit_one"] string: typing_extensions.NotRequired[str] integer: typing_extensions.NotRequired[int] - long_: typing_extensions.NotRequired[typing_extensions.Annotated[int, FieldMetadata(alias="long")]] + long_: typing_extensions.NotRequired[ + typing_extensions.Annotated[int, FieldMetadata(alias="long")] + ] double: typing_extensions.NotRequired[float] - bool_: typing_extensions.NotRequired[typing_extensions.Annotated[bool, FieldMetadata(alias="bool")]] + bool_: typing_extensions.NotRequired[ + typing_extensions.Annotated[bool, FieldMetadata(alias="bool")] + ] datetime: typing_extensions.NotRequired[dt.datetime] date: typing_extensions.NotRequired[dt.date] - uuid_: typing_extensions.NotRequired[typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")]] - base_64: typing_extensions.NotRequired[typing_extensions.Annotated[str, FieldMetadata(alias="base64")]] - list_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")]] - set_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")]] - map_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")]] + uuid_: typing_extensions.NotRequired[ + typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")] + ] + base_64: typing_extensions.NotRequired[ + typing_extensions.Annotated[str, FieldMetadata(alias="base64")] + ] + list_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")] + ] + set_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")] + ] + map_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")] + ] enum: typing_extensions.NotRequired[Color] union: typing_extensions.NotRequired[ShapeParams] second_union: typing_extensions.NotRequired[ShapeParams] diff --git a/seed/python-sdk/oauth-client-credentials/tests/utils/assets/models/shape.py b/seed/python-sdk/oauth-client-credentials/tests/utils/assets/models/shape.py index 2c33c877951..816ffc51bdc 100644 --- a/seed/python-sdk/oauth-client-credentials/tests/utils/assets/models/shape.py +++ b/seed/python-sdk/oauth-client-credentials/tests/utils/assets/models/shape.py @@ -7,6 +7,7 @@ import typing import typing_extensions + from seed.core.serialization import FieldMetadata @@ -15,13 +16,21 @@ class Base(typing_extensions.TypedDict): class Shape_CircleParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["circle"], FieldMetadata(alias="shapeType")] - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["circle"], FieldMetadata(alias="shapeType") + ] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] class Shape_SquareParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["square"], FieldMetadata(alias="shapeType")] - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["square"], FieldMetadata(alias="shapeType") + ] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] ShapeParams = typing.Union[Shape_CircleParams, Shape_SquareParams] diff --git a/seed/python-sdk/oauth-client-credentials/tests/utils/assets/models/square.py b/seed/python-sdk/oauth-client-credentials/tests/utils/assets/models/square.py index b9b7dd319bc..bcf08a723c5 100644 --- a/seed/python-sdk/oauth-client-credentials/tests/utils/assets/models/square.py +++ b/seed/python-sdk/oauth-client-credentials/tests/utils/assets/models/square.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class SquareParams(typing_extensions.TypedDict): - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] diff --git a/seed/python-sdk/oauth-client-credentials/tests/utils/test_http_client.py b/seed/python-sdk/oauth-client-credentials/tests/utils/test_http_client.py index edd11ca7afb..f5a874a75f3 100644 --- a/seed/python-sdk/oauth-client-credentials/tests/utils/test_http_client.py +++ b/seed/python-sdk/oauth-client-credentials/tests/utils/test_http_client.py @@ -9,12 +9,17 @@ def get_request_options() -> RequestOptions: def test_get_json_request_body() -> None: - json_body, data_body = get_request_body(json={"hello": "world"}, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json={"hello": "world"}, data=None, request_options=None, omit=None + ) assert json_body == {"hello": "world"} assert data_body is None json_body_extras, data_body_extras = get_request_body( - json={"goodbye": "world"}, data=None, request_options=get_request_options(), omit=None + json={"goodbye": "world"}, + data=None, + request_options=get_request_options(), + omit=None, ) assert json_body_extras == {"goodbye": "world", "see you": "later"} @@ -22,12 +27,17 @@ def test_get_json_request_body() -> None: def test_get_files_request_body() -> None: - json_body, data_body = get_request_body(json=None, data={"hello": "world"}, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data={"hello": "world"}, request_options=None, omit=None + ) assert data_body == {"hello": "world"} assert json_body is None json_body_extras, data_body_extras = get_request_body( - json=None, data={"goodbye": "world"}, request_options=get_request_options(), omit=None + json=None, + data={"goodbye": "world"}, + request_options=get_request_options(), + omit=None, ) assert data_body_extras == {"goodbye": "world", "see you": "later"} @@ -35,7 +45,9 @@ def test_get_files_request_body() -> None: def test_get_none_request_body() -> None: - json_body, data_body = get_request_body(json=None, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data=None, request_options=None, omit=None + ) assert data_body is None assert json_body is None diff --git a/seed/python-sdk/oauth-client-credentials/tests/utils/test_query_encoding.py b/seed/python-sdk/oauth-client-credentials/tests/utils/test_query_encoding.py index 247e1551b46..fbc8f402167 100644 --- a/seed/python-sdk/oauth-client-credentials/tests/utils/test_query_encoding.py +++ b/seed/python-sdk/oauth-client-credentials/tests/utils/test_query_encoding.py @@ -4,9 +4,15 @@ def test_query_encoding() -> None: - assert encode_query({"hello world": "hello world"}) == {"hello world": "hello world"} - assert encode_query({"hello_world": {"hello": "world"}}) == {"hello_world[hello]": "world"} - assert encode_query({"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"}) == { + assert encode_query({"hello world": "hello world"}) == { + "hello world": "hello world" + } + assert encode_query({"hello_world": {"hello": "world"}}) == { + "hello_world[hello]": "world" + } + assert encode_query( + {"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"} + ) == { "hello_world[hello][world]": "today", "hello_world[test]": "this", "hi": "there", diff --git a/seed/python-sdk/oauth-client-credentials/tests/utils/test_serialization.py b/seed/python-sdk/oauth-client-credentials/tests/utils/test_serialization.py index 58b1ed66e6d..5ca956916dd 100644 --- a/seed/python-sdk/oauth-client-credentials/tests/utils/test_serialization.py +++ b/seed/python-sdk/oauth-client-credentials/tests/utils/test_serialization.py @@ -1,10 +1,12 @@ # This file was auto-generated by Fern from our API Definition. -from typing import Any, List +from typing import List, Any -from seed.core.serialization import convert_and_respect_annotation_metadata +from seed.core.serialization import ( + convert_and_respect_annotation_metadata, +) +from .assets.models import ShapeParams, ObjectWithOptionalFieldParams -from .assets.models import ObjectWithOptionalFieldParams, ShapeParams UNION_TEST: ShapeParams = {"radius_measurement": 1.0, "shape_type": "circle", "id": "1"} UNION_TEST_CONVERTED = {"shapeType": "circle", "radiusMeasurement": 1.0, "id": "1"} @@ -18,20 +20,54 @@ def test_convert_and_respect_annotation_metadata() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) - assert converted == {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"} + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) + assert converted == { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + } def test_convert_and_respect_annotation_metadata_in_list() -> None: data: List[ObjectWithOptionalFieldParams] = [ - {"string": "string", "long_": 12345, "bool_": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long_": 67890, "list_": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long_": 12345, + "bool_": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long_": 67890, + "list_": [], + "literal": "lit_one", + "any": "any", + }, ] - converted = convert_and_respect_annotation_metadata(object_=data, annotation=List[ObjectWithOptionalFieldParams]) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=List[ObjectWithOptionalFieldParams] + ) assert converted == [ - {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long": 67890, "list": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long": 67890, + "list": [], + "literal": "lit_one", + "any": "any", + }, ] @@ -43,7 +79,9 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) assert converted == { "string": "string", @@ -55,12 +93,16 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: def test_convert_and_respect_annotation_metadata_in_union() -> None: - converted = convert_and_respect_annotation_metadata(object_=UNION_TEST, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=UNION_TEST, annotation=ShapeParams + ) assert converted == UNION_TEST_CONVERTED def test_convert_and_respect_annotation_metadata_with_empty_object() -> None: data: Any = {} - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ShapeParams + ) assert converted == data diff --git a/seed/python-sdk/object/pyproject.toml b/seed/python-sdk/object/pyproject.toml index 8b348b1a974..84d3fd55f97 100644 --- a/seed/python-sdk/object/pyproject.toml +++ b/seed/python-sdk/object/pyproject.toml @@ -43,6 +43,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/python-sdk/object/src/seed/client.py b/seed/python-sdk/object/src/seed/client.py index a981f341556..b226d1e59a0 100644 --- a/seed/python-sdk/object/src/seed/client.py +++ b/seed/python-sdk/object/src/seed/client.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .core.client_wrapper import AsyncClientWrapper, SyncClientWrapper +from .core.client_wrapper import SyncClientWrapper +from .core.client_wrapper import AsyncClientWrapper class SeedObject: @@ -40,14 +39,18 @@ def __init__( base_url: str, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.Client] = None + httpx_client: typing.Optional[httpx.Client] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = SyncClientWrapper( base_url=base_url, httpx_client=httpx_client if httpx_client is not None - else httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.Client( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.Client(timeout=_defaulted_timeout), timeout=_defaulted_timeout, @@ -87,14 +90,18 @@ def __init__( base_url: str, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.AsyncClient] = None + httpx_client: typing.Optional[httpx.AsyncClient] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = AsyncClientWrapper( base_url=base_url, httpx_client=httpx_client if httpx_client is not None - else httpx.AsyncClient(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.AsyncClient( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.AsyncClient(timeout=_defaulted_timeout), timeout=_defaulted_timeout, diff --git a/seed/python-sdk/object/src/seed/core/api_error.py b/seed/python-sdk/object/src/seed/core/api_error.py index 2e9fc5431cd..da734b58068 100644 --- a/seed/python-sdk/object/src/seed/core/api_error.py +++ b/seed/python-sdk/object/src/seed/core/api_error.py @@ -7,7 +7,9 @@ class ApiError(Exception): status_code: typing.Optional[int] body: typing.Any - def __init__(self, *, status_code: typing.Optional[int] = None, body: typing.Any = None): + def __init__( + self, *, status_code: typing.Optional[int] = None, body: typing.Any = None + ): self.status_code = status_code self.body = body diff --git a/seed/python-sdk/object/src/seed/core/client_wrapper.py b/seed/python-sdk/object/src/seed/core/client_wrapper.py index 6f333d1a597..f5e767e9301 100644 --- a/seed/python-sdk/object/src/seed/core/client_wrapper.py +++ b/seed/python-sdk/object/src/seed/core/client_wrapper.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .http_client import AsyncHttpClient, HttpClient +from .http_client import HttpClient +from .http_client import AsyncHttpClient class BaseClientWrapper: @@ -28,7 +27,13 @@ def get_timeout(self) -> typing.Optional[float]: class SyncClientWrapper(BaseClientWrapper): - def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, httpx_client: httpx.Client): + def __init__( + self, + *, + base_url: str, + timeout: typing.Optional[float] = None, + httpx_client: httpx.Client, + ): super().__init__(base_url=base_url, timeout=timeout) self.httpx_client = HttpClient( httpx_client=httpx_client, @@ -39,7 +44,13 @@ def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, htt class AsyncClientWrapper(BaseClientWrapper): - def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, httpx_client: httpx.AsyncClient): + def __init__( + self, + *, + base_url: str, + timeout: typing.Optional[float] = None, + httpx_client: httpx.AsyncClient, + ): super().__init__(base_url=base_url, timeout=timeout) self.httpx_client = AsyncHttpClient( httpx_client=httpx_client, diff --git a/seed/python-sdk/object/src/seed/core/datetime_utils.py b/seed/python-sdk/object/src/seed/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/python-sdk/object/src/seed/core/datetime_utils.py +++ b/seed/python-sdk/object/src/seed/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/python-sdk/object/src/seed/core/file.py b/seed/python-sdk/object/src/seed/core/file.py index cb0d40bbbf3..6e0f92bfcb1 100644 --- a/seed/python-sdk/object/src/seed/core/file.py +++ b/seed/python-sdk/object/src/seed/core/file.py @@ -13,12 +13,17 @@ # (filename, file (or bytes), content_type) typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str]], # (filename, file (or bytes), content_type, headers) - typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str], typing.Mapping[str, str]], + typing.Tuple[ + typing.Optional[str], + FileContent, + typing.Optional[str], + typing.Mapping[str, str], + ], ] def convert_file_dict_to_httpx_tuples( - d: typing.Dict[str, typing.Union[File, typing.List[File]]] + d: typing.Dict[str, typing.Union[File, typing.List[File]]], ) -> typing.List[typing.Tuple[str, File]]: """ The format we use is a list of tuples, where the first element is the diff --git a/seed/python-sdk/object/src/seed/core/http_client.py b/seed/python-sdk/object/src/seed/core/http_client.py index 9333d8a7f15..091f71bc185 100644 --- a/seed/python-sdk/object/src/seed/core/http_client.py +++ b/seed/python-sdk/object/src/seed/core/http_client.py @@ -77,7 +77,9 @@ def _retry_timeout(response: httpx.Response, retries: int) -> float: return retry_after # Apply exponential backoff, capped at MAX_RETRY_DELAY_SECONDS. - retry_delay = min(INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS) + retry_delay = min( + INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS + ) # Add a randomness / jitter to the retry delay to avoid overwhelming the server with retries. timeout = retry_delay * (1 - 0.25 * random()) @@ -90,7 +92,8 @@ def _should_retry(response: httpx.Response) -> bool: def remove_omit_from_dict( - original: typing.Dict[str, typing.Optional[typing.Any]], omit: typing.Optional[typing.Any] + original: typing.Dict[str, typing.Optional[typing.Any]], + omit: typing.Optional[typing.Any], ) -> typing.Dict[str, typing.Any]: if omit is None: return original @@ -108,7 +111,8 @@ def maybe_filter_request_body( ) -> typing.Optional[typing.Any]: if data is None: return ( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else None ) @@ -118,7 +122,8 @@ def maybe_filter_request_body( data_content = { **(jsonable_encoder(remove_omit_from_dict(data, omit))), # type: ignore **( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else {} ), @@ -162,7 +167,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url def request( @@ -174,8 +181,12 @@ def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -184,11 +195,14 @@ def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) response = self.httpx_client.request( method=method, @@ -198,7 +212,11 @@ def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -209,7 +227,10 @@ def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -222,11 +243,15 @@ def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: time.sleep(_retry_timeout(response=response, retries=retries)) @@ -256,8 +281,12 @@ def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -266,11 +295,14 @@ def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) with self.httpx_client.stream( method=method, @@ -280,7 +312,11 @@ def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -291,7 +327,9 @@ def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -304,7 +342,9 @@ def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream @@ -327,7 +367,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url async def request( @@ -339,8 +381,12 @@ async def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -349,11 +395,14 @@ async def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) # Add the input to each of these and do None-safety checks response = await self.httpx_client.request( @@ -364,7 +413,11 @@ async def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -375,7 +428,10 @@ async def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -388,11 +444,15 @@ async def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: await asyncio.sleep(_retry_timeout(response=response, retries=retries)) @@ -421,8 +481,12 @@ async def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -431,11 +495,14 @@ async def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) async with self.httpx_client.stream( method=method, @@ -445,7 +512,11 @@ async def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -456,7 +527,9 @@ async def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -469,7 +542,9 @@ async def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream diff --git a/seed/python-sdk/object/src/seed/core/jsonable_encoder.py b/seed/python-sdk/object/src/seed/core/jsonable_encoder.py index d3fd328fd41..12a8b52fc22 100644 --- a/seed/python-sdk/object/src/seed/core/jsonable_encoder.py +++ b/seed/python-sdk/object/src/seed/core/jsonable_encoder.py @@ -19,13 +19,19 @@ import pydantic from .datetime_utils import serialize_datetime -from .pydantic_utilities import IS_PYDANTIC_V2, encode_by_type, to_jsonable_with_fallback +from .pydantic_utilities import ( + IS_PYDANTIC_V2, + encode_by_type, + to_jsonable_with_fallback, +) SetIntStr = Set[Union[int, str]] DictIntStrAny = Dict[Union[int, str], Any] -def jsonable_encoder(obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None) -> Any: +def jsonable_encoder( + obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None +) -> Any: custom_encoder = custom_encoder or {} if custom_encoder: if type(obj) in custom_encoder: diff --git a/seed/python-sdk/object/src/seed/core/pydantic_utilities.py b/seed/python-sdk/object/src/seed/core/pydantic_utilities.py index 170a563d6eb..c63935c32a2 100644 --- a/seed/python-sdk/object/src/seed/core/pydantic_utilities.py +++ b/seed/python-sdk/object/src/seed/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) # type: ignore # Pydantic v1 diff --git a/seed/python-sdk/object/src/seed/core/query_encoder.py b/seed/python-sdk/object/src/seed/core/query_encoder.py index 24076d72ee9..7cb98f52cd7 100644 --- a/seed/python-sdk/object/src/seed/core/query_encoder.py +++ b/seed/python-sdk/object/src/seed/core/query_encoder.py @@ -7,7 +7,9 @@ # Flattens dicts to be of the form {"key[subkey][subkey2]": value} where value is not a dict -def traverse_query_dict(dict_flat: Dict[str, Any], key_prefix: Optional[str] = None) -> Dict[str, Any]: +def traverse_query_dict( + dict_flat: Dict[str, Any], key_prefix: Optional[str] = None +) -> Dict[str, Any]: result = {} for k, v in dict_flat.items(): key = f"{key_prefix}[{k}]" if key_prefix is not None else k @@ -30,4 +32,8 @@ def single_query_encoder(query_key: str, query_value: Any) -> Dict[str, Any]: def encode_query(query: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: - return dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) if query is not None else None + return ( + dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) + if query is not None + else None + ) diff --git a/seed/python-sdk/object/src/seed/core/serialization.py b/seed/python-sdk/object/src/seed/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/python-sdk/object/src/seed/core/serialization.py +++ b/seed/python-sdk/object/src/seed/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/python-sdk/object/src/seed/types/name.py b/seed/python-sdk/object/src/seed/types/name.py index f695269f99d..6c193e1dfab 100644 --- a/seed/python-sdk/object/src/seed/types/name.py +++ b/seed/python-sdk/object/src/seed/types/name.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from ..core.pydantic_utilities import UniversalBaseModel +from ..core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class Name(UniversalBaseModel): """ @@ -23,7 +22,9 @@ class Name(UniversalBaseModel): value: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/object/src/seed/types/type.py b/seed/python-sdk/object/src/seed/types/type.py index 294ce64f748..d1ca9e0dbde 100644 --- a/seed/python-sdk/object/src/seed/types/type.py +++ b/seed/python-sdk/object/src/seed/types/type.py @@ -1,13 +1,12 @@ # This file was auto-generated by Fern from our API Definition. +from ..core.pydantic_utilities import UniversalBaseModel import datetime as dt -import typing import uuid - -import pydantic - -from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +import typing from .name import Name +from ..core.pydantic_utilities import IS_PYDANTIC_V2 +import pydantic class Type(UniversalBaseModel): @@ -88,7 +87,9 @@ class Type(UniversalBaseModel): twentythree: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/object/src/seed/version.py b/seed/python-sdk/object/src/seed/version.py index 2dcf8d1f3fc..39f708d3239 100644 --- a/seed/python-sdk/object/src/seed/version.py +++ b/seed/python-sdk/object/src/seed/version.py @@ -1,4 +1,3 @@ - from importlib import metadata __version__ = metadata.version("fern_object") diff --git a/seed/python-sdk/object/tests/conftest.py b/seed/python-sdk/object/tests/conftest.py index ad922ed765e..bd27e8b59c3 100644 --- a/seed/python-sdk/object/tests/conftest.py +++ b/seed/python-sdk/object/tests/conftest.py @@ -1,9 +1,9 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedObject import os - import pytest -from seed import AsyncSeedObject, SeedObject +from seed import AsyncSeedObject @pytest.fixture diff --git a/seed/python-sdk/object/tests/custom/test_client.py b/seed/python-sdk/object/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/python-sdk/object/tests/custom/test_client.py +++ b/seed/python-sdk/object/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/python-sdk/object/tests/utilities.py b/seed/python-sdk/object/tests/utilities.py index 13da208eb3a..e8f4472564c 100644 --- a/seed/python-sdk/object/tests/utilities.py +++ b/seed/python-sdk/object/tests/utilities.py @@ -3,11 +3,14 @@ import typing import uuid -import pydantic from dateutil import parser +import pydantic + -def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> typing.Any: +def cast_field( + json_expectation: typing.Any, type_expectation: typing.Any +) -> typing.Any: # Cast these specific types which come through as string and expect our # models to cast to the correct type. if type_expectation == "uuid": @@ -25,7 +28,9 @@ def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> ty return json_expectation -def validate_field(response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any) -> None: +def validate_field( + response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectation == "no_validate": return @@ -44,7 +49,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(entry_expectation, dict): is_container_of_complex_type = True validate_response( - response=response[idx], json_expectation=ex, type_expectations=entry_expectation + response=response[idx], + json_expectation=ex, + type_expectations=entry_expectation, ) else: cast_json_expectation.append(cast_field(ex, entry_expectation)) @@ -56,7 +63,10 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # if any of the values of the set have a type_expectation of a dict, we're assuming it's a pydantic # model and keeping it a list. if container_expectation != "set" or not any( - map(lambda value: isinstance(value, dict), list(contents_expectation.values())) + map( + lambda value: isinstance(value, dict), + list(contents_expectation.values()), + ) ): json_expectation = cast_field(json_expectation, container_expectation) elif isinstance(type_expectation, tuple): @@ -65,9 +75,15 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(contents_expectation, dict): json_expectation = { cast_field( - key, contents_expectation.get(idx)[0] if contents_expectation.get(idx) is not None else None # type: ignore + key, + contents_expectation.get(idx)[0] + if contents_expectation.get(idx) is not None + else None, # type: ignore ): cast_field( - value, contents_expectation.get(idx)[1] if contents_expectation.get(idx) is not None else None # type: ignore + value, + contents_expectation.get(idx)[1] + if contents_expectation.get(idx) is not None + else None, # type: ignore ) for idx, (key, value) in enumerate(json_expectation.items()) } @@ -86,7 +102,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # Arg type_expectations is a deeply nested structure that matches the response, but with the values replaced with the expected types -def validate_response(response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any) -> None: +def validate_response( + response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectations == "no_validate": return @@ -96,11 +114,17 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e and not isinstance(response, dict) and not issubclass(type(response), pydantic.BaseModel) ): - validate_field(response=response, json_expectation=json_expectation, type_expectation=type_expectations) + validate_field( + response=response, + json_expectation=json_expectation, + type_expectation=type_expectations, + ) return if isinstance(response, list): - assert len(response) == len(json_expectation), "Length mismatch, expected: {0}, Actual: {1}".format( + assert len(response) == len( + json_expectation + ), "Length mismatch, expected: {0}, Actual: {1}".format( len(response), len(json_expectation) ) content_expectation = type_expectations @@ -108,7 +132,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e content_expectation = type_expectations[1] for idx, item in enumerate(response): validate_response( - response=item, json_expectation=json_expectation[idx], type_expectations=content_expectation[idx] + response=item, + json_expectation=json_expectation[idx], + type_expectations=content_expectation[idx], ) else: response_json = response @@ -116,7 +142,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e response_json = response.dict(by_alias=True) for key, value in json_expectation.items(): - assert key in response_json, "Field {0} not found within the response object: {1}".format( + assert ( + key in response_json + ), "Field {0} not found within the response object: {1}".format( key, response_json ) @@ -128,11 +156,19 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e # Otherwise, we're just validating a single field that's a pydantic model. if isinstance(value, dict) and not isinstance(type_expectation, tuple): validate_response( - response=response_json[key], json_expectation=value, type_expectations=type_expectation + response=response_json[key], + json_expectation=value, + type_expectations=type_expectation, ) else: - validate_field(response=response_json[key], json_expectation=value, type_expectation=type_expectation) + validate_field( + response=response_json[key], + json_expectation=value, + type_expectation=type_expectation, + ) # Ensure there are no additional fields here either del response_json[key] - assert len(response_json) == 0, "Additional fields found, expected None: {0}".format(response_json) + assert ( + len(response_json) == 0 + ), "Additional fields found, expected None: {0}".format(response_json) diff --git a/seed/python-sdk/object/tests/utils/assets/models/__init__.py b/seed/python-sdk/object/tests/utils/assets/models/__init__.py index 2cf01263529..3a1c852e71e 100644 --- a/seed/python-sdk/object/tests/utils/assets/models/__init__.py +++ b/seed/python-sdk/object/tests/utils/assets/models/__init__.py @@ -5,7 +5,7 @@ from .circle import CircleParams from .object_with_defaults import ObjectWithDefaultsParams from .object_with_optional_field import ObjectWithOptionalFieldParams -from .shape import Shape_CircleParams, Shape_SquareParams, ShapeParams +from .shape import ShapeParams, Shape_CircleParams, Shape_SquareParams from .square import SquareParams from .undiscriminated_shape import UndiscriminatedShapeParams diff --git a/seed/python-sdk/object/tests/utils/assets/models/circle.py b/seed/python-sdk/object/tests/utils/assets/models/circle.py index af7a1bf8a8e..253f12d38b3 100644 --- a/seed/python-sdk/object/tests/utils/assets/models/circle.py +++ b/seed/python-sdk/object/tests/utils/assets/models/circle.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class CircleParams(typing_extensions.TypedDict): - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] diff --git a/seed/python-sdk/object/tests/utils/assets/models/object_with_optional_field.py b/seed/python-sdk/object/tests/utils/assets/models/object_with_optional_field.py index 3ad93d5f305..ebe7dc80547 100644 --- a/seed/python-sdk/object/tests/utils/assets/models/object_with_optional_field.py +++ b/seed/python-sdk/object/tests/utils/assets/models/object_with_optional_field.py @@ -7,8 +7,8 @@ import uuid import typing_extensions -from seed.core.serialization import FieldMetadata +from seed.core.serialization import FieldMetadata from .color import Color from .shape import ShapeParams from .undiscriminated_shape import UndiscriminatedShapeParams @@ -18,16 +18,30 @@ class ObjectWithOptionalFieldParams(typing_extensions.TypedDict): literal: typing.Literal["lit_one"] string: typing_extensions.NotRequired[str] integer: typing_extensions.NotRequired[int] - long_: typing_extensions.NotRequired[typing_extensions.Annotated[int, FieldMetadata(alias="long")]] + long_: typing_extensions.NotRequired[ + typing_extensions.Annotated[int, FieldMetadata(alias="long")] + ] double: typing_extensions.NotRequired[float] - bool_: typing_extensions.NotRequired[typing_extensions.Annotated[bool, FieldMetadata(alias="bool")]] + bool_: typing_extensions.NotRequired[ + typing_extensions.Annotated[bool, FieldMetadata(alias="bool")] + ] datetime: typing_extensions.NotRequired[dt.datetime] date: typing_extensions.NotRequired[dt.date] - uuid_: typing_extensions.NotRequired[typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")]] - base_64: typing_extensions.NotRequired[typing_extensions.Annotated[str, FieldMetadata(alias="base64")]] - list_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")]] - set_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")]] - map_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")]] + uuid_: typing_extensions.NotRequired[ + typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")] + ] + base_64: typing_extensions.NotRequired[ + typing_extensions.Annotated[str, FieldMetadata(alias="base64")] + ] + list_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")] + ] + set_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")] + ] + map_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")] + ] enum: typing_extensions.NotRequired[Color] union: typing_extensions.NotRequired[ShapeParams] second_union: typing_extensions.NotRequired[ShapeParams] diff --git a/seed/python-sdk/object/tests/utils/assets/models/shape.py b/seed/python-sdk/object/tests/utils/assets/models/shape.py index 2c33c877951..816ffc51bdc 100644 --- a/seed/python-sdk/object/tests/utils/assets/models/shape.py +++ b/seed/python-sdk/object/tests/utils/assets/models/shape.py @@ -7,6 +7,7 @@ import typing import typing_extensions + from seed.core.serialization import FieldMetadata @@ -15,13 +16,21 @@ class Base(typing_extensions.TypedDict): class Shape_CircleParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["circle"], FieldMetadata(alias="shapeType")] - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["circle"], FieldMetadata(alias="shapeType") + ] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] class Shape_SquareParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["square"], FieldMetadata(alias="shapeType")] - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["square"], FieldMetadata(alias="shapeType") + ] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] ShapeParams = typing.Union[Shape_CircleParams, Shape_SquareParams] diff --git a/seed/python-sdk/object/tests/utils/assets/models/square.py b/seed/python-sdk/object/tests/utils/assets/models/square.py index b9b7dd319bc..bcf08a723c5 100644 --- a/seed/python-sdk/object/tests/utils/assets/models/square.py +++ b/seed/python-sdk/object/tests/utils/assets/models/square.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class SquareParams(typing_extensions.TypedDict): - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] diff --git a/seed/python-sdk/object/tests/utils/test_http_client.py b/seed/python-sdk/object/tests/utils/test_http_client.py index edd11ca7afb..f5a874a75f3 100644 --- a/seed/python-sdk/object/tests/utils/test_http_client.py +++ b/seed/python-sdk/object/tests/utils/test_http_client.py @@ -9,12 +9,17 @@ def get_request_options() -> RequestOptions: def test_get_json_request_body() -> None: - json_body, data_body = get_request_body(json={"hello": "world"}, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json={"hello": "world"}, data=None, request_options=None, omit=None + ) assert json_body == {"hello": "world"} assert data_body is None json_body_extras, data_body_extras = get_request_body( - json={"goodbye": "world"}, data=None, request_options=get_request_options(), omit=None + json={"goodbye": "world"}, + data=None, + request_options=get_request_options(), + omit=None, ) assert json_body_extras == {"goodbye": "world", "see you": "later"} @@ -22,12 +27,17 @@ def test_get_json_request_body() -> None: def test_get_files_request_body() -> None: - json_body, data_body = get_request_body(json=None, data={"hello": "world"}, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data={"hello": "world"}, request_options=None, omit=None + ) assert data_body == {"hello": "world"} assert json_body is None json_body_extras, data_body_extras = get_request_body( - json=None, data={"goodbye": "world"}, request_options=get_request_options(), omit=None + json=None, + data={"goodbye": "world"}, + request_options=get_request_options(), + omit=None, ) assert data_body_extras == {"goodbye": "world", "see you": "later"} @@ -35,7 +45,9 @@ def test_get_files_request_body() -> None: def test_get_none_request_body() -> None: - json_body, data_body = get_request_body(json=None, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data=None, request_options=None, omit=None + ) assert data_body is None assert json_body is None diff --git a/seed/python-sdk/object/tests/utils/test_query_encoding.py b/seed/python-sdk/object/tests/utils/test_query_encoding.py index 247e1551b46..fbc8f402167 100644 --- a/seed/python-sdk/object/tests/utils/test_query_encoding.py +++ b/seed/python-sdk/object/tests/utils/test_query_encoding.py @@ -4,9 +4,15 @@ def test_query_encoding() -> None: - assert encode_query({"hello world": "hello world"}) == {"hello world": "hello world"} - assert encode_query({"hello_world": {"hello": "world"}}) == {"hello_world[hello]": "world"} - assert encode_query({"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"}) == { + assert encode_query({"hello world": "hello world"}) == { + "hello world": "hello world" + } + assert encode_query({"hello_world": {"hello": "world"}}) == { + "hello_world[hello]": "world" + } + assert encode_query( + {"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"} + ) == { "hello_world[hello][world]": "today", "hello_world[test]": "this", "hi": "there", diff --git a/seed/python-sdk/object/tests/utils/test_serialization.py b/seed/python-sdk/object/tests/utils/test_serialization.py index 58b1ed66e6d..5ca956916dd 100644 --- a/seed/python-sdk/object/tests/utils/test_serialization.py +++ b/seed/python-sdk/object/tests/utils/test_serialization.py @@ -1,10 +1,12 @@ # This file was auto-generated by Fern from our API Definition. -from typing import Any, List +from typing import List, Any -from seed.core.serialization import convert_and_respect_annotation_metadata +from seed.core.serialization import ( + convert_and_respect_annotation_metadata, +) +from .assets.models import ShapeParams, ObjectWithOptionalFieldParams -from .assets.models import ObjectWithOptionalFieldParams, ShapeParams UNION_TEST: ShapeParams = {"radius_measurement": 1.0, "shape_type": "circle", "id": "1"} UNION_TEST_CONVERTED = {"shapeType": "circle", "radiusMeasurement": 1.0, "id": "1"} @@ -18,20 +20,54 @@ def test_convert_and_respect_annotation_metadata() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) - assert converted == {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"} + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) + assert converted == { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + } def test_convert_and_respect_annotation_metadata_in_list() -> None: data: List[ObjectWithOptionalFieldParams] = [ - {"string": "string", "long_": 12345, "bool_": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long_": 67890, "list_": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long_": 12345, + "bool_": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long_": 67890, + "list_": [], + "literal": "lit_one", + "any": "any", + }, ] - converted = convert_and_respect_annotation_metadata(object_=data, annotation=List[ObjectWithOptionalFieldParams]) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=List[ObjectWithOptionalFieldParams] + ) assert converted == [ - {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long": 67890, "list": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long": 67890, + "list": [], + "literal": "lit_one", + "any": "any", + }, ] @@ -43,7 +79,9 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) assert converted == { "string": "string", @@ -55,12 +93,16 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: def test_convert_and_respect_annotation_metadata_in_union() -> None: - converted = convert_and_respect_annotation_metadata(object_=UNION_TEST, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=UNION_TEST, annotation=ShapeParams + ) assert converted == UNION_TEST_CONVERTED def test_convert_and_respect_annotation_metadata_with_empty_object() -> None: data: Any = {} - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ShapeParams + ) assert converted == data diff --git a/seed/python-sdk/objects-with-imports/pyproject.toml b/seed/python-sdk/objects-with-imports/pyproject.toml index a7e791f67d9..794cd078f43 100644 --- a/seed/python-sdk/objects-with-imports/pyproject.toml +++ b/seed/python-sdk/objects-with-imports/pyproject.toml @@ -43,6 +43,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/python-sdk/objects-with-imports/src/seed/client.py b/seed/python-sdk/objects-with-imports/src/seed/client.py index addc5597468..762e94e5084 100644 --- a/seed/python-sdk/objects-with-imports/src/seed/client.py +++ b/seed/python-sdk/objects-with-imports/src/seed/client.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .core.client_wrapper import AsyncClientWrapper, SyncClientWrapper +from .core.client_wrapper import SyncClientWrapper +from .core.client_wrapper import AsyncClientWrapper class SeedObjectsWithImports: @@ -40,14 +39,18 @@ def __init__( base_url: str, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.Client] = None + httpx_client: typing.Optional[httpx.Client] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = SyncClientWrapper( base_url=base_url, httpx_client=httpx_client if httpx_client is not None - else httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.Client( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.Client(timeout=_defaulted_timeout), timeout=_defaulted_timeout, @@ -87,14 +90,18 @@ def __init__( base_url: str, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.AsyncClient] = None + httpx_client: typing.Optional[httpx.AsyncClient] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = AsyncClientWrapper( base_url=base_url, httpx_client=httpx_client if httpx_client is not None - else httpx.AsyncClient(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.AsyncClient( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.AsyncClient(timeout=_defaulted_timeout), timeout=_defaulted_timeout, diff --git a/seed/python-sdk/objects-with-imports/src/seed/commons/metadata/types/metadata.py b/seed/python-sdk/objects-with-imports/src/seed/commons/metadata/types/metadata.py index 0315fba8331..e939ed210c3 100644 --- a/seed/python-sdk/objects-with-imports/src/seed/commons/metadata/types/metadata.py +++ b/seed/python-sdk/objects-with-imports/src/seed/commons/metadata/types/metadata.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from ....core.pydantic_utilities import UniversalBaseModel import typing - +from ....core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class Metadata(UniversalBaseModel): """ @@ -23,7 +22,9 @@ class Metadata(UniversalBaseModel): data: typing.Optional[typing.Dict[str, str]] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/objects-with-imports/src/seed/core/api_error.py b/seed/python-sdk/objects-with-imports/src/seed/core/api_error.py index 2e9fc5431cd..da734b58068 100644 --- a/seed/python-sdk/objects-with-imports/src/seed/core/api_error.py +++ b/seed/python-sdk/objects-with-imports/src/seed/core/api_error.py @@ -7,7 +7,9 @@ class ApiError(Exception): status_code: typing.Optional[int] body: typing.Any - def __init__(self, *, status_code: typing.Optional[int] = None, body: typing.Any = None): + def __init__( + self, *, status_code: typing.Optional[int] = None, body: typing.Any = None + ): self.status_code = status_code self.body = body diff --git a/seed/python-sdk/objects-with-imports/src/seed/core/client_wrapper.py b/seed/python-sdk/objects-with-imports/src/seed/core/client_wrapper.py index 2a5da8ebb4d..25b391c13cf 100644 --- a/seed/python-sdk/objects-with-imports/src/seed/core/client_wrapper.py +++ b/seed/python-sdk/objects-with-imports/src/seed/core/client_wrapper.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .http_client import AsyncHttpClient, HttpClient +from .http_client import HttpClient +from .http_client import AsyncHttpClient class BaseClientWrapper: @@ -28,7 +27,13 @@ def get_timeout(self) -> typing.Optional[float]: class SyncClientWrapper(BaseClientWrapper): - def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, httpx_client: httpx.Client): + def __init__( + self, + *, + base_url: str, + timeout: typing.Optional[float] = None, + httpx_client: httpx.Client, + ): super().__init__(base_url=base_url, timeout=timeout) self.httpx_client = HttpClient( httpx_client=httpx_client, @@ -39,7 +44,13 @@ def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, htt class AsyncClientWrapper(BaseClientWrapper): - def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, httpx_client: httpx.AsyncClient): + def __init__( + self, + *, + base_url: str, + timeout: typing.Optional[float] = None, + httpx_client: httpx.AsyncClient, + ): super().__init__(base_url=base_url, timeout=timeout) self.httpx_client = AsyncHttpClient( httpx_client=httpx_client, diff --git a/seed/python-sdk/objects-with-imports/src/seed/core/datetime_utils.py b/seed/python-sdk/objects-with-imports/src/seed/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/python-sdk/objects-with-imports/src/seed/core/datetime_utils.py +++ b/seed/python-sdk/objects-with-imports/src/seed/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/python-sdk/objects-with-imports/src/seed/core/file.py b/seed/python-sdk/objects-with-imports/src/seed/core/file.py index cb0d40bbbf3..6e0f92bfcb1 100644 --- a/seed/python-sdk/objects-with-imports/src/seed/core/file.py +++ b/seed/python-sdk/objects-with-imports/src/seed/core/file.py @@ -13,12 +13,17 @@ # (filename, file (or bytes), content_type) typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str]], # (filename, file (or bytes), content_type, headers) - typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str], typing.Mapping[str, str]], + typing.Tuple[ + typing.Optional[str], + FileContent, + typing.Optional[str], + typing.Mapping[str, str], + ], ] def convert_file_dict_to_httpx_tuples( - d: typing.Dict[str, typing.Union[File, typing.List[File]]] + d: typing.Dict[str, typing.Union[File, typing.List[File]]], ) -> typing.List[typing.Tuple[str, File]]: """ The format we use is a list of tuples, where the first element is the diff --git a/seed/python-sdk/objects-with-imports/src/seed/core/http_client.py b/seed/python-sdk/objects-with-imports/src/seed/core/http_client.py index 9333d8a7f15..091f71bc185 100644 --- a/seed/python-sdk/objects-with-imports/src/seed/core/http_client.py +++ b/seed/python-sdk/objects-with-imports/src/seed/core/http_client.py @@ -77,7 +77,9 @@ def _retry_timeout(response: httpx.Response, retries: int) -> float: return retry_after # Apply exponential backoff, capped at MAX_RETRY_DELAY_SECONDS. - retry_delay = min(INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS) + retry_delay = min( + INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS + ) # Add a randomness / jitter to the retry delay to avoid overwhelming the server with retries. timeout = retry_delay * (1 - 0.25 * random()) @@ -90,7 +92,8 @@ def _should_retry(response: httpx.Response) -> bool: def remove_omit_from_dict( - original: typing.Dict[str, typing.Optional[typing.Any]], omit: typing.Optional[typing.Any] + original: typing.Dict[str, typing.Optional[typing.Any]], + omit: typing.Optional[typing.Any], ) -> typing.Dict[str, typing.Any]: if omit is None: return original @@ -108,7 +111,8 @@ def maybe_filter_request_body( ) -> typing.Optional[typing.Any]: if data is None: return ( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else None ) @@ -118,7 +122,8 @@ def maybe_filter_request_body( data_content = { **(jsonable_encoder(remove_omit_from_dict(data, omit))), # type: ignore **( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else {} ), @@ -162,7 +167,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url def request( @@ -174,8 +181,12 @@ def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -184,11 +195,14 @@ def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) response = self.httpx_client.request( method=method, @@ -198,7 +212,11 @@ def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -209,7 +227,10 @@ def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -222,11 +243,15 @@ def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: time.sleep(_retry_timeout(response=response, retries=retries)) @@ -256,8 +281,12 @@ def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -266,11 +295,14 @@ def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) with self.httpx_client.stream( method=method, @@ -280,7 +312,11 @@ def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -291,7 +327,9 @@ def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -304,7 +342,9 @@ def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream @@ -327,7 +367,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url async def request( @@ -339,8 +381,12 @@ async def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -349,11 +395,14 @@ async def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) # Add the input to each of these and do None-safety checks response = await self.httpx_client.request( @@ -364,7 +413,11 @@ async def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -375,7 +428,10 @@ async def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -388,11 +444,15 @@ async def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: await asyncio.sleep(_retry_timeout(response=response, retries=retries)) @@ -421,8 +481,12 @@ async def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -431,11 +495,14 @@ async def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) async with self.httpx_client.stream( method=method, @@ -445,7 +512,11 @@ async def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -456,7 +527,9 @@ async def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -469,7 +542,9 @@ async def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream diff --git a/seed/python-sdk/objects-with-imports/src/seed/core/jsonable_encoder.py b/seed/python-sdk/objects-with-imports/src/seed/core/jsonable_encoder.py index d3fd328fd41..12a8b52fc22 100644 --- a/seed/python-sdk/objects-with-imports/src/seed/core/jsonable_encoder.py +++ b/seed/python-sdk/objects-with-imports/src/seed/core/jsonable_encoder.py @@ -19,13 +19,19 @@ import pydantic from .datetime_utils import serialize_datetime -from .pydantic_utilities import IS_PYDANTIC_V2, encode_by_type, to_jsonable_with_fallback +from .pydantic_utilities import ( + IS_PYDANTIC_V2, + encode_by_type, + to_jsonable_with_fallback, +) SetIntStr = Set[Union[int, str]] DictIntStrAny = Dict[Union[int, str], Any] -def jsonable_encoder(obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None) -> Any: +def jsonable_encoder( + obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None +) -> Any: custom_encoder = custom_encoder or {} if custom_encoder: if type(obj) in custom_encoder: diff --git a/seed/python-sdk/objects-with-imports/src/seed/core/pydantic_utilities.py b/seed/python-sdk/objects-with-imports/src/seed/core/pydantic_utilities.py index 170a563d6eb..c63935c32a2 100644 --- a/seed/python-sdk/objects-with-imports/src/seed/core/pydantic_utilities.py +++ b/seed/python-sdk/objects-with-imports/src/seed/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) # type: ignore # Pydantic v1 diff --git a/seed/python-sdk/objects-with-imports/src/seed/core/query_encoder.py b/seed/python-sdk/objects-with-imports/src/seed/core/query_encoder.py index 24076d72ee9..7cb98f52cd7 100644 --- a/seed/python-sdk/objects-with-imports/src/seed/core/query_encoder.py +++ b/seed/python-sdk/objects-with-imports/src/seed/core/query_encoder.py @@ -7,7 +7,9 @@ # Flattens dicts to be of the form {"key[subkey][subkey2]": value} where value is not a dict -def traverse_query_dict(dict_flat: Dict[str, Any], key_prefix: Optional[str] = None) -> Dict[str, Any]: +def traverse_query_dict( + dict_flat: Dict[str, Any], key_prefix: Optional[str] = None +) -> Dict[str, Any]: result = {} for k, v in dict_flat.items(): key = f"{key_prefix}[{k}]" if key_prefix is not None else k @@ -30,4 +32,8 @@ def single_query_encoder(query_key: str, query_value: Any) -> Dict[str, Any]: def encode_query(query: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: - return dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) if query is not None else None + return ( + dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) + if query is not None + else None + ) diff --git a/seed/python-sdk/objects-with-imports/src/seed/core/serialization.py b/seed/python-sdk/objects-with-imports/src/seed/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/python-sdk/objects-with-imports/src/seed/core/serialization.py +++ b/seed/python-sdk/objects-with-imports/src/seed/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/python-sdk/objects-with-imports/src/seed/file/directory/types/directory.py b/seed/python-sdk/objects-with-imports/src/seed/file/directory/types/directory.py index 5a46b019bb6..55dc054a371 100644 --- a/seed/python-sdk/objects-with-imports/src/seed/file/directory/types/directory.py +++ b/seed/python-sdk/objects-with-imports/src/seed/file/directory/types/directory.py @@ -1,13 +1,12 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ....core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ....core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel, update_forward_refs from ...types.file import File +from ....core.pydantic_utilities import IS_PYDANTIC_V2 +import pydantic +from ....core.pydantic_utilities import update_forward_refs class Directory(UniversalBaseModel): @@ -46,7 +45,9 @@ class Directory(UniversalBaseModel): directories: typing.Optional[typing.List[Directory]] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/objects-with-imports/src/seed/file/types/file.py b/seed/python-sdk/objects-with-imports/src/seed/file/types/file.py index 2e23f4b5f9c..36c0ef59b41 100644 --- a/seed/python-sdk/objects-with-imports/src/seed/file/types/file.py +++ b/seed/python-sdk/objects-with-imports/src/seed/file/types/file.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from .file_info import FileInfo +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .file_info import FileInfo - class File(UniversalBaseModel): """ @@ -26,7 +25,9 @@ class File(UniversalBaseModel): info: FileInfo if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/objects-with-imports/src/seed/types/node.py b/seed/python-sdk/objects-with-imports/src/seed/types/node.py index d7b9e6e3075..1f1d79e02c4 100644 --- a/seed/python-sdk/objects-with-imports/src/seed/types/node.py +++ b/seed/python-sdk/objects-with-imports/src/seed/types/node.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from ..core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - from ..commons.metadata.types.metadata import Metadata -from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ..core.pydantic_utilities import IS_PYDANTIC_V2 +import pydantic class Node(UniversalBaseModel): @@ -30,7 +29,9 @@ class Node(UniversalBaseModel): metadata: typing.Optional[Metadata] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/objects-with-imports/src/seed/types/tree.py b/seed/python-sdk/objects-with-imports/src/seed/types/tree.py index 485c11a475f..202e87702cd 100644 --- a/seed/python-sdk/objects-with-imports/src/seed/types/tree.py +++ b/seed/python-sdk/objects-with-imports/src/seed/types/tree.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from ..core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .node import Node +from ..core.pydantic_utilities import IS_PYDANTIC_V2 +import pydantic class Tree(UniversalBaseModel): @@ -40,7 +39,9 @@ class Tree(UniversalBaseModel): nodes: typing.Optional[typing.List[Node]] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/objects-with-imports/src/seed/version.py b/seed/python-sdk/objects-with-imports/src/seed/version.py index 8c3841b79f0..ed48b863122 100644 --- a/seed/python-sdk/objects-with-imports/src/seed/version.py +++ b/seed/python-sdk/objects-with-imports/src/seed/version.py @@ -1,4 +1,3 @@ - from importlib import metadata __version__ = metadata.version("fern_objects-with-imports") diff --git a/seed/python-sdk/objects-with-imports/tests/conftest.py b/seed/python-sdk/objects-with-imports/tests/conftest.py index d18c063b5af..feeb143e65b 100644 --- a/seed/python-sdk/objects-with-imports/tests/conftest.py +++ b/seed/python-sdk/objects-with-imports/tests/conftest.py @@ -1,9 +1,9 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedObjectsWithImports import os - import pytest -from seed import AsyncSeedObjectsWithImports, SeedObjectsWithImports +from seed import AsyncSeedObjectsWithImports @pytest.fixture diff --git a/seed/python-sdk/objects-with-imports/tests/custom/test_client.py b/seed/python-sdk/objects-with-imports/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/python-sdk/objects-with-imports/tests/custom/test_client.py +++ b/seed/python-sdk/objects-with-imports/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/python-sdk/objects-with-imports/tests/utilities.py b/seed/python-sdk/objects-with-imports/tests/utilities.py index 13da208eb3a..e8f4472564c 100644 --- a/seed/python-sdk/objects-with-imports/tests/utilities.py +++ b/seed/python-sdk/objects-with-imports/tests/utilities.py @@ -3,11 +3,14 @@ import typing import uuid -import pydantic from dateutil import parser +import pydantic + -def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> typing.Any: +def cast_field( + json_expectation: typing.Any, type_expectation: typing.Any +) -> typing.Any: # Cast these specific types which come through as string and expect our # models to cast to the correct type. if type_expectation == "uuid": @@ -25,7 +28,9 @@ def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> ty return json_expectation -def validate_field(response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any) -> None: +def validate_field( + response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectation == "no_validate": return @@ -44,7 +49,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(entry_expectation, dict): is_container_of_complex_type = True validate_response( - response=response[idx], json_expectation=ex, type_expectations=entry_expectation + response=response[idx], + json_expectation=ex, + type_expectations=entry_expectation, ) else: cast_json_expectation.append(cast_field(ex, entry_expectation)) @@ -56,7 +63,10 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # if any of the values of the set have a type_expectation of a dict, we're assuming it's a pydantic # model and keeping it a list. if container_expectation != "set" or not any( - map(lambda value: isinstance(value, dict), list(contents_expectation.values())) + map( + lambda value: isinstance(value, dict), + list(contents_expectation.values()), + ) ): json_expectation = cast_field(json_expectation, container_expectation) elif isinstance(type_expectation, tuple): @@ -65,9 +75,15 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(contents_expectation, dict): json_expectation = { cast_field( - key, contents_expectation.get(idx)[0] if contents_expectation.get(idx) is not None else None # type: ignore + key, + contents_expectation.get(idx)[0] + if contents_expectation.get(idx) is not None + else None, # type: ignore ): cast_field( - value, contents_expectation.get(idx)[1] if contents_expectation.get(idx) is not None else None # type: ignore + value, + contents_expectation.get(idx)[1] + if contents_expectation.get(idx) is not None + else None, # type: ignore ) for idx, (key, value) in enumerate(json_expectation.items()) } @@ -86,7 +102,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # Arg type_expectations is a deeply nested structure that matches the response, but with the values replaced with the expected types -def validate_response(response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any) -> None: +def validate_response( + response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectations == "no_validate": return @@ -96,11 +114,17 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e and not isinstance(response, dict) and not issubclass(type(response), pydantic.BaseModel) ): - validate_field(response=response, json_expectation=json_expectation, type_expectation=type_expectations) + validate_field( + response=response, + json_expectation=json_expectation, + type_expectation=type_expectations, + ) return if isinstance(response, list): - assert len(response) == len(json_expectation), "Length mismatch, expected: {0}, Actual: {1}".format( + assert len(response) == len( + json_expectation + ), "Length mismatch, expected: {0}, Actual: {1}".format( len(response), len(json_expectation) ) content_expectation = type_expectations @@ -108,7 +132,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e content_expectation = type_expectations[1] for idx, item in enumerate(response): validate_response( - response=item, json_expectation=json_expectation[idx], type_expectations=content_expectation[idx] + response=item, + json_expectation=json_expectation[idx], + type_expectations=content_expectation[idx], ) else: response_json = response @@ -116,7 +142,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e response_json = response.dict(by_alias=True) for key, value in json_expectation.items(): - assert key in response_json, "Field {0} not found within the response object: {1}".format( + assert ( + key in response_json + ), "Field {0} not found within the response object: {1}".format( key, response_json ) @@ -128,11 +156,19 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e # Otherwise, we're just validating a single field that's a pydantic model. if isinstance(value, dict) and not isinstance(type_expectation, tuple): validate_response( - response=response_json[key], json_expectation=value, type_expectations=type_expectation + response=response_json[key], + json_expectation=value, + type_expectations=type_expectation, ) else: - validate_field(response=response_json[key], json_expectation=value, type_expectation=type_expectation) + validate_field( + response=response_json[key], + json_expectation=value, + type_expectation=type_expectation, + ) # Ensure there are no additional fields here either del response_json[key] - assert len(response_json) == 0, "Additional fields found, expected None: {0}".format(response_json) + assert ( + len(response_json) == 0 + ), "Additional fields found, expected None: {0}".format(response_json) diff --git a/seed/python-sdk/objects-with-imports/tests/utils/assets/models/__init__.py b/seed/python-sdk/objects-with-imports/tests/utils/assets/models/__init__.py index 2cf01263529..3a1c852e71e 100644 --- a/seed/python-sdk/objects-with-imports/tests/utils/assets/models/__init__.py +++ b/seed/python-sdk/objects-with-imports/tests/utils/assets/models/__init__.py @@ -5,7 +5,7 @@ from .circle import CircleParams from .object_with_defaults import ObjectWithDefaultsParams from .object_with_optional_field import ObjectWithOptionalFieldParams -from .shape import Shape_CircleParams, Shape_SquareParams, ShapeParams +from .shape import ShapeParams, Shape_CircleParams, Shape_SquareParams from .square import SquareParams from .undiscriminated_shape import UndiscriminatedShapeParams diff --git a/seed/python-sdk/objects-with-imports/tests/utils/assets/models/circle.py b/seed/python-sdk/objects-with-imports/tests/utils/assets/models/circle.py index af7a1bf8a8e..253f12d38b3 100644 --- a/seed/python-sdk/objects-with-imports/tests/utils/assets/models/circle.py +++ b/seed/python-sdk/objects-with-imports/tests/utils/assets/models/circle.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class CircleParams(typing_extensions.TypedDict): - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] diff --git a/seed/python-sdk/objects-with-imports/tests/utils/assets/models/object_with_optional_field.py b/seed/python-sdk/objects-with-imports/tests/utils/assets/models/object_with_optional_field.py index 3ad93d5f305..ebe7dc80547 100644 --- a/seed/python-sdk/objects-with-imports/tests/utils/assets/models/object_with_optional_field.py +++ b/seed/python-sdk/objects-with-imports/tests/utils/assets/models/object_with_optional_field.py @@ -7,8 +7,8 @@ import uuid import typing_extensions -from seed.core.serialization import FieldMetadata +from seed.core.serialization import FieldMetadata from .color import Color from .shape import ShapeParams from .undiscriminated_shape import UndiscriminatedShapeParams @@ -18,16 +18,30 @@ class ObjectWithOptionalFieldParams(typing_extensions.TypedDict): literal: typing.Literal["lit_one"] string: typing_extensions.NotRequired[str] integer: typing_extensions.NotRequired[int] - long_: typing_extensions.NotRequired[typing_extensions.Annotated[int, FieldMetadata(alias="long")]] + long_: typing_extensions.NotRequired[ + typing_extensions.Annotated[int, FieldMetadata(alias="long")] + ] double: typing_extensions.NotRequired[float] - bool_: typing_extensions.NotRequired[typing_extensions.Annotated[bool, FieldMetadata(alias="bool")]] + bool_: typing_extensions.NotRequired[ + typing_extensions.Annotated[bool, FieldMetadata(alias="bool")] + ] datetime: typing_extensions.NotRequired[dt.datetime] date: typing_extensions.NotRequired[dt.date] - uuid_: typing_extensions.NotRequired[typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")]] - base_64: typing_extensions.NotRequired[typing_extensions.Annotated[str, FieldMetadata(alias="base64")]] - list_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")]] - set_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")]] - map_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")]] + uuid_: typing_extensions.NotRequired[ + typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")] + ] + base_64: typing_extensions.NotRequired[ + typing_extensions.Annotated[str, FieldMetadata(alias="base64")] + ] + list_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")] + ] + set_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")] + ] + map_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")] + ] enum: typing_extensions.NotRequired[Color] union: typing_extensions.NotRequired[ShapeParams] second_union: typing_extensions.NotRequired[ShapeParams] diff --git a/seed/python-sdk/objects-with-imports/tests/utils/assets/models/shape.py b/seed/python-sdk/objects-with-imports/tests/utils/assets/models/shape.py index 2c33c877951..816ffc51bdc 100644 --- a/seed/python-sdk/objects-with-imports/tests/utils/assets/models/shape.py +++ b/seed/python-sdk/objects-with-imports/tests/utils/assets/models/shape.py @@ -7,6 +7,7 @@ import typing import typing_extensions + from seed.core.serialization import FieldMetadata @@ -15,13 +16,21 @@ class Base(typing_extensions.TypedDict): class Shape_CircleParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["circle"], FieldMetadata(alias="shapeType")] - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["circle"], FieldMetadata(alias="shapeType") + ] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] class Shape_SquareParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["square"], FieldMetadata(alias="shapeType")] - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["square"], FieldMetadata(alias="shapeType") + ] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] ShapeParams = typing.Union[Shape_CircleParams, Shape_SquareParams] diff --git a/seed/python-sdk/objects-with-imports/tests/utils/assets/models/square.py b/seed/python-sdk/objects-with-imports/tests/utils/assets/models/square.py index b9b7dd319bc..bcf08a723c5 100644 --- a/seed/python-sdk/objects-with-imports/tests/utils/assets/models/square.py +++ b/seed/python-sdk/objects-with-imports/tests/utils/assets/models/square.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class SquareParams(typing_extensions.TypedDict): - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] diff --git a/seed/python-sdk/objects-with-imports/tests/utils/test_http_client.py b/seed/python-sdk/objects-with-imports/tests/utils/test_http_client.py index edd11ca7afb..f5a874a75f3 100644 --- a/seed/python-sdk/objects-with-imports/tests/utils/test_http_client.py +++ b/seed/python-sdk/objects-with-imports/tests/utils/test_http_client.py @@ -9,12 +9,17 @@ def get_request_options() -> RequestOptions: def test_get_json_request_body() -> None: - json_body, data_body = get_request_body(json={"hello": "world"}, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json={"hello": "world"}, data=None, request_options=None, omit=None + ) assert json_body == {"hello": "world"} assert data_body is None json_body_extras, data_body_extras = get_request_body( - json={"goodbye": "world"}, data=None, request_options=get_request_options(), omit=None + json={"goodbye": "world"}, + data=None, + request_options=get_request_options(), + omit=None, ) assert json_body_extras == {"goodbye": "world", "see you": "later"} @@ -22,12 +27,17 @@ def test_get_json_request_body() -> None: def test_get_files_request_body() -> None: - json_body, data_body = get_request_body(json=None, data={"hello": "world"}, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data={"hello": "world"}, request_options=None, omit=None + ) assert data_body == {"hello": "world"} assert json_body is None json_body_extras, data_body_extras = get_request_body( - json=None, data={"goodbye": "world"}, request_options=get_request_options(), omit=None + json=None, + data={"goodbye": "world"}, + request_options=get_request_options(), + omit=None, ) assert data_body_extras == {"goodbye": "world", "see you": "later"} @@ -35,7 +45,9 @@ def test_get_files_request_body() -> None: def test_get_none_request_body() -> None: - json_body, data_body = get_request_body(json=None, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data=None, request_options=None, omit=None + ) assert data_body is None assert json_body is None diff --git a/seed/python-sdk/objects-with-imports/tests/utils/test_query_encoding.py b/seed/python-sdk/objects-with-imports/tests/utils/test_query_encoding.py index 247e1551b46..fbc8f402167 100644 --- a/seed/python-sdk/objects-with-imports/tests/utils/test_query_encoding.py +++ b/seed/python-sdk/objects-with-imports/tests/utils/test_query_encoding.py @@ -4,9 +4,15 @@ def test_query_encoding() -> None: - assert encode_query({"hello world": "hello world"}) == {"hello world": "hello world"} - assert encode_query({"hello_world": {"hello": "world"}}) == {"hello_world[hello]": "world"} - assert encode_query({"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"}) == { + assert encode_query({"hello world": "hello world"}) == { + "hello world": "hello world" + } + assert encode_query({"hello_world": {"hello": "world"}}) == { + "hello_world[hello]": "world" + } + assert encode_query( + {"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"} + ) == { "hello_world[hello][world]": "today", "hello_world[test]": "this", "hi": "there", diff --git a/seed/python-sdk/objects-with-imports/tests/utils/test_serialization.py b/seed/python-sdk/objects-with-imports/tests/utils/test_serialization.py index 58b1ed66e6d..5ca956916dd 100644 --- a/seed/python-sdk/objects-with-imports/tests/utils/test_serialization.py +++ b/seed/python-sdk/objects-with-imports/tests/utils/test_serialization.py @@ -1,10 +1,12 @@ # This file was auto-generated by Fern from our API Definition. -from typing import Any, List +from typing import List, Any -from seed.core.serialization import convert_and_respect_annotation_metadata +from seed.core.serialization import ( + convert_and_respect_annotation_metadata, +) +from .assets.models import ShapeParams, ObjectWithOptionalFieldParams -from .assets.models import ObjectWithOptionalFieldParams, ShapeParams UNION_TEST: ShapeParams = {"radius_measurement": 1.0, "shape_type": "circle", "id": "1"} UNION_TEST_CONVERTED = {"shapeType": "circle", "radiusMeasurement": 1.0, "id": "1"} @@ -18,20 +20,54 @@ def test_convert_and_respect_annotation_metadata() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) - assert converted == {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"} + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) + assert converted == { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + } def test_convert_and_respect_annotation_metadata_in_list() -> None: data: List[ObjectWithOptionalFieldParams] = [ - {"string": "string", "long_": 12345, "bool_": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long_": 67890, "list_": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long_": 12345, + "bool_": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long_": 67890, + "list_": [], + "literal": "lit_one", + "any": "any", + }, ] - converted = convert_and_respect_annotation_metadata(object_=data, annotation=List[ObjectWithOptionalFieldParams]) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=List[ObjectWithOptionalFieldParams] + ) assert converted == [ - {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long": 67890, "list": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long": 67890, + "list": [], + "literal": "lit_one", + "any": "any", + }, ] @@ -43,7 +79,9 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) assert converted == { "string": "string", @@ -55,12 +93,16 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: def test_convert_and_respect_annotation_metadata_in_union() -> None: - converted = convert_and_respect_annotation_metadata(object_=UNION_TEST, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=UNION_TEST, annotation=ShapeParams + ) assert converted == UNION_TEST_CONVERTED def test_convert_and_respect_annotation_metadata_with_empty_object() -> None: data: Any = {} - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ShapeParams + ) assert converted == data diff --git a/seed/python-sdk/optional/pyproject.toml b/seed/python-sdk/optional/pyproject.toml index 2e99dfeaa89..30de017ee03 100644 --- a/seed/python-sdk/optional/pyproject.toml +++ b/seed/python-sdk/optional/pyproject.toml @@ -43,6 +43,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/python-sdk/optional/src/seed/__init__.py b/seed/python-sdk/optional/src/seed/__init__.py index d630c0659a0..941bf701cf4 100644 --- a/seed/python-sdk/optional/src/seed/__init__.py +++ b/seed/python-sdk/optional/src/seed/__init__.py @@ -4,4 +4,9 @@ from .client import AsyncSeedObjectsWithImports, SeedObjectsWithImports from .version import __version__ -__all__ = ["AsyncSeedObjectsWithImports", "SeedObjectsWithImports", "__version__", "optional"] +__all__ = [ + "AsyncSeedObjectsWithImports", + "SeedObjectsWithImports", + "__version__", + "optional", +] diff --git a/seed/python-sdk/optional/src/seed/client.py b/seed/python-sdk/optional/src/seed/client.py index dca747f6e96..1c5f20bb75e 100644 --- a/seed/python-sdk/optional/src/seed/client.py +++ b/seed/python-sdk/optional/src/seed/client.py @@ -1,11 +1,11 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from .optional.client import AsyncOptionalClient, OptionalClient +from .core.client_wrapper import SyncClientWrapper +from .optional.client import OptionalClient +from .core.client_wrapper import AsyncClientWrapper +from .optional.client import AsyncOptionalClient class SeedObjectsWithImports: @@ -41,14 +41,18 @@ def __init__( base_url: str, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.Client] = None + httpx_client: typing.Optional[httpx.Client] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = SyncClientWrapper( base_url=base_url, httpx_client=httpx_client if httpx_client is not None - else httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.Client( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.Client(timeout=_defaulted_timeout), timeout=_defaulted_timeout, @@ -89,14 +93,18 @@ def __init__( base_url: str, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.AsyncClient] = None + httpx_client: typing.Optional[httpx.AsyncClient] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = AsyncClientWrapper( base_url=base_url, httpx_client=httpx_client if httpx_client is not None - else httpx.AsyncClient(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.AsyncClient( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.AsyncClient(timeout=_defaulted_timeout), timeout=_defaulted_timeout, diff --git a/seed/python-sdk/optional/src/seed/core/api_error.py b/seed/python-sdk/optional/src/seed/core/api_error.py index 2e9fc5431cd..da734b58068 100644 --- a/seed/python-sdk/optional/src/seed/core/api_error.py +++ b/seed/python-sdk/optional/src/seed/core/api_error.py @@ -7,7 +7,9 @@ class ApiError(Exception): status_code: typing.Optional[int] body: typing.Any - def __init__(self, *, status_code: typing.Optional[int] = None, body: typing.Any = None): + def __init__( + self, *, status_code: typing.Optional[int] = None, body: typing.Any = None + ): self.status_code = status_code self.body = body diff --git a/seed/python-sdk/optional/src/seed/core/client_wrapper.py b/seed/python-sdk/optional/src/seed/core/client_wrapper.py index 694b3c4cc14..fb6da1ab28d 100644 --- a/seed/python-sdk/optional/src/seed/core/client_wrapper.py +++ b/seed/python-sdk/optional/src/seed/core/client_wrapper.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .http_client import AsyncHttpClient, HttpClient +from .http_client import HttpClient +from .http_client import AsyncHttpClient class BaseClientWrapper: @@ -28,7 +27,13 @@ def get_timeout(self) -> typing.Optional[float]: class SyncClientWrapper(BaseClientWrapper): - def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, httpx_client: httpx.Client): + def __init__( + self, + *, + base_url: str, + timeout: typing.Optional[float] = None, + httpx_client: httpx.Client, + ): super().__init__(base_url=base_url, timeout=timeout) self.httpx_client = HttpClient( httpx_client=httpx_client, @@ -39,7 +44,13 @@ def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, htt class AsyncClientWrapper(BaseClientWrapper): - def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, httpx_client: httpx.AsyncClient): + def __init__( + self, + *, + base_url: str, + timeout: typing.Optional[float] = None, + httpx_client: httpx.AsyncClient, + ): super().__init__(base_url=base_url, timeout=timeout) self.httpx_client = AsyncHttpClient( httpx_client=httpx_client, diff --git a/seed/python-sdk/optional/src/seed/core/datetime_utils.py b/seed/python-sdk/optional/src/seed/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/python-sdk/optional/src/seed/core/datetime_utils.py +++ b/seed/python-sdk/optional/src/seed/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/python-sdk/optional/src/seed/core/file.py b/seed/python-sdk/optional/src/seed/core/file.py index cb0d40bbbf3..6e0f92bfcb1 100644 --- a/seed/python-sdk/optional/src/seed/core/file.py +++ b/seed/python-sdk/optional/src/seed/core/file.py @@ -13,12 +13,17 @@ # (filename, file (or bytes), content_type) typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str]], # (filename, file (or bytes), content_type, headers) - typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str], typing.Mapping[str, str]], + typing.Tuple[ + typing.Optional[str], + FileContent, + typing.Optional[str], + typing.Mapping[str, str], + ], ] def convert_file_dict_to_httpx_tuples( - d: typing.Dict[str, typing.Union[File, typing.List[File]]] + d: typing.Dict[str, typing.Union[File, typing.List[File]]], ) -> typing.List[typing.Tuple[str, File]]: """ The format we use is a list of tuples, where the first element is the diff --git a/seed/python-sdk/optional/src/seed/core/http_client.py b/seed/python-sdk/optional/src/seed/core/http_client.py index 9333d8a7f15..091f71bc185 100644 --- a/seed/python-sdk/optional/src/seed/core/http_client.py +++ b/seed/python-sdk/optional/src/seed/core/http_client.py @@ -77,7 +77,9 @@ def _retry_timeout(response: httpx.Response, retries: int) -> float: return retry_after # Apply exponential backoff, capped at MAX_RETRY_DELAY_SECONDS. - retry_delay = min(INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS) + retry_delay = min( + INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS + ) # Add a randomness / jitter to the retry delay to avoid overwhelming the server with retries. timeout = retry_delay * (1 - 0.25 * random()) @@ -90,7 +92,8 @@ def _should_retry(response: httpx.Response) -> bool: def remove_omit_from_dict( - original: typing.Dict[str, typing.Optional[typing.Any]], omit: typing.Optional[typing.Any] + original: typing.Dict[str, typing.Optional[typing.Any]], + omit: typing.Optional[typing.Any], ) -> typing.Dict[str, typing.Any]: if omit is None: return original @@ -108,7 +111,8 @@ def maybe_filter_request_body( ) -> typing.Optional[typing.Any]: if data is None: return ( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else None ) @@ -118,7 +122,8 @@ def maybe_filter_request_body( data_content = { **(jsonable_encoder(remove_omit_from_dict(data, omit))), # type: ignore **( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else {} ), @@ -162,7 +167,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url def request( @@ -174,8 +181,12 @@ def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -184,11 +195,14 @@ def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) response = self.httpx_client.request( method=method, @@ -198,7 +212,11 @@ def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -209,7 +227,10 @@ def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -222,11 +243,15 @@ def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: time.sleep(_retry_timeout(response=response, retries=retries)) @@ -256,8 +281,12 @@ def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -266,11 +295,14 @@ def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) with self.httpx_client.stream( method=method, @@ -280,7 +312,11 @@ def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -291,7 +327,9 @@ def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -304,7 +342,9 @@ def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream @@ -327,7 +367,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url async def request( @@ -339,8 +381,12 @@ async def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -349,11 +395,14 @@ async def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) # Add the input to each of these and do None-safety checks response = await self.httpx_client.request( @@ -364,7 +413,11 @@ async def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -375,7 +428,10 @@ async def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -388,11 +444,15 @@ async def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: await asyncio.sleep(_retry_timeout(response=response, retries=retries)) @@ -421,8 +481,12 @@ async def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -431,11 +495,14 @@ async def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) async with self.httpx_client.stream( method=method, @@ -445,7 +512,11 @@ async def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -456,7 +527,9 @@ async def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -469,7 +542,9 @@ async def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream diff --git a/seed/python-sdk/optional/src/seed/core/jsonable_encoder.py b/seed/python-sdk/optional/src/seed/core/jsonable_encoder.py index d3fd328fd41..12a8b52fc22 100644 --- a/seed/python-sdk/optional/src/seed/core/jsonable_encoder.py +++ b/seed/python-sdk/optional/src/seed/core/jsonable_encoder.py @@ -19,13 +19,19 @@ import pydantic from .datetime_utils import serialize_datetime -from .pydantic_utilities import IS_PYDANTIC_V2, encode_by_type, to_jsonable_with_fallback +from .pydantic_utilities import ( + IS_PYDANTIC_V2, + encode_by_type, + to_jsonable_with_fallback, +) SetIntStr = Set[Union[int, str]] DictIntStrAny = Dict[Union[int, str], Any] -def jsonable_encoder(obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None) -> Any: +def jsonable_encoder( + obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None +) -> Any: custom_encoder = custom_encoder or {} if custom_encoder: if type(obj) in custom_encoder: diff --git a/seed/python-sdk/optional/src/seed/core/pydantic_utilities.py b/seed/python-sdk/optional/src/seed/core/pydantic_utilities.py index 170a563d6eb..c63935c32a2 100644 --- a/seed/python-sdk/optional/src/seed/core/pydantic_utilities.py +++ b/seed/python-sdk/optional/src/seed/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) # type: ignore # Pydantic v1 diff --git a/seed/python-sdk/optional/src/seed/core/query_encoder.py b/seed/python-sdk/optional/src/seed/core/query_encoder.py index 24076d72ee9..7cb98f52cd7 100644 --- a/seed/python-sdk/optional/src/seed/core/query_encoder.py +++ b/seed/python-sdk/optional/src/seed/core/query_encoder.py @@ -7,7 +7,9 @@ # Flattens dicts to be of the form {"key[subkey][subkey2]": value} where value is not a dict -def traverse_query_dict(dict_flat: Dict[str, Any], key_prefix: Optional[str] = None) -> Dict[str, Any]: +def traverse_query_dict( + dict_flat: Dict[str, Any], key_prefix: Optional[str] = None +) -> Dict[str, Any]: result = {} for k, v in dict_flat.items(): key = f"{key_prefix}[{k}]" if key_prefix is not None else k @@ -30,4 +32,8 @@ def single_query_encoder(query_key: str, query_value: Any) -> Dict[str, Any]: def encode_query(query: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: - return dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) if query is not None else None + return ( + dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) + if query is not None + else None + ) diff --git a/seed/python-sdk/optional/src/seed/core/serialization.py b/seed/python-sdk/optional/src/seed/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/python-sdk/optional/src/seed/core/serialization.py +++ b/seed/python-sdk/optional/src/seed/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/python-sdk/optional/src/seed/optional/client.py b/seed/python-sdk/optional/src/seed/optional/client.py index 4cfbd8d7002..c418636360f 100644 --- a/seed/python-sdk/optional/src/seed/optional/client.py +++ b/seed/python-sdk/optional/src/seed/optional/client.py @@ -1,12 +1,12 @@ # This file was auto-generated by Fern from our API Definition. import typing +from ..core.client_wrapper import SyncClientWrapper +from ..core.request_options import RequestOptions +from ..core.pydantic_utilities import parse_obj_as from json.decoder import JSONDecodeError - from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.pydantic_utilities import parse_obj_as -from ..core.request_options import RequestOptions +from ..core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -20,7 +20,7 @@ def send_optional_body( self, *, request: typing.Optional[typing.Dict[str, typing.Any]] = None, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> str: """ Parameters @@ -47,11 +47,17 @@ def send_optional_body( ) """ _response = self._client_wrapper.httpx_client.request( - "send-optional-body", method="POST", json=request, request_options=request_options, omit=OMIT + "send-optional-body", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -66,7 +72,7 @@ async def send_optional_body( self, *, request: typing.Optional[typing.Dict[str, typing.Any]] = None, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> str: """ Parameters @@ -101,11 +107,17 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "send-optional-body", method="POST", json=request, request_options=request_options, omit=OMIT + "send-optional-body", + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/optional/src/seed/version.py b/seed/python-sdk/optional/src/seed/version.py index b31ea7f77a3..6f2ef04b787 100644 --- a/seed/python-sdk/optional/src/seed/version.py +++ b/seed/python-sdk/optional/src/seed/version.py @@ -1,4 +1,3 @@ - from importlib import metadata __version__ = metadata.version("fern_optional") diff --git a/seed/python-sdk/optional/tests/conftest.py b/seed/python-sdk/optional/tests/conftest.py index d18c063b5af..feeb143e65b 100644 --- a/seed/python-sdk/optional/tests/conftest.py +++ b/seed/python-sdk/optional/tests/conftest.py @@ -1,9 +1,9 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedObjectsWithImports import os - import pytest -from seed import AsyncSeedObjectsWithImports, SeedObjectsWithImports +from seed import AsyncSeedObjectsWithImports @pytest.fixture diff --git a/seed/python-sdk/optional/tests/custom/test_client.py b/seed/python-sdk/optional/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/python-sdk/optional/tests/custom/test_client.py +++ b/seed/python-sdk/optional/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/python-sdk/optional/tests/test_optional.py b/seed/python-sdk/optional/tests/test_optional.py index f723c75f67c..f145329561e 100644 --- a/seed/python-sdk/optional/tests/test_optional.py +++ b/seed/python-sdk/optional/tests/test_optional.py @@ -1,17 +1,20 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedObjectsWithImports +from seed import AsyncSeedObjectsWithImports import typing - -from seed import AsyncSeedObjectsWithImports, SeedObjectsWithImports - from .utilities import validate_response -async def test_send_optional_body(client: SeedObjectsWithImports, async_client: AsyncSeedObjectsWithImports) -> None: +async def test_send_optional_body( + client: SeedObjectsWithImports, async_client: AsyncSeedObjectsWithImports +) -> None: expected_response: typing.Any = "string" expected_types: typing.Any = None response = client.optional.send_optional_body(request={"string": {"key": "value"}}) validate_response(response, expected_response, expected_types) - async_response = await async_client.optional.send_optional_body(request={"string": {"key": "value"}}) + async_response = await async_client.optional.send_optional_body( + request={"string": {"key": "value"}} + ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/optional/tests/utilities.py b/seed/python-sdk/optional/tests/utilities.py index 13da208eb3a..e8f4472564c 100644 --- a/seed/python-sdk/optional/tests/utilities.py +++ b/seed/python-sdk/optional/tests/utilities.py @@ -3,11 +3,14 @@ import typing import uuid -import pydantic from dateutil import parser +import pydantic + -def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> typing.Any: +def cast_field( + json_expectation: typing.Any, type_expectation: typing.Any +) -> typing.Any: # Cast these specific types which come through as string and expect our # models to cast to the correct type. if type_expectation == "uuid": @@ -25,7 +28,9 @@ def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> ty return json_expectation -def validate_field(response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any) -> None: +def validate_field( + response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectation == "no_validate": return @@ -44,7 +49,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(entry_expectation, dict): is_container_of_complex_type = True validate_response( - response=response[idx], json_expectation=ex, type_expectations=entry_expectation + response=response[idx], + json_expectation=ex, + type_expectations=entry_expectation, ) else: cast_json_expectation.append(cast_field(ex, entry_expectation)) @@ -56,7 +63,10 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # if any of the values of the set have a type_expectation of a dict, we're assuming it's a pydantic # model and keeping it a list. if container_expectation != "set" or not any( - map(lambda value: isinstance(value, dict), list(contents_expectation.values())) + map( + lambda value: isinstance(value, dict), + list(contents_expectation.values()), + ) ): json_expectation = cast_field(json_expectation, container_expectation) elif isinstance(type_expectation, tuple): @@ -65,9 +75,15 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(contents_expectation, dict): json_expectation = { cast_field( - key, contents_expectation.get(idx)[0] if contents_expectation.get(idx) is not None else None # type: ignore + key, + contents_expectation.get(idx)[0] + if contents_expectation.get(idx) is not None + else None, # type: ignore ): cast_field( - value, contents_expectation.get(idx)[1] if contents_expectation.get(idx) is not None else None # type: ignore + value, + contents_expectation.get(idx)[1] + if contents_expectation.get(idx) is not None + else None, # type: ignore ) for idx, (key, value) in enumerate(json_expectation.items()) } @@ -86,7 +102,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # Arg type_expectations is a deeply nested structure that matches the response, but with the values replaced with the expected types -def validate_response(response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any) -> None: +def validate_response( + response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectations == "no_validate": return @@ -96,11 +114,17 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e and not isinstance(response, dict) and not issubclass(type(response), pydantic.BaseModel) ): - validate_field(response=response, json_expectation=json_expectation, type_expectation=type_expectations) + validate_field( + response=response, + json_expectation=json_expectation, + type_expectation=type_expectations, + ) return if isinstance(response, list): - assert len(response) == len(json_expectation), "Length mismatch, expected: {0}, Actual: {1}".format( + assert len(response) == len( + json_expectation + ), "Length mismatch, expected: {0}, Actual: {1}".format( len(response), len(json_expectation) ) content_expectation = type_expectations @@ -108,7 +132,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e content_expectation = type_expectations[1] for idx, item in enumerate(response): validate_response( - response=item, json_expectation=json_expectation[idx], type_expectations=content_expectation[idx] + response=item, + json_expectation=json_expectation[idx], + type_expectations=content_expectation[idx], ) else: response_json = response @@ -116,7 +142,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e response_json = response.dict(by_alias=True) for key, value in json_expectation.items(): - assert key in response_json, "Field {0} not found within the response object: {1}".format( + assert ( + key in response_json + ), "Field {0} not found within the response object: {1}".format( key, response_json ) @@ -128,11 +156,19 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e # Otherwise, we're just validating a single field that's a pydantic model. if isinstance(value, dict) and not isinstance(type_expectation, tuple): validate_response( - response=response_json[key], json_expectation=value, type_expectations=type_expectation + response=response_json[key], + json_expectation=value, + type_expectations=type_expectation, ) else: - validate_field(response=response_json[key], json_expectation=value, type_expectation=type_expectation) + validate_field( + response=response_json[key], + json_expectation=value, + type_expectation=type_expectation, + ) # Ensure there are no additional fields here either del response_json[key] - assert len(response_json) == 0, "Additional fields found, expected None: {0}".format(response_json) + assert ( + len(response_json) == 0 + ), "Additional fields found, expected None: {0}".format(response_json) diff --git a/seed/python-sdk/optional/tests/utils/assets/models/__init__.py b/seed/python-sdk/optional/tests/utils/assets/models/__init__.py index 2cf01263529..3a1c852e71e 100644 --- a/seed/python-sdk/optional/tests/utils/assets/models/__init__.py +++ b/seed/python-sdk/optional/tests/utils/assets/models/__init__.py @@ -5,7 +5,7 @@ from .circle import CircleParams from .object_with_defaults import ObjectWithDefaultsParams from .object_with_optional_field import ObjectWithOptionalFieldParams -from .shape import Shape_CircleParams, Shape_SquareParams, ShapeParams +from .shape import ShapeParams, Shape_CircleParams, Shape_SquareParams from .square import SquareParams from .undiscriminated_shape import UndiscriminatedShapeParams diff --git a/seed/python-sdk/optional/tests/utils/assets/models/circle.py b/seed/python-sdk/optional/tests/utils/assets/models/circle.py index af7a1bf8a8e..253f12d38b3 100644 --- a/seed/python-sdk/optional/tests/utils/assets/models/circle.py +++ b/seed/python-sdk/optional/tests/utils/assets/models/circle.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class CircleParams(typing_extensions.TypedDict): - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] diff --git a/seed/python-sdk/optional/tests/utils/assets/models/object_with_optional_field.py b/seed/python-sdk/optional/tests/utils/assets/models/object_with_optional_field.py index 3ad93d5f305..ebe7dc80547 100644 --- a/seed/python-sdk/optional/tests/utils/assets/models/object_with_optional_field.py +++ b/seed/python-sdk/optional/tests/utils/assets/models/object_with_optional_field.py @@ -7,8 +7,8 @@ import uuid import typing_extensions -from seed.core.serialization import FieldMetadata +from seed.core.serialization import FieldMetadata from .color import Color from .shape import ShapeParams from .undiscriminated_shape import UndiscriminatedShapeParams @@ -18,16 +18,30 @@ class ObjectWithOptionalFieldParams(typing_extensions.TypedDict): literal: typing.Literal["lit_one"] string: typing_extensions.NotRequired[str] integer: typing_extensions.NotRequired[int] - long_: typing_extensions.NotRequired[typing_extensions.Annotated[int, FieldMetadata(alias="long")]] + long_: typing_extensions.NotRequired[ + typing_extensions.Annotated[int, FieldMetadata(alias="long")] + ] double: typing_extensions.NotRequired[float] - bool_: typing_extensions.NotRequired[typing_extensions.Annotated[bool, FieldMetadata(alias="bool")]] + bool_: typing_extensions.NotRequired[ + typing_extensions.Annotated[bool, FieldMetadata(alias="bool")] + ] datetime: typing_extensions.NotRequired[dt.datetime] date: typing_extensions.NotRequired[dt.date] - uuid_: typing_extensions.NotRequired[typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")]] - base_64: typing_extensions.NotRequired[typing_extensions.Annotated[str, FieldMetadata(alias="base64")]] - list_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")]] - set_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")]] - map_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")]] + uuid_: typing_extensions.NotRequired[ + typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")] + ] + base_64: typing_extensions.NotRequired[ + typing_extensions.Annotated[str, FieldMetadata(alias="base64")] + ] + list_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")] + ] + set_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")] + ] + map_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")] + ] enum: typing_extensions.NotRequired[Color] union: typing_extensions.NotRequired[ShapeParams] second_union: typing_extensions.NotRequired[ShapeParams] diff --git a/seed/python-sdk/optional/tests/utils/assets/models/shape.py b/seed/python-sdk/optional/tests/utils/assets/models/shape.py index 2c33c877951..816ffc51bdc 100644 --- a/seed/python-sdk/optional/tests/utils/assets/models/shape.py +++ b/seed/python-sdk/optional/tests/utils/assets/models/shape.py @@ -7,6 +7,7 @@ import typing import typing_extensions + from seed.core.serialization import FieldMetadata @@ -15,13 +16,21 @@ class Base(typing_extensions.TypedDict): class Shape_CircleParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["circle"], FieldMetadata(alias="shapeType")] - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["circle"], FieldMetadata(alias="shapeType") + ] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] class Shape_SquareParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["square"], FieldMetadata(alias="shapeType")] - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["square"], FieldMetadata(alias="shapeType") + ] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] ShapeParams = typing.Union[Shape_CircleParams, Shape_SquareParams] diff --git a/seed/python-sdk/optional/tests/utils/assets/models/square.py b/seed/python-sdk/optional/tests/utils/assets/models/square.py index b9b7dd319bc..bcf08a723c5 100644 --- a/seed/python-sdk/optional/tests/utils/assets/models/square.py +++ b/seed/python-sdk/optional/tests/utils/assets/models/square.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class SquareParams(typing_extensions.TypedDict): - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] diff --git a/seed/python-sdk/optional/tests/utils/test_http_client.py b/seed/python-sdk/optional/tests/utils/test_http_client.py index edd11ca7afb..f5a874a75f3 100644 --- a/seed/python-sdk/optional/tests/utils/test_http_client.py +++ b/seed/python-sdk/optional/tests/utils/test_http_client.py @@ -9,12 +9,17 @@ def get_request_options() -> RequestOptions: def test_get_json_request_body() -> None: - json_body, data_body = get_request_body(json={"hello": "world"}, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json={"hello": "world"}, data=None, request_options=None, omit=None + ) assert json_body == {"hello": "world"} assert data_body is None json_body_extras, data_body_extras = get_request_body( - json={"goodbye": "world"}, data=None, request_options=get_request_options(), omit=None + json={"goodbye": "world"}, + data=None, + request_options=get_request_options(), + omit=None, ) assert json_body_extras == {"goodbye": "world", "see you": "later"} @@ -22,12 +27,17 @@ def test_get_json_request_body() -> None: def test_get_files_request_body() -> None: - json_body, data_body = get_request_body(json=None, data={"hello": "world"}, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data={"hello": "world"}, request_options=None, omit=None + ) assert data_body == {"hello": "world"} assert json_body is None json_body_extras, data_body_extras = get_request_body( - json=None, data={"goodbye": "world"}, request_options=get_request_options(), omit=None + json=None, + data={"goodbye": "world"}, + request_options=get_request_options(), + omit=None, ) assert data_body_extras == {"goodbye": "world", "see you": "later"} @@ -35,7 +45,9 @@ def test_get_files_request_body() -> None: def test_get_none_request_body() -> None: - json_body, data_body = get_request_body(json=None, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data=None, request_options=None, omit=None + ) assert data_body is None assert json_body is None diff --git a/seed/python-sdk/optional/tests/utils/test_query_encoding.py b/seed/python-sdk/optional/tests/utils/test_query_encoding.py index 247e1551b46..fbc8f402167 100644 --- a/seed/python-sdk/optional/tests/utils/test_query_encoding.py +++ b/seed/python-sdk/optional/tests/utils/test_query_encoding.py @@ -4,9 +4,15 @@ def test_query_encoding() -> None: - assert encode_query({"hello world": "hello world"}) == {"hello world": "hello world"} - assert encode_query({"hello_world": {"hello": "world"}}) == {"hello_world[hello]": "world"} - assert encode_query({"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"}) == { + assert encode_query({"hello world": "hello world"}) == { + "hello world": "hello world" + } + assert encode_query({"hello_world": {"hello": "world"}}) == { + "hello_world[hello]": "world" + } + assert encode_query( + {"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"} + ) == { "hello_world[hello][world]": "today", "hello_world[test]": "this", "hi": "there", diff --git a/seed/python-sdk/optional/tests/utils/test_serialization.py b/seed/python-sdk/optional/tests/utils/test_serialization.py index 58b1ed66e6d..5ca956916dd 100644 --- a/seed/python-sdk/optional/tests/utils/test_serialization.py +++ b/seed/python-sdk/optional/tests/utils/test_serialization.py @@ -1,10 +1,12 @@ # This file was auto-generated by Fern from our API Definition. -from typing import Any, List +from typing import List, Any -from seed.core.serialization import convert_and_respect_annotation_metadata +from seed.core.serialization import ( + convert_and_respect_annotation_metadata, +) +from .assets.models import ShapeParams, ObjectWithOptionalFieldParams -from .assets.models import ObjectWithOptionalFieldParams, ShapeParams UNION_TEST: ShapeParams = {"radius_measurement": 1.0, "shape_type": "circle", "id": "1"} UNION_TEST_CONVERTED = {"shapeType": "circle", "radiusMeasurement": 1.0, "id": "1"} @@ -18,20 +20,54 @@ def test_convert_and_respect_annotation_metadata() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) - assert converted == {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"} + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) + assert converted == { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + } def test_convert_and_respect_annotation_metadata_in_list() -> None: data: List[ObjectWithOptionalFieldParams] = [ - {"string": "string", "long_": 12345, "bool_": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long_": 67890, "list_": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long_": 12345, + "bool_": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long_": 67890, + "list_": [], + "literal": "lit_one", + "any": "any", + }, ] - converted = convert_and_respect_annotation_metadata(object_=data, annotation=List[ObjectWithOptionalFieldParams]) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=List[ObjectWithOptionalFieldParams] + ) assert converted == [ - {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long": 67890, "list": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long": 67890, + "list": [], + "literal": "lit_one", + "any": "any", + }, ] @@ -43,7 +79,9 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) assert converted == { "string": "string", @@ -55,12 +93,16 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: def test_convert_and_respect_annotation_metadata_in_union() -> None: - converted = convert_and_respect_annotation_metadata(object_=UNION_TEST, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=UNION_TEST, annotation=ShapeParams + ) assert converted == UNION_TEST_CONVERTED def test_convert_and_respect_annotation_metadata_with_empty_object() -> None: data: Any = {} - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ShapeParams + ) assert converted == data diff --git a/seed/python-sdk/package-yml/pyproject.toml b/seed/python-sdk/package-yml/pyproject.toml index f135aec8eae..5c75a3c3784 100644 --- a/seed/python-sdk/package-yml/pyproject.toml +++ b/seed/python-sdk/package-yml/pyproject.toml @@ -43,6 +43,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/python-sdk/package-yml/src/seed/__init__.py b/seed/python-sdk/package-yml/src/seed/__init__.py index bb13feb1938..b2e344a6201 100644 --- a/seed/python-sdk/package-yml/src/seed/__init__.py +++ b/seed/python-sdk/package-yml/src/seed/__init__.py @@ -5,4 +5,10 @@ from .client import AsyncSeedPackageYml, SeedPackageYml from .version import __version__ -__all__ = ["AsyncSeedPackageYml", "EchoRequest", "SeedPackageYml", "__version__", "service"] +__all__ = [ + "AsyncSeedPackageYml", + "EchoRequest", + "SeedPackageYml", + "__version__", + "service", +] diff --git a/seed/python-sdk/package-yml/src/seed/client.py b/seed/python-sdk/package-yml/src/seed/client.py index 3b6d7474bc4..ab89e7bb287 100644 --- a/seed/python-sdk/package-yml/src/seed/client.py +++ b/seed/python-sdk/package-yml/src/seed/client.py @@ -1,16 +1,16 @@ # This file was auto-generated by Fern from our API Definition. import typing -from json.decoder import JSONDecodeError - import httpx - -from .core.api_error import ApiError -from .core.client_wrapper import AsyncClientWrapper, SyncClientWrapper +from .core.client_wrapper import SyncClientWrapper +from .service.client import ServiceClient +from .core.request_options import RequestOptions from .core.jsonable_encoder import jsonable_encoder from .core.pydantic_utilities import parse_obj_as -from .core.request_options import RequestOptions -from .service.client import AsyncServiceClient, ServiceClient +from json.decoder import JSONDecodeError +from .core.api_error import ApiError +from .core.client_wrapper import AsyncClientWrapper +from .service.client import AsyncServiceClient # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -51,19 +51,30 @@ def __init__( follow_redirects: typing.Optional[bool] = True, httpx_client: typing.Optional[httpx.Client] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = SyncClientWrapper( base_url=base_url, httpx_client=httpx_client if httpx_client is not None - else httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.Client( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.Client(timeout=_defaulted_timeout), timeout=_defaulted_timeout, ) self.service = ServiceClient(client_wrapper=self._client_wrapper) - def echo(self, id: str, *, name: str, size: int, request_options: typing.Optional[RequestOptions] = None) -> str: + def echo( + self, + id: str, + *, + name: str, + size: int, + request_options: typing.Optional[RequestOptions] = None, + ) -> str: """ Parameters ---------- @@ -96,13 +107,18 @@ def echo(self, id: str, *, name: str, size: int, request_options: typing.Optiona _response = self._client_wrapper.httpx_client.request( f"{jsonable_encoder(id)}/", method="POST", - json={"name": name, "size": size}, + json={ + "name": name, + "size": size, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -144,12 +160,16 @@ def __init__( follow_redirects: typing.Optional[bool] = True, httpx_client: typing.Optional[httpx.AsyncClient] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = AsyncClientWrapper( base_url=base_url, httpx_client=httpx_client if httpx_client is not None - else httpx.AsyncClient(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.AsyncClient( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.AsyncClient(timeout=_defaulted_timeout), timeout=_defaulted_timeout, @@ -157,7 +177,12 @@ def __init__( self.service = AsyncServiceClient(client_wrapper=self._client_wrapper) async def echo( - self, id: str, *, name: str, size: int, request_options: typing.Optional[RequestOptions] = None + self, + id: str, + *, + name: str, + size: int, + request_options: typing.Optional[RequestOptions] = None, ) -> str: """ Parameters @@ -199,13 +224,18 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( f"{jsonable_encoder(id)}/", method="POST", - json={"name": name, "size": size}, + json={ + "name": name, + "size": size, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/package-yml/src/seed/core/api_error.py b/seed/python-sdk/package-yml/src/seed/core/api_error.py index 2e9fc5431cd..da734b58068 100644 --- a/seed/python-sdk/package-yml/src/seed/core/api_error.py +++ b/seed/python-sdk/package-yml/src/seed/core/api_error.py @@ -7,7 +7,9 @@ class ApiError(Exception): status_code: typing.Optional[int] body: typing.Any - def __init__(self, *, status_code: typing.Optional[int] = None, body: typing.Any = None): + def __init__( + self, *, status_code: typing.Optional[int] = None, body: typing.Any = None + ): self.status_code = status_code self.body = body diff --git a/seed/python-sdk/package-yml/src/seed/core/client_wrapper.py b/seed/python-sdk/package-yml/src/seed/core/client_wrapper.py index 9e295db20a9..f3c92679ef1 100644 --- a/seed/python-sdk/package-yml/src/seed/core/client_wrapper.py +++ b/seed/python-sdk/package-yml/src/seed/core/client_wrapper.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .http_client import AsyncHttpClient, HttpClient +from .http_client import HttpClient +from .http_client import AsyncHttpClient class BaseClientWrapper: @@ -28,7 +27,13 @@ def get_timeout(self) -> typing.Optional[float]: class SyncClientWrapper(BaseClientWrapper): - def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, httpx_client: httpx.Client): + def __init__( + self, + *, + base_url: str, + timeout: typing.Optional[float] = None, + httpx_client: httpx.Client, + ): super().__init__(base_url=base_url, timeout=timeout) self.httpx_client = HttpClient( httpx_client=httpx_client, @@ -39,7 +44,13 @@ def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, htt class AsyncClientWrapper(BaseClientWrapper): - def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, httpx_client: httpx.AsyncClient): + def __init__( + self, + *, + base_url: str, + timeout: typing.Optional[float] = None, + httpx_client: httpx.AsyncClient, + ): super().__init__(base_url=base_url, timeout=timeout) self.httpx_client = AsyncHttpClient( httpx_client=httpx_client, diff --git a/seed/python-sdk/package-yml/src/seed/core/datetime_utils.py b/seed/python-sdk/package-yml/src/seed/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/python-sdk/package-yml/src/seed/core/datetime_utils.py +++ b/seed/python-sdk/package-yml/src/seed/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/python-sdk/package-yml/src/seed/core/file.py b/seed/python-sdk/package-yml/src/seed/core/file.py index cb0d40bbbf3..6e0f92bfcb1 100644 --- a/seed/python-sdk/package-yml/src/seed/core/file.py +++ b/seed/python-sdk/package-yml/src/seed/core/file.py @@ -13,12 +13,17 @@ # (filename, file (or bytes), content_type) typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str]], # (filename, file (or bytes), content_type, headers) - typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str], typing.Mapping[str, str]], + typing.Tuple[ + typing.Optional[str], + FileContent, + typing.Optional[str], + typing.Mapping[str, str], + ], ] def convert_file_dict_to_httpx_tuples( - d: typing.Dict[str, typing.Union[File, typing.List[File]]] + d: typing.Dict[str, typing.Union[File, typing.List[File]]], ) -> typing.List[typing.Tuple[str, File]]: """ The format we use is a list of tuples, where the first element is the diff --git a/seed/python-sdk/package-yml/src/seed/core/http_client.py b/seed/python-sdk/package-yml/src/seed/core/http_client.py index 9333d8a7f15..091f71bc185 100644 --- a/seed/python-sdk/package-yml/src/seed/core/http_client.py +++ b/seed/python-sdk/package-yml/src/seed/core/http_client.py @@ -77,7 +77,9 @@ def _retry_timeout(response: httpx.Response, retries: int) -> float: return retry_after # Apply exponential backoff, capped at MAX_RETRY_DELAY_SECONDS. - retry_delay = min(INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS) + retry_delay = min( + INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS + ) # Add a randomness / jitter to the retry delay to avoid overwhelming the server with retries. timeout = retry_delay * (1 - 0.25 * random()) @@ -90,7 +92,8 @@ def _should_retry(response: httpx.Response) -> bool: def remove_omit_from_dict( - original: typing.Dict[str, typing.Optional[typing.Any]], omit: typing.Optional[typing.Any] + original: typing.Dict[str, typing.Optional[typing.Any]], + omit: typing.Optional[typing.Any], ) -> typing.Dict[str, typing.Any]: if omit is None: return original @@ -108,7 +111,8 @@ def maybe_filter_request_body( ) -> typing.Optional[typing.Any]: if data is None: return ( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else None ) @@ -118,7 +122,8 @@ def maybe_filter_request_body( data_content = { **(jsonable_encoder(remove_omit_from_dict(data, omit))), # type: ignore **( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else {} ), @@ -162,7 +167,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url def request( @@ -174,8 +181,12 @@ def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -184,11 +195,14 @@ def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) response = self.httpx_client.request( method=method, @@ -198,7 +212,11 @@ def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -209,7 +227,10 @@ def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -222,11 +243,15 @@ def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: time.sleep(_retry_timeout(response=response, retries=retries)) @@ -256,8 +281,12 @@ def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -266,11 +295,14 @@ def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) with self.httpx_client.stream( method=method, @@ -280,7 +312,11 @@ def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -291,7 +327,9 @@ def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -304,7 +342,9 @@ def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream @@ -327,7 +367,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url async def request( @@ -339,8 +381,12 @@ async def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -349,11 +395,14 @@ async def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) # Add the input to each of these and do None-safety checks response = await self.httpx_client.request( @@ -364,7 +413,11 @@ async def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -375,7 +428,10 @@ async def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -388,11 +444,15 @@ async def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: await asyncio.sleep(_retry_timeout(response=response, retries=retries)) @@ -421,8 +481,12 @@ async def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -431,11 +495,14 @@ async def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) async with self.httpx_client.stream( method=method, @@ -445,7 +512,11 @@ async def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -456,7 +527,9 @@ async def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -469,7 +542,9 @@ async def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream diff --git a/seed/python-sdk/package-yml/src/seed/core/jsonable_encoder.py b/seed/python-sdk/package-yml/src/seed/core/jsonable_encoder.py index d3fd328fd41..12a8b52fc22 100644 --- a/seed/python-sdk/package-yml/src/seed/core/jsonable_encoder.py +++ b/seed/python-sdk/package-yml/src/seed/core/jsonable_encoder.py @@ -19,13 +19,19 @@ import pydantic from .datetime_utils import serialize_datetime -from .pydantic_utilities import IS_PYDANTIC_V2, encode_by_type, to_jsonable_with_fallback +from .pydantic_utilities import ( + IS_PYDANTIC_V2, + encode_by_type, + to_jsonable_with_fallback, +) SetIntStr = Set[Union[int, str]] DictIntStrAny = Dict[Union[int, str], Any] -def jsonable_encoder(obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None) -> Any: +def jsonable_encoder( + obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None +) -> Any: custom_encoder = custom_encoder or {} if custom_encoder: if type(obj) in custom_encoder: diff --git a/seed/python-sdk/package-yml/src/seed/core/pydantic_utilities.py b/seed/python-sdk/package-yml/src/seed/core/pydantic_utilities.py index 170a563d6eb..c63935c32a2 100644 --- a/seed/python-sdk/package-yml/src/seed/core/pydantic_utilities.py +++ b/seed/python-sdk/package-yml/src/seed/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) # type: ignore # Pydantic v1 diff --git a/seed/python-sdk/package-yml/src/seed/core/query_encoder.py b/seed/python-sdk/package-yml/src/seed/core/query_encoder.py index 24076d72ee9..7cb98f52cd7 100644 --- a/seed/python-sdk/package-yml/src/seed/core/query_encoder.py +++ b/seed/python-sdk/package-yml/src/seed/core/query_encoder.py @@ -7,7 +7,9 @@ # Flattens dicts to be of the form {"key[subkey][subkey2]": value} where value is not a dict -def traverse_query_dict(dict_flat: Dict[str, Any], key_prefix: Optional[str] = None) -> Dict[str, Any]: +def traverse_query_dict( + dict_flat: Dict[str, Any], key_prefix: Optional[str] = None +) -> Dict[str, Any]: result = {} for k, v in dict_flat.items(): key = f"{key_prefix}[{k}]" if key_prefix is not None else k @@ -30,4 +32,8 @@ def single_query_encoder(query_key: str, query_value: Any) -> Dict[str, Any]: def encode_query(query: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: - return dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) if query is not None else None + return ( + dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) + if query is not None + else None + ) diff --git a/seed/python-sdk/package-yml/src/seed/core/serialization.py b/seed/python-sdk/package-yml/src/seed/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/python-sdk/package-yml/src/seed/core/serialization.py +++ b/seed/python-sdk/package-yml/src/seed/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/python-sdk/package-yml/src/seed/service/client.py b/seed/python-sdk/package-yml/src/seed/service/client.py index f5dd2bdd28f..f960b712eea 100644 --- a/seed/python-sdk/package-yml/src/seed/service/client.py +++ b/seed/python-sdk/package-yml/src/seed/service/client.py @@ -1,19 +1,25 @@ # This file was auto-generated by Fern from our API Definition. +from ..core.client_wrapper import SyncClientWrapper import typing +from ..core.request_options import RequestOptions +from ..core.jsonable_encoder import jsonable_encoder from json.decoder import JSONDecodeError - from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.jsonable_encoder import jsonable_encoder -from ..core.request_options import RequestOptions +from ..core.client_wrapper import AsyncClientWrapper class ServiceClient: def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper - def nop(self, id: str, nested_id: str, *, request_options: typing.Optional[RequestOptions] = None) -> None: + def nop( + self, + id: str, + nested_id: str, + *, + request_options: typing.Optional[RequestOptions] = None, + ) -> None: """ Parameters ---------- @@ -41,7 +47,9 @@ def nop(self, id: str, nested_id: str, *, request_options: typing.Optional[Reque ) """ _response = self._client_wrapper.httpx_client.request( - f"{jsonable_encoder(id)}//{jsonable_encoder(nested_id)}", method="GET", request_options=request_options + f"{jsonable_encoder(id)}//{jsonable_encoder(nested_id)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: @@ -56,7 +64,13 @@ class AsyncServiceClient: def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper - async def nop(self, id: str, nested_id: str, *, request_options: typing.Optional[RequestOptions] = None) -> None: + async def nop( + self, + id: str, + nested_id: str, + *, + request_options: typing.Optional[RequestOptions] = None, + ) -> None: """ Parameters ---------- @@ -92,7 +106,9 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - f"{jsonable_encoder(id)}//{jsonable_encoder(nested_id)}", method="GET", request_options=request_options + f"{jsonable_encoder(id)}//{jsonable_encoder(nested_id)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: diff --git a/seed/python-sdk/package-yml/src/seed/types/echo_request.py b/seed/python-sdk/package-yml/src/seed/types/echo_request.py index a720a244a1d..b7ad537784f 100644 --- a/seed/python-sdk/package-yml/src/seed/types/echo_request.py +++ b/seed/python-sdk/package-yml/src/seed/types/echo_request.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from ..core.pydantic_utilities import UniversalBaseModel +from ..core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class EchoRequest(UniversalBaseModel): name: str size: int if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/package-yml/src/seed/version.py b/seed/python-sdk/package-yml/src/seed/version.py index e44412630b0..eafaab79b73 100644 --- a/seed/python-sdk/package-yml/src/seed/version.py +++ b/seed/python-sdk/package-yml/src/seed/version.py @@ -1,4 +1,3 @@ - from importlib import metadata __version__ = metadata.version("fern_package-yml") diff --git a/seed/python-sdk/package-yml/tests/conftest.py b/seed/python-sdk/package-yml/tests/conftest.py index d30cf51071d..c704f98923e 100644 --- a/seed/python-sdk/package-yml/tests/conftest.py +++ b/seed/python-sdk/package-yml/tests/conftest.py @@ -1,9 +1,9 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedPackageYml import os - import pytest -from seed import AsyncSeedPackageYml, SeedPackageYml +from seed import AsyncSeedPackageYml @pytest.fixture diff --git a/seed/python-sdk/package-yml/tests/custom/test_client.py b/seed/python-sdk/package-yml/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/python-sdk/package-yml/tests/custom/test_client.py +++ b/seed/python-sdk/package-yml/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/python-sdk/package-yml/tests/test_root.py b/seed/python-sdk/package-yml/tests/test_root.py index cf12e85c586..b0a9c23e817 100644 --- a/seed/python-sdk/package-yml/tests/test_root.py +++ b/seed/python-sdk/package-yml/tests/test_root.py @@ -1,9 +1,8 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedPackageYml +from seed import AsyncSeedPackageYml import typing - -from seed import AsyncSeedPackageYml, SeedPackageYml - from .utilities import validate_response @@ -13,5 +12,7 @@ async def test_echo(client: SeedPackageYml, async_client: AsyncSeedPackageYml) - response = client.echo(id="id-ksfd9c1", name="Hello world!", size=20) validate_response(response, expected_response, expected_types) - async_response = await async_client.echo(id="id-ksfd9c1", name="Hello world!", size=20) + async_response = await async_client.echo( + id="id-ksfd9c1", name="Hello world!", size=20 + ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/package-yml/tests/test_service.py b/seed/python-sdk/package-yml/tests/test_service.py index c7fc5676a3e..bc5903ff1ae 100644 --- a/seed/python-sdk/package-yml/tests/test_service.py +++ b/seed/python-sdk/package-yml/tests/test_service.py @@ -1,10 +1,13 @@ # This file was auto-generated by Fern from our API Definition. -from seed import AsyncSeedPackageYml, SeedPackageYml +from seed import SeedPackageYml +from seed import AsyncSeedPackageYml async def test_nop(client: SeedPackageYml, async_client: AsyncSeedPackageYml) -> None: # Type ignore to avoid mypy complaining about the function not being meant to return a value assert client.service.nop(id="id-a2ijs82", nested_id="id-219xca8") is None # type: ignore[func-returns-value] - assert await async_client.service.nop(id="id-a2ijs82", nested_id="id-219xca8") is None # type: ignore[func-returns-value] + assert ( + await async_client.service.nop(id="id-a2ijs82", nested_id="id-219xca8") is None + ) # type: ignore[func-returns-value] diff --git a/seed/python-sdk/package-yml/tests/utilities.py b/seed/python-sdk/package-yml/tests/utilities.py index 13da208eb3a..e8f4472564c 100644 --- a/seed/python-sdk/package-yml/tests/utilities.py +++ b/seed/python-sdk/package-yml/tests/utilities.py @@ -3,11 +3,14 @@ import typing import uuid -import pydantic from dateutil import parser +import pydantic + -def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> typing.Any: +def cast_field( + json_expectation: typing.Any, type_expectation: typing.Any +) -> typing.Any: # Cast these specific types which come through as string and expect our # models to cast to the correct type. if type_expectation == "uuid": @@ -25,7 +28,9 @@ def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> ty return json_expectation -def validate_field(response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any) -> None: +def validate_field( + response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectation == "no_validate": return @@ -44,7 +49,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(entry_expectation, dict): is_container_of_complex_type = True validate_response( - response=response[idx], json_expectation=ex, type_expectations=entry_expectation + response=response[idx], + json_expectation=ex, + type_expectations=entry_expectation, ) else: cast_json_expectation.append(cast_field(ex, entry_expectation)) @@ -56,7 +63,10 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # if any of the values of the set have a type_expectation of a dict, we're assuming it's a pydantic # model and keeping it a list. if container_expectation != "set" or not any( - map(lambda value: isinstance(value, dict), list(contents_expectation.values())) + map( + lambda value: isinstance(value, dict), + list(contents_expectation.values()), + ) ): json_expectation = cast_field(json_expectation, container_expectation) elif isinstance(type_expectation, tuple): @@ -65,9 +75,15 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(contents_expectation, dict): json_expectation = { cast_field( - key, contents_expectation.get(idx)[0] if contents_expectation.get(idx) is not None else None # type: ignore + key, + contents_expectation.get(idx)[0] + if contents_expectation.get(idx) is not None + else None, # type: ignore ): cast_field( - value, contents_expectation.get(idx)[1] if contents_expectation.get(idx) is not None else None # type: ignore + value, + contents_expectation.get(idx)[1] + if contents_expectation.get(idx) is not None + else None, # type: ignore ) for idx, (key, value) in enumerate(json_expectation.items()) } @@ -86,7 +102,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # Arg type_expectations is a deeply nested structure that matches the response, but with the values replaced with the expected types -def validate_response(response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any) -> None: +def validate_response( + response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectations == "no_validate": return @@ -96,11 +114,17 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e and not isinstance(response, dict) and not issubclass(type(response), pydantic.BaseModel) ): - validate_field(response=response, json_expectation=json_expectation, type_expectation=type_expectations) + validate_field( + response=response, + json_expectation=json_expectation, + type_expectation=type_expectations, + ) return if isinstance(response, list): - assert len(response) == len(json_expectation), "Length mismatch, expected: {0}, Actual: {1}".format( + assert len(response) == len( + json_expectation + ), "Length mismatch, expected: {0}, Actual: {1}".format( len(response), len(json_expectation) ) content_expectation = type_expectations @@ -108,7 +132,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e content_expectation = type_expectations[1] for idx, item in enumerate(response): validate_response( - response=item, json_expectation=json_expectation[idx], type_expectations=content_expectation[idx] + response=item, + json_expectation=json_expectation[idx], + type_expectations=content_expectation[idx], ) else: response_json = response @@ -116,7 +142,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e response_json = response.dict(by_alias=True) for key, value in json_expectation.items(): - assert key in response_json, "Field {0} not found within the response object: {1}".format( + assert ( + key in response_json + ), "Field {0} not found within the response object: {1}".format( key, response_json ) @@ -128,11 +156,19 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e # Otherwise, we're just validating a single field that's a pydantic model. if isinstance(value, dict) and not isinstance(type_expectation, tuple): validate_response( - response=response_json[key], json_expectation=value, type_expectations=type_expectation + response=response_json[key], + json_expectation=value, + type_expectations=type_expectation, ) else: - validate_field(response=response_json[key], json_expectation=value, type_expectation=type_expectation) + validate_field( + response=response_json[key], + json_expectation=value, + type_expectation=type_expectation, + ) # Ensure there are no additional fields here either del response_json[key] - assert len(response_json) == 0, "Additional fields found, expected None: {0}".format(response_json) + assert ( + len(response_json) == 0 + ), "Additional fields found, expected None: {0}".format(response_json) diff --git a/seed/python-sdk/package-yml/tests/utils/assets/models/__init__.py b/seed/python-sdk/package-yml/tests/utils/assets/models/__init__.py index 2cf01263529..3a1c852e71e 100644 --- a/seed/python-sdk/package-yml/tests/utils/assets/models/__init__.py +++ b/seed/python-sdk/package-yml/tests/utils/assets/models/__init__.py @@ -5,7 +5,7 @@ from .circle import CircleParams from .object_with_defaults import ObjectWithDefaultsParams from .object_with_optional_field import ObjectWithOptionalFieldParams -from .shape import Shape_CircleParams, Shape_SquareParams, ShapeParams +from .shape import ShapeParams, Shape_CircleParams, Shape_SquareParams from .square import SquareParams from .undiscriminated_shape import UndiscriminatedShapeParams diff --git a/seed/python-sdk/package-yml/tests/utils/assets/models/circle.py b/seed/python-sdk/package-yml/tests/utils/assets/models/circle.py index af7a1bf8a8e..253f12d38b3 100644 --- a/seed/python-sdk/package-yml/tests/utils/assets/models/circle.py +++ b/seed/python-sdk/package-yml/tests/utils/assets/models/circle.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class CircleParams(typing_extensions.TypedDict): - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] diff --git a/seed/python-sdk/package-yml/tests/utils/assets/models/object_with_optional_field.py b/seed/python-sdk/package-yml/tests/utils/assets/models/object_with_optional_field.py index 3ad93d5f305..ebe7dc80547 100644 --- a/seed/python-sdk/package-yml/tests/utils/assets/models/object_with_optional_field.py +++ b/seed/python-sdk/package-yml/tests/utils/assets/models/object_with_optional_field.py @@ -7,8 +7,8 @@ import uuid import typing_extensions -from seed.core.serialization import FieldMetadata +from seed.core.serialization import FieldMetadata from .color import Color from .shape import ShapeParams from .undiscriminated_shape import UndiscriminatedShapeParams @@ -18,16 +18,30 @@ class ObjectWithOptionalFieldParams(typing_extensions.TypedDict): literal: typing.Literal["lit_one"] string: typing_extensions.NotRequired[str] integer: typing_extensions.NotRequired[int] - long_: typing_extensions.NotRequired[typing_extensions.Annotated[int, FieldMetadata(alias="long")]] + long_: typing_extensions.NotRequired[ + typing_extensions.Annotated[int, FieldMetadata(alias="long")] + ] double: typing_extensions.NotRequired[float] - bool_: typing_extensions.NotRequired[typing_extensions.Annotated[bool, FieldMetadata(alias="bool")]] + bool_: typing_extensions.NotRequired[ + typing_extensions.Annotated[bool, FieldMetadata(alias="bool")] + ] datetime: typing_extensions.NotRequired[dt.datetime] date: typing_extensions.NotRequired[dt.date] - uuid_: typing_extensions.NotRequired[typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")]] - base_64: typing_extensions.NotRequired[typing_extensions.Annotated[str, FieldMetadata(alias="base64")]] - list_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")]] - set_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")]] - map_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")]] + uuid_: typing_extensions.NotRequired[ + typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")] + ] + base_64: typing_extensions.NotRequired[ + typing_extensions.Annotated[str, FieldMetadata(alias="base64")] + ] + list_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")] + ] + set_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")] + ] + map_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")] + ] enum: typing_extensions.NotRequired[Color] union: typing_extensions.NotRequired[ShapeParams] second_union: typing_extensions.NotRequired[ShapeParams] diff --git a/seed/python-sdk/package-yml/tests/utils/assets/models/shape.py b/seed/python-sdk/package-yml/tests/utils/assets/models/shape.py index 2c33c877951..816ffc51bdc 100644 --- a/seed/python-sdk/package-yml/tests/utils/assets/models/shape.py +++ b/seed/python-sdk/package-yml/tests/utils/assets/models/shape.py @@ -7,6 +7,7 @@ import typing import typing_extensions + from seed.core.serialization import FieldMetadata @@ -15,13 +16,21 @@ class Base(typing_extensions.TypedDict): class Shape_CircleParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["circle"], FieldMetadata(alias="shapeType")] - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["circle"], FieldMetadata(alias="shapeType") + ] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] class Shape_SquareParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["square"], FieldMetadata(alias="shapeType")] - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["square"], FieldMetadata(alias="shapeType") + ] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] ShapeParams = typing.Union[Shape_CircleParams, Shape_SquareParams] diff --git a/seed/python-sdk/package-yml/tests/utils/assets/models/square.py b/seed/python-sdk/package-yml/tests/utils/assets/models/square.py index b9b7dd319bc..bcf08a723c5 100644 --- a/seed/python-sdk/package-yml/tests/utils/assets/models/square.py +++ b/seed/python-sdk/package-yml/tests/utils/assets/models/square.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class SquareParams(typing_extensions.TypedDict): - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] diff --git a/seed/python-sdk/package-yml/tests/utils/test_http_client.py b/seed/python-sdk/package-yml/tests/utils/test_http_client.py index edd11ca7afb..f5a874a75f3 100644 --- a/seed/python-sdk/package-yml/tests/utils/test_http_client.py +++ b/seed/python-sdk/package-yml/tests/utils/test_http_client.py @@ -9,12 +9,17 @@ def get_request_options() -> RequestOptions: def test_get_json_request_body() -> None: - json_body, data_body = get_request_body(json={"hello": "world"}, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json={"hello": "world"}, data=None, request_options=None, omit=None + ) assert json_body == {"hello": "world"} assert data_body is None json_body_extras, data_body_extras = get_request_body( - json={"goodbye": "world"}, data=None, request_options=get_request_options(), omit=None + json={"goodbye": "world"}, + data=None, + request_options=get_request_options(), + omit=None, ) assert json_body_extras == {"goodbye": "world", "see you": "later"} @@ -22,12 +27,17 @@ def test_get_json_request_body() -> None: def test_get_files_request_body() -> None: - json_body, data_body = get_request_body(json=None, data={"hello": "world"}, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data={"hello": "world"}, request_options=None, omit=None + ) assert data_body == {"hello": "world"} assert json_body is None json_body_extras, data_body_extras = get_request_body( - json=None, data={"goodbye": "world"}, request_options=get_request_options(), omit=None + json=None, + data={"goodbye": "world"}, + request_options=get_request_options(), + omit=None, ) assert data_body_extras == {"goodbye": "world", "see you": "later"} @@ -35,7 +45,9 @@ def test_get_files_request_body() -> None: def test_get_none_request_body() -> None: - json_body, data_body = get_request_body(json=None, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data=None, request_options=None, omit=None + ) assert data_body is None assert json_body is None diff --git a/seed/python-sdk/package-yml/tests/utils/test_query_encoding.py b/seed/python-sdk/package-yml/tests/utils/test_query_encoding.py index 247e1551b46..fbc8f402167 100644 --- a/seed/python-sdk/package-yml/tests/utils/test_query_encoding.py +++ b/seed/python-sdk/package-yml/tests/utils/test_query_encoding.py @@ -4,9 +4,15 @@ def test_query_encoding() -> None: - assert encode_query({"hello world": "hello world"}) == {"hello world": "hello world"} - assert encode_query({"hello_world": {"hello": "world"}}) == {"hello_world[hello]": "world"} - assert encode_query({"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"}) == { + assert encode_query({"hello world": "hello world"}) == { + "hello world": "hello world" + } + assert encode_query({"hello_world": {"hello": "world"}}) == { + "hello_world[hello]": "world" + } + assert encode_query( + {"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"} + ) == { "hello_world[hello][world]": "today", "hello_world[test]": "this", "hi": "there", diff --git a/seed/python-sdk/package-yml/tests/utils/test_serialization.py b/seed/python-sdk/package-yml/tests/utils/test_serialization.py index 58b1ed66e6d..5ca956916dd 100644 --- a/seed/python-sdk/package-yml/tests/utils/test_serialization.py +++ b/seed/python-sdk/package-yml/tests/utils/test_serialization.py @@ -1,10 +1,12 @@ # This file was auto-generated by Fern from our API Definition. -from typing import Any, List +from typing import List, Any -from seed.core.serialization import convert_and_respect_annotation_metadata +from seed.core.serialization import ( + convert_and_respect_annotation_metadata, +) +from .assets.models import ShapeParams, ObjectWithOptionalFieldParams -from .assets.models import ObjectWithOptionalFieldParams, ShapeParams UNION_TEST: ShapeParams = {"radius_measurement": 1.0, "shape_type": "circle", "id": "1"} UNION_TEST_CONVERTED = {"shapeType": "circle", "radiusMeasurement": 1.0, "id": "1"} @@ -18,20 +20,54 @@ def test_convert_and_respect_annotation_metadata() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) - assert converted == {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"} + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) + assert converted == { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + } def test_convert_and_respect_annotation_metadata_in_list() -> None: data: List[ObjectWithOptionalFieldParams] = [ - {"string": "string", "long_": 12345, "bool_": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long_": 67890, "list_": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long_": 12345, + "bool_": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long_": 67890, + "list_": [], + "literal": "lit_one", + "any": "any", + }, ] - converted = convert_and_respect_annotation_metadata(object_=data, annotation=List[ObjectWithOptionalFieldParams]) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=List[ObjectWithOptionalFieldParams] + ) assert converted == [ - {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long": 67890, "list": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long": 67890, + "list": [], + "literal": "lit_one", + "any": "any", + }, ] @@ -43,7 +79,9 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) assert converted == { "string": "string", @@ -55,12 +93,16 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: def test_convert_and_respect_annotation_metadata_in_union() -> None: - converted = convert_and_respect_annotation_metadata(object_=UNION_TEST, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=UNION_TEST, annotation=ShapeParams + ) assert converted == UNION_TEST_CONVERTED def test_convert_and_respect_annotation_metadata_with_empty_object() -> None: data: Any = {} - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ShapeParams + ) assert converted == data diff --git a/seed/python-sdk/pagination/pyproject.toml b/seed/python-sdk/pagination/pyproject.toml index 79a4d2cd55d..2363ba83324 100644 --- a/seed/python-sdk/pagination/pyproject.toml +++ b/seed/python-sdk/pagination/pyproject.toml @@ -43,6 +43,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/python-sdk/pagination/src/seed/client.py b/seed/python-sdk/pagination/src/seed/client.py index 9ed376f1e43..f006d04aac8 100644 --- a/seed/python-sdk/pagination/src/seed/client.py +++ b/seed/python-sdk/pagination/src/seed/client.py @@ -1,11 +1,11 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from .users.client import AsyncUsersClient, UsersClient +from .core.client_wrapper import SyncClientWrapper +from .users.client import UsersClient +from .core.client_wrapper import AsyncClientWrapper +from .users.client import AsyncUsersClient class SeedPagination: @@ -44,15 +44,19 @@ def __init__( token: typing.Optional[typing.Union[str, typing.Callable[[], str]]] = None, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.Client] = None + httpx_client: typing.Optional[httpx.Client] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = SyncClientWrapper( base_url=base_url, token=token, httpx_client=httpx_client if httpx_client is not None - else httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.Client( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.Client(timeout=_defaulted_timeout), timeout=_defaulted_timeout, @@ -96,15 +100,19 @@ def __init__( token: typing.Optional[typing.Union[str, typing.Callable[[], str]]] = None, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.AsyncClient] = None + httpx_client: typing.Optional[httpx.AsyncClient] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = AsyncClientWrapper( base_url=base_url, token=token, httpx_client=httpx_client if httpx_client is not None - else httpx.AsyncClient(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.AsyncClient( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.AsyncClient(timeout=_defaulted_timeout), timeout=_defaulted_timeout, diff --git a/seed/python-sdk/pagination/src/seed/core/api_error.py b/seed/python-sdk/pagination/src/seed/core/api_error.py index 2e9fc5431cd..da734b58068 100644 --- a/seed/python-sdk/pagination/src/seed/core/api_error.py +++ b/seed/python-sdk/pagination/src/seed/core/api_error.py @@ -7,7 +7,9 @@ class ApiError(Exception): status_code: typing.Optional[int] body: typing.Any - def __init__(self, *, status_code: typing.Optional[int] = None, body: typing.Any = None): + def __init__( + self, *, status_code: typing.Optional[int] = None, body: typing.Any = None + ): self.status_code = status_code self.body = body diff --git a/seed/python-sdk/pagination/src/seed/core/client_wrapper.py b/seed/python-sdk/pagination/src/seed/core/client_wrapper.py index 366b39cb21d..522221ef687 100644 --- a/seed/python-sdk/pagination/src/seed/core/client_wrapper.py +++ b/seed/python-sdk/pagination/src/seed/core/client_wrapper.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .http_client import AsyncHttpClient, HttpClient +from .http_client import HttpClient +from .http_client import AsyncHttpClient class BaseClientWrapper: diff --git a/seed/python-sdk/pagination/src/seed/core/datetime_utils.py b/seed/python-sdk/pagination/src/seed/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/python-sdk/pagination/src/seed/core/datetime_utils.py +++ b/seed/python-sdk/pagination/src/seed/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/python-sdk/pagination/src/seed/core/file.py b/seed/python-sdk/pagination/src/seed/core/file.py index cb0d40bbbf3..6e0f92bfcb1 100644 --- a/seed/python-sdk/pagination/src/seed/core/file.py +++ b/seed/python-sdk/pagination/src/seed/core/file.py @@ -13,12 +13,17 @@ # (filename, file (or bytes), content_type) typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str]], # (filename, file (or bytes), content_type, headers) - typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str], typing.Mapping[str, str]], + typing.Tuple[ + typing.Optional[str], + FileContent, + typing.Optional[str], + typing.Mapping[str, str], + ], ] def convert_file_dict_to_httpx_tuples( - d: typing.Dict[str, typing.Union[File, typing.List[File]]] + d: typing.Dict[str, typing.Union[File, typing.List[File]]], ) -> typing.List[typing.Tuple[str, File]]: """ The format we use is a list of tuples, where the first element is the diff --git a/seed/python-sdk/pagination/src/seed/core/http_client.py b/seed/python-sdk/pagination/src/seed/core/http_client.py index 9333d8a7f15..091f71bc185 100644 --- a/seed/python-sdk/pagination/src/seed/core/http_client.py +++ b/seed/python-sdk/pagination/src/seed/core/http_client.py @@ -77,7 +77,9 @@ def _retry_timeout(response: httpx.Response, retries: int) -> float: return retry_after # Apply exponential backoff, capped at MAX_RETRY_DELAY_SECONDS. - retry_delay = min(INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS) + retry_delay = min( + INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS + ) # Add a randomness / jitter to the retry delay to avoid overwhelming the server with retries. timeout = retry_delay * (1 - 0.25 * random()) @@ -90,7 +92,8 @@ def _should_retry(response: httpx.Response) -> bool: def remove_omit_from_dict( - original: typing.Dict[str, typing.Optional[typing.Any]], omit: typing.Optional[typing.Any] + original: typing.Dict[str, typing.Optional[typing.Any]], + omit: typing.Optional[typing.Any], ) -> typing.Dict[str, typing.Any]: if omit is None: return original @@ -108,7 +111,8 @@ def maybe_filter_request_body( ) -> typing.Optional[typing.Any]: if data is None: return ( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else None ) @@ -118,7 +122,8 @@ def maybe_filter_request_body( data_content = { **(jsonable_encoder(remove_omit_from_dict(data, omit))), # type: ignore **( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else {} ), @@ -162,7 +167,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url def request( @@ -174,8 +181,12 @@ def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -184,11 +195,14 @@ def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) response = self.httpx_client.request( method=method, @@ -198,7 +212,11 @@ def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -209,7 +227,10 @@ def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -222,11 +243,15 @@ def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: time.sleep(_retry_timeout(response=response, retries=retries)) @@ -256,8 +281,12 @@ def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -266,11 +295,14 @@ def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) with self.httpx_client.stream( method=method, @@ -280,7 +312,11 @@ def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -291,7 +327,9 @@ def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -304,7 +342,9 @@ def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream @@ -327,7 +367,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url async def request( @@ -339,8 +381,12 @@ async def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -349,11 +395,14 @@ async def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) # Add the input to each of these and do None-safety checks response = await self.httpx_client.request( @@ -364,7 +413,11 @@ async def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -375,7 +428,10 @@ async def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -388,11 +444,15 @@ async def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: await asyncio.sleep(_retry_timeout(response=response, retries=retries)) @@ -421,8 +481,12 @@ async def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -431,11 +495,14 @@ async def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) async with self.httpx_client.stream( method=method, @@ -445,7 +512,11 @@ async def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -456,7 +527,9 @@ async def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -469,7 +542,9 @@ async def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream diff --git a/seed/python-sdk/pagination/src/seed/core/jsonable_encoder.py b/seed/python-sdk/pagination/src/seed/core/jsonable_encoder.py index d3fd328fd41..12a8b52fc22 100644 --- a/seed/python-sdk/pagination/src/seed/core/jsonable_encoder.py +++ b/seed/python-sdk/pagination/src/seed/core/jsonable_encoder.py @@ -19,13 +19,19 @@ import pydantic from .datetime_utils import serialize_datetime -from .pydantic_utilities import IS_PYDANTIC_V2, encode_by_type, to_jsonable_with_fallback +from .pydantic_utilities import ( + IS_PYDANTIC_V2, + encode_by_type, + to_jsonable_with_fallback, +) SetIntStr = Set[Union[int, str]] DictIntStrAny = Dict[Union[int, str], Any] -def jsonable_encoder(obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None) -> Any: +def jsonable_encoder( + obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None +) -> Any: custom_encoder = custom_encoder or {} if custom_encoder: if type(obj) in custom_encoder: diff --git a/seed/python-sdk/pagination/src/seed/core/pagination.py b/seed/python-sdk/pagination/src/seed/core/pagination.py index 4a9e1ee550b..51a8d1fce57 100644 --- a/seed/python-sdk/pagination/src/seed/core/pagination.py +++ b/seed/python-sdk/pagination/src/seed/core/pagination.py @@ -2,9 +2,10 @@ import typing -import pydantic from typing_extensions import Self +import pydantic + # Generic to represent the underlying type of the results within a page T = typing.TypeVar("T") @@ -28,7 +29,9 @@ class SyncPage(BasePage[T], typing.Generic[T]): class AsyncPage(BasePage[T], typing.Generic[T]): - get_next: typing.Optional[typing.Callable[[], typing.Awaitable[typing.Optional[Self]]]] + get_next: typing.Optional[ + typing.Callable[[], typing.Awaitable[typing.Optional[Self]]] + ] # ---------------------------- diff --git a/seed/python-sdk/pagination/src/seed/core/pydantic_utilities.py b/seed/python-sdk/pagination/src/seed/core/pydantic_utilities.py index 170a563d6eb..c63935c32a2 100644 --- a/seed/python-sdk/pagination/src/seed/core/pydantic_utilities.py +++ b/seed/python-sdk/pagination/src/seed/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) # type: ignore # Pydantic v1 diff --git a/seed/python-sdk/pagination/src/seed/core/query_encoder.py b/seed/python-sdk/pagination/src/seed/core/query_encoder.py index 24076d72ee9..7cb98f52cd7 100644 --- a/seed/python-sdk/pagination/src/seed/core/query_encoder.py +++ b/seed/python-sdk/pagination/src/seed/core/query_encoder.py @@ -7,7 +7,9 @@ # Flattens dicts to be of the form {"key[subkey][subkey2]": value} where value is not a dict -def traverse_query_dict(dict_flat: Dict[str, Any], key_prefix: Optional[str] = None) -> Dict[str, Any]: +def traverse_query_dict( + dict_flat: Dict[str, Any], key_prefix: Optional[str] = None +) -> Dict[str, Any]: result = {} for k, v in dict_flat.items(): key = f"{key_prefix}[{k}]" if key_prefix is not None else k @@ -30,4 +32,8 @@ def single_query_encoder(query_key: str, query_value: Any) -> Dict[str, Any]: def encode_query(query: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: - return dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) if query is not None else None + return ( + dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) + if query is not None + else None + ) diff --git a/seed/python-sdk/pagination/src/seed/core/serialization.py b/seed/python-sdk/pagination/src/seed/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/python-sdk/pagination/src/seed/core/serialization.py +++ b/seed/python-sdk/pagination/src/seed/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/python-sdk/pagination/src/seed/types/username_cursor.py b/seed/python-sdk/pagination/src/seed/types/username_cursor.py index 46ee93b707f..99490db2512 100644 --- a/seed/python-sdk/pagination/src/seed/types/username_cursor.py +++ b/seed/python-sdk/pagination/src/seed/types/username_cursor.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from ..core.pydantic_utilities import UniversalBaseModel +from .username_page import UsernamePage +from ..core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .username_page import UsernamePage - class UsernameCursor(UniversalBaseModel): cursor: UsernamePage if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/pagination/src/seed/types/username_page.py b/seed/python-sdk/pagination/src/seed/types/username_page.py index e80153a6100..7a9505bece8 100644 --- a/seed/python-sdk/pagination/src/seed/types/username_page.py +++ b/seed/python-sdk/pagination/src/seed/types/username_page.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from ..core.pydantic_utilities import UniversalBaseModel import typing - +from ..core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class UsernamePage(UniversalBaseModel): after: typing.Optional[str] = None data: typing.List[str] if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/pagination/src/seed/users/client.py b/seed/python-sdk/pagination/src/seed/users/client.py index 75142f37962..328bd111e7f 100644 --- a/seed/python-sdk/pagination/src/seed/users/client.py +++ b/seed/python-sdk/pagination/src/seed/users/client.py @@ -1,23 +1,24 @@ # This file was auto-generated by Fern from our API Definition. import typing -import uuid +from ..core.client_wrapper import SyncClientWrapper +from .types.order import Order +from ..core.request_options import RequestOptions +from ..core.pagination import SyncPager +from .types.user import User +from .types.list_users_pagination_response import ListUsersPaginationResponse +from ..core.pydantic_utilities import parse_obj_as from json.decoder import JSONDecodeError - from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper +from .types.with_cursor import WithCursor +from .types.with_page import WithPage +import uuid from ..core.jsonable_encoder import jsonable_encoder -from ..core.pagination import AsyncPager, SyncPager -from ..core.pydantic_utilities import parse_obj_as -from ..core.request_options import RequestOptions -from ..types.username_cursor import UsernameCursor from .types.list_users_extended_response import ListUsersExtendedResponse -from .types.list_users_pagination_response import ListUsersPaginationResponse -from .types.order import Order -from .types.user import User +from ..types.username_cursor import UsernameCursor from .types.username_container import UsernameContainer -from .types.with_cursor import WithCursor -from .types.with_page import WithPage +from ..core.client_wrapper import AsyncClientWrapper +from ..core.pagination import AsyncPager # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -34,7 +35,7 @@ def list_with_cursor_pagination( per_page: typing.Optional[int] = None, order: typing.Optional[Order] = None, starting_after: typing.Optional[str] = None, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> SyncPager[User]: """ Parameters @@ -81,15 +82,28 @@ def list_with_cursor_pagination( _response = self._client_wrapper.httpx_client.request( "users", method="GET", - params={"page": page, "per_page": per_page, "order": order, "starting_after": starting_after}, + params={ + "page": page, + "per_page": per_page, + "order": order, + "starting_after": starting_after, + }, request_options=request_options, ) try: if 200 <= _response.status_code < 300: - _parsed_response = typing.cast(ListUsersPaginationResponse, parse_obj_as(type_=ListUsersPaginationResponse, object_=_response.json())) # type: ignore + _parsed_response = typing.cast( + ListUsersPaginationResponse, + parse_obj_as( + type_=ListUsersPaginationResponse, object_=_response.json() + ), + ) # type: ignore _has_next = False _get_next = None - if _parsed_response.page is not None and _parsed_response.page.next is not None: + if ( + _parsed_response.page is not None + and _parsed_response.page.next is not None + ): _parsed_next = _parsed_response.page.next.starting_after _has_next = _parsed_next is not None _get_next = lambda: self.list_with_cursor_pagination( @@ -107,7 +121,10 @@ def list_with_cursor_pagination( raise ApiError(status_code=_response.status_code, body=_response_json) def list_with_body_cursor_pagination( - self, *, pagination: typing.Optional[WithCursor] = OMIT, request_options: typing.Optional[RequestOptions] = None + self, + *, + pagination: typing.Optional[WithCursor] = OMIT, + request_options: typing.Optional[RequestOptions] = None, ) -> SyncPager[User]: """ Parameters @@ -145,18 +162,33 @@ def list_with_body_cursor_pagination( yield page """ _response = self._client_wrapper.httpx_client.request( - "users", method="POST", json={"pagination": pagination}, request_options=request_options, omit=OMIT + "users", + method="POST", + json={ + "pagination": pagination, + }, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - _parsed_response = typing.cast(ListUsersPaginationResponse, parse_obj_as(type_=ListUsersPaginationResponse, object_=_response.json())) # type: ignore + _parsed_response = typing.cast( + ListUsersPaginationResponse, + parse_obj_as( + type_=ListUsersPaginationResponse, object_=_response.json() + ), + ) # type: ignore _has_next = False _get_next = None - if _parsed_response.page is not None and _parsed_response.page.next is not None: + if ( + _parsed_response.page is not None + and _parsed_response.page.next is not None + ): _parsed_next = _parsed_response.page.next.starting_after _has_next = _parsed_next is not None _get_next = lambda: self.list_with_body_cursor_pagination( - pagination=pagination, request_options=request_options + pagination=pagination, + request_options=request_options, ) _items = _parsed_response.data return SyncPager(has_next=_has_next, items=_items, get_next=_get_next) @@ -172,7 +204,7 @@ def list_with_offset_pagination( per_page: typing.Optional[int] = None, order: typing.Optional[Order] = None, starting_after: typing.Optional[str] = None, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> SyncPager[User]: """ Parameters @@ -220,12 +252,22 @@ def list_with_offset_pagination( _response = self._client_wrapper.httpx_client.request( "users", method="GET", - params={"page": page, "per_page": per_page, "order": order, "starting_after": starting_after}, + params={ + "page": page, + "per_page": per_page, + "order": order, + "starting_after": starting_after, + }, request_options=request_options, ) try: if 200 <= _response.status_code < 300: - _parsed_response = typing.cast(ListUsersPaginationResponse, parse_obj_as(type_=ListUsersPaginationResponse, object_=_response.json())) # type: ignore + _parsed_response = typing.cast( + ListUsersPaginationResponse, + parse_obj_as( + type_=ListUsersPaginationResponse, object_=_response.json() + ), + ) # type: ignore _has_next = True _get_next = lambda: self.list_with_offset_pagination( page=page + 1, @@ -242,7 +284,10 @@ def list_with_offset_pagination( raise ApiError(status_code=_response.status_code, body=_response_json) def list_with_body_offset_pagination( - self, *, pagination: typing.Optional[WithPage] = OMIT, request_options: typing.Optional[RequestOptions] = None + self, + *, + pagination: typing.Optional[WithPage] = OMIT, + request_options: typing.Optional[RequestOptions] = None, ) -> SyncPager[User]: """ Parameters @@ -281,14 +326,26 @@ def list_with_body_offset_pagination( """ page = page if page is not None else 1 _response = self._client_wrapper.httpx_client.request( - "users", method="POST", json={"pagination": pagination}, request_options=request_options, omit=OMIT + "users", + method="POST", + json={ + "pagination": pagination, + }, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - _parsed_response = typing.cast(ListUsersPaginationResponse, parse_obj_as(type_=ListUsersPaginationResponse, object_=_response.json())) # type: ignore + _parsed_response = typing.cast( + ListUsersPaginationResponse, + parse_obj_as( + type_=ListUsersPaginationResponse, object_=_response.json() + ), + ) # type: ignore _has_next = True _get_next = lambda: self.list_with_body_offset_pagination( - pagination=pagination, request_options=request_options + pagination=pagination, + request_options=request_options, ) _items = _parsed_response.data return SyncPager(has_next=_has_next, items=_items, get_next=_get_next) @@ -303,7 +360,7 @@ def list_with_offset_step_pagination( page: typing.Optional[int] = None, limit: typing.Optional[int] = None, order: typing.Optional[Order] = None, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> SyncPager[User]: """ Parameters @@ -348,15 +405,27 @@ def list_with_offset_step_pagination( _response = self._client_wrapper.httpx_client.request( "users", method="GET", - params={"page": page, "limit": limit, "order": order}, + params={ + "page": page, + "limit": limit, + "order": order, + }, request_options=request_options, ) try: if 200 <= _response.status_code < 300: - _parsed_response = typing.cast(ListUsersPaginationResponse, parse_obj_as(type_=ListUsersPaginationResponse, object_=_response.json())) # type: ignore + _parsed_response = typing.cast( + ListUsersPaginationResponse, + parse_obj_as( + type_=ListUsersPaginationResponse, object_=_response.json() + ), + ) # type: ignore _has_next = True _get_next = lambda: self.list_with_offset_step_pagination( - page=page + 1, limit=limit, order=order, request_options=request_options + page=page + 1, + limit=limit, + order=order, + request_options=request_options, ) _items = _parsed_response.data return SyncPager(has_next=_has_next, items=_items, get_next=_get_next) @@ -366,7 +435,10 @@ def list_with_offset_step_pagination( raise ApiError(status_code=_response.status_code, body=_response_json) def list_with_extended_results( - self, *, cursor: typing.Optional[uuid.UUID] = None, request_options: typing.Optional[RequestOptions] = None + self, + *, + cursor: typing.Optional[uuid.UUID] = None, + request_options: typing.Optional[RequestOptions] = None, ) -> SyncPager[User]: """ Parameters @@ -402,15 +474,26 @@ def list_with_extended_results( yield page """ _response = self._client_wrapper.httpx_client.request( - "users", method="GET", params={"cursor": jsonable_encoder(cursor)}, request_options=request_options + "users", + method="GET", + params={ + "cursor": jsonable_encoder(cursor), + }, + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - _parsed_response = typing.cast(ListUsersExtendedResponse, parse_obj_as(type_=ListUsersExtendedResponse, object_=_response.json())) # type: ignore + _parsed_response = typing.cast( + ListUsersExtendedResponse, + parse_obj_as( + type_=ListUsersExtendedResponse, object_=_response.json() + ), + ) # type: ignore _parsed_next = _parsed_response.next _has_next = _parsed_next is not None _get_next = lambda: self.list_with_extended_results( - cursor=_parsed_next, request_options=request_options + cursor=_parsed_next, + request_options=request_options, ) _items = [] if _parsed_response.data is not None: @@ -422,7 +505,10 @@ def list_with_extended_results( raise ApiError(status_code=_response.status_code, body=_response_json) def list_usernames( - self, *, starting_after: typing.Optional[str] = None, request_options: typing.Optional[RequestOptions] = None + self, + *, + starting_after: typing.Optional[str] = None, + request_options: typing.Optional[RequestOptions] = None, ) -> SyncPager[str]: """ Parameters @@ -456,18 +542,27 @@ def list_usernames( yield page """ _response = self._client_wrapper.httpx_client.request( - "users", method="GET", params={"starting_after": starting_after}, request_options=request_options + "users", + method="GET", + params={ + "starting_after": starting_after, + }, + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - _parsed_response = typing.cast(UsernameCursor, parse_obj_as(type_=UsernameCursor, object_=_response.json())) # type: ignore + _parsed_response = typing.cast( + UsernameCursor, + parse_obj_as(type_=UsernameCursor, object_=_response.json()), + ) # type: ignore _has_next = False _get_next = None if _parsed_response.cursor is not None: _parsed_next = _parsed_response.cursor.after _has_next = _parsed_next is not None _get_next = lambda: self.list_usernames( - starting_after=_parsed_next, request_options=request_options + starting_after=_parsed_next, + request_options=request_options, ) _items = [] if _parsed_response.cursor is not None: @@ -479,7 +574,10 @@ def list_usernames( raise ApiError(status_code=_response.status_code, body=_response_json) def list_with_global_config( - self, *, offset: typing.Optional[int] = None, request_options: typing.Optional[RequestOptions] = None + self, + *, + offset: typing.Optional[int] = None, + request_options: typing.Optional[RequestOptions] = None, ) -> SyncPager[str]: """ Parameters @@ -512,13 +610,24 @@ def list_with_global_config( """ offset = offset if offset is not None else 1 _response = self._client_wrapper.httpx_client.request( - "users", method="GET", params={"offset": offset}, request_options=request_options + "users", + method="GET", + params={ + "offset": offset, + }, + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - _parsed_response = typing.cast(UsernameContainer, parse_obj_as(type_=UsernameContainer, object_=_response.json())) # type: ignore + _parsed_response = typing.cast( + UsernameContainer, + parse_obj_as(type_=UsernameContainer, object_=_response.json()), + ) # type: ignore _has_next = True - _get_next = lambda: self.list_with_global_config(offset=offset + 1, request_options=request_options) + _get_next = lambda: self.list_with_global_config( + offset=offset + 1, + request_options=request_options, + ) _items = _parsed_response.results return SyncPager(has_next=_has_next, items=_items, get_next=_get_next) _response_json = _response.json() @@ -538,7 +647,7 @@ async def list_with_cursor_pagination( per_page: typing.Optional[int] = None, order: typing.Optional[Order] = None, starting_after: typing.Optional[str] = None, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> AsyncPager[User]: """ Parameters @@ -593,15 +702,28 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( "users", method="GET", - params={"page": page, "per_page": per_page, "order": order, "starting_after": starting_after}, + params={ + "page": page, + "per_page": per_page, + "order": order, + "starting_after": starting_after, + }, request_options=request_options, ) try: if 200 <= _response.status_code < 300: - _parsed_response = typing.cast(ListUsersPaginationResponse, parse_obj_as(type_=ListUsersPaginationResponse, object_=_response.json())) # type: ignore + _parsed_response = typing.cast( + ListUsersPaginationResponse, + parse_obj_as( + type_=ListUsersPaginationResponse, object_=_response.json() + ), + ) # type: ignore _has_next = False _get_next = None - if _parsed_response.page is not None and _parsed_response.page.next is not None: + if ( + _parsed_response.page is not None + and _parsed_response.page.next is not None + ): _parsed_next = _parsed_response.page.next.starting_after _has_next = _parsed_next is not None _get_next = lambda: self.list_with_cursor_pagination( @@ -619,7 +741,10 @@ async def main() -> None: raise ApiError(status_code=_response.status_code, body=_response_json) async def list_with_body_cursor_pagination( - self, *, pagination: typing.Optional[WithCursor] = OMIT, request_options: typing.Optional[RequestOptions] = None + self, + *, + pagination: typing.Optional[WithCursor] = OMIT, + request_options: typing.Optional[RequestOptions] = None, ) -> AsyncPager[User]: """ Parameters @@ -665,18 +790,33 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "users", method="POST", json={"pagination": pagination}, request_options=request_options, omit=OMIT + "users", + method="POST", + json={ + "pagination": pagination, + }, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - _parsed_response = typing.cast(ListUsersPaginationResponse, parse_obj_as(type_=ListUsersPaginationResponse, object_=_response.json())) # type: ignore + _parsed_response = typing.cast( + ListUsersPaginationResponse, + parse_obj_as( + type_=ListUsersPaginationResponse, object_=_response.json() + ), + ) # type: ignore _has_next = False _get_next = None - if _parsed_response.page is not None and _parsed_response.page.next is not None: + if ( + _parsed_response.page is not None + and _parsed_response.page.next is not None + ): _parsed_next = _parsed_response.page.next.starting_after _has_next = _parsed_next is not None _get_next = lambda: self.list_with_body_cursor_pagination( - pagination=pagination, request_options=request_options + pagination=pagination, + request_options=request_options, ) _items = _parsed_response.data return AsyncPager(has_next=_has_next, items=_items, get_next=_get_next) @@ -692,7 +832,7 @@ async def list_with_offset_pagination( per_page: typing.Optional[int] = None, order: typing.Optional[Order] = None, starting_after: typing.Optional[str] = None, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> AsyncPager[User]: """ Parameters @@ -748,12 +888,22 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( "users", method="GET", - params={"page": page, "per_page": per_page, "order": order, "starting_after": starting_after}, + params={ + "page": page, + "per_page": per_page, + "order": order, + "starting_after": starting_after, + }, request_options=request_options, ) try: if 200 <= _response.status_code < 300: - _parsed_response = typing.cast(ListUsersPaginationResponse, parse_obj_as(type_=ListUsersPaginationResponse, object_=_response.json())) # type: ignore + _parsed_response = typing.cast( + ListUsersPaginationResponse, + parse_obj_as( + type_=ListUsersPaginationResponse, object_=_response.json() + ), + ) # type: ignore _has_next = True _get_next = lambda: self.list_with_offset_pagination( page=page + 1, @@ -770,7 +920,10 @@ async def main() -> None: raise ApiError(status_code=_response.status_code, body=_response_json) async def list_with_body_offset_pagination( - self, *, pagination: typing.Optional[WithPage] = OMIT, request_options: typing.Optional[RequestOptions] = None + self, + *, + pagination: typing.Optional[WithPage] = OMIT, + request_options: typing.Optional[RequestOptions] = None, ) -> AsyncPager[User]: """ Parameters @@ -817,14 +970,26 @@ async def main() -> None: """ page = page if page is not None else 1 _response = await self._client_wrapper.httpx_client.request( - "users", method="POST", json={"pagination": pagination}, request_options=request_options, omit=OMIT + "users", + method="POST", + json={ + "pagination": pagination, + }, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - _parsed_response = typing.cast(ListUsersPaginationResponse, parse_obj_as(type_=ListUsersPaginationResponse, object_=_response.json())) # type: ignore + _parsed_response = typing.cast( + ListUsersPaginationResponse, + parse_obj_as( + type_=ListUsersPaginationResponse, object_=_response.json() + ), + ) # type: ignore _has_next = True _get_next = lambda: self.list_with_body_offset_pagination( - pagination=pagination, request_options=request_options + pagination=pagination, + request_options=request_options, ) _items = _parsed_response.data return AsyncPager(has_next=_has_next, items=_items, get_next=_get_next) @@ -839,7 +1004,7 @@ async def list_with_offset_step_pagination( page: typing.Optional[int] = None, limit: typing.Optional[int] = None, order: typing.Optional[Order] = None, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> AsyncPager[User]: """ Parameters @@ -892,15 +1057,27 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( "users", method="GET", - params={"page": page, "limit": limit, "order": order}, + params={ + "page": page, + "limit": limit, + "order": order, + }, request_options=request_options, ) try: if 200 <= _response.status_code < 300: - _parsed_response = typing.cast(ListUsersPaginationResponse, parse_obj_as(type_=ListUsersPaginationResponse, object_=_response.json())) # type: ignore + _parsed_response = typing.cast( + ListUsersPaginationResponse, + parse_obj_as( + type_=ListUsersPaginationResponse, object_=_response.json() + ), + ) # type: ignore _has_next = True _get_next = lambda: self.list_with_offset_step_pagination( - page=page + 1, limit=limit, order=order, request_options=request_options + page=page + 1, + limit=limit, + order=order, + request_options=request_options, ) _items = _parsed_response.data return AsyncPager(has_next=_has_next, items=_items, get_next=_get_next) @@ -910,7 +1087,10 @@ async def main() -> None: raise ApiError(status_code=_response.status_code, body=_response_json) async def list_with_extended_results( - self, *, cursor: typing.Optional[uuid.UUID] = None, request_options: typing.Optional[RequestOptions] = None + self, + *, + cursor: typing.Optional[uuid.UUID] = None, + request_options: typing.Optional[RequestOptions] = None, ) -> AsyncPager[User]: """ Parameters @@ -953,15 +1133,26 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "users", method="GET", params={"cursor": jsonable_encoder(cursor)}, request_options=request_options + "users", + method="GET", + params={ + "cursor": jsonable_encoder(cursor), + }, + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - _parsed_response = typing.cast(ListUsersExtendedResponse, parse_obj_as(type_=ListUsersExtendedResponse, object_=_response.json())) # type: ignore + _parsed_response = typing.cast( + ListUsersExtendedResponse, + parse_obj_as( + type_=ListUsersExtendedResponse, object_=_response.json() + ), + ) # type: ignore _parsed_next = _parsed_response.next _has_next = _parsed_next is not None _get_next = lambda: self.list_with_extended_results( - cursor=_parsed_next, request_options=request_options + cursor=_parsed_next, + request_options=request_options, ) _items = [] if _parsed_response.data is not None: @@ -973,7 +1164,10 @@ async def main() -> None: raise ApiError(status_code=_response.status_code, body=_response_json) async def list_usernames( - self, *, starting_after: typing.Optional[str] = None, request_options: typing.Optional[RequestOptions] = None + self, + *, + starting_after: typing.Optional[str] = None, + request_options: typing.Optional[RequestOptions] = None, ) -> AsyncPager[str]: """ Parameters @@ -1015,18 +1209,27 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "users", method="GET", params={"starting_after": starting_after}, request_options=request_options + "users", + method="GET", + params={ + "starting_after": starting_after, + }, + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - _parsed_response = typing.cast(UsernameCursor, parse_obj_as(type_=UsernameCursor, object_=_response.json())) # type: ignore + _parsed_response = typing.cast( + UsernameCursor, + parse_obj_as(type_=UsernameCursor, object_=_response.json()), + ) # type: ignore _has_next = False _get_next = None if _parsed_response.cursor is not None: _parsed_next = _parsed_response.cursor.after _has_next = _parsed_next is not None _get_next = lambda: self.list_usernames( - starting_after=_parsed_next, request_options=request_options + starting_after=_parsed_next, + request_options=request_options, ) _items = [] if _parsed_response.cursor is not None: @@ -1038,7 +1241,10 @@ async def main() -> None: raise ApiError(status_code=_response.status_code, body=_response_json) async def list_with_global_config( - self, *, offset: typing.Optional[int] = None, request_options: typing.Optional[RequestOptions] = None + self, + *, + offset: typing.Optional[int] = None, + request_options: typing.Optional[RequestOptions] = None, ) -> AsyncPager[str]: """ Parameters @@ -1079,13 +1285,24 @@ async def main() -> None: """ offset = offset if offset is not None else 1 _response = await self._client_wrapper.httpx_client.request( - "users", method="GET", params={"offset": offset}, request_options=request_options + "users", + method="GET", + params={ + "offset": offset, + }, + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - _parsed_response = typing.cast(UsernameContainer, parse_obj_as(type_=UsernameContainer, object_=_response.json())) # type: ignore + _parsed_response = typing.cast( + UsernameContainer, + parse_obj_as(type_=UsernameContainer, object_=_response.json()), + ) # type: ignore _has_next = True - _get_next = lambda: self.list_with_global_config(offset=offset + 1, request_options=request_options) + _get_next = lambda: self.list_with_global_config( + offset=offset + 1, + request_options=request_options, + ) _items = _parsed_response.results return AsyncPager(has_next=_has_next, items=_items, get_next=_get_next) _response_json = _response.json() diff --git a/seed/python-sdk/pagination/src/seed/users/types/list_users_extended_response.py b/seed/python-sdk/pagination/src/seed/users/types/list_users_extended_response.py index 767ca22c389..92d74b162c6 100644 --- a/seed/python-sdk/pagination/src/seed/users/types/list_users_extended_response.py +++ b/seed/python-sdk/pagination/src/seed/users/types/list_users_extended_response.py @@ -1,11 +1,9 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from .user_page import UserPage import pydantic - from ...core.pydantic_utilities import IS_PYDANTIC_V2 -from .user_page import UserPage +import typing class ListUsersExtendedResponse(UserPage): @@ -15,7 +13,9 @@ class ListUsersExtendedResponse(UserPage): """ if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/pagination/src/seed/users/types/list_users_pagination_response.py b/seed/python-sdk/pagination/src/seed/users/types/list_users_pagination_response.py index 801d21d6bef..2da99b6ea5a 100644 --- a/seed/python-sdk/pagination/src/seed/users/types/list_users_pagination_response.py +++ b/seed/python-sdk/pagination/src/seed/users/types/list_users_pagination_response.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .page import Page +import pydantic from .user import User +from ...core.pydantic_utilities import IS_PYDANTIC_V2 class ListUsersPaginationResponse(UniversalBaseModel): @@ -19,7 +18,9 @@ class ListUsersPaginationResponse(UniversalBaseModel): data: typing.List[User] if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/pagination/src/seed/users/types/next_page.py b/seed/python-sdk/pagination/src/seed/users/types/next_page.py index 016cce4d457..d2c084baba7 100644 --- a/seed/python-sdk/pagination/src/seed/users/types/next_page.py +++ b/seed/python-sdk/pagination/src/seed/users/types/next_page.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class NextPage(UniversalBaseModel): page: int starting_after: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/pagination/src/seed/users/types/page.py b/seed/python-sdk/pagination/src/seed/users/types/page.py index 96ec4e13a5e..9d9b19a3de7 100644 --- a/seed/python-sdk/pagination/src/seed/users/types/page.py +++ b/seed/python-sdk/pagination/src/seed/users/types/page.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. -import typing - +from ...core.pydantic_utilities import UniversalBaseModel import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +import typing from .next_page import NextPage +from ...core.pydantic_utilities import IS_PYDANTIC_V2 class Page(UniversalBaseModel): @@ -19,7 +18,9 @@ class Page(UniversalBaseModel): total_page: int if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/pagination/src/seed/users/types/user.py b/seed/python-sdk/pagination/src/seed/users/types/user.py index bf67f8806c5..fdab49e3070 100644 --- a/seed/python-sdk/pagination/src/seed/users/types/user.py +++ b/seed/python-sdk/pagination/src/seed/users/types/user.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class User(UniversalBaseModel): name: str id: int if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/pagination/src/seed/users/types/user_list_container.py b/seed/python-sdk/pagination/src/seed/users/types/user_list_container.py index a1ad04dd58e..4d524a977f5 100644 --- a/seed/python-sdk/pagination/src/seed/users/types/user_list_container.py +++ b/seed/python-sdk/pagination/src/seed/users/types/user_list_container.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel import typing - -import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .user import User +from ...core.pydantic_utilities import IS_PYDANTIC_V2 +import pydantic class UserListContainer(UniversalBaseModel): users: typing.List[User] if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/pagination/src/seed/users/types/user_page.py b/seed/python-sdk/pagination/src/seed/users/types/user_page.py index 968cacf8368..b2022e1f395 100644 --- a/seed/python-sdk/pagination/src/seed/users/types/user_page.py +++ b/seed/python-sdk/pagination/src/seed/users/types/user_page.py @@ -1,20 +1,21 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from .user_list_container import UserListContainer import typing import uuid - +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .user_list_container import UserListContainer - class UserPage(UniversalBaseModel): data: UserListContainer next: typing.Optional[uuid.UUID] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/pagination/src/seed/users/types/username_container.py b/seed/python-sdk/pagination/src/seed/users/types/username_container.py index 7de3df94187..154b25e04dc 100644 --- a/seed/python-sdk/pagination/src/seed/users/types/username_container.py +++ b/seed/python-sdk/pagination/src/seed/users/types/username_container.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel import typing - +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class UsernameContainer(UniversalBaseModel): results: typing.List[str] if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/pagination/src/seed/users/types/with_cursor.py b/seed/python-sdk/pagination/src/seed/users/types/with_cursor.py index 0ca1afe6fda..7680dedef54 100644 --- a/seed/python-sdk/pagination/src/seed/users/types/with_cursor.py +++ b/seed/python-sdk/pagination/src/seed/users/types/with_cursor.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel import typing - +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class WithCursor(UniversalBaseModel): cursor: typing.Optional[str] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/pagination/src/seed/users/types/with_page.py b/seed/python-sdk/pagination/src/seed/users/types/with_page.py index 126f636b603..ffbcb9609ab 100644 --- a/seed/python-sdk/pagination/src/seed/users/types/with_page.py +++ b/seed/python-sdk/pagination/src/seed/users/types/with_page.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel import typing - +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class WithPage(UniversalBaseModel): page: typing.Optional[int] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/pagination/src/seed/version.py b/seed/python-sdk/pagination/src/seed/version.py index c0ba46a528e..181c142ebf3 100644 --- a/seed/python-sdk/pagination/src/seed/version.py +++ b/seed/python-sdk/pagination/src/seed/version.py @@ -1,4 +1,3 @@ - from importlib import metadata __version__ = metadata.version("fern_pagination") diff --git a/seed/python-sdk/pagination/tests/conftest.py b/seed/python-sdk/pagination/tests/conftest.py index a00a406d327..19c39da4e1a 100644 --- a/seed/python-sdk/pagination/tests/conftest.py +++ b/seed/python-sdk/pagination/tests/conftest.py @@ -1,16 +1,22 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedPagination import os - import pytest -from seed import AsyncSeedPagination, SeedPagination +from seed import AsyncSeedPagination @pytest.fixture def client() -> SeedPagination: - return SeedPagination(token=os.getenv("ENV_TOKEN", "token"), base_url=os.getenv("TESTS_BASE_URL", "base_url")) + return SeedPagination( + token=os.getenv("ENV_TOKEN", "token"), + base_url=os.getenv("TESTS_BASE_URL", "base_url"), + ) @pytest.fixture def async_client() -> AsyncSeedPagination: - return AsyncSeedPagination(token=os.getenv("ENV_TOKEN", "token"), base_url=os.getenv("TESTS_BASE_URL", "base_url")) + return AsyncSeedPagination( + token=os.getenv("ENV_TOKEN", "token"), + base_url=os.getenv("TESTS_BASE_URL", "base_url"), + ) diff --git a/seed/python-sdk/pagination/tests/custom/test_client.py b/seed/python-sdk/pagination/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/python-sdk/pagination/tests/custom/test_client.py +++ b/seed/python-sdk/pagination/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/python-sdk/pagination/tests/utilities.py b/seed/python-sdk/pagination/tests/utilities.py index 13da208eb3a..e8f4472564c 100644 --- a/seed/python-sdk/pagination/tests/utilities.py +++ b/seed/python-sdk/pagination/tests/utilities.py @@ -3,11 +3,14 @@ import typing import uuid -import pydantic from dateutil import parser +import pydantic + -def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> typing.Any: +def cast_field( + json_expectation: typing.Any, type_expectation: typing.Any +) -> typing.Any: # Cast these specific types which come through as string and expect our # models to cast to the correct type. if type_expectation == "uuid": @@ -25,7 +28,9 @@ def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> ty return json_expectation -def validate_field(response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any) -> None: +def validate_field( + response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectation == "no_validate": return @@ -44,7 +49,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(entry_expectation, dict): is_container_of_complex_type = True validate_response( - response=response[idx], json_expectation=ex, type_expectations=entry_expectation + response=response[idx], + json_expectation=ex, + type_expectations=entry_expectation, ) else: cast_json_expectation.append(cast_field(ex, entry_expectation)) @@ -56,7 +63,10 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # if any of the values of the set have a type_expectation of a dict, we're assuming it's a pydantic # model and keeping it a list. if container_expectation != "set" or not any( - map(lambda value: isinstance(value, dict), list(contents_expectation.values())) + map( + lambda value: isinstance(value, dict), + list(contents_expectation.values()), + ) ): json_expectation = cast_field(json_expectation, container_expectation) elif isinstance(type_expectation, tuple): @@ -65,9 +75,15 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(contents_expectation, dict): json_expectation = { cast_field( - key, contents_expectation.get(idx)[0] if contents_expectation.get(idx) is not None else None # type: ignore + key, + contents_expectation.get(idx)[0] + if contents_expectation.get(idx) is not None + else None, # type: ignore ): cast_field( - value, contents_expectation.get(idx)[1] if contents_expectation.get(idx) is not None else None # type: ignore + value, + contents_expectation.get(idx)[1] + if contents_expectation.get(idx) is not None + else None, # type: ignore ) for idx, (key, value) in enumerate(json_expectation.items()) } @@ -86,7 +102,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # Arg type_expectations is a deeply nested structure that matches the response, but with the values replaced with the expected types -def validate_response(response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any) -> None: +def validate_response( + response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectations == "no_validate": return @@ -96,11 +114,17 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e and not isinstance(response, dict) and not issubclass(type(response), pydantic.BaseModel) ): - validate_field(response=response, json_expectation=json_expectation, type_expectation=type_expectations) + validate_field( + response=response, + json_expectation=json_expectation, + type_expectation=type_expectations, + ) return if isinstance(response, list): - assert len(response) == len(json_expectation), "Length mismatch, expected: {0}, Actual: {1}".format( + assert len(response) == len( + json_expectation + ), "Length mismatch, expected: {0}, Actual: {1}".format( len(response), len(json_expectation) ) content_expectation = type_expectations @@ -108,7 +132,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e content_expectation = type_expectations[1] for idx, item in enumerate(response): validate_response( - response=item, json_expectation=json_expectation[idx], type_expectations=content_expectation[idx] + response=item, + json_expectation=json_expectation[idx], + type_expectations=content_expectation[idx], ) else: response_json = response @@ -116,7 +142,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e response_json = response.dict(by_alias=True) for key, value in json_expectation.items(): - assert key in response_json, "Field {0} not found within the response object: {1}".format( + assert ( + key in response_json + ), "Field {0} not found within the response object: {1}".format( key, response_json ) @@ -128,11 +156,19 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e # Otherwise, we're just validating a single field that's a pydantic model. if isinstance(value, dict) and not isinstance(type_expectation, tuple): validate_response( - response=response_json[key], json_expectation=value, type_expectations=type_expectation + response=response_json[key], + json_expectation=value, + type_expectations=type_expectation, ) else: - validate_field(response=response_json[key], json_expectation=value, type_expectation=type_expectation) + validate_field( + response=response_json[key], + json_expectation=value, + type_expectation=type_expectation, + ) # Ensure there are no additional fields here either del response_json[key] - assert len(response_json) == 0, "Additional fields found, expected None: {0}".format(response_json) + assert ( + len(response_json) == 0 + ), "Additional fields found, expected None: {0}".format(response_json) diff --git a/seed/python-sdk/pagination/tests/utils/assets/models/__init__.py b/seed/python-sdk/pagination/tests/utils/assets/models/__init__.py index 2cf01263529..3a1c852e71e 100644 --- a/seed/python-sdk/pagination/tests/utils/assets/models/__init__.py +++ b/seed/python-sdk/pagination/tests/utils/assets/models/__init__.py @@ -5,7 +5,7 @@ from .circle import CircleParams from .object_with_defaults import ObjectWithDefaultsParams from .object_with_optional_field import ObjectWithOptionalFieldParams -from .shape import Shape_CircleParams, Shape_SquareParams, ShapeParams +from .shape import ShapeParams, Shape_CircleParams, Shape_SquareParams from .square import SquareParams from .undiscriminated_shape import UndiscriminatedShapeParams diff --git a/seed/python-sdk/pagination/tests/utils/assets/models/circle.py b/seed/python-sdk/pagination/tests/utils/assets/models/circle.py index af7a1bf8a8e..253f12d38b3 100644 --- a/seed/python-sdk/pagination/tests/utils/assets/models/circle.py +++ b/seed/python-sdk/pagination/tests/utils/assets/models/circle.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class CircleParams(typing_extensions.TypedDict): - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] diff --git a/seed/python-sdk/pagination/tests/utils/assets/models/object_with_optional_field.py b/seed/python-sdk/pagination/tests/utils/assets/models/object_with_optional_field.py index 3ad93d5f305..ebe7dc80547 100644 --- a/seed/python-sdk/pagination/tests/utils/assets/models/object_with_optional_field.py +++ b/seed/python-sdk/pagination/tests/utils/assets/models/object_with_optional_field.py @@ -7,8 +7,8 @@ import uuid import typing_extensions -from seed.core.serialization import FieldMetadata +from seed.core.serialization import FieldMetadata from .color import Color from .shape import ShapeParams from .undiscriminated_shape import UndiscriminatedShapeParams @@ -18,16 +18,30 @@ class ObjectWithOptionalFieldParams(typing_extensions.TypedDict): literal: typing.Literal["lit_one"] string: typing_extensions.NotRequired[str] integer: typing_extensions.NotRequired[int] - long_: typing_extensions.NotRequired[typing_extensions.Annotated[int, FieldMetadata(alias="long")]] + long_: typing_extensions.NotRequired[ + typing_extensions.Annotated[int, FieldMetadata(alias="long")] + ] double: typing_extensions.NotRequired[float] - bool_: typing_extensions.NotRequired[typing_extensions.Annotated[bool, FieldMetadata(alias="bool")]] + bool_: typing_extensions.NotRequired[ + typing_extensions.Annotated[bool, FieldMetadata(alias="bool")] + ] datetime: typing_extensions.NotRequired[dt.datetime] date: typing_extensions.NotRequired[dt.date] - uuid_: typing_extensions.NotRequired[typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")]] - base_64: typing_extensions.NotRequired[typing_extensions.Annotated[str, FieldMetadata(alias="base64")]] - list_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")]] - set_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")]] - map_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")]] + uuid_: typing_extensions.NotRequired[ + typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")] + ] + base_64: typing_extensions.NotRequired[ + typing_extensions.Annotated[str, FieldMetadata(alias="base64")] + ] + list_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")] + ] + set_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")] + ] + map_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")] + ] enum: typing_extensions.NotRequired[Color] union: typing_extensions.NotRequired[ShapeParams] second_union: typing_extensions.NotRequired[ShapeParams] diff --git a/seed/python-sdk/pagination/tests/utils/assets/models/shape.py b/seed/python-sdk/pagination/tests/utils/assets/models/shape.py index 2c33c877951..816ffc51bdc 100644 --- a/seed/python-sdk/pagination/tests/utils/assets/models/shape.py +++ b/seed/python-sdk/pagination/tests/utils/assets/models/shape.py @@ -7,6 +7,7 @@ import typing import typing_extensions + from seed.core.serialization import FieldMetadata @@ -15,13 +16,21 @@ class Base(typing_extensions.TypedDict): class Shape_CircleParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["circle"], FieldMetadata(alias="shapeType")] - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["circle"], FieldMetadata(alias="shapeType") + ] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] class Shape_SquareParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["square"], FieldMetadata(alias="shapeType")] - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["square"], FieldMetadata(alias="shapeType") + ] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] ShapeParams = typing.Union[Shape_CircleParams, Shape_SquareParams] diff --git a/seed/python-sdk/pagination/tests/utils/assets/models/square.py b/seed/python-sdk/pagination/tests/utils/assets/models/square.py index b9b7dd319bc..bcf08a723c5 100644 --- a/seed/python-sdk/pagination/tests/utils/assets/models/square.py +++ b/seed/python-sdk/pagination/tests/utils/assets/models/square.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class SquareParams(typing_extensions.TypedDict): - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] diff --git a/seed/python-sdk/pagination/tests/utils/test_http_client.py b/seed/python-sdk/pagination/tests/utils/test_http_client.py index edd11ca7afb..f5a874a75f3 100644 --- a/seed/python-sdk/pagination/tests/utils/test_http_client.py +++ b/seed/python-sdk/pagination/tests/utils/test_http_client.py @@ -9,12 +9,17 @@ def get_request_options() -> RequestOptions: def test_get_json_request_body() -> None: - json_body, data_body = get_request_body(json={"hello": "world"}, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json={"hello": "world"}, data=None, request_options=None, omit=None + ) assert json_body == {"hello": "world"} assert data_body is None json_body_extras, data_body_extras = get_request_body( - json={"goodbye": "world"}, data=None, request_options=get_request_options(), omit=None + json={"goodbye": "world"}, + data=None, + request_options=get_request_options(), + omit=None, ) assert json_body_extras == {"goodbye": "world", "see you": "later"} @@ -22,12 +27,17 @@ def test_get_json_request_body() -> None: def test_get_files_request_body() -> None: - json_body, data_body = get_request_body(json=None, data={"hello": "world"}, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data={"hello": "world"}, request_options=None, omit=None + ) assert data_body == {"hello": "world"} assert json_body is None json_body_extras, data_body_extras = get_request_body( - json=None, data={"goodbye": "world"}, request_options=get_request_options(), omit=None + json=None, + data={"goodbye": "world"}, + request_options=get_request_options(), + omit=None, ) assert data_body_extras == {"goodbye": "world", "see you": "later"} @@ -35,7 +45,9 @@ def test_get_files_request_body() -> None: def test_get_none_request_body() -> None: - json_body, data_body = get_request_body(json=None, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data=None, request_options=None, omit=None + ) assert data_body is None assert json_body is None diff --git a/seed/python-sdk/pagination/tests/utils/test_query_encoding.py b/seed/python-sdk/pagination/tests/utils/test_query_encoding.py index 247e1551b46..fbc8f402167 100644 --- a/seed/python-sdk/pagination/tests/utils/test_query_encoding.py +++ b/seed/python-sdk/pagination/tests/utils/test_query_encoding.py @@ -4,9 +4,15 @@ def test_query_encoding() -> None: - assert encode_query({"hello world": "hello world"}) == {"hello world": "hello world"} - assert encode_query({"hello_world": {"hello": "world"}}) == {"hello_world[hello]": "world"} - assert encode_query({"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"}) == { + assert encode_query({"hello world": "hello world"}) == { + "hello world": "hello world" + } + assert encode_query({"hello_world": {"hello": "world"}}) == { + "hello_world[hello]": "world" + } + assert encode_query( + {"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"} + ) == { "hello_world[hello][world]": "today", "hello_world[test]": "this", "hi": "there", diff --git a/seed/python-sdk/pagination/tests/utils/test_serialization.py b/seed/python-sdk/pagination/tests/utils/test_serialization.py index 58b1ed66e6d..5ca956916dd 100644 --- a/seed/python-sdk/pagination/tests/utils/test_serialization.py +++ b/seed/python-sdk/pagination/tests/utils/test_serialization.py @@ -1,10 +1,12 @@ # This file was auto-generated by Fern from our API Definition. -from typing import Any, List +from typing import List, Any -from seed.core.serialization import convert_and_respect_annotation_metadata +from seed.core.serialization import ( + convert_and_respect_annotation_metadata, +) +from .assets.models import ShapeParams, ObjectWithOptionalFieldParams -from .assets.models import ObjectWithOptionalFieldParams, ShapeParams UNION_TEST: ShapeParams = {"radius_measurement": 1.0, "shape_type": "circle", "id": "1"} UNION_TEST_CONVERTED = {"shapeType": "circle", "radiusMeasurement": 1.0, "id": "1"} @@ -18,20 +20,54 @@ def test_convert_and_respect_annotation_metadata() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) - assert converted == {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"} + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) + assert converted == { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + } def test_convert_and_respect_annotation_metadata_in_list() -> None: data: List[ObjectWithOptionalFieldParams] = [ - {"string": "string", "long_": 12345, "bool_": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long_": 67890, "list_": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long_": 12345, + "bool_": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long_": 67890, + "list_": [], + "literal": "lit_one", + "any": "any", + }, ] - converted = convert_and_respect_annotation_metadata(object_=data, annotation=List[ObjectWithOptionalFieldParams]) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=List[ObjectWithOptionalFieldParams] + ) assert converted == [ - {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long": 67890, "list": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long": 67890, + "list": [], + "literal": "lit_one", + "any": "any", + }, ] @@ -43,7 +79,9 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) assert converted == { "string": "string", @@ -55,12 +93,16 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: def test_convert_and_respect_annotation_metadata_in_union() -> None: - converted = convert_and_respect_annotation_metadata(object_=UNION_TEST, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=UNION_TEST, annotation=ShapeParams + ) assert converted == UNION_TEST_CONVERTED def test_convert_and_respect_annotation_metadata_with_empty_object() -> None: data: Any = {} - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ShapeParams + ) assert converted == data diff --git a/seed/python-sdk/plain-text/pyproject.toml b/seed/python-sdk/plain-text/pyproject.toml index eb6d90f5cb8..16fcd1eb746 100644 --- a/seed/python-sdk/plain-text/pyproject.toml +++ b/seed/python-sdk/plain-text/pyproject.toml @@ -43,6 +43,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/python-sdk/plain-text/src/seed/client.py b/seed/python-sdk/plain-text/src/seed/client.py index 67e801702ed..6e3b4e534e8 100644 --- a/seed/python-sdk/plain-text/src/seed/client.py +++ b/seed/python-sdk/plain-text/src/seed/client.py @@ -1,11 +1,11 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from .service.client import AsyncServiceClient, ServiceClient +from .core.client_wrapper import SyncClientWrapper +from .service.client import ServiceClient +from .core.client_wrapper import AsyncClientWrapper +from .service.client import AsyncServiceClient class SeedPlainText: @@ -41,14 +41,18 @@ def __init__( base_url: str, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.Client] = None + httpx_client: typing.Optional[httpx.Client] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = SyncClientWrapper( base_url=base_url, httpx_client=httpx_client if httpx_client is not None - else httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.Client( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.Client(timeout=_defaulted_timeout), timeout=_defaulted_timeout, @@ -89,14 +93,18 @@ def __init__( base_url: str, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.AsyncClient] = None + httpx_client: typing.Optional[httpx.AsyncClient] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = AsyncClientWrapper( base_url=base_url, httpx_client=httpx_client if httpx_client is not None - else httpx.AsyncClient(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.AsyncClient( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.AsyncClient(timeout=_defaulted_timeout), timeout=_defaulted_timeout, diff --git a/seed/python-sdk/plain-text/src/seed/core/api_error.py b/seed/python-sdk/plain-text/src/seed/core/api_error.py index 2e9fc5431cd..da734b58068 100644 --- a/seed/python-sdk/plain-text/src/seed/core/api_error.py +++ b/seed/python-sdk/plain-text/src/seed/core/api_error.py @@ -7,7 +7,9 @@ class ApiError(Exception): status_code: typing.Optional[int] body: typing.Any - def __init__(self, *, status_code: typing.Optional[int] = None, body: typing.Any = None): + def __init__( + self, *, status_code: typing.Optional[int] = None, body: typing.Any = None + ): self.status_code = status_code self.body = body diff --git a/seed/python-sdk/plain-text/src/seed/core/client_wrapper.py b/seed/python-sdk/plain-text/src/seed/core/client_wrapper.py index 6ca6c4865ca..ba10c6aeba4 100644 --- a/seed/python-sdk/plain-text/src/seed/core/client_wrapper.py +++ b/seed/python-sdk/plain-text/src/seed/core/client_wrapper.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .http_client import AsyncHttpClient, HttpClient +from .http_client import HttpClient +from .http_client import AsyncHttpClient class BaseClientWrapper: @@ -28,7 +27,13 @@ def get_timeout(self) -> typing.Optional[float]: class SyncClientWrapper(BaseClientWrapper): - def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, httpx_client: httpx.Client): + def __init__( + self, + *, + base_url: str, + timeout: typing.Optional[float] = None, + httpx_client: httpx.Client, + ): super().__init__(base_url=base_url, timeout=timeout) self.httpx_client = HttpClient( httpx_client=httpx_client, @@ -39,7 +44,13 @@ def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, htt class AsyncClientWrapper(BaseClientWrapper): - def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, httpx_client: httpx.AsyncClient): + def __init__( + self, + *, + base_url: str, + timeout: typing.Optional[float] = None, + httpx_client: httpx.AsyncClient, + ): super().__init__(base_url=base_url, timeout=timeout) self.httpx_client = AsyncHttpClient( httpx_client=httpx_client, diff --git a/seed/python-sdk/plain-text/src/seed/core/datetime_utils.py b/seed/python-sdk/plain-text/src/seed/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/python-sdk/plain-text/src/seed/core/datetime_utils.py +++ b/seed/python-sdk/plain-text/src/seed/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/python-sdk/plain-text/src/seed/core/file.py b/seed/python-sdk/plain-text/src/seed/core/file.py index cb0d40bbbf3..6e0f92bfcb1 100644 --- a/seed/python-sdk/plain-text/src/seed/core/file.py +++ b/seed/python-sdk/plain-text/src/seed/core/file.py @@ -13,12 +13,17 @@ # (filename, file (or bytes), content_type) typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str]], # (filename, file (or bytes), content_type, headers) - typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str], typing.Mapping[str, str]], + typing.Tuple[ + typing.Optional[str], + FileContent, + typing.Optional[str], + typing.Mapping[str, str], + ], ] def convert_file_dict_to_httpx_tuples( - d: typing.Dict[str, typing.Union[File, typing.List[File]]] + d: typing.Dict[str, typing.Union[File, typing.List[File]]], ) -> typing.List[typing.Tuple[str, File]]: """ The format we use is a list of tuples, where the first element is the diff --git a/seed/python-sdk/plain-text/src/seed/core/http_client.py b/seed/python-sdk/plain-text/src/seed/core/http_client.py index 9333d8a7f15..091f71bc185 100644 --- a/seed/python-sdk/plain-text/src/seed/core/http_client.py +++ b/seed/python-sdk/plain-text/src/seed/core/http_client.py @@ -77,7 +77,9 @@ def _retry_timeout(response: httpx.Response, retries: int) -> float: return retry_after # Apply exponential backoff, capped at MAX_RETRY_DELAY_SECONDS. - retry_delay = min(INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS) + retry_delay = min( + INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS + ) # Add a randomness / jitter to the retry delay to avoid overwhelming the server with retries. timeout = retry_delay * (1 - 0.25 * random()) @@ -90,7 +92,8 @@ def _should_retry(response: httpx.Response) -> bool: def remove_omit_from_dict( - original: typing.Dict[str, typing.Optional[typing.Any]], omit: typing.Optional[typing.Any] + original: typing.Dict[str, typing.Optional[typing.Any]], + omit: typing.Optional[typing.Any], ) -> typing.Dict[str, typing.Any]: if omit is None: return original @@ -108,7 +111,8 @@ def maybe_filter_request_body( ) -> typing.Optional[typing.Any]: if data is None: return ( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else None ) @@ -118,7 +122,8 @@ def maybe_filter_request_body( data_content = { **(jsonable_encoder(remove_omit_from_dict(data, omit))), # type: ignore **( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else {} ), @@ -162,7 +167,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url def request( @@ -174,8 +181,12 @@ def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -184,11 +195,14 @@ def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) response = self.httpx_client.request( method=method, @@ -198,7 +212,11 @@ def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -209,7 +227,10 @@ def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -222,11 +243,15 @@ def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: time.sleep(_retry_timeout(response=response, retries=retries)) @@ -256,8 +281,12 @@ def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -266,11 +295,14 @@ def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) with self.httpx_client.stream( method=method, @@ -280,7 +312,11 @@ def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -291,7 +327,9 @@ def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -304,7 +342,9 @@ def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream @@ -327,7 +367,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url async def request( @@ -339,8 +381,12 @@ async def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -349,11 +395,14 @@ async def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) # Add the input to each of these and do None-safety checks response = await self.httpx_client.request( @@ -364,7 +413,11 @@ async def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -375,7 +428,10 @@ async def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -388,11 +444,15 @@ async def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: await asyncio.sleep(_retry_timeout(response=response, retries=retries)) @@ -421,8 +481,12 @@ async def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -431,11 +495,14 @@ async def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) async with self.httpx_client.stream( method=method, @@ -445,7 +512,11 @@ async def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -456,7 +527,9 @@ async def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -469,7 +542,9 @@ async def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream diff --git a/seed/python-sdk/plain-text/src/seed/core/jsonable_encoder.py b/seed/python-sdk/plain-text/src/seed/core/jsonable_encoder.py index d3fd328fd41..12a8b52fc22 100644 --- a/seed/python-sdk/plain-text/src/seed/core/jsonable_encoder.py +++ b/seed/python-sdk/plain-text/src/seed/core/jsonable_encoder.py @@ -19,13 +19,19 @@ import pydantic from .datetime_utils import serialize_datetime -from .pydantic_utilities import IS_PYDANTIC_V2, encode_by_type, to_jsonable_with_fallback +from .pydantic_utilities import ( + IS_PYDANTIC_V2, + encode_by_type, + to_jsonable_with_fallback, +) SetIntStr = Set[Union[int, str]] DictIntStrAny = Dict[Union[int, str], Any] -def jsonable_encoder(obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None) -> Any: +def jsonable_encoder( + obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None +) -> Any: custom_encoder = custom_encoder or {} if custom_encoder: if type(obj) in custom_encoder: diff --git a/seed/python-sdk/plain-text/src/seed/core/pydantic_utilities.py b/seed/python-sdk/plain-text/src/seed/core/pydantic_utilities.py index 170a563d6eb..c63935c32a2 100644 --- a/seed/python-sdk/plain-text/src/seed/core/pydantic_utilities.py +++ b/seed/python-sdk/plain-text/src/seed/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) # type: ignore # Pydantic v1 diff --git a/seed/python-sdk/plain-text/src/seed/core/query_encoder.py b/seed/python-sdk/plain-text/src/seed/core/query_encoder.py index 24076d72ee9..7cb98f52cd7 100644 --- a/seed/python-sdk/plain-text/src/seed/core/query_encoder.py +++ b/seed/python-sdk/plain-text/src/seed/core/query_encoder.py @@ -7,7 +7,9 @@ # Flattens dicts to be of the form {"key[subkey][subkey2]": value} where value is not a dict -def traverse_query_dict(dict_flat: Dict[str, Any], key_prefix: Optional[str] = None) -> Dict[str, Any]: +def traverse_query_dict( + dict_flat: Dict[str, Any], key_prefix: Optional[str] = None +) -> Dict[str, Any]: result = {} for k, v in dict_flat.items(): key = f"{key_prefix}[{k}]" if key_prefix is not None else k @@ -30,4 +32,8 @@ def single_query_encoder(query_key: str, query_value: Any) -> Dict[str, Any]: def encode_query(query: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: - return dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) if query is not None else None + return ( + dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) + if query is not None + else None + ) diff --git a/seed/python-sdk/plain-text/src/seed/core/serialization.py b/seed/python-sdk/plain-text/src/seed/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/python-sdk/plain-text/src/seed/core/serialization.py +++ b/seed/python-sdk/plain-text/src/seed/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/python-sdk/plain-text/src/seed/service/client.py b/seed/python-sdk/plain-text/src/seed/service/client.py index f482a6313c0..e2001879232 100644 --- a/seed/python-sdk/plain-text/src/seed/service/client.py +++ b/seed/python-sdk/plain-text/src/seed/service/client.py @@ -1,18 +1,20 @@ # This file was auto-generated by Fern from our API Definition. +from ..core.client_wrapper import SyncClientWrapper import typing +from ..core.request_options import RequestOptions from json.decoder import JSONDecodeError - from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.request_options import RequestOptions +from ..core.client_wrapper import AsyncClientWrapper class ServiceClient: def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper - def get_text(self, *, request_options: typing.Optional[RequestOptions] = None) -> str: + def get_text( + self, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -32,7 +34,11 @@ def get_text(self, *, request_options: typing.Optional[RequestOptions] = None) - ) client.service.get_text() """ - _response = self._client_wrapper.httpx_client.request("text", method="POST", request_options=request_options) + _response = self._client_wrapper.httpx_client.request( + "text", + method="POST", + request_options=request_options, + ) try: if 200 <= _response.status_code < 300: return _response.text # type: ignore @@ -46,7 +52,9 @@ class AsyncServiceClient: def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper - async def get_text(self, *, request_options: typing.Optional[RequestOptions] = None) -> str: + async def get_text( + self, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -75,7 +83,9 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "text", method="POST", request_options=request_options + "text", + method="POST", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: diff --git a/seed/python-sdk/plain-text/src/seed/version.py b/seed/python-sdk/plain-text/src/seed/version.py index 222dd53bf98..78d8e0d2423 100644 --- a/seed/python-sdk/plain-text/src/seed/version.py +++ b/seed/python-sdk/plain-text/src/seed/version.py @@ -1,4 +1,3 @@ - from importlib import metadata __version__ = metadata.version("fern_plain-text") diff --git a/seed/python-sdk/plain-text/tests/conftest.py b/seed/python-sdk/plain-text/tests/conftest.py index 2d818c3c69a..530e420e4db 100644 --- a/seed/python-sdk/plain-text/tests/conftest.py +++ b/seed/python-sdk/plain-text/tests/conftest.py @@ -1,9 +1,9 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedPlainText import os - import pytest -from seed import AsyncSeedPlainText, SeedPlainText +from seed import AsyncSeedPlainText @pytest.fixture diff --git a/seed/python-sdk/plain-text/tests/custom/test_client.py b/seed/python-sdk/plain-text/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/python-sdk/plain-text/tests/custom/test_client.py +++ b/seed/python-sdk/plain-text/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/python-sdk/plain-text/tests/test_service.py b/seed/python-sdk/plain-text/tests/test_service.py index 653a4890d08..44f162d02dc 100644 --- a/seed/python-sdk/plain-text/tests/test_service.py +++ b/seed/python-sdk/plain-text/tests/test_service.py @@ -1,13 +1,14 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedPlainText +from seed import AsyncSeedPlainText import typing - -from seed import AsyncSeedPlainText, SeedPlainText - from .utilities import validate_response -async def test_get_text(client: SeedPlainText, async_client: AsyncSeedPlainText) -> None: +async def test_get_text( + client: SeedPlainText, async_client: AsyncSeedPlainText +) -> None: expected_response: typing.Any = "string" expected_types: typing.Any = None response = client.service.get_text() diff --git a/seed/python-sdk/plain-text/tests/utilities.py b/seed/python-sdk/plain-text/tests/utilities.py index 13da208eb3a..e8f4472564c 100644 --- a/seed/python-sdk/plain-text/tests/utilities.py +++ b/seed/python-sdk/plain-text/tests/utilities.py @@ -3,11 +3,14 @@ import typing import uuid -import pydantic from dateutil import parser +import pydantic + -def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> typing.Any: +def cast_field( + json_expectation: typing.Any, type_expectation: typing.Any +) -> typing.Any: # Cast these specific types which come through as string and expect our # models to cast to the correct type. if type_expectation == "uuid": @@ -25,7 +28,9 @@ def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> ty return json_expectation -def validate_field(response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any) -> None: +def validate_field( + response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectation == "no_validate": return @@ -44,7 +49,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(entry_expectation, dict): is_container_of_complex_type = True validate_response( - response=response[idx], json_expectation=ex, type_expectations=entry_expectation + response=response[idx], + json_expectation=ex, + type_expectations=entry_expectation, ) else: cast_json_expectation.append(cast_field(ex, entry_expectation)) @@ -56,7 +63,10 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # if any of the values of the set have a type_expectation of a dict, we're assuming it's a pydantic # model and keeping it a list. if container_expectation != "set" or not any( - map(lambda value: isinstance(value, dict), list(contents_expectation.values())) + map( + lambda value: isinstance(value, dict), + list(contents_expectation.values()), + ) ): json_expectation = cast_field(json_expectation, container_expectation) elif isinstance(type_expectation, tuple): @@ -65,9 +75,15 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(contents_expectation, dict): json_expectation = { cast_field( - key, contents_expectation.get(idx)[0] if contents_expectation.get(idx) is not None else None # type: ignore + key, + contents_expectation.get(idx)[0] + if contents_expectation.get(idx) is not None + else None, # type: ignore ): cast_field( - value, contents_expectation.get(idx)[1] if contents_expectation.get(idx) is not None else None # type: ignore + value, + contents_expectation.get(idx)[1] + if contents_expectation.get(idx) is not None + else None, # type: ignore ) for idx, (key, value) in enumerate(json_expectation.items()) } @@ -86,7 +102,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # Arg type_expectations is a deeply nested structure that matches the response, but with the values replaced with the expected types -def validate_response(response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any) -> None: +def validate_response( + response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectations == "no_validate": return @@ -96,11 +114,17 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e and not isinstance(response, dict) and not issubclass(type(response), pydantic.BaseModel) ): - validate_field(response=response, json_expectation=json_expectation, type_expectation=type_expectations) + validate_field( + response=response, + json_expectation=json_expectation, + type_expectation=type_expectations, + ) return if isinstance(response, list): - assert len(response) == len(json_expectation), "Length mismatch, expected: {0}, Actual: {1}".format( + assert len(response) == len( + json_expectation + ), "Length mismatch, expected: {0}, Actual: {1}".format( len(response), len(json_expectation) ) content_expectation = type_expectations @@ -108,7 +132,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e content_expectation = type_expectations[1] for idx, item in enumerate(response): validate_response( - response=item, json_expectation=json_expectation[idx], type_expectations=content_expectation[idx] + response=item, + json_expectation=json_expectation[idx], + type_expectations=content_expectation[idx], ) else: response_json = response @@ -116,7 +142,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e response_json = response.dict(by_alias=True) for key, value in json_expectation.items(): - assert key in response_json, "Field {0} not found within the response object: {1}".format( + assert ( + key in response_json + ), "Field {0} not found within the response object: {1}".format( key, response_json ) @@ -128,11 +156,19 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e # Otherwise, we're just validating a single field that's a pydantic model. if isinstance(value, dict) and not isinstance(type_expectation, tuple): validate_response( - response=response_json[key], json_expectation=value, type_expectations=type_expectation + response=response_json[key], + json_expectation=value, + type_expectations=type_expectation, ) else: - validate_field(response=response_json[key], json_expectation=value, type_expectation=type_expectation) + validate_field( + response=response_json[key], + json_expectation=value, + type_expectation=type_expectation, + ) # Ensure there are no additional fields here either del response_json[key] - assert len(response_json) == 0, "Additional fields found, expected None: {0}".format(response_json) + assert ( + len(response_json) == 0 + ), "Additional fields found, expected None: {0}".format(response_json) diff --git a/seed/python-sdk/plain-text/tests/utils/assets/models/__init__.py b/seed/python-sdk/plain-text/tests/utils/assets/models/__init__.py index 2cf01263529..3a1c852e71e 100644 --- a/seed/python-sdk/plain-text/tests/utils/assets/models/__init__.py +++ b/seed/python-sdk/plain-text/tests/utils/assets/models/__init__.py @@ -5,7 +5,7 @@ from .circle import CircleParams from .object_with_defaults import ObjectWithDefaultsParams from .object_with_optional_field import ObjectWithOptionalFieldParams -from .shape import Shape_CircleParams, Shape_SquareParams, ShapeParams +from .shape import ShapeParams, Shape_CircleParams, Shape_SquareParams from .square import SquareParams from .undiscriminated_shape import UndiscriminatedShapeParams diff --git a/seed/python-sdk/plain-text/tests/utils/assets/models/circle.py b/seed/python-sdk/plain-text/tests/utils/assets/models/circle.py index af7a1bf8a8e..253f12d38b3 100644 --- a/seed/python-sdk/plain-text/tests/utils/assets/models/circle.py +++ b/seed/python-sdk/plain-text/tests/utils/assets/models/circle.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class CircleParams(typing_extensions.TypedDict): - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] diff --git a/seed/python-sdk/plain-text/tests/utils/assets/models/object_with_optional_field.py b/seed/python-sdk/plain-text/tests/utils/assets/models/object_with_optional_field.py index 3ad93d5f305..ebe7dc80547 100644 --- a/seed/python-sdk/plain-text/tests/utils/assets/models/object_with_optional_field.py +++ b/seed/python-sdk/plain-text/tests/utils/assets/models/object_with_optional_field.py @@ -7,8 +7,8 @@ import uuid import typing_extensions -from seed.core.serialization import FieldMetadata +from seed.core.serialization import FieldMetadata from .color import Color from .shape import ShapeParams from .undiscriminated_shape import UndiscriminatedShapeParams @@ -18,16 +18,30 @@ class ObjectWithOptionalFieldParams(typing_extensions.TypedDict): literal: typing.Literal["lit_one"] string: typing_extensions.NotRequired[str] integer: typing_extensions.NotRequired[int] - long_: typing_extensions.NotRequired[typing_extensions.Annotated[int, FieldMetadata(alias="long")]] + long_: typing_extensions.NotRequired[ + typing_extensions.Annotated[int, FieldMetadata(alias="long")] + ] double: typing_extensions.NotRequired[float] - bool_: typing_extensions.NotRequired[typing_extensions.Annotated[bool, FieldMetadata(alias="bool")]] + bool_: typing_extensions.NotRequired[ + typing_extensions.Annotated[bool, FieldMetadata(alias="bool")] + ] datetime: typing_extensions.NotRequired[dt.datetime] date: typing_extensions.NotRequired[dt.date] - uuid_: typing_extensions.NotRequired[typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")]] - base_64: typing_extensions.NotRequired[typing_extensions.Annotated[str, FieldMetadata(alias="base64")]] - list_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")]] - set_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")]] - map_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")]] + uuid_: typing_extensions.NotRequired[ + typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")] + ] + base_64: typing_extensions.NotRequired[ + typing_extensions.Annotated[str, FieldMetadata(alias="base64")] + ] + list_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")] + ] + set_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")] + ] + map_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")] + ] enum: typing_extensions.NotRequired[Color] union: typing_extensions.NotRequired[ShapeParams] second_union: typing_extensions.NotRequired[ShapeParams] diff --git a/seed/python-sdk/plain-text/tests/utils/assets/models/shape.py b/seed/python-sdk/plain-text/tests/utils/assets/models/shape.py index 2c33c877951..816ffc51bdc 100644 --- a/seed/python-sdk/plain-text/tests/utils/assets/models/shape.py +++ b/seed/python-sdk/plain-text/tests/utils/assets/models/shape.py @@ -7,6 +7,7 @@ import typing import typing_extensions + from seed.core.serialization import FieldMetadata @@ -15,13 +16,21 @@ class Base(typing_extensions.TypedDict): class Shape_CircleParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["circle"], FieldMetadata(alias="shapeType")] - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["circle"], FieldMetadata(alias="shapeType") + ] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] class Shape_SquareParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["square"], FieldMetadata(alias="shapeType")] - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["square"], FieldMetadata(alias="shapeType") + ] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] ShapeParams = typing.Union[Shape_CircleParams, Shape_SquareParams] diff --git a/seed/python-sdk/plain-text/tests/utils/assets/models/square.py b/seed/python-sdk/plain-text/tests/utils/assets/models/square.py index b9b7dd319bc..bcf08a723c5 100644 --- a/seed/python-sdk/plain-text/tests/utils/assets/models/square.py +++ b/seed/python-sdk/plain-text/tests/utils/assets/models/square.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class SquareParams(typing_extensions.TypedDict): - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] diff --git a/seed/python-sdk/plain-text/tests/utils/test_http_client.py b/seed/python-sdk/plain-text/tests/utils/test_http_client.py index edd11ca7afb..f5a874a75f3 100644 --- a/seed/python-sdk/plain-text/tests/utils/test_http_client.py +++ b/seed/python-sdk/plain-text/tests/utils/test_http_client.py @@ -9,12 +9,17 @@ def get_request_options() -> RequestOptions: def test_get_json_request_body() -> None: - json_body, data_body = get_request_body(json={"hello": "world"}, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json={"hello": "world"}, data=None, request_options=None, omit=None + ) assert json_body == {"hello": "world"} assert data_body is None json_body_extras, data_body_extras = get_request_body( - json={"goodbye": "world"}, data=None, request_options=get_request_options(), omit=None + json={"goodbye": "world"}, + data=None, + request_options=get_request_options(), + omit=None, ) assert json_body_extras == {"goodbye": "world", "see you": "later"} @@ -22,12 +27,17 @@ def test_get_json_request_body() -> None: def test_get_files_request_body() -> None: - json_body, data_body = get_request_body(json=None, data={"hello": "world"}, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data={"hello": "world"}, request_options=None, omit=None + ) assert data_body == {"hello": "world"} assert json_body is None json_body_extras, data_body_extras = get_request_body( - json=None, data={"goodbye": "world"}, request_options=get_request_options(), omit=None + json=None, + data={"goodbye": "world"}, + request_options=get_request_options(), + omit=None, ) assert data_body_extras == {"goodbye": "world", "see you": "later"} @@ -35,7 +45,9 @@ def test_get_files_request_body() -> None: def test_get_none_request_body() -> None: - json_body, data_body = get_request_body(json=None, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data=None, request_options=None, omit=None + ) assert data_body is None assert json_body is None diff --git a/seed/python-sdk/plain-text/tests/utils/test_query_encoding.py b/seed/python-sdk/plain-text/tests/utils/test_query_encoding.py index 247e1551b46..fbc8f402167 100644 --- a/seed/python-sdk/plain-text/tests/utils/test_query_encoding.py +++ b/seed/python-sdk/plain-text/tests/utils/test_query_encoding.py @@ -4,9 +4,15 @@ def test_query_encoding() -> None: - assert encode_query({"hello world": "hello world"}) == {"hello world": "hello world"} - assert encode_query({"hello_world": {"hello": "world"}}) == {"hello_world[hello]": "world"} - assert encode_query({"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"}) == { + assert encode_query({"hello world": "hello world"}) == { + "hello world": "hello world" + } + assert encode_query({"hello_world": {"hello": "world"}}) == { + "hello_world[hello]": "world" + } + assert encode_query( + {"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"} + ) == { "hello_world[hello][world]": "today", "hello_world[test]": "this", "hi": "there", diff --git a/seed/python-sdk/plain-text/tests/utils/test_serialization.py b/seed/python-sdk/plain-text/tests/utils/test_serialization.py index 58b1ed66e6d..5ca956916dd 100644 --- a/seed/python-sdk/plain-text/tests/utils/test_serialization.py +++ b/seed/python-sdk/plain-text/tests/utils/test_serialization.py @@ -1,10 +1,12 @@ # This file was auto-generated by Fern from our API Definition. -from typing import Any, List +from typing import List, Any -from seed.core.serialization import convert_and_respect_annotation_metadata +from seed.core.serialization import ( + convert_and_respect_annotation_metadata, +) +from .assets.models import ShapeParams, ObjectWithOptionalFieldParams -from .assets.models import ObjectWithOptionalFieldParams, ShapeParams UNION_TEST: ShapeParams = {"radius_measurement": 1.0, "shape_type": "circle", "id": "1"} UNION_TEST_CONVERTED = {"shapeType": "circle", "radiusMeasurement": 1.0, "id": "1"} @@ -18,20 +20,54 @@ def test_convert_and_respect_annotation_metadata() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) - assert converted == {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"} + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) + assert converted == { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + } def test_convert_and_respect_annotation_metadata_in_list() -> None: data: List[ObjectWithOptionalFieldParams] = [ - {"string": "string", "long_": 12345, "bool_": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long_": 67890, "list_": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long_": 12345, + "bool_": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long_": 67890, + "list_": [], + "literal": "lit_one", + "any": "any", + }, ] - converted = convert_and_respect_annotation_metadata(object_=data, annotation=List[ObjectWithOptionalFieldParams]) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=List[ObjectWithOptionalFieldParams] + ) assert converted == [ - {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long": 67890, "list": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long": 67890, + "list": [], + "literal": "lit_one", + "any": "any", + }, ] @@ -43,7 +79,9 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) assert converted == { "string": "string", @@ -55,12 +93,16 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: def test_convert_and_respect_annotation_metadata_in_union() -> None: - converted = convert_and_respect_annotation_metadata(object_=UNION_TEST, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=UNION_TEST, annotation=ShapeParams + ) assert converted == UNION_TEST_CONVERTED def test_convert_and_respect_annotation_metadata_with_empty_object() -> None: data: Any = {} - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ShapeParams + ) assert converted == data diff --git a/seed/python-sdk/query-parameters/pyproject.toml b/seed/python-sdk/query-parameters/pyproject.toml index 421ccee1a35..a8346a25a49 100644 --- a/seed/python-sdk/query-parameters/pyproject.toml +++ b/seed/python-sdk/query-parameters/pyproject.toml @@ -43,6 +43,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/python-sdk/query-parameters/src/seed/__init__.py b/seed/python-sdk/query-parameters/src/seed/__init__.py index 2bdc18a4602..e17dec92a4f 100644 --- a/seed/python-sdk/query-parameters/src/seed/__init__.py +++ b/seed/python-sdk/query-parameters/src/seed/__init__.py @@ -5,4 +5,11 @@ from .user import NestedUser, User from .version import __version__ -__all__ = ["AsyncSeedQueryParameters", "NestedUser", "SeedQueryParameters", "User", "__version__", "user"] +__all__ = [ + "AsyncSeedQueryParameters", + "NestedUser", + "SeedQueryParameters", + "User", + "__version__", + "user", +] diff --git a/seed/python-sdk/query-parameters/src/seed/client.py b/seed/python-sdk/query-parameters/src/seed/client.py index 03b51635778..87917f37bfa 100644 --- a/seed/python-sdk/query-parameters/src/seed/client.py +++ b/seed/python-sdk/query-parameters/src/seed/client.py @@ -1,11 +1,11 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from .user.client import AsyncUserClient, UserClient +from .core.client_wrapper import SyncClientWrapper +from .user.client import UserClient +from .core.client_wrapper import AsyncClientWrapper +from .user.client import AsyncUserClient class SeedQueryParameters: @@ -41,14 +41,18 @@ def __init__( base_url: str, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.Client] = None + httpx_client: typing.Optional[httpx.Client] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = SyncClientWrapper( base_url=base_url, httpx_client=httpx_client if httpx_client is not None - else httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.Client( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.Client(timeout=_defaulted_timeout), timeout=_defaulted_timeout, @@ -89,14 +93,18 @@ def __init__( base_url: str, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.AsyncClient] = None + httpx_client: typing.Optional[httpx.AsyncClient] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = AsyncClientWrapper( base_url=base_url, httpx_client=httpx_client if httpx_client is not None - else httpx.AsyncClient(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.AsyncClient( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.AsyncClient(timeout=_defaulted_timeout), timeout=_defaulted_timeout, diff --git a/seed/python-sdk/query-parameters/src/seed/core/api_error.py b/seed/python-sdk/query-parameters/src/seed/core/api_error.py index 2e9fc5431cd..da734b58068 100644 --- a/seed/python-sdk/query-parameters/src/seed/core/api_error.py +++ b/seed/python-sdk/query-parameters/src/seed/core/api_error.py @@ -7,7 +7,9 @@ class ApiError(Exception): status_code: typing.Optional[int] body: typing.Any - def __init__(self, *, status_code: typing.Optional[int] = None, body: typing.Any = None): + def __init__( + self, *, status_code: typing.Optional[int] = None, body: typing.Any = None + ): self.status_code = status_code self.body = body diff --git a/seed/python-sdk/query-parameters/src/seed/core/client_wrapper.py b/seed/python-sdk/query-parameters/src/seed/core/client_wrapper.py index ff1ab771aeb..5c8e61763e2 100644 --- a/seed/python-sdk/query-parameters/src/seed/core/client_wrapper.py +++ b/seed/python-sdk/query-parameters/src/seed/core/client_wrapper.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .http_client import AsyncHttpClient, HttpClient +from .http_client import HttpClient +from .http_client import AsyncHttpClient class BaseClientWrapper: @@ -28,7 +27,13 @@ def get_timeout(self) -> typing.Optional[float]: class SyncClientWrapper(BaseClientWrapper): - def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, httpx_client: httpx.Client): + def __init__( + self, + *, + base_url: str, + timeout: typing.Optional[float] = None, + httpx_client: httpx.Client, + ): super().__init__(base_url=base_url, timeout=timeout) self.httpx_client = HttpClient( httpx_client=httpx_client, @@ -39,7 +44,13 @@ def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, htt class AsyncClientWrapper(BaseClientWrapper): - def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, httpx_client: httpx.AsyncClient): + def __init__( + self, + *, + base_url: str, + timeout: typing.Optional[float] = None, + httpx_client: httpx.AsyncClient, + ): super().__init__(base_url=base_url, timeout=timeout) self.httpx_client = AsyncHttpClient( httpx_client=httpx_client, diff --git a/seed/python-sdk/query-parameters/src/seed/core/datetime_utils.py b/seed/python-sdk/query-parameters/src/seed/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/python-sdk/query-parameters/src/seed/core/datetime_utils.py +++ b/seed/python-sdk/query-parameters/src/seed/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/python-sdk/query-parameters/src/seed/core/file.py b/seed/python-sdk/query-parameters/src/seed/core/file.py index cb0d40bbbf3..6e0f92bfcb1 100644 --- a/seed/python-sdk/query-parameters/src/seed/core/file.py +++ b/seed/python-sdk/query-parameters/src/seed/core/file.py @@ -13,12 +13,17 @@ # (filename, file (or bytes), content_type) typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str]], # (filename, file (or bytes), content_type, headers) - typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str], typing.Mapping[str, str]], + typing.Tuple[ + typing.Optional[str], + FileContent, + typing.Optional[str], + typing.Mapping[str, str], + ], ] def convert_file_dict_to_httpx_tuples( - d: typing.Dict[str, typing.Union[File, typing.List[File]]] + d: typing.Dict[str, typing.Union[File, typing.List[File]]], ) -> typing.List[typing.Tuple[str, File]]: """ The format we use is a list of tuples, where the first element is the diff --git a/seed/python-sdk/query-parameters/src/seed/core/http_client.py b/seed/python-sdk/query-parameters/src/seed/core/http_client.py index 9333d8a7f15..091f71bc185 100644 --- a/seed/python-sdk/query-parameters/src/seed/core/http_client.py +++ b/seed/python-sdk/query-parameters/src/seed/core/http_client.py @@ -77,7 +77,9 @@ def _retry_timeout(response: httpx.Response, retries: int) -> float: return retry_after # Apply exponential backoff, capped at MAX_RETRY_DELAY_SECONDS. - retry_delay = min(INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS) + retry_delay = min( + INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS + ) # Add a randomness / jitter to the retry delay to avoid overwhelming the server with retries. timeout = retry_delay * (1 - 0.25 * random()) @@ -90,7 +92,8 @@ def _should_retry(response: httpx.Response) -> bool: def remove_omit_from_dict( - original: typing.Dict[str, typing.Optional[typing.Any]], omit: typing.Optional[typing.Any] + original: typing.Dict[str, typing.Optional[typing.Any]], + omit: typing.Optional[typing.Any], ) -> typing.Dict[str, typing.Any]: if omit is None: return original @@ -108,7 +111,8 @@ def maybe_filter_request_body( ) -> typing.Optional[typing.Any]: if data is None: return ( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else None ) @@ -118,7 +122,8 @@ def maybe_filter_request_body( data_content = { **(jsonable_encoder(remove_omit_from_dict(data, omit))), # type: ignore **( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else {} ), @@ -162,7 +167,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url def request( @@ -174,8 +181,12 @@ def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -184,11 +195,14 @@ def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) response = self.httpx_client.request( method=method, @@ -198,7 +212,11 @@ def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -209,7 +227,10 @@ def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -222,11 +243,15 @@ def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: time.sleep(_retry_timeout(response=response, retries=retries)) @@ -256,8 +281,12 @@ def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -266,11 +295,14 @@ def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) with self.httpx_client.stream( method=method, @@ -280,7 +312,11 @@ def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -291,7 +327,9 @@ def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -304,7 +342,9 @@ def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream @@ -327,7 +367,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url async def request( @@ -339,8 +381,12 @@ async def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -349,11 +395,14 @@ async def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) # Add the input to each of these and do None-safety checks response = await self.httpx_client.request( @@ -364,7 +413,11 @@ async def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -375,7 +428,10 @@ async def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -388,11 +444,15 @@ async def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: await asyncio.sleep(_retry_timeout(response=response, retries=retries)) @@ -421,8 +481,12 @@ async def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -431,11 +495,14 @@ async def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) async with self.httpx_client.stream( method=method, @@ -445,7 +512,11 @@ async def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -456,7 +527,9 @@ async def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -469,7 +542,9 @@ async def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream diff --git a/seed/python-sdk/query-parameters/src/seed/core/jsonable_encoder.py b/seed/python-sdk/query-parameters/src/seed/core/jsonable_encoder.py index d3fd328fd41..12a8b52fc22 100644 --- a/seed/python-sdk/query-parameters/src/seed/core/jsonable_encoder.py +++ b/seed/python-sdk/query-parameters/src/seed/core/jsonable_encoder.py @@ -19,13 +19,19 @@ import pydantic from .datetime_utils import serialize_datetime -from .pydantic_utilities import IS_PYDANTIC_V2, encode_by_type, to_jsonable_with_fallback +from .pydantic_utilities import ( + IS_PYDANTIC_V2, + encode_by_type, + to_jsonable_with_fallback, +) SetIntStr = Set[Union[int, str]] DictIntStrAny = Dict[Union[int, str], Any] -def jsonable_encoder(obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None) -> Any: +def jsonable_encoder( + obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None +) -> Any: custom_encoder = custom_encoder or {} if custom_encoder: if type(obj) in custom_encoder: diff --git a/seed/python-sdk/query-parameters/src/seed/core/pydantic_utilities.py b/seed/python-sdk/query-parameters/src/seed/core/pydantic_utilities.py index 170a563d6eb..c63935c32a2 100644 --- a/seed/python-sdk/query-parameters/src/seed/core/pydantic_utilities.py +++ b/seed/python-sdk/query-parameters/src/seed/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) # type: ignore # Pydantic v1 diff --git a/seed/python-sdk/query-parameters/src/seed/core/query_encoder.py b/seed/python-sdk/query-parameters/src/seed/core/query_encoder.py index 24076d72ee9..7cb98f52cd7 100644 --- a/seed/python-sdk/query-parameters/src/seed/core/query_encoder.py +++ b/seed/python-sdk/query-parameters/src/seed/core/query_encoder.py @@ -7,7 +7,9 @@ # Flattens dicts to be of the form {"key[subkey][subkey2]": value} where value is not a dict -def traverse_query_dict(dict_flat: Dict[str, Any], key_prefix: Optional[str] = None) -> Dict[str, Any]: +def traverse_query_dict( + dict_flat: Dict[str, Any], key_prefix: Optional[str] = None +) -> Dict[str, Any]: result = {} for k, v in dict_flat.items(): key = f"{key_prefix}[{k}]" if key_prefix is not None else k @@ -30,4 +32,8 @@ def single_query_encoder(query_key: str, query_value: Any) -> Dict[str, Any]: def encode_query(query: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: - return dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) if query is not None else None + return ( + dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) + if query is not None + else None + ) diff --git a/seed/python-sdk/query-parameters/src/seed/core/serialization.py b/seed/python-sdk/query-parameters/src/seed/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/python-sdk/query-parameters/src/seed/core/serialization.py +++ b/seed/python-sdk/query-parameters/src/seed/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/python-sdk/query-parameters/src/seed/user/client.py b/seed/python-sdk/query-parameters/src/seed/user/client.py index b623480d823..e9680763c53 100644 --- a/seed/python-sdk/query-parameters/src/seed/user/client.py +++ b/seed/python-sdk/query-parameters/src/seed/user/client.py @@ -1,18 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ..core.client_wrapper import SyncClientWrapper +import uuid import datetime as dt +from .types.user import User import typing -import uuid -from json.decoder import JSONDecodeError - -from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.datetime_utils import serialize_datetime +from .types.nested_user import NestedUser +from ..core.request_options import RequestOptions from ..core.jsonable_encoder import jsonable_encoder +from ..core.datetime_utils import serialize_datetime from ..core.pydantic_utilities import parse_obj_as -from ..core.request_options import RequestOptions -from .types.nested_user import NestedUser -from .types.user import User +from json.decoder import JSONDecodeError +from ..core.api_error import ApiError +from ..core.client_wrapper import AsyncClientWrapper class UserClient: @@ -36,7 +36,7 @@ def get_username( optional_deadline: typing.Optional[dt.datetime] = None, optional_string: typing.Optional[str] = None, optional_user: typing.Optional[User] = None, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> User: """ Parameters @@ -143,7 +143,9 @@ def get_username( "bytes": jsonable_encoder(bytes), "user": jsonable_encoder(user), "userList": jsonable_encoder(user_list), - "optionalDeadline": serialize_datetime(optional_deadline) if optional_deadline is not None else None, + "optionalDeadline": serialize_datetime(optional_deadline) + if optional_deadline is not None + else None, "keyValue": jsonable_encoder(key_value), "optionalString": optional_string, "nestedUser": jsonable_encoder(nested_user), @@ -155,7 +157,9 @@ def get_username( ) try: if 200 <= _response.status_code < 300: - return typing.cast(User, parse_obj_as(type_=User, object_=_response.json())) # type: ignore + return typing.cast( + User, parse_obj_as(type_=User, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -183,7 +187,7 @@ async def get_username( optional_deadline: typing.Optional[dt.datetime] = None, optional_string: typing.Optional[str] = None, optional_user: typing.Optional[User] = None, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> User: """ Parameters @@ -297,7 +301,9 @@ async def main() -> None: "bytes": jsonable_encoder(bytes), "user": jsonable_encoder(user), "userList": jsonable_encoder(user_list), - "optionalDeadline": serialize_datetime(optional_deadline) if optional_deadline is not None else None, + "optionalDeadline": serialize_datetime(optional_deadline) + if optional_deadline is not None + else None, "keyValue": jsonable_encoder(key_value), "optionalString": optional_string, "nestedUser": jsonable_encoder(nested_user), @@ -309,7 +315,9 @@ async def main() -> None: ) try: if 200 <= _response.status_code < 300: - return typing.cast(User, parse_obj_as(type_=User, object_=_response.json())) # type: ignore + return typing.cast( + User, parse_obj_as(type_=User, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/query-parameters/src/seed/user/types/nested_user.py b/seed/python-sdk/query-parameters/src/seed/user/types/nested_user.py index 4d961638885..01ebef05d3a 100644 --- a/seed/python-sdk/query-parameters/src/seed/user/types/nested_user.py +++ b/seed/python-sdk/query-parameters/src/seed/user/types/nested_user.py @@ -1,19 +1,20 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from .user import User +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .user import User - class NestedUser(UniversalBaseModel): name: str user: User if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/query-parameters/src/seed/user/types/user.py b/seed/python-sdk/query-parameters/src/seed/user/types/user.py index 6c9a6739e36..81f18043020 100644 --- a/seed/python-sdk/query-parameters/src/seed/user/types/user.py +++ b/seed/python-sdk/query-parameters/src/seed/user/types/user.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel import typing - +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class User(UniversalBaseModel): name: str tags: typing.List[str] if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/query-parameters/src/seed/version.py b/seed/python-sdk/query-parameters/src/seed/version.py index 448d25b0cd7..71bbdab6949 100644 --- a/seed/python-sdk/query-parameters/src/seed/version.py +++ b/seed/python-sdk/query-parameters/src/seed/version.py @@ -1,4 +1,3 @@ - from importlib import metadata __version__ = metadata.version("fern_query-parameters") diff --git a/seed/python-sdk/query-parameters/tests/conftest.py b/seed/python-sdk/query-parameters/tests/conftest.py index 2bb1fd8c235..7737fdf5462 100644 --- a/seed/python-sdk/query-parameters/tests/conftest.py +++ b/seed/python-sdk/query-parameters/tests/conftest.py @@ -1,9 +1,9 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedQueryParameters import os - import pytest -from seed import AsyncSeedQueryParameters, SeedQueryParameters +from seed import AsyncSeedQueryParameters @pytest.fixture diff --git a/seed/python-sdk/query-parameters/tests/custom/test_client.py b/seed/python-sdk/query-parameters/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/python-sdk/query-parameters/tests/custom/test_client.py +++ b/seed/python-sdk/query-parameters/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/python-sdk/query-parameters/tests/test_user.py b/seed/python-sdk/query-parameters/tests/test_user.py index 937cfc1bba5..beafa6aa458 100644 --- a/seed/python-sdk/query-parameters/tests/test_user.py +++ b/seed/python-sdk/query-parameters/tests/test_user.py @@ -1,16 +1,18 @@ # This file was auto-generated by Fern from our API Definition. -import datetime +from seed import SeedQueryParameters +from seed import AsyncSeedQueryParameters import typing import uuid - -from seed import AsyncSeedQueryParameters, SeedQueryParameters -from seed.user import NestedUser, User - +import datetime +from seed.user import User +from seed.user import NestedUser from .utilities import validate_response -async def test_get_username(client: SeedQueryParameters, async_client: AsyncSeedQueryParameters) -> None: +async def test_get_username( + client: SeedQueryParameters, async_client: AsyncSeedQueryParameters +) -> None: expected_response: typing.Any = {"name": "string", "tags": ["string"]} expected_types: typing.Any = {"name": None, "tags": ("list", {0: None})} response = client.user.get_username( @@ -24,7 +26,9 @@ async def test_get_username(client: SeedQueryParameters, async_client: AsyncSeed optional_deadline=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), key_value={"string": "string"}, optional_string="string", - nested_user=NestedUser(name="string", user=User(name="string", tags=["string"])), + nested_user=NestedUser( + name="string", user=User(name="string", tags=["string"]) + ), optional_user=User(name="string", tags=["string"]), exclude_user=User(name="string", tags=["string"]), filter="string", @@ -42,7 +46,9 @@ async def test_get_username(client: SeedQueryParameters, async_client: AsyncSeed optional_deadline=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), key_value={"string": "string"}, optional_string="string", - nested_user=NestedUser(name="string", user=User(name="string", tags=["string"])), + nested_user=NestedUser( + name="string", user=User(name="string", tags=["string"]) + ), optional_user=User(name="string", tags=["string"]), exclude_user=User(name="string", tags=["string"]), filter="string", diff --git a/seed/python-sdk/query-parameters/tests/utilities.py b/seed/python-sdk/query-parameters/tests/utilities.py index 13da208eb3a..e8f4472564c 100644 --- a/seed/python-sdk/query-parameters/tests/utilities.py +++ b/seed/python-sdk/query-parameters/tests/utilities.py @@ -3,11 +3,14 @@ import typing import uuid -import pydantic from dateutil import parser +import pydantic + -def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> typing.Any: +def cast_field( + json_expectation: typing.Any, type_expectation: typing.Any +) -> typing.Any: # Cast these specific types which come through as string and expect our # models to cast to the correct type. if type_expectation == "uuid": @@ -25,7 +28,9 @@ def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> ty return json_expectation -def validate_field(response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any) -> None: +def validate_field( + response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectation == "no_validate": return @@ -44,7 +49,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(entry_expectation, dict): is_container_of_complex_type = True validate_response( - response=response[idx], json_expectation=ex, type_expectations=entry_expectation + response=response[idx], + json_expectation=ex, + type_expectations=entry_expectation, ) else: cast_json_expectation.append(cast_field(ex, entry_expectation)) @@ -56,7 +63,10 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # if any of the values of the set have a type_expectation of a dict, we're assuming it's a pydantic # model and keeping it a list. if container_expectation != "set" or not any( - map(lambda value: isinstance(value, dict), list(contents_expectation.values())) + map( + lambda value: isinstance(value, dict), + list(contents_expectation.values()), + ) ): json_expectation = cast_field(json_expectation, container_expectation) elif isinstance(type_expectation, tuple): @@ -65,9 +75,15 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(contents_expectation, dict): json_expectation = { cast_field( - key, contents_expectation.get(idx)[0] if contents_expectation.get(idx) is not None else None # type: ignore + key, + contents_expectation.get(idx)[0] + if contents_expectation.get(idx) is not None + else None, # type: ignore ): cast_field( - value, contents_expectation.get(idx)[1] if contents_expectation.get(idx) is not None else None # type: ignore + value, + contents_expectation.get(idx)[1] + if contents_expectation.get(idx) is not None + else None, # type: ignore ) for idx, (key, value) in enumerate(json_expectation.items()) } @@ -86,7 +102,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # Arg type_expectations is a deeply nested structure that matches the response, but with the values replaced with the expected types -def validate_response(response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any) -> None: +def validate_response( + response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectations == "no_validate": return @@ -96,11 +114,17 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e and not isinstance(response, dict) and not issubclass(type(response), pydantic.BaseModel) ): - validate_field(response=response, json_expectation=json_expectation, type_expectation=type_expectations) + validate_field( + response=response, + json_expectation=json_expectation, + type_expectation=type_expectations, + ) return if isinstance(response, list): - assert len(response) == len(json_expectation), "Length mismatch, expected: {0}, Actual: {1}".format( + assert len(response) == len( + json_expectation + ), "Length mismatch, expected: {0}, Actual: {1}".format( len(response), len(json_expectation) ) content_expectation = type_expectations @@ -108,7 +132,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e content_expectation = type_expectations[1] for idx, item in enumerate(response): validate_response( - response=item, json_expectation=json_expectation[idx], type_expectations=content_expectation[idx] + response=item, + json_expectation=json_expectation[idx], + type_expectations=content_expectation[idx], ) else: response_json = response @@ -116,7 +142,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e response_json = response.dict(by_alias=True) for key, value in json_expectation.items(): - assert key in response_json, "Field {0} not found within the response object: {1}".format( + assert ( + key in response_json + ), "Field {0} not found within the response object: {1}".format( key, response_json ) @@ -128,11 +156,19 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e # Otherwise, we're just validating a single field that's a pydantic model. if isinstance(value, dict) and not isinstance(type_expectation, tuple): validate_response( - response=response_json[key], json_expectation=value, type_expectations=type_expectation + response=response_json[key], + json_expectation=value, + type_expectations=type_expectation, ) else: - validate_field(response=response_json[key], json_expectation=value, type_expectation=type_expectation) + validate_field( + response=response_json[key], + json_expectation=value, + type_expectation=type_expectation, + ) # Ensure there are no additional fields here either del response_json[key] - assert len(response_json) == 0, "Additional fields found, expected None: {0}".format(response_json) + assert ( + len(response_json) == 0 + ), "Additional fields found, expected None: {0}".format(response_json) diff --git a/seed/python-sdk/query-parameters/tests/utils/assets/models/__init__.py b/seed/python-sdk/query-parameters/tests/utils/assets/models/__init__.py index 2cf01263529..3a1c852e71e 100644 --- a/seed/python-sdk/query-parameters/tests/utils/assets/models/__init__.py +++ b/seed/python-sdk/query-parameters/tests/utils/assets/models/__init__.py @@ -5,7 +5,7 @@ from .circle import CircleParams from .object_with_defaults import ObjectWithDefaultsParams from .object_with_optional_field import ObjectWithOptionalFieldParams -from .shape import Shape_CircleParams, Shape_SquareParams, ShapeParams +from .shape import ShapeParams, Shape_CircleParams, Shape_SquareParams from .square import SquareParams from .undiscriminated_shape import UndiscriminatedShapeParams diff --git a/seed/python-sdk/query-parameters/tests/utils/assets/models/circle.py b/seed/python-sdk/query-parameters/tests/utils/assets/models/circle.py index af7a1bf8a8e..253f12d38b3 100644 --- a/seed/python-sdk/query-parameters/tests/utils/assets/models/circle.py +++ b/seed/python-sdk/query-parameters/tests/utils/assets/models/circle.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class CircleParams(typing_extensions.TypedDict): - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] diff --git a/seed/python-sdk/query-parameters/tests/utils/assets/models/object_with_optional_field.py b/seed/python-sdk/query-parameters/tests/utils/assets/models/object_with_optional_field.py index 3ad93d5f305..ebe7dc80547 100644 --- a/seed/python-sdk/query-parameters/tests/utils/assets/models/object_with_optional_field.py +++ b/seed/python-sdk/query-parameters/tests/utils/assets/models/object_with_optional_field.py @@ -7,8 +7,8 @@ import uuid import typing_extensions -from seed.core.serialization import FieldMetadata +from seed.core.serialization import FieldMetadata from .color import Color from .shape import ShapeParams from .undiscriminated_shape import UndiscriminatedShapeParams @@ -18,16 +18,30 @@ class ObjectWithOptionalFieldParams(typing_extensions.TypedDict): literal: typing.Literal["lit_one"] string: typing_extensions.NotRequired[str] integer: typing_extensions.NotRequired[int] - long_: typing_extensions.NotRequired[typing_extensions.Annotated[int, FieldMetadata(alias="long")]] + long_: typing_extensions.NotRequired[ + typing_extensions.Annotated[int, FieldMetadata(alias="long")] + ] double: typing_extensions.NotRequired[float] - bool_: typing_extensions.NotRequired[typing_extensions.Annotated[bool, FieldMetadata(alias="bool")]] + bool_: typing_extensions.NotRequired[ + typing_extensions.Annotated[bool, FieldMetadata(alias="bool")] + ] datetime: typing_extensions.NotRequired[dt.datetime] date: typing_extensions.NotRequired[dt.date] - uuid_: typing_extensions.NotRequired[typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")]] - base_64: typing_extensions.NotRequired[typing_extensions.Annotated[str, FieldMetadata(alias="base64")]] - list_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")]] - set_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")]] - map_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")]] + uuid_: typing_extensions.NotRequired[ + typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")] + ] + base_64: typing_extensions.NotRequired[ + typing_extensions.Annotated[str, FieldMetadata(alias="base64")] + ] + list_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")] + ] + set_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")] + ] + map_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")] + ] enum: typing_extensions.NotRequired[Color] union: typing_extensions.NotRequired[ShapeParams] second_union: typing_extensions.NotRequired[ShapeParams] diff --git a/seed/python-sdk/query-parameters/tests/utils/assets/models/shape.py b/seed/python-sdk/query-parameters/tests/utils/assets/models/shape.py index 2c33c877951..816ffc51bdc 100644 --- a/seed/python-sdk/query-parameters/tests/utils/assets/models/shape.py +++ b/seed/python-sdk/query-parameters/tests/utils/assets/models/shape.py @@ -7,6 +7,7 @@ import typing import typing_extensions + from seed.core.serialization import FieldMetadata @@ -15,13 +16,21 @@ class Base(typing_extensions.TypedDict): class Shape_CircleParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["circle"], FieldMetadata(alias="shapeType")] - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["circle"], FieldMetadata(alias="shapeType") + ] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] class Shape_SquareParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["square"], FieldMetadata(alias="shapeType")] - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["square"], FieldMetadata(alias="shapeType") + ] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] ShapeParams = typing.Union[Shape_CircleParams, Shape_SquareParams] diff --git a/seed/python-sdk/query-parameters/tests/utils/assets/models/square.py b/seed/python-sdk/query-parameters/tests/utils/assets/models/square.py index b9b7dd319bc..bcf08a723c5 100644 --- a/seed/python-sdk/query-parameters/tests/utils/assets/models/square.py +++ b/seed/python-sdk/query-parameters/tests/utils/assets/models/square.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class SquareParams(typing_extensions.TypedDict): - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] diff --git a/seed/python-sdk/query-parameters/tests/utils/test_http_client.py b/seed/python-sdk/query-parameters/tests/utils/test_http_client.py index edd11ca7afb..f5a874a75f3 100644 --- a/seed/python-sdk/query-parameters/tests/utils/test_http_client.py +++ b/seed/python-sdk/query-parameters/tests/utils/test_http_client.py @@ -9,12 +9,17 @@ def get_request_options() -> RequestOptions: def test_get_json_request_body() -> None: - json_body, data_body = get_request_body(json={"hello": "world"}, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json={"hello": "world"}, data=None, request_options=None, omit=None + ) assert json_body == {"hello": "world"} assert data_body is None json_body_extras, data_body_extras = get_request_body( - json={"goodbye": "world"}, data=None, request_options=get_request_options(), omit=None + json={"goodbye": "world"}, + data=None, + request_options=get_request_options(), + omit=None, ) assert json_body_extras == {"goodbye": "world", "see you": "later"} @@ -22,12 +27,17 @@ def test_get_json_request_body() -> None: def test_get_files_request_body() -> None: - json_body, data_body = get_request_body(json=None, data={"hello": "world"}, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data={"hello": "world"}, request_options=None, omit=None + ) assert data_body == {"hello": "world"} assert json_body is None json_body_extras, data_body_extras = get_request_body( - json=None, data={"goodbye": "world"}, request_options=get_request_options(), omit=None + json=None, + data={"goodbye": "world"}, + request_options=get_request_options(), + omit=None, ) assert data_body_extras == {"goodbye": "world", "see you": "later"} @@ -35,7 +45,9 @@ def test_get_files_request_body() -> None: def test_get_none_request_body() -> None: - json_body, data_body = get_request_body(json=None, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data=None, request_options=None, omit=None + ) assert data_body is None assert json_body is None diff --git a/seed/python-sdk/query-parameters/tests/utils/test_query_encoding.py b/seed/python-sdk/query-parameters/tests/utils/test_query_encoding.py index 247e1551b46..fbc8f402167 100644 --- a/seed/python-sdk/query-parameters/tests/utils/test_query_encoding.py +++ b/seed/python-sdk/query-parameters/tests/utils/test_query_encoding.py @@ -4,9 +4,15 @@ def test_query_encoding() -> None: - assert encode_query({"hello world": "hello world"}) == {"hello world": "hello world"} - assert encode_query({"hello_world": {"hello": "world"}}) == {"hello_world[hello]": "world"} - assert encode_query({"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"}) == { + assert encode_query({"hello world": "hello world"}) == { + "hello world": "hello world" + } + assert encode_query({"hello_world": {"hello": "world"}}) == { + "hello_world[hello]": "world" + } + assert encode_query( + {"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"} + ) == { "hello_world[hello][world]": "today", "hello_world[test]": "this", "hi": "there", diff --git a/seed/python-sdk/query-parameters/tests/utils/test_serialization.py b/seed/python-sdk/query-parameters/tests/utils/test_serialization.py index 58b1ed66e6d..5ca956916dd 100644 --- a/seed/python-sdk/query-parameters/tests/utils/test_serialization.py +++ b/seed/python-sdk/query-parameters/tests/utils/test_serialization.py @@ -1,10 +1,12 @@ # This file was auto-generated by Fern from our API Definition. -from typing import Any, List +from typing import List, Any -from seed.core.serialization import convert_and_respect_annotation_metadata +from seed.core.serialization import ( + convert_and_respect_annotation_metadata, +) +from .assets.models import ShapeParams, ObjectWithOptionalFieldParams -from .assets.models import ObjectWithOptionalFieldParams, ShapeParams UNION_TEST: ShapeParams = {"radius_measurement": 1.0, "shape_type": "circle", "id": "1"} UNION_TEST_CONVERTED = {"shapeType": "circle", "radiusMeasurement": 1.0, "id": "1"} @@ -18,20 +20,54 @@ def test_convert_and_respect_annotation_metadata() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) - assert converted == {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"} + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) + assert converted == { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + } def test_convert_and_respect_annotation_metadata_in_list() -> None: data: List[ObjectWithOptionalFieldParams] = [ - {"string": "string", "long_": 12345, "bool_": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long_": 67890, "list_": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long_": 12345, + "bool_": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long_": 67890, + "list_": [], + "literal": "lit_one", + "any": "any", + }, ] - converted = convert_and_respect_annotation_metadata(object_=data, annotation=List[ObjectWithOptionalFieldParams]) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=List[ObjectWithOptionalFieldParams] + ) assert converted == [ - {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long": 67890, "list": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long": 67890, + "list": [], + "literal": "lit_one", + "any": "any", + }, ] @@ -43,7 +79,9 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) assert converted == { "string": "string", @@ -55,12 +93,16 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: def test_convert_and_respect_annotation_metadata_in_union() -> None: - converted = convert_and_respect_annotation_metadata(object_=UNION_TEST, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=UNION_TEST, annotation=ShapeParams + ) assert converted == UNION_TEST_CONVERTED def test_convert_and_respect_annotation_metadata_with_empty_object() -> None: data: Any = {} - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ShapeParams + ) assert converted == data diff --git a/seed/python-sdk/reserved-keywords/pyproject.toml b/seed/python-sdk/reserved-keywords/pyproject.toml index 3a6e085da5d..246ea7b9b97 100644 --- a/seed/python-sdk/reserved-keywords/pyproject.toml +++ b/seed/python-sdk/reserved-keywords/pyproject.toml @@ -43,6 +43,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/python-sdk/reserved-keywords/src/seed/__init__.py b/seed/python-sdk/reserved-keywords/src/seed/__init__.py index 721650748f3..f165c1a3659 100644 --- a/seed/python-sdk/reserved-keywords/src/seed/__init__.py +++ b/seed/python-sdk/reserved-keywords/src/seed/__init__.py @@ -5,4 +5,11 @@ from .package import Package, Record from .version import __version__ -__all__ = ["AsyncSeedNurseryApi", "Package", "Record", "SeedNurseryApi", "__version__", "package"] +__all__ = [ + "AsyncSeedNurseryApi", + "Package", + "Record", + "SeedNurseryApi", + "__version__", + "package", +] diff --git a/seed/python-sdk/reserved-keywords/src/seed/client.py b/seed/python-sdk/reserved-keywords/src/seed/client.py index a32e2b872af..396c27875e4 100644 --- a/seed/python-sdk/reserved-keywords/src/seed/client.py +++ b/seed/python-sdk/reserved-keywords/src/seed/client.py @@ -1,11 +1,11 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from .package.client import AsyncPackageClient, PackageClient +from .core.client_wrapper import SyncClientWrapper +from .package.client import PackageClient +from .core.client_wrapper import AsyncClientWrapper +from .package.client import AsyncPackageClient class SeedNurseryApi: @@ -41,14 +41,18 @@ def __init__( base_url: str, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.Client] = None + httpx_client: typing.Optional[httpx.Client] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = SyncClientWrapper( base_url=base_url, httpx_client=httpx_client if httpx_client is not None - else httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.Client( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.Client(timeout=_defaulted_timeout), timeout=_defaulted_timeout, @@ -89,14 +93,18 @@ def __init__( base_url: str, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.AsyncClient] = None + httpx_client: typing.Optional[httpx.AsyncClient] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = AsyncClientWrapper( base_url=base_url, httpx_client=httpx_client if httpx_client is not None - else httpx.AsyncClient(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.AsyncClient( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.AsyncClient(timeout=_defaulted_timeout), timeout=_defaulted_timeout, diff --git a/seed/python-sdk/reserved-keywords/src/seed/core/api_error.py b/seed/python-sdk/reserved-keywords/src/seed/core/api_error.py index 2e9fc5431cd..da734b58068 100644 --- a/seed/python-sdk/reserved-keywords/src/seed/core/api_error.py +++ b/seed/python-sdk/reserved-keywords/src/seed/core/api_error.py @@ -7,7 +7,9 @@ class ApiError(Exception): status_code: typing.Optional[int] body: typing.Any - def __init__(self, *, status_code: typing.Optional[int] = None, body: typing.Any = None): + def __init__( + self, *, status_code: typing.Optional[int] = None, body: typing.Any = None + ): self.status_code = status_code self.body = body diff --git a/seed/python-sdk/reserved-keywords/src/seed/core/client_wrapper.py b/seed/python-sdk/reserved-keywords/src/seed/core/client_wrapper.py index 1a751ae0d5d..8b48e2a5aed 100644 --- a/seed/python-sdk/reserved-keywords/src/seed/core/client_wrapper.py +++ b/seed/python-sdk/reserved-keywords/src/seed/core/client_wrapper.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .http_client import AsyncHttpClient, HttpClient +from .http_client import HttpClient +from .http_client import AsyncHttpClient class BaseClientWrapper: @@ -28,7 +27,13 @@ def get_timeout(self) -> typing.Optional[float]: class SyncClientWrapper(BaseClientWrapper): - def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, httpx_client: httpx.Client): + def __init__( + self, + *, + base_url: str, + timeout: typing.Optional[float] = None, + httpx_client: httpx.Client, + ): super().__init__(base_url=base_url, timeout=timeout) self.httpx_client = HttpClient( httpx_client=httpx_client, @@ -39,7 +44,13 @@ def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, htt class AsyncClientWrapper(BaseClientWrapper): - def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, httpx_client: httpx.AsyncClient): + def __init__( + self, + *, + base_url: str, + timeout: typing.Optional[float] = None, + httpx_client: httpx.AsyncClient, + ): super().__init__(base_url=base_url, timeout=timeout) self.httpx_client = AsyncHttpClient( httpx_client=httpx_client, diff --git a/seed/python-sdk/reserved-keywords/src/seed/core/datetime_utils.py b/seed/python-sdk/reserved-keywords/src/seed/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/python-sdk/reserved-keywords/src/seed/core/datetime_utils.py +++ b/seed/python-sdk/reserved-keywords/src/seed/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/python-sdk/reserved-keywords/src/seed/core/file.py b/seed/python-sdk/reserved-keywords/src/seed/core/file.py index cb0d40bbbf3..6e0f92bfcb1 100644 --- a/seed/python-sdk/reserved-keywords/src/seed/core/file.py +++ b/seed/python-sdk/reserved-keywords/src/seed/core/file.py @@ -13,12 +13,17 @@ # (filename, file (or bytes), content_type) typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str]], # (filename, file (or bytes), content_type, headers) - typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str], typing.Mapping[str, str]], + typing.Tuple[ + typing.Optional[str], + FileContent, + typing.Optional[str], + typing.Mapping[str, str], + ], ] def convert_file_dict_to_httpx_tuples( - d: typing.Dict[str, typing.Union[File, typing.List[File]]] + d: typing.Dict[str, typing.Union[File, typing.List[File]]], ) -> typing.List[typing.Tuple[str, File]]: """ The format we use is a list of tuples, where the first element is the diff --git a/seed/python-sdk/reserved-keywords/src/seed/core/http_client.py b/seed/python-sdk/reserved-keywords/src/seed/core/http_client.py index 9333d8a7f15..091f71bc185 100644 --- a/seed/python-sdk/reserved-keywords/src/seed/core/http_client.py +++ b/seed/python-sdk/reserved-keywords/src/seed/core/http_client.py @@ -77,7 +77,9 @@ def _retry_timeout(response: httpx.Response, retries: int) -> float: return retry_after # Apply exponential backoff, capped at MAX_RETRY_DELAY_SECONDS. - retry_delay = min(INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS) + retry_delay = min( + INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS + ) # Add a randomness / jitter to the retry delay to avoid overwhelming the server with retries. timeout = retry_delay * (1 - 0.25 * random()) @@ -90,7 +92,8 @@ def _should_retry(response: httpx.Response) -> bool: def remove_omit_from_dict( - original: typing.Dict[str, typing.Optional[typing.Any]], omit: typing.Optional[typing.Any] + original: typing.Dict[str, typing.Optional[typing.Any]], + omit: typing.Optional[typing.Any], ) -> typing.Dict[str, typing.Any]: if omit is None: return original @@ -108,7 +111,8 @@ def maybe_filter_request_body( ) -> typing.Optional[typing.Any]: if data is None: return ( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else None ) @@ -118,7 +122,8 @@ def maybe_filter_request_body( data_content = { **(jsonable_encoder(remove_omit_from_dict(data, omit))), # type: ignore **( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else {} ), @@ -162,7 +167,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url def request( @@ -174,8 +181,12 @@ def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -184,11 +195,14 @@ def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) response = self.httpx_client.request( method=method, @@ -198,7 +212,11 @@ def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -209,7 +227,10 @@ def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -222,11 +243,15 @@ def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: time.sleep(_retry_timeout(response=response, retries=retries)) @@ -256,8 +281,12 @@ def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -266,11 +295,14 @@ def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) with self.httpx_client.stream( method=method, @@ -280,7 +312,11 @@ def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -291,7 +327,9 @@ def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -304,7 +342,9 @@ def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream @@ -327,7 +367,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url async def request( @@ -339,8 +381,12 @@ async def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -349,11 +395,14 @@ async def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) # Add the input to each of these and do None-safety checks response = await self.httpx_client.request( @@ -364,7 +413,11 @@ async def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -375,7 +428,10 @@ async def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -388,11 +444,15 @@ async def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: await asyncio.sleep(_retry_timeout(response=response, retries=retries)) @@ -421,8 +481,12 @@ async def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -431,11 +495,14 @@ async def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) async with self.httpx_client.stream( method=method, @@ -445,7 +512,11 @@ async def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -456,7 +527,9 @@ async def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -469,7 +542,9 @@ async def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream diff --git a/seed/python-sdk/reserved-keywords/src/seed/core/jsonable_encoder.py b/seed/python-sdk/reserved-keywords/src/seed/core/jsonable_encoder.py index d3fd328fd41..12a8b52fc22 100644 --- a/seed/python-sdk/reserved-keywords/src/seed/core/jsonable_encoder.py +++ b/seed/python-sdk/reserved-keywords/src/seed/core/jsonable_encoder.py @@ -19,13 +19,19 @@ import pydantic from .datetime_utils import serialize_datetime -from .pydantic_utilities import IS_PYDANTIC_V2, encode_by_type, to_jsonable_with_fallback +from .pydantic_utilities import ( + IS_PYDANTIC_V2, + encode_by_type, + to_jsonable_with_fallback, +) SetIntStr = Set[Union[int, str]] DictIntStrAny = Dict[Union[int, str], Any] -def jsonable_encoder(obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None) -> Any: +def jsonable_encoder( + obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None +) -> Any: custom_encoder = custom_encoder or {} if custom_encoder: if type(obj) in custom_encoder: diff --git a/seed/python-sdk/reserved-keywords/src/seed/core/pydantic_utilities.py b/seed/python-sdk/reserved-keywords/src/seed/core/pydantic_utilities.py index 170a563d6eb..c63935c32a2 100644 --- a/seed/python-sdk/reserved-keywords/src/seed/core/pydantic_utilities.py +++ b/seed/python-sdk/reserved-keywords/src/seed/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) # type: ignore # Pydantic v1 diff --git a/seed/python-sdk/reserved-keywords/src/seed/core/query_encoder.py b/seed/python-sdk/reserved-keywords/src/seed/core/query_encoder.py index 24076d72ee9..7cb98f52cd7 100644 --- a/seed/python-sdk/reserved-keywords/src/seed/core/query_encoder.py +++ b/seed/python-sdk/reserved-keywords/src/seed/core/query_encoder.py @@ -7,7 +7,9 @@ # Flattens dicts to be of the form {"key[subkey][subkey2]": value} where value is not a dict -def traverse_query_dict(dict_flat: Dict[str, Any], key_prefix: Optional[str] = None) -> Dict[str, Any]: +def traverse_query_dict( + dict_flat: Dict[str, Any], key_prefix: Optional[str] = None +) -> Dict[str, Any]: result = {} for k, v in dict_flat.items(): key = f"{key_prefix}[{k}]" if key_prefix is not None else k @@ -30,4 +32,8 @@ def single_query_encoder(query_key: str, query_value: Any) -> Dict[str, Any]: def encode_query(query: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: - return dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) if query is not None else None + return ( + dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) + if query is not None + else None + ) diff --git a/seed/python-sdk/reserved-keywords/src/seed/core/serialization.py b/seed/python-sdk/reserved-keywords/src/seed/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/python-sdk/reserved-keywords/src/seed/core/serialization.py +++ b/seed/python-sdk/reserved-keywords/src/seed/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/python-sdk/reserved-keywords/src/seed/package/client.py b/seed/python-sdk/reserved-keywords/src/seed/package/client.py index e7d46fc1f7e..89825fe2ec6 100644 --- a/seed/python-sdk/reserved-keywords/src/seed/package/client.py +++ b/seed/python-sdk/reserved-keywords/src/seed/package/client.py @@ -1,18 +1,20 @@ # This file was auto-generated by Fern from our API Definition. +from ..core.client_wrapper import SyncClientWrapper import typing +from ..core.request_options import RequestOptions from json.decoder import JSONDecodeError - from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.request_options import RequestOptions +from ..core.client_wrapper import AsyncClientWrapper class PackageClient: def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper - def test(self, *, for_: str, request_options: typing.Optional[RequestOptions] = None) -> None: + def test( + self, *, for_: str, request_options: typing.Optional[RequestOptions] = None + ) -> None: """ Parameters ---------- @@ -37,7 +39,11 @@ def test(self, *, for_: str, request_options: typing.Optional[RequestOptions] = ) """ _response = self._client_wrapper.httpx_client.request( - method="POST", params={"for": for_}, request_options=request_options + method="POST", + params={ + "for": for_, + }, + request_options=request_options, ) if 200 <= _response.status_code < 300: return @@ -52,7 +58,9 @@ class AsyncPackageClient: def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper - async def test(self, *, for_: str, request_options: typing.Optional[RequestOptions] = None) -> None: + async def test( + self, *, for_: str, request_options: typing.Optional[RequestOptions] = None + ) -> None: """ Parameters ---------- @@ -85,7 +93,11 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - method="POST", params={"for": for_}, request_options=request_options + method="POST", + params={ + "for": for_, + }, + request_options=request_options, ) if 200 <= _response.status_code < 300: return diff --git a/seed/python-sdk/reserved-keywords/src/seed/package/types/package.py b/seed/python-sdk/reserved-keywords/src/seed/package/types/package.py index 60406583711..8bc48cdc18f 100644 --- a/seed/python-sdk/reserved-keywords/src/seed/package/types/package.py +++ b/seed/python-sdk/reserved-keywords/src/seed/package/types/package.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class Package(UniversalBaseModel): name: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/reserved-keywords/src/seed/package/types/record.py b/seed/python-sdk/reserved-keywords/src/seed/package/types/record.py index a58ca9d2b43..4a2ebec31da 100644 --- a/seed/python-sdk/reserved-keywords/src/seed/package/types/record.py +++ b/seed/python-sdk/reserved-keywords/src/seed/package/types/record.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel import typing - import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 class Record(UniversalBaseModel): @@ -12,7 +11,9 @@ class Record(UniversalBaseModel): f_3_d: int = pydantic.Field(alias="3d") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/reserved-keywords/src/seed/version.py b/seed/python-sdk/reserved-keywords/src/seed/version.py index 077a4cb9473..5dc78815b01 100644 --- a/seed/python-sdk/reserved-keywords/src/seed/version.py +++ b/seed/python-sdk/reserved-keywords/src/seed/version.py @@ -1,4 +1,3 @@ - from importlib import metadata __version__ = metadata.version("fern_reserved-keywords") diff --git a/seed/python-sdk/reserved-keywords/tests/conftest.py b/seed/python-sdk/reserved-keywords/tests/conftest.py index 104c6bf31cb..c75c49d3f93 100644 --- a/seed/python-sdk/reserved-keywords/tests/conftest.py +++ b/seed/python-sdk/reserved-keywords/tests/conftest.py @@ -1,9 +1,9 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedNurseryApi import os - import pytest -from seed import AsyncSeedNurseryApi, SeedNurseryApi +from seed import AsyncSeedNurseryApi @pytest.fixture diff --git a/seed/python-sdk/reserved-keywords/tests/custom/test_client.py b/seed/python-sdk/reserved-keywords/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/python-sdk/reserved-keywords/tests/custom/test_client.py +++ b/seed/python-sdk/reserved-keywords/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/python-sdk/reserved-keywords/tests/test_package.py b/seed/python-sdk/reserved-keywords/tests/test_package.py index 256caecb0ef..f790d91c9ef 100644 --- a/seed/python-sdk/reserved-keywords/tests/test_package.py +++ b/seed/python-sdk/reserved-keywords/tests/test_package.py @@ -1,6 +1,7 @@ # This file was auto-generated by Fern from our API Definition. -from seed import AsyncSeedNurseryApi, SeedNurseryApi +from seed import SeedNurseryApi +from seed import AsyncSeedNurseryApi async def test_test(client: SeedNurseryApi, async_client: AsyncSeedNurseryApi) -> None: diff --git a/seed/python-sdk/reserved-keywords/tests/utilities.py b/seed/python-sdk/reserved-keywords/tests/utilities.py index 13da208eb3a..e8f4472564c 100644 --- a/seed/python-sdk/reserved-keywords/tests/utilities.py +++ b/seed/python-sdk/reserved-keywords/tests/utilities.py @@ -3,11 +3,14 @@ import typing import uuid -import pydantic from dateutil import parser +import pydantic + -def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> typing.Any: +def cast_field( + json_expectation: typing.Any, type_expectation: typing.Any +) -> typing.Any: # Cast these specific types which come through as string and expect our # models to cast to the correct type. if type_expectation == "uuid": @@ -25,7 +28,9 @@ def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> ty return json_expectation -def validate_field(response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any) -> None: +def validate_field( + response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectation == "no_validate": return @@ -44,7 +49,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(entry_expectation, dict): is_container_of_complex_type = True validate_response( - response=response[idx], json_expectation=ex, type_expectations=entry_expectation + response=response[idx], + json_expectation=ex, + type_expectations=entry_expectation, ) else: cast_json_expectation.append(cast_field(ex, entry_expectation)) @@ -56,7 +63,10 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # if any of the values of the set have a type_expectation of a dict, we're assuming it's a pydantic # model and keeping it a list. if container_expectation != "set" or not any( - map(lambda value: isinstance(value, dict), list(contents_expectation.values())) + map( + lambda value: isinstance(value, dict), + list(contents_expectation.values()), + ) ): json_expectation = cast_field(json_expectation, container_expectation) elif isinstance(type_expectation, tuple): @@ -65,9 +75,15 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(contents_expectation, dict): json_expectation = { cast_field( - key, contents_expectation.get(idx)[0] if contents_expectation.get(idx) is not None else None # type: ignore + key, + contents_expectation.get(idx)[0] + if contents_expectation.get(idx) is not None + else None, # type: ignore ): cast_field( - value, contents_expectation.get(idx)[1] if contents_expectation.get(idx) is not None else None # type: ignore + value, + contents_expectation.get(idx)[1] + if contents_expectation.get(idx) is not None + else None, # type: ignore ) for idx, (key, value) in enumerate(json_expectation.items()) } @@ -86,7 +102,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # Arg type_expectations is a deeply nested structure that matches the response, but with the values replaced with the expected types -def validate_response(response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any) -> None: +def validate_response( + response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectations == "no_validate": return @@ -96,11 +114,17 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e and not isinstance(response, dict) and not issubclass(type(response), pydantic.BaseModel) ): - validate_field(response=response, json_expectation=json_expectation, type_expectation=type_expectations) + validate_field( + response=response, + json_expectation=json_expectation, + type_expectation=type_expectations, + ) return if isinstance(response, list): - assert len(response) == len(json_expectation), "Length mismatch, expected: {0}, Actual: {1}".format( + assert len(response) == len( + json_expectation + ), "Length mismatch, expected: {0}, Actual: {1}".format( len(response), len(json_expectation) ) content_expectation = type_expectations @@ -108,7 +132,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e content_expectation = type_expectations[1] for idx, item in enumerate(response): validate_response( - response=item, json_expectation=json_expectation[idx], type_expectations=content_expectation[idx] + response=item, + json_expectation=json_expectation[idx], + type_expectations=content_expectation[idx], ) else: response_json = response @@ -116,7 +142,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e response_json = response.dict(by_alias=True) for key, value in json_expectation.items(): - assert key in response_json, "Field {0} not found within the response object: {1}".format( + assert ( + key in response_json + ), "Field {0} not found within the response object: {1}".format( key, response_json ) @@ -128,11 +156,19 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e # Otherwise, we're just validating a single field that's a pydantic model. if isinstance(value, dict) and not isinstance(type_expectation, tuple): validate_response( - response=response_json[key], json_expectation=value, type_expectations=type_expectation + response=response_json[key], + json_expectation=value, + type_expectations=type_expectation, ) else: - validate_field(response=response_json[key], json_expectation=value, type_expectation=type_expectation) + validate_field( + response=response_json[key], + json_expectation=value, + type_expectation=type_expectation, + ) # Ensure there are no additional fields here either del response_json[key] - assert len(response_json) == 0, "Additional fields found, expected None: {0}".format(response_json) + assert ( + len(response_json) == 0 + ), "Additional fields found, expected None: {0}".format(response_json) diff --git a/seed/python-sdk/reserved-keywords/tests/utils/assets/models/__init__.py b/seed/python-sdk/reserved-keywords/tests/utils/assets/models/__init__.py index 2cf01263529..3a1c852e71e 100644 --- a/seed/python-sdk/reserved-keywords/tests/utils/assets/models/__init__.py +++ b/seed/python-sdk/reserved-keywords/tests/utils/assets/models/__init__.py @@ -5,7 +5,7 @@ from .circle import CircleParams from .object_with_defaults import ObjectWithDefaultsParams from .object_with_optional_field import ObjectWithOptionalFieldParams -from .shape import Shape_CircleParams, Shape_SquareParams, ShapeParams +from .shape import ShapeParams, Shape_CircleParams, Shape_SquareParams from .square import SquareParams from .undiscriminated_shape import UndiscriminatedShapeParams diff --git a/seed/python-sdk/reserved-keywords/tests/utils/assets/models/circle.py b/seed/python-sdk/reserved-keywords/tests/utils/assets/models/circle.py index af7a1bf8a8e..253f12d38b3 100644 --- a/seed/python-sdk/reserved-keywords/tests/utils/assets/models/circle.py +++ b/seed/python-sdk/reserved-keywords/tests/utils/assets/models/circle.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class CircleParams(typing_extensions.TypedDict): - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] diff --git a/seed/python-sdk/reserved-keywords/tests/utils/assets/models/object_with_optional_field.py b/seed/python-sdk/reserved-keywords/tests/utils/assets/models/object_with_optional_field.py index 3ad93d5f305..ebe7dc80547 100644 --- a/seed/python-sdk/reserved-keywords/tests/utils/assets/models/object_with_optional_field.py +++ b/seed/python-sdk/reserved-keywords/tests/utils/assets/models/object_with_optional_field.py @@ -7,8 +7,8 @@ import uuid import typing_extensions -from seed.core.serialization import FieldMetadata +from seed.core.serialization import FieldMetadata from .color import Color from .shape import ShapeParams from .undiscriminated_shape import UndiscriminatedShapeParams @@ -18,16 +18,30 @@ class ObjectWithOptionalFieldParams(typing_extensions.TypedDict): literal: typing.Literal["lit_one"] string: typing_extensions.NotRequired[str] integer: typing_extensions.NotRequired[int] - long_: typing_extensions.NotRequired[typing_extensions.Annotated[int, FieldMetadata(alias="long")]] + long_: typing_extensions.NotRequired[ + typing_extensions.Annotated[int, FieldMetadata(alias="long")] + ] double: typing_extensions.NotRequired[float] - bool_: typing_extensions.NotRequired[typing_extensions.Annotated[bool, FieldMetadata(alias="bool")]] + bool_: typing_extensions.NotRequired[ + typing_extensions.Annotated[bool, FieldMetadata(alias="bool")] + ] datetime: typing_extensions.NotRequired[dt.datetime] date: typing_extensions.NotRequired[dt.date] - uuid_: typing_extensions.NotRequired[typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")]] - base_64: typing_extensions.NotRequired[typing_extensions.Annotated[str, FieldMetadata(alias="base64")]] - list_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")]] - set_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")]] - map_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")]] + uuid_: typing_extensions.NotRequired[ + typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")] + ] + base_64: typing_extensions.NotRequired[ + typing_extensions.Annotated[str, FieldMetadata(alias="base64")] + ] + list_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")] + ] + set_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")] + ] + map_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")] + ] enum: typing_extensions.NotRequired[Color] union: typing_extensions.NotRequired[ShapeParams] second_union: typing_extensions.NotRequired[ShapeParams] diff --git a/seed/python-sdk/reserved-keywords/tests/utils/assets/models/shape.py b/seed/python-sdk/reserved-keywords/tests/utils/assets/models/shape.py index 2c33c877951..816ffc51bdc 100644 --- a/seed/python-sdk/reserved-keywords/tests/utils/assets/models/shape.py +++ b/seed/python-sdk/reserved-keywords/tests/utils/assets/models/shape.py @@ -7,6 +7,7 @@ import typing import typing_extensions + from seed.core.serialization import FieldMetadata @@ -15,13 +16,21 @@ class Base(typing_extensions.TypedDict): class Shape_CircleParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["circle"], FieldMetadata(alias="shapeType")] - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["circle"], FieldMetadata(alias="shapeType") + ] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] class Shape_SquareParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["square"], FieldMetadata(alias="shapeType")] - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["square"], FieldMetadata(alias="shapeType") + ] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] ShapeParams = typing.Union[Shape_CircleParams, Shape_SquareParams] diff --git a/seed/python-sdk/reserved-keywords/tests/utils/assets/models/square.py b/seed/python-sdk/reserved-keywords/tests/utils/assets/models/square.py index b9b7dd319bc..bcf08a723c5 100644 --- a/seed/python-sdk/reserved-keywords/tests/utils/assets/models/square.py +++ b/seed/python-sdk/reserved-keywords/tests/utils/assets/models/square.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class SquareParams(typing_extensions.TypedDict): - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] diff --git a/seed/python-sdk/reserved-keywords/tests/utils/test_http_client.py b/seed/python-sdk/reserved-keywords/tests/utils/test_http_client.py index edd11ca7afb..f5a874a75f3 100644 --- a/seed/python-sdk/reserved-keywords/tests/utils/test_http_client.py +++ b/seed/python-sdk/reserved-keywords/tests/utils/test_http_client.py @@ -9,12 +9,17 @@ def get_request_options() -> RequestOptions: def test_get_json_request_body() -> None: - json_body, data_body = get_request_body(json={"hello": "world"}, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json={"hello": "world"}, data=None, request_options=None, omit=None + ) assert json_body == {"hello": "world"} assert data_body is None json_body_extras, data_body_extras = get_request_body( - json={"goodbye": "world"}, data=None, request_options=get_request_options(), omit=None + json={"goodbye": "world"}, + data=None, + request_options=get_request_options(), + omit=None, ) assert json_body_extras == {"goodbye": "world", "see you": "later"} @@ -22,12 +27,17 @@ def test_get_json_request_body() -> None: def test_get_files_request_body() -> None: - json_body, data_body = get_request_body(json=None, data={"hello": "world"}, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data={"hello": "world"}, request_options=None, omit=None + ) assert data_body == {"hello": "world"} assert json_body is None json_body_extras, data_body_extras = get_request_body( - json=None, data={"goodbye": "world"}, request_options=get_request_options(), omit=None + json=None, + data={"goodbye": "world"}, + request_options=get_request_options(), + omit=None, ) assert data_body_extras == {"goodbye": "world", "see you": "later"} @@ -35,7 +45,9 @@ def test_get_files_request_body() -> None: def test_get_none_request_body() -> None: - json_body, data_body = get_request_body(json=None, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data=None, request_options=None, omit=None + ) assert data_body is None assert json_body is None diff --git a/seed/python-sdk/reserved-keywords/tests/utils/test_query_encoding.py b/seed/python-sdk/reserved-keywords/tests/utils/test_query_encoding.py index 247e1551b46..fbc8f402167 100644 --- a/seed/python-sdk/reserved-keywords/tests/utils/test_query_encoding.py +++ b/seed/python-sdk/reserved-keywords/tests/utils/test_query_encoding.py @@ -4,9 +4,15 @@ def test_query_encoding() -> None: - assert encode_query({"hello world": "hello world"}) == {"hello world": "hello world"} - assert encode_query({"hello_world": {"hello": "world"}}) == {"hello_world[hello]": "world"} - assert encode_query({"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"}) == { + assert encode_query({"hello world": "hello world"}) == { + "hello world": "hello world" + } + assert encode_query({"hello_world": {"hello": "world"}}) == { + "hello_world[hello]": "world" + } + assert encode_query( + {"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"} + ) == { "hello_world[hello][world]": "today", "hello_world[test]": "this", "hi": "there", diff --git a/seed/python-sdk/reserved-keywords/tests/utils/test_serialization.py b/seed/python-sdk/reserved-keywords/tests/utils/test_serialization.py index 58b1ed66e6d..5ca956916dd 100644 --- a/seed/python-sdk/reserved-keywords/tests/utils/test_serialization.py +++ b/seed/python-sdk/reserved-keywords/tests/utils/test_serialization.py @@ -1,10 +1,12 @@ # This file was auto-generated by Fern from our API Definition. -from typing import Any, List +from typing import List, Any -from seed.core.serialization import convert_and_respect_annotation_metadata +from seed.core.serialization import ( + convert_and_respect_annotation_metadata, +) +from .assets.models import ShapeParams, ObjectWithOptionalFieldParams -from .assets.models import ObjectWithOptionalFieldParams, ShapeParams UNION_TEST: ShapeParams = {"radius_measurement": 1.0, "shape_type": "circle", "id": "1"} UNION_TEST_CONVERTED = {"shapeType": "circle", "radiusMeasurement": 1.0, "id": "1"} @@ -18,20 +20,54 @@ def test_convert_and_respect_annotation_metadata() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) - assert converted == {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"} + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) + assert converted == { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + } def test_convert_and_respect_annotation_metadata_in_list() -> None: data: List[ObjectWithOptionalFieldParams] = [ - {"string": "string", "long_": 12345, "bool_": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long_": 67890, "list_": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long_": 12345, + "bool_": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long_": 67890, + "list_": [], + "literal": "lit_one", + "any": "any", + }, ] - converted = convert_and_respect_annotation_metadata(object_=data, annotation=List[ObjectWithOptionalFieldParams]) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=List[ObjectWithOptionalFieldParams] + ) assert converted == [ - {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long": 67890, "list": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long": 67890, + "list": [], + "literal": "lit_one", + "any": "any", + }, ] @@ -43,7 +79,9 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) assert converted == { "string": "string", @@ -55,12 +93,16 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: def test_convert_and_respect_annotation_metadata_in_union() -> None: - converted = convert_and_respect_annotation_metadata(object_=UNION_TEST, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=UNION_TEST, annotation=ShapeParams + ) assert converted == UNION_TEST_CONVERTED def test_convert_and_respect_annotation_metadata_with_empty_object() -> None: data: Any = {} - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ShapeParams + ) assert converted == data diff --git a/seed/python-sdk/server-sent-events/pyproject.toml b/seed/python-sdk/server-sent-events/pyproject.toml index e015b23de1c..a47d399c16d 100644 --- a/seed/python-sdk/server-sent-events/pyproject.toml +++ b/seed/python-sdk/server-sent-events/pyproject.toml @@ -44,6 +44,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/python-sdk/server-sent-events/src/seed/__init__.py b/seed/python-sdk/server-sent-events/src/seed/__init__.py index 72f7f34f66a..c4ba3176904 100644 --- a/seed/python-sdk/server-sent-events/src/seed/__init__.py +++ b/seed/python-sdk/server-sent-events/src/seed/__init__.py @@ -5,4 +5,10 @@ from .completions import StreamedCompletion from .version import __version__ -__all__ = ["AsyncSeedServerSentEvents", "SeedServerSentEvents", "StreamedCompletion", "__version__", "completions"] +__all__ = [ + "AsyncSeedServerSentEvents", + "SeedServerSentEvents", + "StreamedCompletion", + "__version__", + "completions", +] diff --git a/seed/python-sdk/server-sent-events/src/seed/client.py b/seed/python-sdk/server-sent-events/src/seed/client.py index b86a5eeb7b0..aa57382265a 100644 --- a/seed/python-sdk/server-sent-events/src/seed/client.py +++ b/seed/python-sdk/server-sent-events/src/seed/client.py @@ -1,11 +1,11 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .completions.client import AsyncCompletionsClient, CompletionsClient -from .core.client_wrapper import AsyncClientWrapper, SyncClientWrapper +from .core.client_wrapper import SyncClientWrapper +from .completions.client import CompletionsClient +from .core.client_wrapper import AsyncClientWrapper +from .completions.client import AsyncCompletionsClient class SeedServerSentEvents: @@ -41,14 +41,18 @@ def __init__( base_url: str, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.Client] = None + httpx_client: typing.Optional[httpx.Client] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = SyncClientWrapper( base_url=base_url, httpx_client=httpx_client if httpx_client is not None - else httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.Client( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.Client(timeout=_defaulted_timeout), timeout=_defaulted_timeout, @@ -89,14 +93,18 @@ def __init__( base_url: str, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.AsyncClient] = None + httpx_client: typing.Optional[httpx.AsyncClient] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = AsyncClientWrapper( base_url=base_url, httpx_client=httpx_client if httpx_client is not None - else httpx.AsyncClient(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.AsyncClient( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.AsyncClient(timeout=_defaulted_timeout), timeout=_defaulted_timeout, diff --git a/seed/python-sdk/server-sent-events/src/seed/completions/client.py b/seed/python-sdk/server-sent-events/src/seed/completions/client.py index 6fa60a74eb1..70193e279a8 100644 --- a/seed/python-sdk/server-sent-events/src/seed/completions/client.py +++ b/seed/python-sdk/server-sent-events/src/seed/completions/client.py @@ -1,16 +1,15 @@ # This file was auto-generated by Fern from our API Definition. -import json import typing -from json.decoder import JSONDecodeError - -import httpx_sse - -from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.pydantic_utilities import parse_obj_as +from ..core.client_wrapper import SyncClientWrapper from ..core.request_options import RequestOptions from .types.streamed_completion import StreamedCompletion +import httpx_sse +from ..core.pydantic_utilities import parse_obj_as +import json +from json.decoder import JSONDecodeError +from ..core.api_error import ApiError +from ..core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -49,7 +48,13 @@ def stream( yield chunk """ with self._client_wrapper.httpx_client.stream( - "stream", method="POST", json={"query": query}, request_options=request_options, omit=OMIT + "stream", + method="POST", + json={ + "query": query, + }, + request_options=request_options, + omit=OMIT, ) as _response: try: if 200 <= _response.status_code < 300: @@ -58,7 +63,13 @@ def stream( if _sse.data == "[[DONE]]": return try: - yield typing.cast(StreamedCompletion, parse_obj_as(type_=StreamedCompletion, object_=json.loads(_sse.data))) # type: ignore + yield typing.cast( + StreamedCompletion, + parse_obj_as( + type_=StreamedCompletion, + object_=json.loads(_sse.data), + ), + ) # type: ignore except: pass return @@ -110,7 +121,13 @@ async def main() -> None: asyncio.run(main()) """ async with self._client_wrapper.httpx_client.stream( - "stream", method="POST", json={"query": query}, request_options=request_options, omit=OMIT + "stream", + method="POST", + json={ + "query": query, + }, + request_options=request_options, + omit=OMIT, ) as _response: try: if 200 <= _response.status_code < 300: @@ -119,7 +136,13 @@ async def main() -> None: if _sse.data == "[[DONE]]": return try: - yield typing.cast(StreamedCompletion, parse_obj_as(type_=StreamedCompletion, object_=json.loads(_sse.data))) # type: ignore + yield typing.cast( + StreamedCompletion, + parse_obj_as( + type_=StreamedCompletion, + object_=json.loads(_sse.data), + ), + ) # type: ignore except: pass return diff --git a/seed/python-sdk/server-sent-events/src/seed/completions/types/streamed_completion.py b/seed/python-sdk/server-sent-events/src/seed/completions/types/streamed_completion.py index fb19671bc9a..c16584f88b2 100644 --- a/seed/python-sdk/server-sent-events/src/seed/completions/types/streamed_completion.py +++ b/seed/python-sdk/server-sent-events/src/seed/completions/types/streamed_completion.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel import typing - +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class StreamedCompletion(UniversalBaseModel): delta: str tokens: typing.Optional[int] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/server-sent-events/src/seed/core/api_error.py b/seed/python-sdk/server-sent-events/src/seed/core/api_error.py index 2e9fc5431cd..da734b58068 100644 --- a/seed/python-sdk/server-sent-events/src/seed/core/api_error.py +++ b/seed/python-sdk/server-sent-events/src/seed/core/api_error.py @@ -7,7 +7,9 @@ class ApiError(Exception): status_code: typing.Optional[int] body: typing.Any - def __init__(self, *, status_code: typing.Optional[int] = None, body: typing.Any = None): + def __init__( + self, *, status_code: typing.Optional[int] = None, body: typing.Any = None + ): self.status_code = status_code self.body = body diff --git a/seed/python-sdk/server-sent-events/src/seed/core/client_wrapper.py b/seed/python-sdk/server-sent-events/src/seed/core/client_wrapper.py index bb41c804457..71a96144acb 100644 --- a/seed/python-sdk/server-sent-events/src/seed/core/client_wrapper.py +++ b/seed/python-sdk/server-sent-events/src/seed/core/client_wrapper.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .http_client import AsyncHttpClient, HttpClient +from .http_client import HttpClient +from .http_client import AsyncHttpClient class BaseClientWrapper: @@ -28,7 +27,13 @@ def get_timeout(self) -> typing.Optional[float]: class SyncClientWrapper(BaseClientWrapper): - def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, httpx_client: httpx.Client): + def __init__( + self, + *, + base_url: str, + timeout: typing.Optional[float] = None, + httpx_client: httpx.Client, + ): super().__init__(base_url=base_url, timeout=timeout) self.httpx_client = HttpClient( httpx_client=httpx_client, @@ -39,7 +44,13 @@ def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, htt class AsyncClientWrapper(BaseClientWrapper): - def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, httpx_client: httpx.AsyncClient): + def __init__( + self, + *, + base_url: str, + timeout: typing.Optional[float] = None, + httpx_client: httpx.AsyncClient, + ): super().__init__(base_url=base_url, timeout=timeout) self.httpx_client = AsyncHttpClient( httpx_client=httpx_client, diff --git a/seed/python-sdk/server-sent-events/src/seed/core/datetime_utils.py b/seed/python-sdk/server-sent-events/src/seed/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/python-sdk/server-sent-events/src/seed/core/datetime_utils.py +++ b/seed/python-sdk/server-sent-events/src/seed/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/python-sdk/server-sent-events/src/seed/core/file.py b/seed/python-sdk/server-sent-events/src/seed/core/file.py index cb0d40bbbf3..6e0f92bfcb1 100644 --- a/seed/python-sdk/server-sent-events/src/seed/core/file.py +++ b/seed/python-sdk/server-sent-events/src/seed/core/file.py @@ -13,12 +13,17 @@ # (filename, file (or bytes), content_type) typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str]], # (filename, file (or bytes), content_type, headers) - typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str], typing.Mapping[str, str]], + typing.Tuple[ + typing.Optional[str], + FileContent, + typing.Optional[str], + typing.Mapping[str, str], + ], ] def convert_file_dict_to_httpx_tuples( - d: typing.Dict[str, typing.Union[File, typing.List[File]]] + d: typing.Dict[str, typing.Union[File, typing.List[File]]], ) -> typing.List[typing.Tuple[str, File]]: """ The format we use is a list of tuples, where the first element is the diff --git a/seed/python-sdk/server-sent-events/src/seed/core/http_client.py b/seed/python-sdk/server-sent-events/src/seed/core/http_client.py index 9333d8a7f15..091f71bc185 100644 --- a/seed/python-sdk/server-sent-events/src/seed/core/http_client.py +++ b/seed/python-sdk/server-sent-events/src/seed/core/http_client.py @@ -77,7 +77,9 @@ def _retry_timeout(response: httpx.Response, retries: int) -> float: return retry_after # Apply exponential backoff, capped at MAX_RETRY_DELAY_SECONDS. - retry_delay = min(INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS) + retry_delay = min( + INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS + ) # Add a randomness / jitter to the retry delay to avoid overwhelming the server with retries. timeout = retry_delay * (1 - 0.25 * random()) @@ -90,7 +92,8 @@ def _should_retry(response: httpx.Response) -> bool: def remove_omit_from_dict( - original: typing.Dict[str, typing.Optional[typing.Any]], omit: typing.Optional[typing.Any] + original: typing.Dict[str, typing.Optional[typing.Any]], + omit: typing.Optional[typing.Any], ) -> typing.Dict[str, typing.Any]: if omit is None: return original @@ -108,7 +111,8 @@ def maybe_filter_request_body( ) -> typing.Optional[typing.Any]: if data is None: return ( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else None ) @@ -118,7 +122,8 @@ def maybe_filter_request_body( data_content = { **(jsonable_encoder(remove_omit_from_dict(data, omit))), # type: ignore **( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else {} ), @@ -162,7 +167,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url def request( @@ -174,8 +181,12 @@ def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -184,11 +195,14 @@ def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) response = self.httpx_client.request( method=method, @@ -198,7 +212,11 @@ def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -209,7 +227,10 @@ def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -222,11 +243,15 @@ def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: time.sleep(_retry_timeout(response=response, retries=retries)) @@ -256,8 +281,12 @@ def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -266,11 +295,14 @@ def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) with self.httpx_client.stream( method=method, @@ -280,7 +312,11 @@ def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -291,7 +327,9 @@ def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -304,7 +342,9 @@ def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream @@ -327,7 +367,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url async def request( @@ -339,8 +381,12 @@ async def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -349,11 +395,14 @@ async def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) # Add the input to each of these and do None-safety checks response = await self.httpx_client.request( @@ -364,7 +413,11 @@ async def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -375,7 +428,10 @@ async def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -388,11 +444,15 @@ async def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: await asyncio.sleep(_retry_timeout(response=response, retries=retries)) @@ -421,8 +481,12 @@ async def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -431,11 +495,14 @@ async def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) async with self.httpx_client.stream( method=method, @@ -445,7 +512,11 @@ async def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -456,7 +527,9 @@ async def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -469,7 +542,9 @@ async def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream diff --git a/seed/python-sdk/server-sent-events/src/seed/core/jsonable_encoder.py b/seed/python-sdk/server-sent-events/src/seed/core/jsonable_encoder.py index d3fd328fd41..12a8b52fc22 100644 --- a/seed/python-sdk/server-sent-events/src/seed/core/jsonable_encoder.py +++ b/seed/python-sdk/server-sent-events/src/seed/core/jsonable_encoder.py @@ -19,13 +19,19 @@ import pydantic from .datetime_utils import serialize_datetime -from .pydantic_utilities import IS_PYDANTIC_V2, encode_by_type, to_jsonable_with_fallback +from .pydantic_utilities import ( + IS_PYDANTIC_V2, + encode_by_type, + to_jsonable_with_fallback, +) SetIntStr = Set[Union[int, str]] DictIntStrAny = Dict[Union[int, str], Any] -def jsonable_encoder(obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None) -> Any: +def jsonable_encoder( + obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None +) -> Any: custom_encoder = custom_encoder or {} if custom_encoder: if type(obj) in custom_encoder: diff --git a/seed/python-sdk/server-sent-events/src/seed/core/pydantic_utilities.py b/seed/python-sdk/server-sent-events/src/seed/core/pydantic_utilities.py index 170a563d6eb..c63935c32a2 100644 --- a/seed/python-sdk/server-sent-events/src/seed/core/pydantic_utilities.py +++ b/seed/python-sdk/server-sent-events/src/seed/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) # type: ignore # Pydantic v1 diff --git a/seed/python-sdk/server-sent-events/src/seed/core/query_encoder.py b/seed/python-sdk/server-sent-events/src/seed/core/query_encoder.py index 24076d72ee9..7cb98f52cd7 100644 --- a/seed/python-sdk/server-sent-events/src/seed/core/query_encoder.py +++ b/seed/python-sdk/server-sent-events/src/seed/core/query_encoder.py @@ -7,7 +7,9 @@ # Flattens dicts to be of the form {"key[subkey][subkey2]": value} where value is not a dict -def traverse_query_dict(dict_flat: Dict[str, Any], key_prefix: Optional[str] = None) -> Dict[str, Any]: +def traverse_query_dict( + dict_flat: Dict[str, Any], key_prefix: Optional[str] = None +) -> Dict[str, Any]: result = {} for k, v in dict_flat.items(): key = f"{key_prefix}[{k}]" if key_prefix is not None else k @@ -30,4 +32,8 @@ def single_query_encoder(query_key: str, query_value: Any) -> Dict[str, Any]: def encode_query(query: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: - return dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) if query is not None else None + return ( + dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) + if query is not None + else None + ) diff --git a/seed/python-sdk/server-sent-events/src/seed/core/serialization.py b/seed/python-sdk/server-sent-events/src/seed/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/python-sdk/server-sent-events/src/seed/core/serialization.py +++ b/seed/python-sdk/server-sent-events/src/seed/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/python-sdk/server-sent-events/src/seed/version.py b/seed/python-sdk/server-sent-events/src/seed/version.py index e7cfffe78d0..4cb76c6f0cf 100644 --- a/seed/python-sdk/server-sent-events/src/seed/version.py +++ b/seed/python-sdk/server-sent-events/src/seed/version.py @@ -1,4 +1,3 @@ - from importlib import metadata __version__ = metadata.version("fern_server-sent-events") diff --git a/seed/python-sdk/server-sent-events/tests/conftest.py b/seed/python-sdk/server-sent-events/tests/conftest.py index b30ea753333..49cf8e75871 100644 --- a/seed/python-sdk/server-sent-events/tests/conftest.py +++ b/seed/python-sdk/server-sent-events/tests/conftest.py @@ -1,9 +1,9 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedServerSentEvents import os - import pytest -from seed import AsyncSeedServerSentEvents, SeedServerSentEvents +from seed import AsyncSeedServerSentEvents @pytest.fixture diff --git a/seed/python-sdk/server-sent-events/tests/custom/test_client.py b/seed/python-sdk/server-sent-events/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/python-sdk/server-sent-events/tests/custom/test_client.py +++ b/seed/python-sdk/server-sent-events/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/python-sdk/server-sent-events/tests/utilities.py b/seed/python-sdk/server-sent-events/tests/utilities.py index 13da208eb3a..e8f4472564c 100644 --- a/seed/python-sdk/server-sent-events/tests/utilities.py +++ b/seed/python-sdk/server-sent-events/tests/utilities.py @@ -3,11 +3,14 @@ import typing import uuid -import pydantic from dateutil import parser +import pydantic + -def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> typing.Any: +def cast_field( + json_expectation: typing.Any, type_expectation: typing.Any +) -> typing.Any: # Cast these specific types which come through as string and expect our # models to cast to the correct type. if type_expectation == "uuid": @@ -25,7 +28,9 @@ def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> ty return json_expectation -def validate_field(response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any) -> None: +def validate_field( + response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectation == "no_validate": return @@ -44,7 +49,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(entry_expectation, dict): is_container_of_complex_type = True validate_response( - response=response[idx], json_expectation=ex, type_expectations=entry_expectation + response=response[idx], + json_expectation=ex, + type_expectations=entry_expectation, ) else: cast_json_expectation.append(cast_field(ex, entry_expectation)) @@ -56,7 +63,10 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # if any of the values of the set have a type_expectation of a dict, we're assuming it's a pydantic # model and keeping it a list. if container_expectation != "set" or not any( - map(lambda value: isinstance(value, dict), list(contents_expectation.values())) + map( + lambda value: isinstance(value, dict), + list(contents_expectation.values()), + ) ): json_expectation = cast_field(json_expectation, container_expectation) elif isinstance(type_expectation, tuple): @@ -65,9 +75,15 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(contents_expectation, dict): json_expectation = { cast_field( - key, contents_expectation.get(idx)[0] if contents_expectation.get(idx) is not None else None # type: ignore + key, + contents_expectation.get(idx)[0] + if contents_expectation.get(idx) is not None + else None, # type: ignore ): cast_field( - value, contents_expectation.get(idx)[1] if contents_expectation.get(idx) is not None else None # type: ignore + value, + contents_expectation.get(idx)[1] + if contents_expectation.get(idx) is not None + else None, # type: ignore ) for idx, (key, value) in enumerate(json_expectation.items()) } @@ -86,7 +102,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # Arg type_expectations is a deeply nested structure that matches the response, but with the values replaced with the expected types -def validate_response(response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any) -> None: +def validate_response( + response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectations == "no_validate": return @@ -96,11 +114,17 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e and not isinstance(response, dict) and not issubclass(type(response), pydantic.BaseModel) ): - validate_field(response=response, json_expectation=json_expectation, type_expectation=type_expectations) + validate_field( + response=response, + json_expectation=json_expectation, + type_expectation=type_expectations, + ) return if isinstance(response, list): - assert len(response) == len(json_expectation), "Length mismatch, expected: {0}, Actual: {1}".format( + assert len(response) == len( + json_expectation + ), "Length mismatch, expected: {0}, Actual: {1}".format( len(response), len(json_expectation) ) content_expectation = type_expectations @@ -108,7 +132,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e content_expectation = type_expectations[1] for idx, item in enumerate(response): validate_response( - response=item, json_expectation=json_expectation[idx], type_expectations=content_expectation[idx] + response=item, + json_expectation=json_expectation[idx], + type_expectations=content_expectation[idx], ) else: response_json = response @@ -116,7 +142,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e response_json = response.dict(by_alias=True) for key, value in json_expectation.items(): - assert key in response_json, "Field {0} not found within the response object: {1}".format( + assert ( + key in response_json + ), "Field {0} not found within the response object: {1}".format( key, response_json ) @@ -128,11 +156,19 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e # Otherwise, we're just validating a single field that's a pydantic model. if isinstance(value, dict) and not isinstance(type_expectation, tuple): validate_response( - response=response_json[key], json_expectation=value, type_expectations=type_expectation + response=response_json[key], + json_expectation=value, + type_expectations=type_expectation, ) else: - validate_field(response=response_json[key], json_expectation=value, type_expectation=type_expectation) + validate_field( + response=response_json[key], + json_expectation=value, + type_expectation=type_expectation, + ) # Ensure there are no additional fields here either del response_json[key] - assert len(response_json) == 0, "Additional fields found, expected None: {0}".format(response_json) + assert ( + len(response_json) == 0 + ), "Additional fields found, expected None: {0}".format(response_json) diff --git a/seed/python-sdk/server-sent-events/tests/utils/assets/models/__init__.py b/seed/python-sdk/server-sent-events/tests/utils/assets/models/__init__.py index 2cf01263529..3a1c852e71e 100644 --- a/seed/python-sdk/server-sent-events/tests/utils/assets/models/__init__.py +++ b/seed/python-sdk/server-sent-events/tests/utils/assets/models/__init__.py @@ -5,7 +5,7 @@ from .circle import CircleParams from .object_with_defaults import ObjectWithDefaultsParams from .object_with_optional_field import ObjectWithOptionalFieldParams -from .shape import Shape_CircleParams, Shape_SquareParams, ShapeParams +from .shape import ShapeParams, Shape_CircleParams, Shape_SquareParams from .square import SquareParams from .undiscriminated_shape import UndiscriminatedShapeParams diff --git a/seed/python-sdk/server-sent-events/tests/utils/assets/models/circle.py b/seed/python-sdk/server-sent-events/tests/utils/assets/models/circle.py index af7a1bf8a8e..253f12d38b3 100644 --- a/seed/python-sdk/server-sent-events/tests/utils/assets/models/circle.py +++ b/seed/python-sdk/server-sent-events/tests/utils/assets/models/circle.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class CircleParams(typing_extensions.TypedDict): - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] diff --git a/seed/python-sdk/server-sent-events/tests/utils/assets/models/object_with_optional_field.py b/seed/python-sdk/server-sent-events/tests/utils/assets/models/object_with_optional_field.py index 3ad93d5f305..ebe7dc80547 100644 --- a/seed/python-sdk/server-sent-events/tests/utils/assets/models/object_with_optional_field.py +++ b/seed/python-sdk/server-sent-events/tests/utils/assets/models/object_with_optional_field.py @@ -7,8 +7,8 @@ import uuid import typing_extensions -from seed.core.serialization import FieldMetadata +from seed.core.serialization import FieldMetadata from .color import Color from .shape import ShapeParams from .undiscriminated_shape import UndiscriminatedShapeParams @@ -18,16 +18,30 @@ class ObjectWithOptionalFieldParams(typing_extensions.TypedDict): literal: typing.Literal["lit_one"] string: typing_extensions.NotRequired[str] integer: typing_extensions.NotRequired[int] - long_: typing_extensions.NotRequired[typing_extensions.Annotated[int, FieldMetadata(alias="long")]] + long_: typing_extensions.NotRequired[ + typing_extensions.Annotated[int, FieldMetadata(alias="long")] + ] double: typing_extensions.NotRequired[float] - bool_: typing_extensions.NotRequired[typing_extensions.Annotated[bool, FieldMetadata(alias="bool")]] + bool_: typing_extensions.NotRequired[ + typing_extensions.Annotated[bool, FieldMetadata(alias="bool")] + ] datetime: typing_extensions.NotRequired[dt.datetime] date: typing_extensions.NotRequired[dt.date] - uuid_: typing_extensions.NotRequired[typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")]] - base_64: typing_extensions.NotRequired[typing_extensions.Annotated[str, FieldMetadata(alias="base64")]] - list_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")]] - set_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")]] - map_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")]] + uuid_: typing_extensions.NotRequired[ + typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")] + ] + base_64: typing_extensions.NotRequired[ + typing_extensions.Annotated[str, FieldMetadata(alias="base64")] + ] + list_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")] + ] + set_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")] + ] + map_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")] + ] enum: typing_extensions.NotRequired[Color] union: typing_extensions.NotRequired[ShapeParams] second_union: typing_extensions.NotRequired[ShapeParams] diff --git a/seed/python-sdk/server-sent-events/tests/utils/assets/models/shape.py b/seed/python-sdk/server-sent-events/tests/utils/assets/models/shape.py index 2c33c877951..816ffc51bdc 100644 --- a/seed/python-sdk/server-sent-events/tests/utils/assets/models/shape.py +++ b/seed/python-sdk/server-sent-events/tests/utils/assets/models/shape.py @@ -7,6 +7,7 @@ import typing import typing_extensions + from seed.core.serialization import FieldMetadata @@ -15,13 +16,21 @@ class Base(typing_extensions.TypedDict): class Shape_CircleParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["circle"], FieldMetadata(alias="shapeType")] - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["circle"], FieldMetadata(alias="shapeType") + ] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] class Shape_SquareParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["square"], FieldMetadata(alias="shapeType")] - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["square"], FieldMetadata(alias="shapeType") + ] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] ShapeParams = typing.Union[Shape_CircleParams, Shape_SquareParams] diff --git a/seed/python-sdk/server-sent-events/tests/utils/assets/models/square.py b/seed/python-sdk/server-sent-events/tests/utils/assets/models/square.py index b9b7dd319bc..bcf08a723c5 100644 --- a/seed/python-sdk/server-sent-events/tests/utils/assets/models/square.py +++ b/seed/python-sdk/server-sent-events/tests/utils/assets/models/square.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class SquareParams(typing_extensions.TypedDict): - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] diff --git a/seed/python-sdk/server-sent-events/tests/utils/test_http_client.py b/seed/python-sdk/server-sent-events/tests/utils/test_http_client.py index edd11ca7afb..f5a874a75f3 100644 --- a/seed/python-sdk/server-sent-events/tests/utils/test_http_client.py +++ b/seed/python-sdk/server-sent-events/tests/utils/test_http_client.py @@ -9,12 +9,17 @@ def get_request_options() -> RequestOptions: def test_get_json_request_body() -> None: - json_body, data_body = get_request_body(json={"hello": "world"}, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json={"hello": "world"}, data=None, request_options=None, omit=None + ) assert json_body == {"hello": "world"} assert data_body is None json_body_extras, data_body_extras = get_request_body( - json={"goodbye": "world"}, data=None, request_options=get_request_options(), omit=None + json={"goodbye": "world"}, + data=None, + request_options=get_request_options(), + omit=None, ) assert json_body_extras == {"goodbye": "world", "see you": "later"} @@ -22,12 +27,17 @@ def test_get_json_request_body() -> None: def test_get_files_request_body() -> None: - json_body, data_body = get_request_body(json=None, data={"hello": "world"}, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data={"hello": "world"}, request_options=None, omit=None + ) assert data_body == {"hello": "world"} assert json_body is None json_body_extras, data_body_extras = get_request_body( - json=None, data={"goodbye": "world"}, request_options=get_request_options(), omit=None + json=None, + data={"goodbye": "world"}, + request_options=get_request_options(), + omit=None, ) assert data_body_extras == {"goodbye": "world", "see you": "later"} @@ -35,7 +45,9 @@ def test_get_files_request_body() -> None: def test_get_none_request_body() -> None: - json_body, data_body = get_request_body(json=None, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data=None, request_options=None, omit=None + ) assert data_body is None assert json_body is None diff --git a/seed/python-sdk/server-sent-events/tests/utils/test_query_encoding.py b/seed/python-sdk/server-sent-events/tests/utils/test_query_encoding.py index 247e1551b46..fbc8f402167 100644 --- a/seed/python-sdk/server-sent-events/tests/utils/test_query_encoding.py +++ b/seed/python-sdk/server-sent-events/tests/utils/test_query_encoding.py @@ -4,9 +4,15 @@ def test_query_encoding() -> None: - assert encode_query({"hello world": "hello world"}) == {"hello world": "hello world"} - assert encode_query({"hello_world": {"hello": "world"}}) == {"hello_world[hello]": "world"} - assert encode_query({"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"}) == { + assert encode_query({"hello world": "hello world"}) == { + "hello world": "hello world" + } + assert encode_query({"hello_world": {"hello": "world"}}) == { + "hello_world[hello]": "world" + } + assert encode_query( + {"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"} + ) == { "hello_world[hello][world]": "today", "hello_world[test]": "this", "hi": "there", diff --git a/seed/python-sdk/server-sent-events/tests/utils/test_serialization.py b/seed/python-sdk/server-sent-events/tests/utils/test_serialization.py index 58b1ed66e6d..5ca956916dd 100644 --- a/seed/python-sdk/server-sent-events/tests/utils/test_serialization.py +++ b/seed/python-sdk/server-sent-events/tests/utils/test_serialization.py @@ -1,10 +1,12 @@ # This file was auto-generated by Fern from our API Definition. -from typing import Any, List +from typing import List, Any -from seed.core.serialization import convert_and_respect_annotation_metadata +from seed.core.serialization import ( + convert_and_respect_annotation_metadata, +) +from .assets.models import ShapeParams, ObjectWithOptionalFieldParams -from .assets.models import ObjectWithOptionalFieldParams, ShapeParams UNION_TEST: ShapeParams = {"radius_measurement": 1.0, "shape_type": "circle", "id": "1"} UNION_TEST_CONVERTED = {"shapeType": "circle", "radiusMeasurement": 1.0, "id": "1"} @@ -18,20 +20,54 @@ def test_convert_and_respect_annotation_metadata() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) - assert converted == {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"} + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) + assert converted == { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + } def test_convert_and_respect_annotation_metadata_in_list() -> None: data: List[ObjectWithOptionalFieldParams] = [ - {"string": "string", "long_": 12345, "bool_": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long_": 67890, "list_": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long_": 12345, + "bool_": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long_": 67890, + "list_": [], + "literal": "lit_one", + "any": "any", + }, ] - converted = convert_and_respect_annotation_metadata(object_=data, annotation=List[ObjectWithOptionalFieldParams]) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=List[ObjectWithOptionalFieldParams] + ) assert converted == [ - {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long": 67890, "list": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long": 67890, + "list": [], + "literal": "lit_one", + "any": "any", + }, ] @@ -43,7 +79,9 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) assert converted == { "string": "string", @@ -55,12 +93,16 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: def test_convert_and_respect_annotation_metadata_in_union() -> None: - converted = convert_and_respect_annotation_metadata(object_=UNION_TEST, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=UNION_TEST, annotation=ShapeParams + ) assert converted == UNION_TEST_CONVERTED def test_convert_and_respect_annotation_metadata_with_empty_object() -> None: data: Any = {} - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ShapeParams + ) assert converted == data diff --git a/seed/python-sdk/single-url-environment-default/pyproject.toml b/seed/python-sdk/single-url-environment-default/pyproject.toml index 2e87b9f6328..1a499af74d5 100644 --- a/seed/python-sdk/single-url-environment-default/pyproject.toml +++ b/seed/python-sdk/single-url-environment-default/pyproject.toml @@ -43,6 +43,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/python-sdk/single-url-environment-default/src/seed/__init__.py b/seed/python-sdk/single-url-environment-default/src/seed/__init__.py index 5736aca1e9d..db45f85e468 100644 --- a/seed/python-sdk/single-url-environment-default/src/seed/__init__.py +++ b/seed/python-sdk/single-url-environment-default/src/seed/__init__.py @@ -1,7 +1,10 @@ # This file was auto-generated by Fern from our API Definition. from . import dummy -from .client import AsyncSeedSingleUrlEnvironmentDefault, SeedSingleUrlEnvironmentDefault +from .client import ( + AsyncSeedSingleUrlEnvironmentDefault, + SeedSingleUrlEnvironmentDefault, +) from .environment import SeedSingleUrlEnvironmentDefaultEnvironment from .version import __version__ diff --git a/seed/python-sdk/single-url-environment-default/src/seed/client.py b/seed/python-sdk/single-url-environment-default/src/seed/client.py index 38c938ebda6..86ca6348fed 100644 --- a/seed/python-sdk/single-url-environment-default/src/seed/client.py +++ b/seed/python-sdk/single-url-environment-default/src/seed/client.py @@ -1,12 +1,12 @@ # This file was auto-generated by Fern from our API Definition. import typing - -import httpx - -from .core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from .dummy.client import AsyncDummyClient, DummyClient from .environment import SeedSingleUrlEnvironmentDefaultEnvironment +import httpx +from .core.client_wrapper import SyncClientWrapper +from .dummy.client import DummyClient +from .core.client_wrapper import AsyncClientWrapper +from .dummy.client import AsyncDummyClient class SeedSingleUrlEnvironmentDefault: @@ -21,8 +21,6 @@ class SeedSingleUrlEnvironmentDefault: environment : SeedSingleUrlEnvironmentDefaultEnvironment The environment to use for requests from the client. from .environment import SeedSingleUrlEnvironmentDefaultEnvironment - - Defaults to SeedSingleUrlEnvironmentDefaultEnvironment.PRODUCTION @@ -54,15 +52,19 @@ def __init__( token: typing.Union[str, typing.Callable[[], str]], timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.Client] = None + httpx_client: typing.Optional[httpx.Client] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = SyncClientWrapper( base_url=_get_base_url(base_url=base_url, environment=environment), token=token, httpx_client=httpx_client if httpx_client is not None - else httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.Client( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.Client(timeout=_defaulted_timeout), timeout=_defaulted_timeout, @@ -82,8 +84,6 @@ class AsyncSeedSingleUrlEnvironmentDefault: environment : SeedSingleUrlEnvironmentDefaultEnvironment The environment to use for requests from the client. from .environment import SeedSingleUrlEnvironmentDefaultEnvironment - - Defaults to SeedSingleUrlEnvironmentDefaultEnvironment.PRODUCTION @@ -115,15 +115,19 @@ def __init__( token: typing.Union[str, typing.Callable[[], str]], timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.AsyncClient] = None + httpx_client: typing.Optional[httpx.AsyncClient] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = AsyncClientWrapper( base_url=_get_base_url(base_url=base_url, environment=environment), token=token, httpx_client=httpx_client if httpx_client is not None - else httpx.AsyncClient(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.AsyncClient( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.AsyncClient(timeout=_defaulted_timeout), timeout=_defaulted_timeout, @@ -132,11 +136,15 @@ def __init__( def _get_base_url( - *, base_url: typing.Optional[str] = None, environment: SeedSingleUrlEnvironmentDefaultEnvironment + *, + base_url: typing.Optional[str] = None, + environment: SeedSingleUrlEnvironmentDefaultEnvironment, ) -> str: if base_url is not None: return base_url elif environment is not None: return environment.value else: - raise Exception("Please pass in either base_url or environment to construct the client") + raise Exception( + "Please pass in either base_url or environment to construct the client" + ) diff --git a/seed/python-sdk/single-url-environment-default/src/seed/core/api_error.py b/seed/python-sdk/single-url-environment-default/src/seed/core/api_error.py index 2e9fc5431cd..da734b58068 100644 --- a/seed/python-sdk/single-url-environment-default/src/seed/core/api_error.py +++ b/seed/python-sdk/single-url-environment-default/src/seed/core/api_error.py @@ -7,7 +7,9 @@ class ApiError(Exception): status_code: typing.Optional[int] body: typing.Any - def __init__(self, *, status_code: typing.Optional[int] = None, body: typing.Any = None): + def __init__( + self, *, status_code: typing.Optional[int] = None, body: typing.Any = None + ): self.status_code = status_code self.body = body diff --git a/seed/python-sdk/single-url-environment-default/src/seed/core/client_wrapper.py b/seed/python-sdk/single-url-environment-default/src/seed/core/client_wrapper.py index 6887b2415a6..a750d57aa5f 100644 --- a/seed/python-sdk/single-url-environment-default/src/seed/core/client_wrapper.py +++ b/seed/python-sdk/single-url-environment-default/src/seed/core/client_wrapper.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .http_client import AsyncHttpClient, HttpClient +from .http_client import HttpClient +from .http_client import AsyncHttpClient class BaseClientWrapper: diff --git a/seed/python-sdk/single-url-environment-default/src/seed/core/datetime_utils.py b/seed/python-sdk/single-url-environment-default/src/seed/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/python-sdk/single-url-environment-default/src/seed/core/datetime_utils.py +++ b/seed/python-sdk/single-url-environment-default/src/seed/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/python-sdk/single-url-environment-default/src/seed/core/file.py b/seed/python-sdk/single-url-environment-default/src/seed/core/file.py index cb0d40bbbf3..6e0f92bfcb1 100644 --- a/seed/python-sdk/single-url-environment-default/src/seed/core/file.py +++ b/seed/python-sdk/single-url-environment-default/src/seed/core/file.py @@ -13,12 +13,17 @@ # (filename, file (or bytes), content_type) typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str]], # (filename, file (or bytes), content_type, headers) - typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str], typing.Mapping[str, str]], + typing.Tuple[ + typing.Optional[str], + FileContent, + typing.Optional[str], + typing.Mapping[str, str], + ], ] def convert_file_dict_to_httpx_tuples( - d: typing.Dict[str, typing.Union[File, typing.List[File]]] + d: typing.Dict[str, typing.Union[File, typing.List[File]]], ) -> typing.List[typing.Tuple[str, File]]: """ The format we use is a list of tuples, where the first element is the diff --git a/seed/python-sdk/single-url-environment-default/src/seed/core/http_client.py b/seed/python-sdk/single-url-environment-default/src/seed/core/http_client.py index 9333d8a7f15..091f71bc185 100644 --- a/seed/python-sdk/single-url-environment-default/src/seed/core/http_client.py +++ b/seed/python-sdk/single-url-environment-default/src/seed/core/http_client.py @@ -77,7 +77,9 @@ def _retry_timeout(response: httpx.Response, retries: int) -> float: return retry_after # Apply exponential backoff, capped at MAX_RETRY_DELAY_SECONDS. - retry_delay = min(INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS) + retry_delay = min( + INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS + ) # Add a randomness / jitter to the retry delay to avoid overwhelming the server with retries. timeout = retry_delay * (1 - 0.25 * random()) @@ -90,7 +92,8 @@ def _should_retry(response: httpx.Response) -> bool: def remove_omit_from_dict( - original: typing.Dict[str, typing.Optional[typing.Any]], omit: typing.Optional[typing.Any] + original: typing.Dict[str, typing.Optional[typing.Any]], + omit: typing.Optional[typing.Any], ) -> typing.Dict[str, typing.Any]: if omit is None: return original @@ -108,7 +111,8 @@ def maybe_filter_request_body( ) -> typing.Optional[typing.Any]: if data is None: return ( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else None ) @@ -118,7 +122,8 @@ def maybe_filter_request_body( data_content = { **(jsonable_encoder(remove_omit_from_dict(data, omit))), # type: ignore **( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else {} ), @@ -162,7 +167,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url def request( @@ -174,8 +181,12 @@ def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -184,11 +195,14 @@ def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) response = self.httpx_client.request( method=method, @@ -198,7 +212,11 @@ def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -209,7 +227,10 @@ def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -222,11 +243,15 @@ def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: time.sleep(_retry_timeout(response=response, retries=retries)) @@ -256,8 +281,12 @@ def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -266,11 +295,14 @@ def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) with self.httpx_client.stream( method=method, @@ -280,7 +312,11 @@ def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -291,7 +327,9 @@ def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -304,7 +342,9 @@ def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream @@ -327,7 +367,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url async def request( @@ -339,8 +381,12 @@ async def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -349,11 +395,14 @@ async def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) # Add the input to each of these and do None-safety checks response = await self.httpx_client.request( @@ -364,7 +413,11 @@ async def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -375,7 +428,10 @@ async def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -388,11 +444,15 @@ async def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: await asyncio.sleep(_retry_timeout(response=response, retries=retries)) @@ -421,8 +481,12 @@ async def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -431,11 +495,14 @@ async def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) async with self.httpx_client.stream( method=method, @@ -445,7 +512,11 @@ async def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -456,7 +527,9 @@ async def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -469,7 +542,9 @@ async def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream diff --git a/seed/python-sdk/single-url-environment-default/src/seed/core/jsonable_encoder.py b/seed/python-sdk/single-url-environment-default/src/seed/core/jsonable_encoder.py index d3fd328fd41..12a8b52fc22 100644 --- a/seed/python-sdk/single-url-environment-default/src/seed/core/jsonable_encoder.py +++ b/seed/python-sdk/single-url-environment-default/src/seed/core/jsonable_encoder.py @@ -19,13 +19,19 @@ import pydantic from .datetime_utils import serialize_datetime -from .pydantic_utilities import IS_PYDANTIC_V2, encode_by_type, to_jsonable_with_fallback +from .pydantic_utilities import ( + IS_PYDANTIC_V2, + encode_by_type, + to_jsonable_with_fallback, +) SetIntStr = Set[Union[int, str]] DictIntStrAny = Dict[Union[int, str], Any] -def jsonable_encoder(obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None) -> Any: +def jsonable_encoder( + obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None +) -> Any: custom_encoder = custom_encoder or {} if custom_encoder: if type(obj) in custom_encoder: diff --git a/seed/python-sdk/single-url-environment-default/src/seed/core/pydantic_utilities.py b/seed/python-sdk/single-url-environment-default/src/seed/core/pydantic_utilities.py index 170a563d6eb..c63935c32a2 100644 --- a/seed/python-sdk/single-url-environment-default/src/seed/core/pydantic_utilities.py +++ b/seed/python-sdk/single-url-environment-default/src/seed/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) # type: ignore # Pydantic v1 diff --git a/seed/python-sdk/single-url-environment-default/src/seed/core/query_encoder.py b/seed/python-sdk/single-url-environment-default/src/seed/core/query_encoder.py index 24076d72ee9..7cb98f52cd7 100644 --- a/seed/python-sdk/single-url-environment-default/src/seed/core/query_encoder.py +++ b/seed/python-sdk/single-url-environment-default/src/seed/core/query_encoder.py @@ -7,7 +7,9 @@ # Flattens dicts to be of the form {"key[subkey][subkey2]": value} where value is not a dict -def traverse_query_dict(dict_flat: Dict[str, Any], key_prefix: Optional[str] = None) -> Dict[str, Any]: +def traverse_query_dict( + dict_flat: Dict[str, Any], key_prefix: Optional[str] = None +) -> Dict[str, Any]: result = {} for k, v in dict_flat.items(): key = f"{key_prefix}[{k}]" if key_prefix is not None else k @@ -30,4 +32,8 @@ def single_query_encoder(query_key: str, query_value: Any) -> Dict[str, Any]: def encode_query(query: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: - return dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) if query is not None else None + return ( + dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) + if query is not None + else None + ) diff --git a/seed/python-sdk/single-url-environment-default/src/seed/core/serialization.py b/seed/python-sdk/single-url-environment-default/src/seed/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/python-sdk/single-url-environment-default/src/seed/core/serialization.py +++ b/seed/python-sdk/single-url-environment-default/src/seed/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/python-sdk/single-url-environment-default/src/seed/dummy/client.py b/seed/python-sdk/single-url-environment-default/src/seed/dummy/client.py index 7532f75653d..f93441565e5 100644 --- a/seed/python-sdk/single-url-environment-default/src/seed/dummy/client.py +++ b/seed/python-sdk/single-url-environment-default/src/seed/dummy/client.py @@ -1,19 +1,21 @@ # This file was auto-generated by Fern from our API Definition. +from ..core.client_wrapper import SyncClientWrapper import typing +from ..core.request_options import RequestOptions +from ..core.pydantic_utilities import parse_obj_as from json.decoder import JSONDecodeError - from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.pydantic_utilities import parse_obj_as -from ..core.request_options import RequestOptions +from ..core.client_wrapper import AsyncClientWrapper class DummyClient: def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper - def get_dummy(self, *, request_options: typing.Optional[RequestOptions] = None) -> str: + def get_dummy( + self, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -33,10 +35,16 @@ def get_dummy(self, *, request_options: typing.Optional[RequestOptions] = None) ) client.dummy.get_dummy() """ - _response = self._client_wrapper.httpx_client.request("dummy", method="GET", request_options=request_options) + _response = self._client_wrapper.httpx_client.request( + "dummy", + method="GET", + request_options=request_options, + ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -47,7 +55,9 @@ class AsyncDummyClient: def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper - async def get_dummy(self, *, request_options: typing.Optional[RequestOptions] = None) -> str: + async def get_dummy( + self, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -76,11 +86,15 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "dummy", method="GET", request_options=request_options + "dummy", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/single-url-environment-default/src/seed/version.py b/seed/python-sdk/single-url-environment-default/src/seed/version.py index 44453cf6a72..f4c18925752 100644 --- a/seed/python-sdk/single-url-environment-default/src/seed/version.py +++ b/seed/python-sdk/single-url-environment-default/src/seed/version.py @@ -1,4 +1,3 @@ - from importlib import metadata __version__ = metadata.version("fern_single-url-environment-default") diff --git a/seed/python-sdk/single-url-environment-default/tests/conftest.py b/seed/python-sdk/single-url-environment-default/tests/conftest.py index 7a7164d0044..9a9e4f4d9c8 100644 --- a/seed/python-sdk/single-url-environment-default/tests/conftest.py +++ b/seed/python-sdk/single-url-environment-default/tests/conftest.py @@ -1,20 +1,22 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedSingleUrlEnvironmentDefault import os - import pytest -from seed import AsyncSeedSingleUrlEnvironmentDefault, SeedSingleUrlEnvironmentDefault +from seed import AsyncSeedSingleUrlEnvironmentDefault @pytest.fixture def client() -> SeedSingleUrlEnvironmentDefault: return SeedSingleUrlEnvironmentDefault( - token=os.getenv("ENV_TOKEN", "token"), base_url=os.getenv("TESTS_BASE_URL", "base_url") + token=os.getenv("ENV_TOKEN", "token"), + base_url=os.getenv("TESTS_BASE_URL", "base_url"), ) @pytest.fixture def async_client() -> AsyncSeedSingleUrlEnvironmentDefault: return AsyncSeedSingleUrlEnvironmentDefault( - token=os.getenv("ENV_TOKEN", "token"), base_url=os.getenv("TESTS_BASE_URL", "base_url") + token=os.getenv("ENV_TOKEN", "token"), + base_url=os.getenv("TESTS_BASE_URL", "base_url"), ) diff --git a/seed/python-sdk/single-url-environment-default/tests/custom/test_client.py b/seed/python-sdk/single-url-environment-default/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/python-sdk/single-url-environment-default/tests/custom/test_client.py +++ b/seed/python-sdk/single-url-environment-default/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/python-sdk/single-url-environment-default/tests/test_dummy.py b/seed/python-sdk/single-url-environment-default/tests/test_dummy.py index 15cc8e23770..93e2dcd20d8 100644 --- a/seed/python-sdk/single-url-environment-default/tests/test_dummy.py +++ b/seed/python-sdk/single-url-environment-default/tests/test_dummy.py @@ -1,14 +1,14 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedSingleUrlEnvironmentDefault +from seed import AsyncSeedSingleUrlEnvironmentDefault import typing - -from seed import AsyncSeedSingleUrlEnvironmentDefault, SeedSingleUrlEnvironmentDefault - from .utilities import validate_response async def test_get_dummy( - client: SeedSingleUrlEnvironmentDefault, async_client: AsyncSeedSingleUrlEnvironmentDefault + client: SeedSingleUrlEnvironmentDefault, + async_client: AsyncSeedSingleUrlEnvironmentDefault, ) -> None: expected_response: typing.Any = "string" expected_types: typing.Any = None diff --git a/seed/python-sdk/single-url-environment-default/tests/utilities.py b/seed/python-sdk/single-url-environment-default/tests/utilities.py index 13da208eb3a..e8f4472564c 100644 --- a/seed/python-sdk/single-url-environment-default/tests/utilities.py +++ b/seed/python-sdk/single-url-environment-default/tests/utilities.py @@ -3,11 +3,14 @@ import typing import uuid -import pydantic from dateutil import parser +import pydantic + -def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> typing.Any: +def cast_field( + json_expectation: typing.Any, type_expectation: typing.Any +) -> typing.Any: # Cast these specific types which come through as string and expect our # models to cast to the correct type. if type_expectation == "uuid": @@ -25,7 +28,9 @@ def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> ty return json_expectation -def validate_field(response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any) -> None: +def validate_field( + response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectation == "no_validate": return @@ -44,7 +49,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(entry_expectation, dict): is_container_of_complex_type = True validate_response( - response=response[idx], json_expectation=ex, type_expectations=entry_expectation + response=response[idx], + json_expectation=ex, + type_expectations=entry_expectation, ) else: cast_json_expectation.append(cast_field(ex, entry_expectation)) @@ -56,7 +63,10 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # if any of the values of the set have a type_expectation of a dict, we're assuming it's a pydantic # model and keeping it a list. if container_expectation != "set" or not any( - map(lambda value: isinstance(value, dict), list(contents_expectation.values())) + map( + lambda value: isinstance(value, dict), + list(contents_expectation.values()), + ) ): json_expectation = cast_field(json_expectation, container_expectation) elif isinstance(type_expectation, tuple): @@ -65,9 +75,15 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(contents_expectation, dict): json_expectation = { cast_field( - key, contents_expectation.get(idx)[0] if contents_expectation.get(idx) is not None else None # type: ignore + key, + contents_expectation.get(idx)[0] + if contents_expectation.get(idx) is not None + else None, # type: ignore ): cast_field( - value, contents_expectation.get(idx)[1] if contents_expectation.get(idx) is not None else None # type: ignore + value, + contents_expectation.get(idx)[1] + if contents_expectation.get(idx) is not None + else None, # type: ignore ) for idx, (key, value) in enumerate(json_expectation.items()) } @@ -86,7 +102,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # Arg type_expectations is a deeply nested structure that matches the response, but with the values replaced with the expected types -def validate_response(response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any) -> None: +def validate_response( + response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectations == "no_validate": return @@ -96,11 +114,17 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e and not isinstance(response, dict) and not issubclass(type(response), pydantic.BaseModel) ): - validate_field(response=response, json_expectation=json_expectation, type_expectation=type_expectations) + validate_field( + response=response, + json_expectation=json_expectation, + type_expectation=type_expectations, + ) return if isinstance(response, list): - assert len(response) == len(json_expectation), "Length mismatch, expected: {0}, Actual: {1}".format( + assert len(response) == len( + json_expectation + ), "Length mismatch, expected: {0}, Actual: {1}".format( len(response), len(json_expectation) ) content_expectation = type_expectations @@ -108,7 +132,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e content_expectation = type_expectations[1] for idx, item in enumerate(response): validate_response( - response=item, json_expectation=json_expectation[idx], type_expectations=content_expectation[idx] + response=item, + json_expectation=json_expectation[idx], + type_expectations=content_expectation[idx], ) else: response_json = response @@ -116,7 +142,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e response_json = response.dict(by_alias=True) for key, value in json_expectation.items(): - assert key in response_json, "Field {0} not found within the response object: {1}".format( + assert ( + key in response_json + ), "Field {0} not found within the response object: {1}".format( key, response_json ) @@ -128,11 +156,19 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e # Otherwise, we're just validating a single field that's a pydantic model. if isinstance(value, dict) and not isinstance(type_expectation, tuple): validate_response( - response=response_json[key], json_expectation=value, type_expectations=type_expectation + response=response_json[key], + json_expectation=value, + type_expectations=type_expectation, ) else: - validate_field(response=response_json[key], json_expectation=value, type_expectation=type_expectation) + validate_field( + response=response_json[key], + json_expectation=value, + type_expectation=type_expectation, + ) # Ensure there are no additional fields here either del response_json[key] - assert len(response_json) == 0, "Additional fields found, expected None: {0}".format(response_json) + assert ( + len(response_json) == 0 + ), "Additional fields found, expected None: {0}".format(response_json) diff --git a/seed/python-sdk/single-url-environment-default/tests/utils/assets/models/__init__.py b/seed/python-sdk/single-url-environment-default/tests/utils/assets/models/__init__.py index 2cf01263529..3a1c852e71e 100644 --- a/seed/python-sdk/single-url-environment-default/tests/utils/assets/models/__init__.py +++ b/seed/python-sdk/single-url-environment-default/tests/utils/assets/models/__init__.py @@ -5,7 +5,7 @@ from .circle import CircleParams from .object_with_defaults import ObjectWithDefaultsParams from .object_with_optional_field import ObjectWithOptionalFieldParams -from .shape import Shape_CircleParams, Shape_SquareParams, ShapeParams +from .shape import ShapeParams, Shape_CircleParams, Shape_SquareParams from .square import SquareParams from .undiscriminated_shape import UndiscriminatedShapeParams diff --git a/seed/python-sdk/single-url-environment-default/tests/utils/assets/models/circle.py b/seed/python-sdk/single-url-environment-default/tests/utils/assets/models/circle.py index af7a1bf8a8e..253f12d38b3 100644 --- a/seed/python-sdk/single-url-environment-default/tests/utils/assets/models/circle.py +++ b/seed/python-sdk/single-url-environment-default/tests/utils/assets/models/circle.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class CircleParams(typing_extensions.TypedDict): - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] diff --git a/seed/python-sdk/single-url-environment-default/tests/utils/assets/models/object_with_optional_field.py b/seed/python-sdk/single-url-environment-default/tests/utils/assets/models/object_with_optional_field.py index 3ad93d5f305..ebe7dc80547 100644 --- a/seed/python-sdk/single-url-environment-default/tests/utils/assets/models/object_with_optional_field.py +++ b/seed/python-sdk/single-url-environment-default/tests/utils/assets/models/object_with_optional_field.py @@ -7,8 +7,8 @@ import uuid import typing_extensions -from seed.core.serialization import FieldMetadata +from seed.core.serialization import FieldMetadata from .color import Color from .shape import ShapeParams from .undiscriminated_shape import UndiscriminatedShapeParams @@ -18,16 +18,30 @@ class ObjectWithOptionalFieldParams(typing_extensions.TypedDict): literal: typing.Literal["lit_one"] string: typing_extensions.NotRequired[str] integer: typing_extensions.NotRequired[int] - long_: typing_extensions.NotRequired[typing_extensions.Annotated[int, FieldMetadata(alias="long")]] + long_: typing_extensions.NotRequired[ + typing_extensions.Annotated[int, FieldMetadata(alias="long")] + ] double: typing_extensions.NotRequired[float] - bool_: typing_extensions.NotRequired[typing_extensions.Annotated[bool, FieldMetadata(alias="bool")]] + bool_: typing_extensions.NotRequired[ + typing_extensions.Annotated[bool, FieldMetadata(alias="bool")] + ] datetime: typing_extensions.NotRequired[dt.datetime] date: typing_extensions.NotRequired[dt.date] - uuid_: typing_extensions.NotRequired[typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")]] - base_64: typing_extensions.NotRequired[typing_extensions.Annotated[str, FieldMetadata(alias="base64")]] - list_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")]] - set_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")]] - map_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")]] + uuid_: typing_extensions.NotRequired[ + typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")] + ] + base_64: typing_extensions.NotRequired[ + typing_extensions.Annotated[str, FieldMetadata(alias="base64")] + ] + list_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")] + ] + set_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")] + ] + map_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")] + ] enum: typing_extensions.NotRequired[Color] union: typing_extensions.NotRequired[ShapeParams] second_union: typing_extensions.NotRequired[ShapeParams] diff --git a/seed/python-sdk/single-url-environment-default/tests/utils/assets/models/shape.py b/seed/python-sdk/single-url-environment-default/tests/utils/assets/models/shape.py index 2c33c877951..816ffc51bdc 100644 --- a/seed/python-sdk/single-url-environment-default/tests/utils/assets/models/shape.py +++ b/seed/python-sdk/single-url-environment-default/tests/utils/assets/models/shape.py @@ -7,6 +7,7 @@ import typing import typing_extensions + from seed.core.serialization import FieldMetadata @@ -15,13 +16,21 @@ class Base(typing_extensions.TypedDict): class Shape_CircleParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["circle"], FieldMetadata(alias="shapeType")] - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["circle"], FieldMetadata(alias="shapeType") + ] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] class Shape_SquareParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["square"], FieldMetadata(alias="shapeType")] - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["square"], FieldMetadata(alias="shapeType") + ] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] ShapeParams = typing.Union[Shape_CircleParams, Shape_SquareParams] diff --git a/seed/python-sdk/single-url-environment-default/tests/utils/assets/models/square.py b/seed/python-sdk/single-url-environment-default/tests/utils/assets/models/square.py index b9b7dd319bc..bcf08a723c5 100644 --- a/seed/python-sdk/single-url-environment-default/tests/utils/assets/models/square.py +++ b/seed/python-sdk/single-url-environment-default/tests/utils/assets/models/square.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class SquareParams(typing_extensions.TypedDict): - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] diff --git a/seed/python-sdk/single-url-environment-default/tests/utils/test_http_client.py b/seed/python-sdk/single-url-environment-default/tests/utils/test_http_client.py index edd11ca7afb..f5a874a75f3 100644 --- a/seed/python-sdk/single-url-environment-default/tests/utils/test_http_client.py +++ b/seed/python-sdk/single-url-environment-default/tests/utils/test_http_client.py @@ -9,12 +9,17 @@ def get_request_options() -> RequestOptions: def test_get_json_request_body() -> None: - json_body, data_body = get_request_body(json={"hello": "world"}, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json={"hello": "world"}, data=None, request_options=None, omit=None + ) assert json_body == {"hello": "world"} assert data_body is None json_body_extras, data_body_extras = get_request_body( - json={"goodbye": "world"}, data=None, request_options=get_request_options(), omit=None + json={"goodbye": "world"}, + data=None, + request_options=get_request_options(), + omit=None, ) assert json_body_extras == {"goodbye": "world", "see you": "later"} @@ -22,12 +27,17 @@ def test_get_json_request_body() -> None: def test_get_files_request_body() -> None: - json_body, data_body = get_request_body(json=None, data={"hello": "world"}, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data={"hello": "world"}, request_options=None, omit=None + ) assert data_body == {"hello": "world"} assert json_body is None json_body_extras, data_body_extras = get_request_body( - json=None, data={"goodbye": "world"}, request_options=get_request_options(), omit=None + json=None, + data={"goodbye": "world"}, + request_options=get_request_options(), + omit=None, ) assert data_body_extras == {"goodbye": "world", "see you": "later"} @@ -35,7 +45,9 @@ def test_get_files_request_body() -> None: def test_get_none_request_body() -> None: - json_body, data_body = get_request_body(json=None, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data=None, request_options=None, omit=None + ) assert data_body is None assert json_body is None diff --git a/seed/python-sdk/single-url-environment-default/tests/utils/test_query_encoding.py b/seed/python-sdk/single-url-environment-default/tests/utils/test_query_encoding.py index 247e1551b46..fbc8f402167 100644 --- a/seed/python-sdk/single-url-environment-default/tests/utils/test_query_encoding.py +++ b/seed/python-sdk/single-url-environment-default/tests/utils/test_query_encoding.py @@ -4,9 +4,15 @@ def test_query_encoding() -> None: - assert encode_query({"hello world": "hello world"}) == {"hello world": "hello world"} - assert encode_query({"hello_world": {"hello": "world"}}) == {"hello_world[hello]": "world"} - assert encode_query({"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"}) == { + assert encode_query({"hello world": "hello world"}) == { + "hello world": "hello world" + } + assert encode_query({"hello_world": {"hello": "world"}}) == { + "hello_world[hello]": "world" + } + assert encode_query( + {"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"} + ) == { "hello_world[hello][world]": "today", "hello_world[test]": "this", "hi": "there", diff --git a/seed/python-sdk/single-url-environment-default/tests/utils/test_serialization.py b/seed/python-sdk/single-url-environment-default/tests/utils/test_serialization.py index 58b1ed66e6d..5ca956916dd 100644 --- a/seed/python-sdk/single-url-environment-default/tests/utils/test_serialization.py +++ b/seed/python-sdk/single-url-environment-default/tests/utils/test_serialization.py @@ -1,10 +1,12 @@ # This file was auto-generated by Fern from our API Definition. -from typing import Any, List +from typing import List, Any -from seed.core.serialization import convert_and_respect_annotation_metadata +from seed.core.serialization import ( + convert_and_respect_annotation_metadata, +) +from .assets.models import ShapeParams, ObjectWithOptionalFieldParams -from .assets.models import ObjectWithOptionalFieldParams, ShapeParams UNION_TEST: ShapeParams = {"radius_measurement": 1.0, "shape_type": "circle", "id": "1"} UNION_TEST_CONVERTED = {"shapeType": "circle", "radiusMeasurement": 1.0, "id": "1"} @@ -18,20 +20,54 @@ def test_convert_and_respect_annotation_metadata() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) - assert converted == {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"} + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) + assert converted == { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + } def test_convert_and_respect_annotation_metadata_in_list() -> None: data: List[ObjectWithOptionalFieldParams] = [ - {"string": "string", "long_": 12345, "bool_": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long_": 67890, "list_": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long_": 12345, + "bool_": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long_": 67890, + "list_": [], + "literal": "lit_one", + "any": "any", + }, ] - converted = convert_and_respect_annotation_metadata(object_=data, annotation=List[ObjectWithOptionalFieldParams]) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=List[ObjectWithOptionalFieldParams] + ) assert converted == [ - {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long": 67890, "list": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long": 67890, + "list": [], + "literal": "lit_one", + "any": "any", + }, ] @@ -43,7 +79,9 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) assert converted == { "string": "string", @@ -55,12 +93,16 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: def test_convert_and_respect_annotation_metadata_in_union() -> None: - converted = convert_and_respect_annotation_metadata(object_=UNION_TEST, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=UNION_TEST, annotation=ShapeParams + ) assert converted == UNION_TEST_CONVERTED def test_convert_and_respect_annotation_metadata_with_empty_object() -> None: data: Any = {} - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ShapeParams + ) assert converted == data diff --git a/seed/python-sdk/single-url-environment-no-default/pyproject.toml b/seed/python-sdk/single-url-environment-no-default/pyproject.toml index 2a3b17253a6..a92ec246a80 100644 --- a/seed/python-sdk/single-url-environment-no-default/pyproject.toml +++ b/seed/python-sdk/single-url-environment-no-default/pyproject.toml @@ -43,6 +43,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/python-sdk/single-url-environment-no-default/src/seed/__init__.py b/seed/python-sdk/single-url-environment-no-default/src/seed/__init__.py index 6817ee204ae..feca3ab4bca 100644 --- a/seed/python-sdk/single-url-environment-no-default/src/seed/__init__.py +++ b/seed/python-sdk/single-url-environment-no-default/src/seed/__init__.py @@ -1,7 +1,10 @@ # This file was auto-generated by Fern from our API Definition. from . import dummy -from .client import AsyncSeedSingleUrlEnvironmentNoDefault, SeedSingleUrlEnvironmentNoDefault +from .client import ( + AsyncSeedSingleUrlEnvironmentNoDefault, + SeedSingleUrlEnvironmentNoDefault, +) from .environment import SeedSingleUrlEnvironmentNoDefaultEnvironment from .version import __version__ diff --git a/seed/python-sdk/single-url-environment-no-default/src/seed/client.py b/seed/python-sdk/single-url-environment-no-default/src/seed/client.py index 91aa0ad1433..f9f617fc9c0 100644 --- a/seed/python-sdk/single-url-environment-no-default/src/seed/client.py +++ b/seed/python-sdk/single-url-environment-no-default/src/seed/client.py @@ -1,12 +1,12 @@ # This file was auto-generated by Fern from our API Definition. import typing - -import httpx - -from .core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from .dummy.client import AsyncDummyClient, DummyClient from .environment import SeedSingleUrlEnvironmentNoDefaultEnvironment +import httpx +from .core.client_wrapper import SyncClientWrapper +from .dummy.client import DummyClient +from .core.client_wrapper import AsyncClientWrapper +from .dummy.client import AsyncDummyClient class SeedSingleUrlEnvironmentNoDefault: @@ -46,19 +46,25 @@ def __init__( self, *, base_url: typing.Optional[str] = None, - environment: typing.Optional[SeedSingleUrlEnvironmentNoDefaultEnvironment] = None, + environment: typing.Optional[ + SeedSingleUrlEnvironmentNoDefaultEnvironment + ] = None, token: typing.Union[str, typing.Callable[[], str]], timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.Client] = None + httpx_client: typing.Optional[httpx.Client] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = SyncClientWrapper( base_url=_get_base_url(base_url=base_url, environment=environment), token=token, httpx_client=httpx_client if httpx_client is not None - else httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.Client( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.Client(timeout=_defaulted_timeout), timeout=_defaulted_timeout, @@ -103,19 +109,25 @@ def __init__( self, *, base_url: typing.Optional[str] = None, - environment: typing.Optional[SeedSingleUrlEnvironmentNoDefaultEnvironment] = None, + environment: typing.Optional[ + SeedSingleUrlEnvironmentNoDefaultEnvironment + ] = None, token: typing.Union[str, typing.Callable[[], str]], timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.AsyncClient] = None + httpx_client: typing.Optional[httpx.AsyncClient] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = AsyncClientWrapper( base_url=_get_base_url(base_url=base_url, environment=environment), token=token, httpx_client=httpx_client if httpx_client is not None - else httpx.AsyncClient(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.AsyncClient( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.AsyncClient(timeout=_defaulted_timeout), timeout=_defaulted_timeout, @@ -126,11 +138,13 @@ def __init__( def _get_base_url( *, base_url: typing.Optional[str] = None, - environment: typing.Optional[SeedSingleUrlEnvironmentNoDefaultEnvironment] = None + environment: typing.Optional[SeedSingleUrlEnvironmentNoDefaultEnvironment] = None, ) -> str: if base_url is not None: return base_url elif environment is not None: return environment.value else: - raise Exception("Please pass in either base_url or environment to construct the client") + raise Exception( + "Please pass in either base_url or environment to construct the client" + ) diff --git a/seed/python-sdk/single-url-environment-no-default/src/seed/core/api_error.py b/seed/python-sdk/single-url-environment-no-default/src/seed/core/api_error.py index 2e9fc5431cd..da734b58068 100644 --- a/seed/python-sdk/single-url-environment-no-default/src/seed/core/api_error.py +++ b/seed/python-sdk/single-url-environment-no-default/src/seed/core/api_error.py @@ -7,7 +7,9 @@ class ApiError(Exception): status_code: typing.Optional[int] body: typing.Any - def __init__(self, *, status_code: typing.Optional[int] = None, body: typing.Any = None): + def __init__( + self, *, status_code: typing.Optional[int] = None, body: typing.Any = None + ): self.status_code = status_code self.body = body diff --git a/seed/python-sdk/single-url-environment-no-default/src/seed/core/client_wrapper.py b/seed/python-sdk/single-url-environment-no-default/src/seed/core/client_wrapper.py index 721db61d27f..72a1c311396 100644 --- a/seed/python-sdk/single-url-environment-no-default/src/seed/core/client_wrapper.py +++ b/seed/python-sdk/single-url-environment-no-default/src/seed/core/client_wrapper.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .http_client import AsyncHttpClient, HttpClient +from .http_client import HttpClient +from .http_client import AsyncHttpClient class BaseClientWrapper: diff --git a/seed/python-sdk/single-url-environment-no-default/src/seed/core/datetime_utils.py b/seed/python-sdk/single-url-environment-no-default/src/seed/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/python-sdk/single-url-environment-no-default/src/seed/core/datetime_utils.py +++ b/seed/python-sdk/single-url-environment-no-default/src/seed/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/python-sdk/single-url-environment-no-default/src/seed/core/file.py b/seed/python-sdk/single-url-environment-no-default/src/seed/core/file.py index cb0d40bbbf3..6e0f92bfcb1 100644 --- a/seed/python-sdk/single-url-environment-no-default/src/seed/core/file.py +++ b/seed/python-sdk/single-url-environment-no-default/src/seed/core/file.py @@ -13,12 +13,17 @@ # (filename, file (or bytes), content_type) typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str]], # (filename, file (or bytes), content_type, headers) - typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str], typing.Mapping[str, str]], + typing.Tuple[ + typing.Optional[str], + FileContent, + typing.Optional[str], + typing.Mapping[str, str], + ], ] def convert_file_dict_to_httpx_tuples( - d: typing.Dict[str, typing.Union[File, typing.List[File]]] + d: typing.Dict[str, typing.Union[File, typing.List[File]]], ) -> typing.List[typing.Tuple[str, File]]: """ The format we use is a list of tuples, where the first element is the diff --git a/seed/python-sdk/single-url-environment-no-default/src/seed/core/http_client.py b/seed/python-sdk/single-url-environment-no-default/src/seed/core/http_client.py index 9333d8a7f15..091f71bc185 100644 --- a/seed/python-sdk/single-url-environment-no-default/src/seed/core/http_client.py +++ b/seed/python-sdk/single-url-environment-no-default/src/seed/core/http_client.py @@ -77,7 +77,9 @@ def _retry_timeout(response: httpx.Response, retries: int) -> float: return retry_after # Apply exponential backoff, capped at MAX_RETRY_DELAY_SECONDS. - retry_delay = min(INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS) + retry_delay = min( + INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS + ) # Add a randomness / jitter to the retry delay to avoid overwhelming the server with retries. timeout = retry_delay * (1 - 0.25 * random()) @@ -90,7 +92,8 @@ def _should_retry(response: httpx.Response) -> bool: def remove_omit_from_dict( - original: typing.Dict[str, typing.Optional[typing.Any]], omit: typing.Optional[typing.Any] + original: typing.Dict[str, typing.Optional[typing.Any]], + omit: typing.Optional[typing.Any], ) -> typing.Dict[str, typing.Any]: if omit is None: return original @@ -108,7 +111,8 @@ def maybe_filter_request_body( ) -> typing.Optional[typing.Any]: if data is None: return ( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else None ) @@ -118,7 +122,8 @@ def maybe_filter_request_body( data_content = { **(jsonable_encoder(remove_omit_from_dict(data, omit))), # type: ignore **( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else {} ), @@ -162,7 +167,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url def request( @@ -174,8 +181,12 @@ def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -184,11 +195,14 @@ def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) response = self.httpx_client.request( method=method, @@ -198,7 +212,11 @@ def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -209,7 +227,10 @@ def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -222,11 +243,15 @@ def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: time.sleep(_retry_timeout(response=response, retries=retries)) @@ -256,8 +281,12 @@ def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -266,11 +295,14 @@ def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) with self.httpx_client.stream( method=method, @@ -280,7 +312,11 @@ def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -291,7 +327,9 @@ def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -304,7 +342,9 @@ def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream @@ -327,7 +367,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url async def request( @@ -339,8 +381,12 @@ async def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -349,11 +395,14 @@ async def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) # Add the input to each of these and do None-safety checks response = await self.httpx_client.request( @@ -364,7 +413,11 @@ async def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -375,7 +428,10 @@ async def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -388,11 +444,15 @@ async def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: await asyncio.sleep(_retry_timeout(response=response, retries=retries)) @@ -421,8 +481,12 @@ async def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -431,11 +495,14 @@ async def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) async with self.httpx_client.stream( method=method, @@ -445,7 +512,11 @@ async def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -456,7 +527,9 @@ async def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -469,7 +542,9 @@ async def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream diff --git a/seed/python-sdk/single-url-environment-no-default/src/seed/core/jsonable_encoder.py b/seed/python-sdk/single-url-environment-no-default/src/seed/core/jsonable_encoder.py index d3fd328fd41..12a8b52fc22 100644 --- a/seed/python-sdk/single-url-environment-no-default/src/seed/core/jsonable_encoder.py +++ b/seed/python-sdk/single-url-environment-no-default/src/seed/core/jsonable_encoder.py @@ -19,13 +19,19 @@ import pydantic from .datetime_utils import serialize_datetime -from .pydantic_utilities import IS_PYDANTIC_V2, encode_by_type, to_jsonable_with_fallback +from .pydantic_utilities import ( + IS_PYDANTIC_V2, + encode_by_type, + to_jsonable_with_fallback, +) SetIntStr = Set[Union[int, str]] DictIntStrAny = Dict[Union[int, str], Any] -def jsonable_encoder(obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None) -> Any: +def jsonable_encoder( + obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None +) -> Any: custom_encoder = custom_encoder or {} if custom_encoder: if type(obj) in custom_encoder: diff --git a/seed/python-sdk/single-url-environment-no-default/src/seed/core/pydantic_utilities.py b/seed/python-sdk/single-url-environment-no-default/src/seed/core/pydantic_utilities.py index 170a563d6eb..c63935c32a2 100644 --- a/seed/python-sdk/single-url-environment-no-default/src/seed/core/pydantic_utilities.py +++ b/seed/python-sdk/single-url-environment-no-default/src/seed/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) # type: ignore # Pydantic v1 diff --git a/seed/python-sdk/single-url-environment-no-default/src/seed/core/query_encoder.py b/seed/python-sdk/single-url-environment-no-default/src/seed/core/query_encoder.py index 24076d72ee9..7cb98f52cd7 100644 --- a/seed/python-sdk/single-url-environment-no-default/src/seed/core/query_encoder.py +++ b/seed/python-sdk/single-url-environment-no-default/src/seed/core/query_encoder.py @@ -7,7 +7,9 @@ # Flattens dicts to be of the form {"key[subkey][subkey2]": value} where value is not a dict -def traverse_query_dict(dict_flat: Dict[str, Any], key_prefix: Optional[str] = None) -> Dict[str, Any]: +def traverse_query_dict( + dict_flat: Dict[str, Any], key_prefix: Optional[str] = None +) -> Dict[str, Any]: result = {} for k, v in dict_flat.items(): key = f"{key_prefix}[{k}]" if key_prefix is not None else k @@ -30,4 +32,8 @@ def single_query_encoder(query_key: str, query_value: Any) -> Dict[str, Any]: def encode_query(query: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: - return dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) if query is not None else None + return ( + dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) + if query is not None + else None + ) diff --git a/seed/python-sdk/single-url-environment-no-default/src/seed/core/serialization.py b/seed/python-sdk/single-url-environment-no-default/src/seed/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/python-sdk/single-url-environment-no-default/src/seed/core/serialization.py +++ b/seed/python-sdk/single-url-environment-no-default/src/seed/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/python-sdk/single-url-environment-no-default/src/seed/dummy/client.py b/seed/python-sdk/single-url-environment-no-default/src/seed/dummy/client.py index 9c0cc7dc053..e229b245717 100644 --- a/seed/python-sdk/single-url-environment-no-default/src/seed/dummy/client.py +++ b/seed/python-sdk/single-url-environment-no-default/src/seed/dummy/client.py @@ -1,19 +1,21 @@ # This file was auto-generated by Fern from our API Definition. +from ..core.client_wrapper import SyncClientWrapper import typing +from ..core.request_options import RequestOptions +from ..core.pydantic_utilities import parse_obj_as from json.decoder import JSONDecodeError - from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.pydantic_utilities import parse_obj_as -from ..core.request_options import RequestOptions +from ..core.client_wrapper import AsyncClientWrapper class DummyClient: def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper - def get_dummy(self, *, request_options: typing.Optional[RequestOptions] = None) -> str: + def get_dummy( + self, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -35,10 +37,16 @@ def get_dummy(self, *, request_options: typing.Optional[RequestOptions] = None) ) client.dummy.get_dummy() """ - _response = self._client_wrapper.httpx_client.request("dummy", method="GET", request_options=request_options) + _response = self._client_wrapper.httpx_client.request( + "dummy", + method="GET", + request_options=request_options, + ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -49,7 +57,9 @@ class AsyncDummyClient: def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper - async def get_dummy(self, *, request_options: typing.Optional[RequestOptions] = None) -> str: + async def get_dummy( + self, *, request_options: typing.Optional[RequestOptions] = None + ) -> str: """ Parameters ---------- @@ -80,11 +90,15 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "dummy", method="GET", request_options=request_options + "dummy", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(str, parse_obj_as(type_=str, object_=_response.json())) # type: ignore + return typing.cast( + str, parse_obj_as(type_=str, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/single-url-environment-no-default/src/seed/version.py b/seed/python-sdk/single-url-environment-no-default/src/seed/version.py index 00a9ec56b22..71644dcab01 100644 --- a/seed/python-sdk/single-url-environment-no-default/src/seed/version.py +++ b/seed/python-sdk/single-url-environment-no-default/src/seed/version.py @@ -1,4 +1,3 @@ - from importlib import metadata __version__ = metadata.version("fern_single-url-environment-no-default") diff --git a/seed/python-sdk/single-url-environment-no-default/tests/conftest.py b/seed/python-sdk/single-url-environment-no-default/tests/conftest.py index 4858eceef95..5b63312a8b3 100644 --- a/seed/python-sdk/single-url-environment-no-default/tests/conftest.py +++ b/seed/python-sdk/single-url-environment-no-default/tests/conftest.py @@ -1,20 +1,22 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedSingleUrlEnvironmentNoDefault import os - import pytest -from seed import AsyncSeedSingleUrlEnvironmentNoDefault, SeedSingleUrlEnvironmentNoDefault +from seed import AsyncSeedSingleUrlEnvironmentNoDefault @pytest.fixture def client() -> SeedSingleUrlEnvironmentNoDefault: return SeedSingleUrlEnvironmentNoDefault( - token=os.getenv("ENV_TOKEN", "token"), base_url=os.getenv("TESTS_BASE_URL", "base_url") + token=os.getenv("ENV_TOKEN", "token"), + base_url=os.getenv("TESTS_BASE_URL", "base_url"), ) @pytest.fixture def async_client() -> AsyncSeedSingleUrlEnvironmentNoDefault: return AsyncSeedSingleUrlEnvironmentNoDefault( - token=os.getenv("ENV_TOKEN", "token"), base_url=os.getenv("TESTS_BASE_URL", "base_url") + token=os.getenv("ENV_TOKEN", "token"), + base_url=os.getenv("TESTS_BASE_URL", "base_url"), ) diff --git a/seed/python-sdk/single-url-environment-no-default/tests/custom/test_client.py b/seed/python-sdk/single-url-environment-no-default/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/python-sdk/single-url-environment-no-default/tests/custom/test_client.py +++ b/seed/python-sdk/single-url-environment-no-default/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/python-sdk/single-url-environment-no-default/tests/test_dummy.py b/seed/python-sdk/single-url-environment-no-default/tests/test_dummy.py index 7d52b4bc612..a774cc1ad87 100644 --- a/seed/python-sdk/single-url-environment-no-default/tests/test_dummy.py +++ b/seed/python-sdk/single-url-environment-no-default/tests/test_dummy.py @@ -1,14 +1,14 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedSingleUrlEnvironmentNoDefault +from seed import AsyncSeedSingleUrlEnvironmentNoDefault import typing - -from seed import AsyncSeedSingleUrlEnvironmentNoDefault, SeedSingleUrlEnvironmentNoDefault - from .utilities import validate_response async def test_get_dummy( - client: SeedSingleUrlEnvironmentNoDefault, async_client: AsyncSeedSingleUrlEnvironmentNoDefault + client: SeedSingleUrlEnvironmentNoDefault, + async_client: AsyncSeedSingleUrlEnvironmentNoDefault, ) -> None: expected_response: typing.Any = "string" expected_types: typing.Any = None diff --git a/seed/python-sdk/single-url-environment-no-default/tests/utilities.py b/seed/python-sdk/single-url-environment-no-default/tests/utilities.py index 13da208eb3a..e8f4472564c 100644 --- a/seed/python-sdk/single-url-environment-no-default/tests/utilities.py +++ b/seed/python-sdk/single-url-environment-no-default/tests/utilities.py @@ -3,11 +3,14 @@ import typing import uuid -import pydantic from dateutil import parser +import pydantic + -def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> typing.Any: +def cast_field( + json_expectation: typing.Any, type_expectation: typing.Any +) -> typing.Any: # Cast these specific types which come through as string and expect our # models to cast to the correct type. if type_expectation == "uuid": @@ -25,7 +28,9 @@ def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> ty return json_expectation -def validate_field(response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any) -> None: +def validate_field( + response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectation == "no_validate": return @@ -44,7 +49,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(entry_expectation, dict): is_container_of_complex_type = True validate_response( - response=response[idx], json_expectation=ex, type_expectations=entry_expectation + response=response[idx], + json_expectation=ex, + type_expectations=entry_expectation, ) else: cast_json_expectation.append(cast_field(ex, entry_expectation)) @@ -56,7 +63,10 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # if any of the values of the set have a type_expectation of a dict, we're assuming it's a pydantic # model and keeping it a list. if container_expectation != "set" or not any( - map(lambda value: isinstance(value, dict), list(contents_expectation.values())) + map( + lambda value: isinstance(value, dict), + list(contents_expectation.values()), + ) ): json_expectation = cast_field(json_expectation, container_expectation) elif isinstance(type_expectation, tuple): @@ -65,9 +75,15 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(contents_expectation, dict): json_expectation = { cast_field( - key, contents_expectation.get(idx)[0] if contents_expectation.get(idx) is not None else None # type: ignore + key, + contents_expectation.get(idx)[0] + if contents_expectation.get(idx) is not None + else None, # type: ignore ): cast_field( - value, contents_expectation.get(idx)[1] if contents_expectation.get(idx) is not None else None # type: ignore + value, + contents_expectation.get(idx)[1] + if contents_expectation.get(idx) is not None + else None, # type: ignore ) for idx, (key, value) in enumerate(json_expectation.items()) } @@ -86,7 +102,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # Arg type_expectations is a deeply nested structure that matches the response, but with the values replaced with the expected types -def validate_response(response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any) -> None: +def validate_response( + response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectations == "no_validate": return @@ -96,11 +114,17 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e and not isinstance(response, dict) and not issubclass(type(response), pydantic.BaseModel) ): - validate_field(response=response, json_expectation=json_expectation, type_expectation=type_expectations) + validate_field( + response=response, + json_expectation=json_expectation, + type_expectation=type_expectations, + ) return if isinstance(response, list): - assert len(response) == len(json_expectation), "Length mismatch, expected: {0}, Actual: {1}".format( + assert len(response) == len( + json_expectation + ), "Length mismatch, expected: {0}, Actual: {1}".format( len(response), len(json_expectation) ) content_expectation = type_expectations @@ -108,7 +132,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e content_expectation = type_expectations[1] for idx, item in enumerate(response): validate_response( - response=item, json_expectation=json_expectation[idx], type_expectations=content_expectation[idx] + response=item, + json_expectation=json_expectation[idx], + type_expectations=content_expectation[idx], ) else: response_json = response @@ -116,7 +142,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e response_json = response.dict(by_alias=True) for key, value in json_expectation.items(): - assert key in response_json, "Field {0} not found within the response object: {1}".format( + assert ( + key in response_json + ), "Field {0} not found within the response object: {1}".format( key, response_json ) @@ -128,11 +156,19 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e # Otherwise, we're just validating a single field that's a pydantic model. if isinstance(value, dict) and not isinstance(type_expectation, tuple): validate_response( - response=response_json[key], json_expectation=value, type_expectations=type_expectation + response=response_json[key], + json_expectation=value, + type_expectations=type_expectation, ) else: - validate_field(response=response_json[key], json_expectation=value, type_expectation=type_expectation) + validate_field( + response=response_json[key], + json_expectation=value, + type_expectation=type_expectation, + ) # Ensure there are no additional fields here either del response_json[key] - assert len(response_json) == 0, "Additional fields found, expected None: {0}".format(response_json) + assert ( + len(response_json) == 0 + ), "Additional fields found, expected None: {0}".format(response_json) diff --git a/seed/python-sdk/single-url-environment-no-default/tests/utils/assets/models/__init__.py b/seed/python-sdk/single-url-environment-no-default/tests/utils/assets/models/__init__.py index 2cf01263529..3a1c852e71e 100644 --- a/seed/python-sdk/single-url-environment-no-default/tests/utils/assets/models/__init__.py +++ b/seed/python-sdk/single-url-environment-no-default/tests/utils/assets/models/__init__.py @@ -5,7 +5,7 @@ from .circle import CircleParams from .object_with_defaults import ObjectWithDefaultsParams from .object_with_optional_field import ObjectWithOptionalFieldParams -from .shape import Shape_CircleParams, Shape_SquareParams, ShapeParams +from .shape import ShapeParams, Shape_CircleParams, Shape_SquareParams from .square import SquareParams from .undiscriminated_shape import UndiscriminatedShapeParams diff --git a/seed/python-sdk/single-url-environment-no-default/tests/utils/assets/models/circle.py b/seed/python-sdk/single-url-environment-no-default/tests/utils/assets/models/circle.py index af7a1bf8a8e..253f12d38b3 100644 --- a/seed/python-sdk/single-url-environment-no-default/tests/utils/assets/models/circle.py +++ b/seed/python-sdk/single-url-environment-no-default/tests/utils/assets/models/circle.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class CircleParams(typing_extensions.TypedDict): - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] diff --git a/seed/python-sdk/single-url-environment-no-default/tests/utils/assets/models/object_with_optional_field.py b/seed/python-sdk/single-url-environment-no-default/tests/utils/assets/models/object_with_optional_field.py index 3ad93d5f305..ebe7dc80547 100644 --- a/seed/python-sdk/single-url-environment-no-default/tests/utils/assets/models/object_with_optional_field.py +++ b/seed/python-sdk/single-url-environment-no-default/tests/utils/assets/models/object_with_optional_field.py @@ -7,8 +7,8 @@ import uuid import typing_extensions -from seed.core.serialization import FieldMetadata +from seed.core.serialization import FieldMetadata from .color import Color from .shape import ShapeParams from .undiscriminated_shape import UndiscriminatedShapeParams @@ -18,16 +18,30 @@ class ObjectWithOptionalFieldParams(typing_extensions.TypedDict): literal: typing.Literal["lit_one"] string: typing_extensions.NotRequired[str] integer: typing_extensions.NotRequired[int] - long_: typing_extensions.NotRequired[typing_extensions.Annotated[int, FieldMetadata(alias="long")]] + long_: typing_extensions.NotRequired[ + typing_extensions.Annotated[int, FieldMetadata(alias="long")] + ] double: typing_extensions.NotRequired[float] - bool_: typing_extensions.NotRequired[typing_extensions.Annotated[bool, FieldMetadata(alias="bool")]] + bool_: typing_extensions.NotRequired[ + typing_extensions.Annotated[bool, FieldMetadata(alias="bool")] + ] datetime: typing_extensions.NotRequired[dt.datetime] date: typing_extensions.NotRequired[dt.date] - uuid_: typing_extensions.NotRequired[typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")]] - base_64: typing_extensions.NotRequired[typing_extensions.Annotated[str, FieldMetadata(alias="base64")]] - list_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")]] - set_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")]] - map_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")]] + uuid_: typing_extensions.NotRequired[ + typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")] + ] + base_64: typing_extensions.NotRequired[ + typing_extensions.Annotated[str, FieldMetadata(alias="base64")] + ] + list_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")] + ] + set_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")] + ] + map_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")] + ] enum: typing_extensions.NotRequired[Color] union: typing_extensions.NotRequired[ShapeParams] second_union: typing_extensions.NotRequired[ShapeParams] diff --git a/seed/python-sdk/single-url-environment-no-default/tests/utils/assets/models/shape.py b/seed/python-sdk/single-url-environment-no-default/tests/utils/assets/models/shape.py index 2c33c877951..816ffc51bdc 100644 --- a/seed/python-sdk/single-url-environment-no-default/tests/utils/assets/models/shape.py +++ b/seed/python-sdk/single-url-environment-no-default/tests/utils/assets/models/shape.py @@ -7,6 +7,7 @@ import typing import typing_extensions + from seed.core.serialization import FieldMetadata @@ -15,13 +16,21 @@ class Base(typing_extensions.TypedDict): class Shape_CircleParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["circle"], FieldMetadata(alias="shapeType")] - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["circle"], FieldMetadata(alias="shapeType") + ] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] class Shape_SquareParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["square"], FieldMetadata(alias="shapeType")] - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["square"], FieldMetadata(alias="shapeType") + ] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] ShapeParams = typing.Union[Shape_CircleParams, Shape_SquareParams] diff --git a/seed/python-sdk/single-url-environment-no-default/tests/utils/assets/models/square.py b/seed/python-sdk/single-url-environment-no-default/tests/utils/assets/models/square.py index b9b7dd319bc..bcf08a723c5 100644 --- a/seed/python-sdk/single-url-environment-no-default/tests/utils/assets/models/square.py +++ b/seed/python-sdk/single-url-environment-no-default/tests/utils/assets/models/square.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class SquareParams(typing_extensions.TypedDict): - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] diff --git a/seed/python-sdk/single-url-environment-no-default/tests/utils/test_http_client.py b/seed/python-sdk/single-url-environment-no-default/tests/utils/test_http_client.py index edd11ca7afb..f5a874a75f3 100644 --- a/seed/python-sdk/single-url-environment-no-default/tests/utils/test_http_client.py +++ b/seed/python-sdk/single-url-environment-no-default/tests/utils/test_http_client.py @@ -9,12 +9,17 @@ def get_request_options() -> RequestOptions: def test_get_json_request_body() -> None: - json_body, data_body = get_request_body(json={"hello": "world"}, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json={"hello": "world"}, data=None, request_options=None, omit=None + ) assert json_body == {"hello": "world"} assert data_body is None json_body_extras, data_body_extras = get_request_body( - json={"goodbye": "world"}, data=None, request_options=get_request_options(), omit=None + json={"goodbye": "world"}, + data=None, + request_options=get_request_options(), + omit=None, ) assert json_body_extras == {"goodbye": "world", "see you": "later"} @@ -22,12 +27,17 @@ def test_get_json_request_body() -> None: def test_get_files_request_body() -> None: - json_body, data_body = get_request_body(json=None, data={"hello": "world"}, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data={"hello": "world"}, request_options=None, omit=None + ) assert data_body == {"hello": "world"} assert json_body is None json_body_extras, data_body_extras = get_request_body( - json=None, data={"goodbye": "world"}, request_options=get_request_options(), omit=None + json=None, + data={"goodbye": "world"}, + request_options=get_request_options(), + omit=None, ) assert data_body_extras == {"goodbye": "world", "see you": "later"} @@ -35,7 +45,9 @@ def test_get_files_request_body() -> None: def test_get_none_request_body() -> None: - json_body, data_body = get_request_body(json=None, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data=None, request_options=None, omit=None + ) assert data_body is None assert json_body is None diff --git a/seed/python-sdk/single-url-environment-no-default/tests/utils/test_query_encoding.py b/seed/python-sdk/single-url-environment-no-default/tests/utils/test_query_encoding.py index 247e1551b46..fbc8f402167 100644 --- a/seed/python-sdk/single-url-environment-no-default/tests/utils/test_query_encoding.py +++ b/seed/python-sdk/single-url-environment-no-default/tests/utils/test_query_encoding.py @@ -4,9 +4,15 @@ def test_query_encoding() -> None: - assert encode_query({"hello world": "hello world"}) == {"hello world": "hello world"} - assert encode_query({"hello_world": {"hello": "world"}}) == {"hello_world[hello]": "world"} - assert encode_query({"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"}) == { + assert encode_query({"hello world": "hello world"}) == { + "hello world": "hello world" + } + assert encode_query({"hello_world": {"hello": "world"}}) == { + "hello_world[hello]": "world" + } + assert encode_query( + {"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"} + ) == { "hello_world[hello][world]": "today", "hello_world[test]": "this", "hi": "there", diff --git a/seed/python-sdk/single-url-environment-no-default/tests/utils/test_serialization.py b/seed/python-sdk/single-url-environment-no-default/tests/utils/test_serialization.py index 58b1ed66e6d..5ca956916dd 100644 --- a/seed/python-sdk/single-url-environment-no-default/tests/utils/test_serialization.py +++ b/seed/python-sdk/single-url-environment-no-default/tests/utils/test_serialization.py @@ -1,10 +1,12 @@ # This file was auto-generated by Fern from our API Definition. -from typing import Any, List +from typing import List, Any -from seed.core.serialization import convert_and_respect_annotation_metadata +from seed.core.serialization import ( + convert_and_respect_annotation_metadata, +) +from .assets.models import ShapeParams, ObjectWithOptionalFieldParams -from .assets.models import ObjectWithOptionalFieldParams, ShapeParams UNION_TEST: ShapeParams = {"radius_measurement": 1.0, "shape_type": "circle", "id": "1"} UNION_TEST_CONVERTED = {"shapeType": "circle", "radiusMeasurement": 1.0, "id": "1"} @@ -18,20 +20,54 @@ def test_convert_and_respect_annotation_metadata() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) - assert converted == {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"} + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) + assert converted == { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + } def test_convert_and_respect_annotation_metadata_in_list() -> None: data: List[ObjectWithOptionalFieldParams] = [ - {"string": "string", "long_": 12345, "bool_": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long_": 67890, "list_": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long_": 12345, + "bool_": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long_": 67890, + "list_": [], + "literal": "lit_one", + "any": "any", + }, ] - converted = convert_and_respect_annotation_metadata(object_=data, annotation=List[ObjectWithOptionalFieldParams]) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=List[ObjectWithOptionalFieldParams] + ) assert converted == [ - {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long": 67890, "list": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long": 67890, + "list": [], + "literal": "lit_one", + "any": "any", + }, ] @@ -43,7 +79,9 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) assert converted == { "string": "string", @@ -55,12 +93,16 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: def test_convert_and_respect_annotation_metadata_in_union() -> None: - converted = convert_and_respect_annotation_metadata(object_=UNION_TEST, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=UNION_TEST, annotation=ShapeParams + ) assert converted == UNION_TEST_CONVERTED def test_convert_and_respect_annotation_metadata_with_empty_object() -> None: data: Any = {} - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ShapeParams + ) assert converted == data diff --git a/seed/python-sdk/streaming-parameter/pyproject.toml b/seed/python-sdk/streaming-parameter/pyproject.toml index 72d4140d5bf..a4283bbeb43 100644 --- a/seed/python-sdk/streaming-parameter/pyproject.toml +++ b/seed/python-sdk/streaming-parameter/pyproject.toml @@ -43,6 +43,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/python-sdk/streaming-parameter/src/seed/__init__.py b/seed/python-sdk/streaming-parameter/src/seed/__init__.py index 6e55ab1b636..eebe0b5688c 100644 --- a/seed/python-sdk/streaming-parameter/src/seed/__init__.py +++ b/seed/python-sdk/streaming-parameter/src/seed/__init__.py @@ -5,4 +5,11 @@ from .dummy import RegularResponse, StreamResponse from .version import __version__ -__all__ = ["AsyncSeedStreaming", "RegularResponse", "SeedStreaming", "StreamResponse", "__version__", "dummy"] +__all__ = [ + "AsyncSeedStreaming", + "RegularResponse", + "SeedStreaming", + "StreamResponse", + "__version__", + "dummy", +] diff --git a/seed/python-sdk/streaming-parameter/src/seed/client.py b/seed/python-sdk/streaming-parameter/src/seed/client.py index cb008619005..0395cc355e1 100644 --- a/seed/python-sdk/streaming-parameter/src/seed/client.py +++ b/seed/python-sdk/streaming-parameter/src/seed/client.py @@ -1,11 +1,11 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from .dummy.client import AsyncDummyClient, DummyClient +from .core.client_wrapper import SyncClientWrapper +from .dummy.client import DummyClient +from .core.client_wrapper import AsyncClientWrapper +from .dummy.client import AsyncDummyClient class SeedStreaming: @@ -41,14 +41,18 @@ def __init__( base_url: str, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.Client] = None + httpx_client: typing.Optional[httpx.Client] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = SyncClientWrapper( base_url=base_url, httpx_client=httpx_client if httpx_client is not None - else httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.Client( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.Client(timeout=_defaulted_timeout), timeout=_defaulted_timeout, @@ -89,14 +93,18 @@ def __init__( base_url: str, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.AsyncClient] = None + httpx_client: typing.Optional[httpx.AsyncClient] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = AsyncClientWrapper( base_url=base_url, httpx_client=httpx_client if httpx_client is not None - else httpx.AsyncClient(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.AsyncClient( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.AsyncClient(timeout=_defaulted_timeout), timeout=_defaulted_timeout, diff --git a/seed/python-sdk/streaming-parameter/src/seed/core/api_error.py b/seed/python-sdk/streaming-parameter/src/seed/core/api_error.py index 2e9fc5431cd..da734b58068 100644 --- a/seed/python-sdk/streaming-parameter/src/seed/core/api_error.py +++ b/seed/python-sdk/streaming-parameter/src/seed/core/api_error.py @@ -7,7 +7,9 @@ class ApiError(Exception): status_code: typing.Optional[int] body: typing.Any - def __init__(self, *, status_code: typing.Optional[int] = None, body: typing.Any = None): + def __init__( + self, *, status_code: typing.Optional[int] = None, body: typing.Any = None + ): self.status_code = status_code self.body = body diff --git a/seed/python-sdk/streaming-parameter/src/seed/core/client_wrapper.py b/seed/python-sdk/streaming-parameter/src/seed/core/client_wrapper.py index 6a270fafe15..09cc1f9a5df 100644 --- a/seed/python-sdk/streaming-parameter/src/seed/core/client_wrapper.py +++ b/seed/python-sdk/streaming-parameter/src/seed/core/client_wrapper.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .http_client import AsyncHttpClient, HttpClient +from .http_client import HttpClient +from .http_client import AsyncHttpClient class BaseClientWrapper: @@ -28,7 +27,13 @@ def get_timeout(self) -> typing.Optional[float]: class SyncClientWrapper(BaseClientWrapper): - def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, httpx_client: httpx.Client): + def __init__( + self, + *, + base_url: str, + timeout: typing.Optional[float] = None, + httpx_client: httpx.Client, + ): super().__init__(base_url=base_url, timeout=timeout) self.httpx_client = HttpClient( httpx_client=httpx_client, @@ -39,7 +44,13 @@ def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, htt class AsyncClientWrapper(BaseClientWrapper): - def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, httpx_client: httpx.AsyncClient): + def __init__( + self, + *, + base_url: str, + timeout: typing.Optional[float] = None, + httpx_client: httpx.AsyncClient, + ): super().__init__(base_url=base_url, timeout=timeout) self.httpx_client = AsyncHttpClient( httpx_client=httpx_client, diff --git a/seed/python-sdk/streaming-parameter/src/seed/core/datetime_utils.py b/seed/python-sdk/streaming-parameter/src/seed/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/python-sdk/streaming-parameter/src/seed/core/datetime_utils.py +++ b/seed/python-sdk/streaming-parameter/src/seed/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/python-sdk/streaming-parameter/src/seed/core/file.py b/seed/python-sdk/streaming-parameter/src/seed/core/file.py index cb0d40bbbf3..6e0f92bfcb1 100644 --- a/seed/python-sdk/streaming-parameter/src/seed/core/file.py +++ b/seed/python-sdk/streaming-parameter/src/seed/core/file.py @@ -13,12 +13,17 @@ # (filename, file (or bytes), content_type) typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str]], # (filename, file (or bytes), content_type, headers) - typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str], typing.Mapping[str, str]], + typing.Tuple[ + typing.Optional[str], + FileContent, + typing.Optional[str], + typing.Mapping[str, str], + ], ] def convert_file_dict_to_httpx_tuples( - d: typing.Dict[str, typing.Union[File, typing.List[File]]] + d: typing.Dict[str, typing.Union[File, typing.List[File]]], ) -> typing.List[typing.Tuple[str, File]]: """ The format we use is a list of tuples, where the first element is the diff --git a/seed/python-sdk/streaming-parameter/src/seed/core/http_client.py b/seed/python-sdk/streaming-parameter/src/seed/core/http_client.py index 9333d8a7f15..091f71bc185 100644 --- a/seed/python-sdk/streaming-parameter/src/seed/core/http_client.py +++ b/seed/python-sdk/streaming-parameter/src/seed/core/http_client.py @@ -77,7 +77,9 @@ def _retry_timeout(response: httpx.Response, retries: int) -> float: return retry_after # Apply exponential backoff, capped at MAX_RETRY_DELAY_SECONDS. - retry_delay = min(INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS) + retry_delay = min( + INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS + ) # Add a randomness / jitter to the retry delay to avoid overwhelming the server with retries. timeout = retry_delay * (1 - 0.25 * random()) @@ -90,7 +92,8 @@ def _should_retry(response: httpx.Response) -> bool: def remove_omit_from_dict( - original: typing.Dict[str, typing.Optional[typing.Any]], omit: typing.Optional[typing.Any] + original: typing.Dict[str, typing.Optional[typing.Any]], + omit: typing.Optional[typing.Any], ) -> typing.Dict[str, typing.Any]: if omit is None: return original @@ -108,7 +111,8 @@ def maybe_filter_request_body( ) -> typing.Optional[typing.Any]: if data is None: return ( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else None ) @@ -118,7 +122,8 @@ def maybe_filter_request_body( data_content = { **(jsonable_encoder(remove_omit_from_dict(data, omit))), # type: ignore **( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else {} ), @@ -162,7 +167,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url def request( @@ -174,8 +181,12 @@ def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -184,11 +195,14 @@ def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) response = self.httpx_client.request( method=method, @@ -198,7 +212,11 @@ def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -209,7 +227,10 @@ def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -222,11 +243,15 @@ def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: time.sleep(_retry_timeout(response=response, retries=retries)) @@ -256,8 +281,12 @@ def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -266,11 +295,14 @@ def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) with self.httpx_client.stream( method=method, @@ -280,7 +312,11 @@ def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -291,7 +327,9 @@ def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -304,7 +342,9 @@ def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream @@ -327,7 +367,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url async def request( @@ -339,8 +381,12 @@ async def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -349,11 +395,14 @@ async def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) # Add the input to each of these and do None-safety checks response = await self.httpx_client.request( @@ -364,7 +413,11 @@ async def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -375,7 +428,10 @@ async def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -388,11 +444,15 @@ async def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: await asyncio.sleep(_retry_timeout(response=response, retries=retries)) @@ -421,8 +481,12 @@ async def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -431,11 +495,14 @@ async def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) async with self.httpx_client.stream( method=method, @@ -445,7 +512,11 @@ async def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -456,7 +527,9 @@ async def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -469,7 +542,9 @@ async def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream diff --git a/seed/python-sdk/streaming-parameter/src/seed/core/jsonable_encoder.py b/seed/python-sdk/streaming-parameter/src/seed/core/jsonable_encoder.py index d3fd328fd41..12a8b52fc22 100644 --- a/seed/python-sdk/streaming-parameter/src/seed/core/jsonable_encoder.py +++ b/seed/python-sdk/streaming-parameter/src/seed/core/jsonable_encoder.py @@ -19,13 +19,19 @@ import pydantic from .datetime_utils import serialize_datetime -from .pydantic_utilities import IS_PYDANTIC_V2, encode_by_type, to_jsonable_with_fallback +from .pydantic_utilities import ( + IS_PYDANTIC_V2, + encode_by_type, + to_jsonable_with_fallback, +) SetIntStr = Set[Union[int, str]] DictIntStrAny = Dict[Union[int, str], Any] -def jsonable_encoder(obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None) -> Any: +def jsonable_encoder( + obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None +) -> Any: custom_encoder = custom_encoder or {} if custom_encoder: if type(obj) in custom_encoder: diff --git a/seed/python-sdk/streaming-parameter/src/seed/core/pydantic_utilities.py b/seed/python-sdk/streaming-parameter/src/seed/core/pydantic_utilities.py index 170a563d6eb..c63935c32a2 100644 --- a/seed/python-sdk/streaming-parameter/src/seed/core/pydantic_utilities.py +++ b/seed/python-sdk/streaming-parameter/src/seed/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) # type: ignore # Pydantic v1 diff --git a/seed/python-sdk/streaming-parameter/src/seed/core/query_encoder.py b/seed/python-sdk/streaming-parameter/src/seed/core/query_encoder.py index 24076d72ee9..7cb98f52cd7 100644 --- a/seed/python-sdk/streaming-parameter/src/seed/core/query_encoder.py +++ b/seed/python-sdk/streaming-parameter/src/seed/core/query_encoder.py @@ -7,7 +7,9 @@ # Flattens dicts to be of the form {"key[subkey][subkey2]": value} where value is not a dict -def traverse_query_dict(dict_flat: Dict[str, Any], key_prefix: Optional[str] = None) -> Dict[str, Any]: +def traverse_query_dict( + dict_flat: Dict[str, Any], key_prefix: Optional[str] = None +) -> Dict[str, Any]: result = {} for k, v in dict_flat.items(): key = f"{key_prefix}[{k}]" if key_prefix is not None else k @@ -30,4 +32,8 @@ def single_query_encoder(query_key: str, query_value: Any) -> Dict[str, Any]: def encode_query(query: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: - return dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) if query is not None else None + return ( + dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) + if query is not None + else None + ) diff --git a/seed/python-sdk/streaming-parameter/src/seed/core/serialization.py b/seed/python-sdk/streaming-parameter/src/seed/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/python-sdk/streaming-parameter/src/seed/core/serialization.py +++ b/seed/python-sdk/streaming-parameter/src/seed/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/python-sdk/streaming-parameter/src/seed/dummy/client.py b/seed/python-sdk/streaming-parameter/src/seed/dummy/client.py index 2b078c04c02..eb1916b5452 100644 --- a/seed/python-sdk/streaming-parameter/src/seed/dummy/client.py +++ b/seed/python-sdk/streaming-parameter/src/seed/dummy/client.py @@ -1,15 +1,15 @@ # This file was auto-generated by Fern from our API Definition. -import json import typing -from json.decoder import JSONDecodeError - -from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.pydantic_utilities import parse_obj_as +from ..core.client_wrapper import SyncClientWrapper from ..core.request_options import RequestOptions -from .types.regular_response import RegularResponse from .types.stream_response import StreamResponse +from .types.regular_response import RegularResponse +from ..core.pydantic_utilities import parse_obj_as +import json +from json.decoder import JSONDecodeError +from ..core.api_error import ApiError +from ..core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -21,7 +21,11 @@ def __init__(self, *, client_wrapper: SyncClientWrapper): @typing.overload def generate( - self, *, stream: typing.Literal[True], num_events: int, request_options: typing.Optional[RequestOptions] = None + self, + *, + stream: typing.Literal[True], + num_events: int, + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Iterator[StreamResponse]: """ Parameters @@ -52,7 +56,11 @@ def generate( @typing.overload def generate( - self, *, stream: typing.Literal[False], num_events: int, request_options: typing.Optional[RequestOptions] = None + self, + *, + stream: typing.Literal[False], + num_events: int, + request_options: typing.Optional[RequestOptions] = None, ) -> RegularResponse: """ Parameters @@ -80,7 +88,11 @@ def generate( ... def generate( - self, *, stream: bool, num_events: int, request_options: typing.Optional[RequestOptions] = None + self, + *, + stream: bool, + num_events: int, + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Union[typing.Iterator[StreamResponse], RegularResponse]: """ Parameters @@ -93,12 +105,19 @@ def generate( Request-specific configuration. """ - _request_json = {"stream": stream, "num_events": num_events} + _request_json = { + "stream": stream, + "num_events": num_events, + } if stream: async def stream_generator(): with self._client_wrapper.httpx_client.stream( - "generate", method="POST", json=_request_json, request_options=request_options, omit=OMIT + "generate", + method="POST", + json=_request_json, + request_options=request_options, + omit=OMIT, ) as _response: try: if 200 <= _response.status_code < 300: @@ -106,24 +125,41 @@ async def stream_generator(): try: if len(_text) == 0: continue - yield typing.cast(StreamResponse, parse_obj_as(type_=StreamResponse, object_=json.loads(_text))) # type: ignore + yield typing.cast( + StreamResponse, + parse_obj_as( + type_=StreamResponse, + object_=json.loads(_text), + ), + ) # type: ignore except: pass return _response.read() _response_json = _response.json() except JSONDecodeError: - raise ApiError(status_code=_response.status_code, body=_response.text) - raise ApiError(status_code=_response.status_code, body=_response_json) + raise ApiError( + status_code=_response.status_code, body=_response.text + ) + raise ApiError( + status_code=_response.status_code, body=_response_json + ) return stream_generator() else: _response = self._client_wrapper.httpx_client.request( - "generate", method="POST", json=_request_json, request_options=request_options, omit=OMIT + "generate", + method="POST", + json=_request_json, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(RegularResponse, parse_obj_as(type_=RegularResponse, object_=_response.json())) # type: ignore + return typing.cast( + RegularResponse, + parse_obj_as(type_=RegularResponse, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -136,7 +172,11 @@ def __init__(self, *, client_wrapper: AsyncClientWrapper): @typing.overload async def generate( - self, *, stream: typing.Literal[True], num_events: int, request_options: typing.Optional[RequestOptions] = None + self, + *, + stream: typing.Literal[True], + num_events: int, + request_options: typing.Optional[RequestOptions] = None, ) -> typing.AsyncIterator[StreamResponse]: """ Parameters @@ -175,7 +215,11 @@ async def main() -> None: @typing.overload async def generate( - self, *, stream: typing.Literal[False], num_events: int, request_options: typing.Optional[RequestOptions] = None + self, + *, + stream: typing.Literal[False], + num_events: int, + request_options: typing.Optional[RequestOptions] = None, ) -> RegularResponse: """ Parameters @@ -211,7 +255,11 @@ async def main() -> None: ... async def generate( - self, *, stream: bool, num_events: int, request_options: typing.Optional[RequestOptions] = None + self, + *, + stream: bool, + num_events: int, + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Union[typing.AsyncIterator[StreamResponse], RegularResponse]: """ Parameters @@ -224,12 +272,19 @@ async def generate( Request-specific configuration. """ - _request_json = {"stream": stream, "num_events": num_events} + _request_json = { + "stream": stream, + "num_events": num_events, + } if stream: async def stream_generator(): async with self._client_wrapper.httpx_client.stream( - "generate", method="POST", json=_request_json, request_options=request_options, omit=OMIT + "generate", + method="POST", + json=_request_json, + request_options=request_options, + omit=OMIT, ) as _response: try: if 200 <= _response.status_code < 300: @@ -237,24 +292,41 @@ async def stream_generator(): try: if len(_text) == 0: continue - yield typing.cast(StreamResponse, parse_obj_as(type_=StreamResponse, object_=json.loads(_text))) # type: ignore + yield typing.cast( + StreamResponse, + parse_obj_as( + type_=StreamResponse, + object_=json.loads(_text), + ), + ) # type: ignore except: pass return await _response.aread() _response_json = _response.json() except JSONDecodeError: - raise ApiError(status_code=_response.status_code, body=_response.text) - raise ApiError(status_code=_response.status_code, body=_response_json) + raise ApiError( + status_code=_response.status_code, body=_response.text + ) + raise ApiError( + status_code=_response.status_code, body=_response_json + ) return stream_generator() else: _response = await self._client_wrapper.httpx_client.request( - "generate", method="POST", json=_request_json, request_options=request_options, omit=OMIT + "generate", + method="POST", + json=_request_json, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(RegularResponse, parse_obj_as(type_=RegularResponse, object_=_response.json())) # type: ignore + return typing.cast( + RegularResponse, + parse_obj_as(type_=RegularResponse, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/streaming-parameter/src/seed/dummy/types/regular_response.py b/seed/python-sdk/streaming-parameter/src/seed/dummy/types/regular_response.py index 3a9513347d8..6046cd49d74 100644 --- a/seed/python-sdk/streaming-parameter/src/seed/dummy/types/regular_response.py +++ b/seed/python-sdk/streaming-parameter/src/seed/dummy/types/regular_response.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel import typing - +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class RegularResponse(UniversalBaseModel): id: str name: typing.Optional[str] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/streaming-parameter/src/seed/dummy/types/stream_response.py b/seed/python-sdk/streaming-parameter/src/seed/dummy/types/stream_response.py index 9a9385376ec..05a127e5f8d 100644 --- a/seed/python-sdk/streaming-parameter/src/seed/dummy/types/stream_response.py +++ b/seed/python-sdk/streaming-parameter/src/seed/dummy/types/stream_response.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel import typing - +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class StreamResponse(UniversalBaseModel): id: str name: typing.Optional[str] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/streaming-parameter/src/seed/version.py b/seed/python-sdk/streaming-parameter/src/seed/version.py index 07907c8554c..1a18a9646f8 100644 --- a/seed/python-sdk/streaming-parameter/src/seed/version.py +++ b/seed/python-sdk/streaming-parameter/src/seed/version.py @@ -1,4 +1,3 @@ - from importlib import metadata __version__ = metadata.version("fern_streaming-parameter") diff --git a/seed/python-sdk/streaming-parameter/tests/conftest.py b/seed/python-sdk/streaming-parameter/tests/conftest.py index 45cf3f5003a..5df2bde2264 100644 --- a/seed/python-sdk/streaming-parameter/tests/conftest.py +++ b/seed/python-sdk/streaming-parameter/tests/conftest.py @@ -1,9 +1,9 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedStreaming import os - import pytest -from seed import AsyncSeedStreaming, SeedStreaming +from seed import AsyncSeedStreaming @pytest.fixture diff --git a/seed/python-sdk/streaming-parameter/tests/custom/test_client.py b/seed/python-sdk/streaming-parameter/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/python-sdk/streaming-parameter/tests/custom/test_client.py +++ b/seed/python-sdk/streaming-parameter/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/python-sdk/streaming-parameter/tests/test_dummy.py b/seed/python-sdk/streaming-parameter/tests/test_dummy.py index d1479f47ba9..edfc5d43b2d 100644 --- a/seed/python-sdk/streaming-parameter/tests/test_dummy.py +++ b/seed/python-sdk/streaming-parameter/tests/test_dummy.py @@ -1,13 +1,14 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedStreaming +from seed import AsyncSeedStreaming import typing - -from seed import AsyncSeedStreaming, SeedStreaming - from .utilities import validate_response -async def test_generate(client: SeedStreaming, async_client: AsyncSeedStreaming) -> None: +async def test_generate( + client: SeedStreaming, async_client: AsyncSeedStreaming +) -> None: expected_response: typing.Any = {"id": "id", "name": "name"} expected_types: typing.Any = {"id": None, "name": None} response = client.dummy.generate(stream=False, num_events=5) diff --git a/seed/python-sdk/streaming-parameter/tests/utilities.py b/seed/python-sdk/streaming-parameter/tests/utilities.py index 13da208eb3a..e8f4472564c 100644 --- a/seed/python-sdk/streaming-parameter/tests/utilities.py +++ b/seed/python-sdk/streaming-parameter/tests/utilities.py @@ -3,11 +3,14 @@ import typing import uuid -import pydantic from dateutil import parser +import pydantic + -def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> typing.Any: +def cast_field( + json_expectation: typing.Any, type_expectation: typing.Any +) -> typing.Any: # Cast these specific types which come through as string and expect our # models to cast to the correct type. if type_expectation == "uuid": @@ -25,7 +28,9 @@ def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> ty return json_expectation -def validate_field(response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any) -> None: +def validate_field( + response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectation == "no_validate": return @@ -44,7 +49,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(entry_expectation, dict): is_container_of_complex_type = True validate_response( - response=response[idx], json_expectation=ex, type_expectations=entry_expectation + response=response[idx], + json_expectation=ex, + type_expectations=entry_expectation, ) else: cast_json_expectation.append(cast_field(ex, entry_expectation)) @@ -56,7 +63,10 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # if any of the values of the set have a type_expectation of a dict, we're assuming it's a pydantic # model and keeping it a list. if container_expectation != "set" or not any( - map(lambda value: isinstance(value, dict), list(contents_expectation.values())) + map( + lambda value: isinstance(value, dict), + list(contents_expectation.values()), + ) ): json_expectation = cast_field(json_expectation, container_expectation) elif isinstance(type_expectation, tuple): @@ -65,9 +75,15 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(contents_expectation, dict): json_expectation = { cast_field( - key, contents_expectation.get(idx)[0] if contents_expectation.get(idx) is not None else None # type: ignore + key, + contents_expectation.get(idx)[0] + if contents_expectation.get(idx) is not None + else None, # type: ignore ): cast_field( - value, contents_expectation.get(idx)[1] if contents_expectation.get(idx) is not None else None # type: ignore + value, + contents_expectation.get(idx)[1] + if contents_expectation.get(idx) is not None + else None, # type: ignore ) for idx, (key, value) in enumerate(json_expectation.items()) } @@ -86,7 +102,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # Arg type_expectations is a deeply nested structure that matches the response, but with the values replaced with the expected types -def validate_response(response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any) -> None: +def validate_response( + response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectations == "no_validate": return @@ -96,11 +114,17 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e and not isinstance(response, dict) and not issubclass(type(response), pydantic.BaseModel) ): - validate_field(response=response, json_expectation=json_expectation, type_expectation=type_expectations) + validate_field( + response=response, + json_expectation=json_expectation, + type_expectation=type_expectations, + ) return if isinstance(response, list): - assert len(response) == len(json_expectation), "Length mismatch, expected: {0}, Actual: {1}".format( + assert len(response) == len( + json_expectation + ), "Length mismatch, expected: {0}, Actual: {1}".format( len(response), len(json_expectation) ) content_expectation = type_expectations @@ -108,7 +132,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e content_expectation = type_expectations[1] for idx, item in enumerate(response): validate_response( - response=item, json_expectation=json_expectation[idx], type_expectations=content_expectation[idx] + response=item, + json_expectation=json_expectation[idx], + type_expectations=content_expectation[idx], ) else: response_json = response @@ -116,7 +142,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e response_json = response.dict(by_alias=True) for key, value in json_expectation.items(): - assert key in response_json, "Field {0} not found within the response object: {1}".format( + assert ( + key in response_json + ), "Field {0} not found within the response object: {1}".format( key, response_json ) @@ -128,11 +156,19 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e # Otherwise, we're just validating a single field that's a pydantic model. if isinstance(value, dict) and not isinstance(type_expectation, tuple): validate_response( - response=response_json[key], json_expectation=value, type_expectations=type_expectation + response=response_json[key], + json_expectation=value, + type_expectations=type_expectation, ) else: - validate_field(response=response_json[key], json_expectation=value, type_expectation=type_expectation) + validate_field( + response=response_json[key], + json_expectation=value, + type_expectation=type_expectation, + ) # Ensure there are no additional fields here either del response_json[key] - assert len(response_json) == 0, "Additional fields found, expected None: {0}".format(response_json) + assert ( + len(response_json) == 0 + ), "Additional fields found, expected None: {0}".format(response_json) diff --git a/seed/python-sdk/streaming-parameter/tests/utils/assets/models/__init__.py b/seed/python-sdk/streaming-parameter/tests/utils/assets/models/__init__.py index 2cf01263529..3a1c852e71e 100644 --- a/seed/python-sdk/streaming-parameter/tests/utils/assets/models/__init__.py +++ b/seed/python-sdk/streaming-parameter/tests/utils/assets/models/__init__.py @@ -5,7 +5,7 @@ from .circle import CircleParams from .object_with_defaults import ObjectWithDefaultsParams from .object_with_optional_field import ObjectWithOptionalFieldParams -from .shape import Shape_CircleParams, Shape_SquareParams, ShapeParams +from .shape import ShapeParams, Shape_CircleParams, Shape_SquareParams from .square import SquareParams from .undiscriminated_shape import UndiscriminatedShapeParams diff --git a/seed/python-sdk/streaming-parameter/tests/utils/assets/models/circle.py b/seed/python-sdk/streaming-parameter/tests/utils/assets/models/circle.py index af7a1bf8a8e..253f12d38b3 100644 --- a/seed/python-sdk/streaming-parameter/tests/utils/assets/models/circle.py +++ b/seed/python-sdk/streaming-parameter/tests/utils/assets/models/circle.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class CircleParams(typing_extensions.TypedDict): - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] diff --git a/seed/python-sdk/streaming-parameter/tests/utils/assets/models/object_with_optional_field.py b/seed/python-sdk/streaming-parameter/tests/utils/assets/models/object_with_optional_field.py index 3ad93d5f305..ebe7dc80547 100644 --- a/seed/python-sdk/streaming-parameter/tests/utils/assets/models/object_with_optional_field.py +++ b/seed/python-sdk/streaming-parameter/tests/utils/assets/models/object_with_optional_field.py @@ -7,8 +7,8 @@ import uuid import typing_extensions -from seed.core.serialization import FieldMetadata +from seed.core.serialization import FieldMetadata from .color import Color from .shape import ShapeParams from .undiscriminated_shape import UndiscriminatedShapeParams @@ -18,16 +18,30 @@ class ObjectWithOptionalFieldParams(typing_extensions.TypedDict): literal: typing.Literal["lit_one"] string: typing_extensions.NotRequired[str] integer: typing_extensions.NotRequired[int] - long_: typing_extensions.NotRequired[typing_extensions.Annotated[int, FieldMetadata(alias="long")]] + long_: typing_extensions.NotRequired[ + typing_extensions.Annotated[int, FieldMetadata(alias="long")] + ] double: typing_extensions.NotRequired[float] - bool_: typing_extensions.NotRequired[typing_extensions.Annotated[bool, FieldMetadata(alias="bool")]] + bool_: typing_extensions.NotRequired[ + typing_extensions.Annotated[bool, FieldMetadata(alias="bool")] + ] datetime: typing_extensions.NotRequired[dt.datetime] date: typing_extensions.NotRequired[dt.date] - uuid_: typing_extensions.NotRequired[typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")]] - base_64: typing_extensions.NotRequired[typing_extensions.Annotated[str, FieldMetadata(alias="base64")]] - list_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")]] - set_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")]] - map_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")]] + uuid_: typing_extensions.NotRequired[ + typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")] + ] + base_64: typing_extensions.NotRequired[ + typing_extensions.Annotated[str, FieldMetadata(alias="base64")] + ] + list_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")] + ] + set_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")] + ] + map_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")] + ] enum: typing_extensions.NotRequired[Color] union: typing_extensions.NotRequired[ShapeParams] second_union: typing_extensions.NotRequired[ShapeParams] diff --git a/seed/python-sdk/streaming-parameter/tests/utils/assets/models/shape.py b/seed/python-sdk/streaming-parameter/tests/utils/assets/models/shape.py index 2c33c877951..816ffc51bdc 100644 --- a/seed/python-sdk/streaming-parameter/tests/utils/assets/models/shape.py +++ b/seed/python-sdk/streaming-parameter/tests/utils/assets/models/shape.py @@ -7,6 +7,7 @@ import typing import typing_extensions + from seed.core.serialization import FieldMetadata @@ -15,13 +16,21 @@ class Base(typing_extensions.TypedDict): class Shape_CircleParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["circle"], FieldMetadata(alias="shapeType")] - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["circle"], FieldMetadata(alias="shapeType") + ] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] class Shape_SquareParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["square"], FieldMetadata(alias="shapeType")] - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["square"], FieldMetadata(alias="shapeType") + ] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] ShapeParams = typing.Union[Shape_CircleParams, Shape_SquareParams] diff --git a/seed/python-sdk/streaming-parameter/tests/utils/assets/models/square.py b/seed/python-sdk/streaming-parameter/tests/utils/assets/models/square.py index b9b7dd319bc..bcf08a723c5 100644 --- a/seed/python-sdk/streaming-parameter/tests/utils/assets/models/square.py +++ b/seed/python-sdk/streaming-parameter/tests/utils/assets/models/square.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class SquareParams(typing_extensions.TypedDict): - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] diff --git a/seed/python-sdk/streaming-parameter/tests/utils/test_http_client.py b/seed/python-sdk/streaming-parameter/tests/utils/test_http_client.py index edd11ca7afb..f5a874a75f3 100644 --- a/seed/python-sdk/streaming-parameter/tests/utils/test_http_client.py +++ b/seed/python-sdk/streaming-parameter/tests/utils/test_http_client.py @@ -9,12 +9,17 @@ def get_request_options() -> RequestOptions: def test_get_json_request_body() -> None: - json_body, data_body = get_request_body(json={"hello": "world"}, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json={"hello": "world"}, data=None, request_options=None, omit=None + ) assert json_body == {"hello": "world"} assert data_body is None json_body_extras, data_body_extras = get_request_body( - json={"goodbye": "world"}, data=None, request_options=get_request_options(), omit=None + json={"goodbye": "world"}, + data=None, + request_options=get_request_options(), + omit=None, ) assert json_body_extras == {"goodbye": "world", "see you": "later"} @@ -22,12 +27,17 @@ def test_get_json_request_body() -> None: def test_get_files_request_body() -> None: - json_body, data_body = get_request_body(json=None, data={"hello": "world"}, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data={"hello": "world"}, request_options=None, omit=None + ) assert data_body == {"hello": "world"} assert json_body is None json_body_extras, data_body_extras = get_request_body( - json=None, data={"goodbye": "world"}, request_options=get_request_options(), omit=None + json=None, + data={"goodbye": "world"}, + request_options=get_request_options(), + omit=None, ) assert data_body_extras == {"goodbye": "world", "see you": "later"} @@ -35,7 +45,9 @@ def test_get_files_request_body() -> None: def test_get_none_request_body() -> None: - json_body, data_body = get_request_body(json=None, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data=None, request_options=None, omit=None + ) assert data_body is None assert json_body is None diff --git a/seed/python-sdk/streaming-parameter/tests/utils/test_query_encoding.py b/seed/python-sdk/streaming-parameter/tests/utils/test_query_encoding.py index 247e1551b46..fbc8f402167 100644 --- a/seed/python-sdk/streaming-parameter/tests/utils/test_query_encoding.py +++ b/seed/python-sdk/streaming-parameter/tests/utils/test_query_encoding.py @@ -4,9 +4,15 @@ def test_query_encoding() -> None: - assert encode_query({"hello world": "hello world"}) == {"hello world": "hello world"} - assert encode_query({"hello_world": {"hello": "world"}}) == {"hello_world[hello]": "world"} - assert encode_query({"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"}) == { + assert encode_query({"hello world": "hello world"}) == { + "hello world": "hello world" + } + assert encode_query({"hello_world": {"hello": "world"}}) == { + "hello_world[hello]": "world" + } + assert encode_query( + {"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"} + ) == { "hello_world[hello][world]": "today", "hello_world[test]": "this", "hi": "there", diff --git a/seed/python-sdk/streaming-parameter/tests/utils/test_serialization.py b/seed/python-sdk/streaming-parameter/tests/utils/test_serialization.py index 58b1ed66e6d..5ca956916dd 100644 --- a/seed/python-sdk/streaming-parameter/tests/utils/test_serialization.py +++ b/seed/python-sdk/streaming-parameter/tests/utils/test_serialization.py @@ -1,10 +1,12 @@ # This file was auto-generated by Fern from our API Definition. -from typing import Any, List +from typing import List, Any -from seed.core.serialization import convert_and_respect_annotation_metadata +from seed.core.serialization import ( + convert_and_respect_annotation_metadata, +) +from .assets.models import ShapeParams, ObjectWithOptionalFieldParams -from .assets.models import ObjectWithOptionalFieldParams, ShapeParams UNION_TEST: ShapeParams = {"radius_measurement": 1.0, "shape_type": "circle", "id": "1"} UNION_TEST_CONVERTED = {"shapeType": "circle", "radiusMeasurement": 1.0, "id": "1"} @@ -18,20 +20,54 @@ def test_convert_and_respect_annotation_metadata() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) - assert converted == {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"} + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) + assert converted == { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + } def test_convert_and_respect_annotation_metadata_in_list() -> None: data: List[ObjectWithOptionalFieldParams] = [ - {"string": "string", "long_": 12345, "bool_": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long_": 67890, "list_": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long_": 12345, + "bool_": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long_": 67890, + "list_": [], + "literal": "lit_one", + "any": "any", + }, ] - converted = convert_and_respect_annotation_metadata(object_=data, annotation=List[ObjectWithOptionalFieldParams]) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=List[ObjectWithOptionalFieldParams] + ) assert converted == [ - {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long": 67890, "list": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long": 67890, + "list": [], + "literal": "lit_one", + "any": "any", + }, ] @@ -43,7 +79,9 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) assert converted == { "string": "string", @@ -55,12 +93,16 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: def test_convert_and_respect_annotation_metadata_in_union() -> None: - converted = convert_and_respect_annotation_metadata(object_=UNION_TEST, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=UNION_TEST, annotation=ShapeParams + ) assert converted == UNION_TEST_CONVERTED def test_convert_and_respect_annotation_metadata_with_empty_object() -> None: data: Any = {} - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ShapeParams + ) assert converted == data diff --git a/seed/python-sdk/streaming/no-custom-config/pyproject.toml b/seed/python-sdk/streaming/no-custom-config/pyproject.toml index 8c1b1ca948f..41f6f015bce 100644 --- a/seed/python-sdk/streaming/no-custom-config/pyproject.toml +++ b/seed/python-sdk/streaming/no-custom-config/pyproject.toml @@ -43,6 +43,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/python-sdk/streaming/no-custom-config/src/seed/__init__.py b/seed/python-sdk/streaming/no-custom-config/src/seed/__init__.py index 8d93d0c1029..04a2311759c 100644 --- a/seed/python-sdk/streaming/no-custom-config/src/seed/__init__.py +++ b/seed/python-sdk/streaming/no-custom-config/src/seed/__init__.py @@ -5,4 +5,10 @@ from .dummy import StreamResponse from .version import __version__ -__all__ = ["AsyncSeedStreaming", "SeedStreaming", "StreamResponse", "__version__", "dummy"] +__all__ = [ + "AsyncSeedStreaming", + "SeedStreaming", + "StreamResponse", + "__version__", + "dummy", +] diff --git a/seed/python-sdk/streaming/no-custom-config/src/seed/client.py b/seed/python-sdk/streaming/no-custom-config/src/seed/client.py index cb008619005..0395cc355e1 100644 --- a/seed/python-sdk/streaming/no-custom-config/src/seed/client.py +++ b/seed/python-sdk/streaming/no-custom-config/src/seed/client.py @@ -1,11 +1,11 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from .dummy.client import AsyncDummyClient, DummyClient +from .core.client_wrapper import SyncClientWrapper +from .dummy.client import DummyClient +from .core.client_wrapper import AsyncClientWrapper +from .dummy.client import AsyncDummyClient class SeedStreaming: @@ -41,14 +41,18 @@ def __init__( base_url: str, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.Client] = None + httpx_client: typing.Optional[httpx.Client] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = SyncClientWrapper( base_url=base_url, httpx_client=httpx_client if httpx_client is not None - else httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.Client( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.Client(timeout=_defaulted_timeout), timeout=_defaulted_timeout, @@ -89,14 +93,18 @@ def __init__( base_url: str, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.AsyncClient] = None + httpx_client: typing.Optional[httpx.AsyncClient] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = AsyncClientWrapper( base_url=base_url, httpx_client=httpx_client if httpx_client is not None - else httpx.AsyncClient(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.AsyncClient( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.AsyncClient(timeout=_defaulted_timeout), timeout=_defaulted_timeout, diff --git a/seed/python-sdk/streaming/no-custom-config/src/seed/core/api_error.py b/seed/python-sdk/streaming/no-custom-config/src/seed/core/api_error.py index 2e9fc5431cd..da734b58068 100644 --- a/seed/python-sdk/streaming/no-custom-config/src/seed/core/api_error.py +++ b/seed/python-sdk/streaming/no-custom-config/src/seed/core/api_error.py @@ -7,7 +7,9 @@ class ApiError(Exception): status_code: typing.Optional[int] body: typing.Any - def __init__(self, *, status_code: typing.Optional[int] = None, body: typing.Any = None): + def __init__( + self, *, status_code: typing.Optional[int] = None, body: typing.Any = None + ): self.status_code = status_code self.body = body diff --git a/seed/python-sdk/streaming/no-custom-config/src/seed/core/client_wrapper.py b/seed/python-sdk/streaming/no-custom-config/src/seed/core/client_wrapper.py index f5a3cbe0a1d..de6ec6dbddd 100644 --- a/seed/python-sdk/streaming/no-custom-config/src/seed/core/client_wrapper.py +++ b/seed/python-sdk/streaming/no-custom-config/src/seed/core/client_wrapper.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .http_client import AsyncHttpClient, HttpClient +from .http_client import HttpClient +from .http_client import AsyncHttpClient class BaseClientWrapper: @@ -28,7 +27,13 @@ def get_timeout(self) -> typing.Optional[float]: class SyncClientWrapper(BaseClientWrapper): - def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, httpx_client: httpx.Client): + def __init__( + self, + *, + base_url: str, + timeout: typing.Optional[float] = None, + httpx_client: httpx.Client, + ): super().__init__(base_url=base_url, timeout=timeout) self.httpx_client = HttpClient( httpx_client=httpx_client, @@ -39,7 +44,13 @@ def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, htt class AsyncClientWrapper(BaseClientWrapper): - def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, httpx_client: httpx.AsyncClient): + def __init__( + self, + *, + base_url: str, + timeout: typing.Optional[float] = None, + httpx_client: httpx.AsyncClient, + ): super().__init__(base_url=base_url, timeout=timeout) self.httpx_client = AsyncHttpClient( httpx_client=httpx_client, diff --git a/seed/python-sdk/streaming/no-custom-config/src/seed/core/datetime_utils.py b/seed/python-sdk/streaming/no-custom-config/src/seed/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/python-sdk/streaming/no-custom-config/src/seed/core/datetime_utils.py +++ b/seed/python-sdk/streaming/no-custom-config/src/seed/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/python-sdk/streaming/no-custom-config/src/seed/core/file.py b/seed/python-sdk/streaming/no-custom-config/src/seed/core/file.py index cb0d40bbbf3..6e0f92bfcb1 100644 --- a/seed/python-sdk/streaming/no-custom-config/src/seed/core/file.py +++ b/seed/python-sdk/streaming/no-custom-config/src/seed/core/file.py @@ -13,12 +13,17 @@ # (filename, file (or bytes), content_type) typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str]], # (filename, file (or bytes), content_type, headers) - typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str], typing.Mapping[str, str]], + typing.Tuple[ + typing.Optional[str], + FileContent, + typing.Optional[str], + typing.Mapping[str, str], + ], ] def convert_file_dict_to_httpx_tuples( - d: typing.Dict[str, typing.Union[File, typing.List[File]]] + d: typing.Dict[str, typing.Union[File, typing.List[File]]], ) -> typing.List[typing.Tuple[str, File]]: """ The format we use is a list of tuples, where the first element is the diff --git a/seed/python-sdk/streaming/no-custom-config/src/seed/core/http_client.py b/seed/python-sdk/streaming/no-custom-config/src/seed/core/http_client.py index 9333d8a7f15..091f71bc185 100644 --- a/seed/python-sdk/streaming/no-custom-config/src/seed/core/http_client.py +++ b/seed/python-sdk/streaming/no-custom-config/src/seed/core/http_client.py @@ -77,7 +77,9 @@ def _retry_timeout(response: httpx.Response, retries: int) -> float: return retry_after # Apply exponential backoff, capped at MAX_RETRY_DELAY_SECONDS. - retry_delay = min(INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS) + retry_delay = min( + INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS + ) # Add a randomness / jitter to the retry delay to avoid overwhelming the server with retries. timeout = retry_delay * (1 - 0.25 * random()) @@ -90,7 +92,8 @@ def _should_retry(response: httpx.Response) -> bool: def remove_omit_from_dict( - original: typing.Dict[str, typing.Optional[typing.Any]], omit: typing.Optional[typing.Any] + original: typing.Dict[str, typing.Optional[typing.Any]], + omit: typing.Optional[typing.Any], ) -> typing.Dict[str, typing.Any]: if omit is None: return original @@ -108,7 +111,8 @@ def maybe_filter_request_body( ) -> typing.Optional[typing.Any]: if data is None: return ( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else None ) @@ -118,7 +122,8 @@ def maybe_filter_request_body( data_content = { **(jsonable_encoder(remove_omit_from_dict(data, omit))), # type: ignore **( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else {} ), @@ -162,7 +167,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url def request( @@ -174,8 +181,12 @@ def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -184,11 +195,14 @@ def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) response = self.httpx_client.request( method=method, @@ -198,7 +212,11 @@ def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -209,7 +227,10 @@ def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -222,11 +243,15 @@ def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: time.sleep(_retry_timeout(response=response, retries=retries)) @@ -256,8 +281,12 @@ def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -266,11 +295,14 @@ def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) with self.httpx_client.stream( method=method, @@ -280,7 +312,11 @@ def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -291,7 +327,9 @@ def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -304,7 +342,9 @@ def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream @@ -327,7 +367,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url async def request( @@ -339,8 +381,12 @@ async def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -349,11 +395,14 @@ async def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) # Add the input to each of these and do None-safety checks response = await self.httpx_client.request( @@ -364,7 +413,11 @@ async def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -375,7 +428,10 @@ async def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -388,11 +444,15 @@ async def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: await asyncio.sleep(_retry_timeout(response=response, retries=retries)) @@ -421,8 +481,12 @@ async def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -431,11 +495,14 @@ async def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) async with self.httpx_client.stream( method=method, @@ -445,7 +512,11 @@ async def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -456,7 +527,9 @@ async def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -469,7 +542,9 @@ async def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream diff --git a/seed/python-sdk/streaming/no-custom-config/src/seed/core/jsonable_encoder.py b/seed/python-sdk/streaming/no-custom-config/src/seed/core/jsonable_encoder.py index d3fd328fd41..12a8b52fc22 100644 --- a/seed/python-sdk/streaming/no-custom-config/src/seed/core/jsonable_encoder.py +++ b/seed/python-sdk/streaming/no-custom-config/src/seed/core/jsonable_encoder.py @@ -19,13 +19,19 @@ import pydantic from .datetime_utils import serialize_datetime -from .pydantic_utilities import IS_PYDANTIC_V2, encode_by_type, to_jsonable_with_fallback +from .pydantic_utilities import ( + IS_PYDANTIC_V2, + encode_by_type, + to_jsonable_with_fallback, +) SetIntStr = Set[Union[int, str]] DictIntStrAny = Dict[Union[int, str], Any] -def jsonable_encoder(obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None) -> Any: +def jsonable_encoder( + obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None +) -> Any: custom_encoder = custom_encoder or {} if custom_encoder: if type(obj) in custom_encoder: diff --git a/seed/python-sdk/streaming/no-custom-config/src/seed/core/pydantic_utilities.py b/seed/python-sdk/streaming/no-custom-config/src/seed/core/pydantic_utilities.py index 170a563d6eb..c63935c32a2 100644 --- a/seed/python-sdk/streaming/no-custom-config/src/seed/core/pydantic_utilities.py +++ b/seed/python-sdk/streaming/no-custom-config/src/seed/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) # type: ignore # Pydantic v1 diff --git a/seed/python-sdk/streaming/no-custom-config/src/seed/core/query_encoder.py b/seed/python-sdk/streaming/no-custom-config/src/seed/core/query_encoder.py index 24076d72ee9..7cb98f52cd7 100644 --- a/seed/python-sdk/streaming/no-custom-config/src/seed/core/query_encoder.py +++ b/seed/python-sdk/streaming/no-custom-config/src/seed/core/query_encoder.py @@ -7,7 +7,9 @@ # Flattens dicts to be of the form {"key[subkey][subkey2]": value} where value is not a dict -def traverse_query_dict(dict_flat: Dict[str, Any], key_prefix: Optional[str] = None) -> Dict[str, Any]: +def traverse_query_dict( + dict_flat: Dict[str, Any], key_prefix: Optional[str] = None +) -> Dict[str, Any]: result = {} for k, v in dict_flat.items(): key = f"{key_prefix}[{k}]" if key_prefix is not None else k @@ -30,4 +32,8 @@ def single_query_encoder(query_key: str, query_value: Any) -> Dict[str, Any]: def encode_query(query: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: - return dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) if query is not None else None + return ( + dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) + if query is not None + else None + ) diff --git a/seed/python-sdk/streaming/no-custom-config/src/seed/core/serialization.py b/seed/python-sdk/streaming/no-custom-config/src/seed/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/python-sdk/streaming/no-custom-config/src/seed/core/serialization.py +++ b/seed/python-sdk/streaming/no-custom-config/src/seed/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/python-sdk/streaming/no-custom-config/src/seed/dummy/client.py b/seed/python-sdk/streaming/no-custom-config/src/seed/dummy/client.py index 0b3b93028c2..7f2cbc411e6 100644 --- a/seed/python-sdk/streaming/no-custom-config/src/seed/dummy/client.py +++ b/seed/python-sdk/streaming/no-custom-config/src/seed/dummy/client.py @@ -1,14 +1,14 @@ # This file was auto-generated by Fern from our API Definition. -import json import typing -from json.decoder import JSONDecodeError - -from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.pydantic_utilities import parse_obj_as +from ..core.client_wrapper import SyncClientWrapper from ..core.request_options import RequestOptions from .types.stream_response import StreamResponse +from ..core.pydantic_utilities import parse_obj_as +import json +from json.decoder import JSONDecodeError +from ..core.api_error import ApiError +from ..core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -19,7 +19,10 @@ def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper def generate_stream( - self, *, num_events: int, request_options: typing.Optional[RequestOptions] = None + self, + *, + num_events: int, + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Iterator[StreamResponse]: """ Parameters @@ -49,7 +52,10 @@ def generate_stream( with self._client_wrapper.httpx_client.stream( "generate-stream", method="POST", - json={"num_events": num_events, "stream": True}, + json={ + "num_events": num_events, + "stream": True, + }, request_options=request_options, omit=OMIT, ) as _response: @@ -59,7 +65,12 @@ def generate_stream( try: if len(_text) == 0: continue - yield typing.cast(StreamResponse, parse_obj_as(type_=StreamResponse, object_=json.loads(_text))) # type: ignore + yield typing.cast( + StreamResponse, + parse_obj_as( + type_=StreamResponse, object_=json.loads(_text) + ), + ) # type: ignore except: pass return @@ -69,7 +80,12 @@ def generate_stream( raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def generate(self, *, num_events: int, request_options: typing.Optional[RequestOptions] = None) -> StreamResponse: + def generate( + self, + *, + num_events: int, + request_options: typing.Optional[RequestOptions] = None, + ) -> StreamResponse: """ Parameters ---------- @@ -96,13 +112,19 @@ def generate(self, *, num_events: int, request_options: typing.Optional[RequestO _response = self._client_wrapper.httpx_client.request( "generate", method="POST", - json={"num_events": num_events, "stream": False}, + json={ + "num_events": num_events, + "stream": False, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(StreamResponse, parse_obj_as(type_=StreamResponse, object_=_response.json())) # type: ignore + return typing.cast( + StreamResponse, + parse_obj_as(type_=StreamResponse, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -114,7 +136,10 @@ def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper async def generate_stream( - self, *, num_events: int, request_options: typing.Optional[RequestOptions] = None + self, + *, + num_events: int, + request_options: typing.Optional[RequestOptions] = None, ) -> typing.AsyncIterator[StreamResponse]: """ Parameters @@ -152,7 +177,10 @@ async def main() -> None: async with self._client_wrapper.httpx_client.stream( "generate-stream", method="POST", - json={"num_events": num_events, "stream": True}, + json={ + "num_events": num_events, + "stream": True, + }, request_options=request_options, omit=OMIT, ) as _response: @@ -162,7 +190,12 @@ async def main() -> None: try: if len(_text) == 0: continue - yield typing.cast(StreamResponse, parse_obj_as(type_=StreamResponse, object_=json.loads(_text))) # type: ignore + yield typing.cast( + StreamResponse, + parse_obj_as( + type_=StreamResponse, object_=json.loads(_text) + ), + ) # type: ignore except: pass return @@ -173,7 +206,10 @@ async def main() -> None: raise ApiError(status_code=_response.status_code, body=_response_json) async def generate( - self, *, num_events: int, request_options: typing.Optional[RequestOptions] = None + self, + *, + num_events: int, + request_options: typing.Optional[RequestOptions] = None, ) -> StreamResponse: """ Parameters @@ -209,13 +245,19 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( "generate", method="POST", - json={"num_events": num_events, "stream": False}, + json={ + "num_events": num_events, + "stream": False, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(StreamResponse, parse_obj_as(type_=StreamResponse, object_=_response.json())) # type: ignore + return typing.cast( + StreamResponse, + parse_obj_as(type_=StreamResponse, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/streaming/no-custom-config/src/seed/dummy/types/stream_response.py b/seed/python-sdk/streaming/no-custom-config/src/seed/dummy/types/stream_response.py index 9a9385376ec..05a127e5f8d 100644 --- a/seed/python-sdk/streaming/no-custom-config/src/seed/dummy/types/stream_response.py +++ b/seed/python-sdk/streaming/no-custom-config/src/seed/dummy/types/stream_response.py @@ -1,18 +1,19 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel import typing - +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class StreamResponse(UniversalBaseModel): id: str name: typing.Optional[str] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/streaming/no-custom-config/src/seed/version.py b/seed/python-sdk/streaming/no-custom-config/src/seed/version.py index ad0eb823c17..c1691d5b0dd 100644 --- a/seed/python-sdk/streaming/no-custom-config/src/seed/version.py +++ b/seed/python-sdk/streaming/no-custom-config/src/seed/version.py @@ -1,4 +1,3 @@ - from importlib import metadata __version__ = metadata.version("fern_streaming") diff --git a/seed/python-sdk/streaming/no-custom-config/tests/conftest.py b/seed/python-sdk/streaming/no-custom-config/tests/conftest.py index 45cf3f5003a..5df2bde2264 100644 --- a/seed/python-sdk/streaming/no-custom-config/tests/conftest.py +++ b/seed/python-sdk/streaming/no-custom-config/tests/conftest.py @@ -1,9 +1,9 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedStreaming import os - import pytest -from seed import AsyncSeedStreaming, SeedStreaming +from seed import AsyncSeedStreaming @pytest.fixture diff --git a/seed/python-sdk/streaming/no-custom-config/tests/custom/test_client.py b/seed/python-sdk/streaming/no-custom-config/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/python-sdk/streaming/no-custom-config/tests/custom/test_client.py +++ b/seed/python-sdk/streaming/no-custom-config/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/python-sdk/streaming/no-custom-config/tests/test_dummy.py b/seed/python-sdk/streaming/no-custom-config/tests/test_dummy.py index e5a1d2264c2..acd269f5d60 100644 --- a/seed/python-sdk/streaming/no-custom-config/tests/test_dummy.py +++ b/seed/python-sdk/streaming/no-custom-config/tests/test_dummy.py @@ -1,13 +1,14 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedStreaming +from seed import AsyncSeedStreaming import typing - -from seed import AsyncSeedStreaming, SeedStreaming - from .utilities import validate_response -async def test_generate(client: SeedStreaming, async_client: AsyncSeedStreaming) -> None: +async def test_generate( + client: SeedStreaming, async_client: AsyncSeedStreaming +) -> None: expected_response: typing.Any = {"id": "id", "name": "name"} expected_types: typing.Any = {"id": None, "name": None} response = client.dummy.generate(num_events=5) diff --git a/seed/python-sdk/streaming/no-custom-config/tests/utilities.py b/seed/python-sdk/streaming/no-custom-config/tests/utilities.py index 13da208eb3a..e8f4472564c 100644 --- a/seed/python-sdk/streaming/no-custom-config/tests/utilities.py +++ b/seed/python-sdk/streaming/no-custom-config/tests/utilities.py @@ -3,11 +3,14 @@ import typing import uuid -import pydantic from dateutil import parser +import pydantic + -def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> typing.Any: +def cast_field( + json_expectation: typing.Any, type_expectation: typing.Any +) -> typing.Any: # Cast these specific types which come through as string and expect our # models to cast to the correct type. if type_expectation == "uuid": @@ -25,7 +28,9 @@ def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> ty return json_expectation -def validate_field(response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any) -> None: +def validate_field( + response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectation == "no_validate": return @@ -44,7 +49,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(entry_expectation, dict): is_container_of_complex_type = True validate_response( - response=response[idx], json_expectation=ex, type_expectations=entry_expectation + response=response[idx], + json_expectation=ex, + type_expectations=entry_expectation, ) else: cast_json_expectation.append(cast_field(ex, entry_expectation)) @@ -56,7 +63,10 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # if any of the values of the set have a type_expectation of a dict, we're assuming it's a pydantic # model and keeping it a list. if container_expectation != "set" or not any( - map(lambda value: isinstance(value, dict), list(contents_expectation.values())) + map( + lambda value: isinstance(value, dict), + list(contents_expectation.values()), + ) ): json_expectation = cast_field(json_expectation, container_expectation) elif isinstance(type_expectation, tuple): @@ -65,9 +75,15 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(contents_expectation, dict): json_expectation = { cast_field( - key, contents_expectation.get(idx)[0] if contents_expectation.get(idx) is not None else None # type: ignore + key, + contents_expectation.get(idx)[0] + if contents_expectation.get(idx) is not None + else None, # type: ignore ): cast_field( - value, contents_expectation.get(idx)[1] if contents_expectation.get(idx) is not None else None # type: ignore + value, + contents_expectation.get(idx)[1] + if contents_expectation.get(idx) is not None + else None, # type: ignore ) for idx, (key, value) in enumerate(json_expectation.items()) } @@ -86,7 +102,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # Arg type_expectations is a deeply nested structure that matches the response, but with the values replaced with the expected types -def validate_response(response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any) -> None: +def validate_response( + response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectations == "no_validate": return @@ -96,11 +114,17 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e and not isinstance(response, dict) and not issubclass(type(response), pydantic.BaseModel) ): - validate_field(response=response, json_expectation=json_expectation, type_expectation=type_expectations) + validate_field( + response=response, + json_expectation=json_expectation, + type_expectation=type_expectations, + ) return if isinstance(response, list): - assert len(response) == len(json_expectation), "Length mismatch, expected: {0}, Actual: {1}".format( + assert len(response) == len( + json_expectation + ), "Length mismatch, expected: {0}, Actual: {1}".format( len(response), len(json_expectation) ) content_expectation = type_expectations @@ -108,7 +132,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e content_expectation = type_expectations[1] for idx, item in enumerate(response): validate_response( - response=item, json_expectation=json_expectation[idx], type_expectations=content_expectation[idx] + response=item, + json_expectation=json_expectation[idx], + type_expectations=content_expectation[idx], ) else: response_json = response @@ -116,7 +142,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e response_json = response.dict(by_alias=True) for key, value in json_expectation.items(): - assert key in response_json, "Field {0} not found within the response object: {1}".format( + assert ( + key in response_json + ), "Field {0} not found within the response object: {1}".format( key, response_json ) @@ -128,11 +156,19 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e # Otherwise, we're just validating a single field that's a pydantic model. if isinstance(value, dict) and not isinstance(type_expectation, tuple): validate_response( - response=response_json[key], json_expectation=value, type_expectations=type_expectation + response=response_json[key], + json_expectation=value, + type_expectations=type_expectation, ) else: - validate_field(response=response_json[key], json_expectation=value, type_expectation=type_expectation) + validate_field( + response=response_json[key], + json_expectation=value, + type_expectation=type_expectation, + ) # Ensure there are no additional fields here either del response_json[key] - assert len(response_json) == 0, "Additional fields found, expected None: {0}".format(response_json) + assert ( + len(response_json) == 0 + ), "Additional fields found, expected None: {0}".format(response_json) diff --git a/seed/python-sdk/streaming/no-custom-config/tests/utils/assets/models/__init__.py b/seed/python-sdk/streaming/no-custom-config/tests/utils/assets/models/__init__.py index 2cf01263529..3a1c852e71e 100644 --- a/seed/python-sdk/streaming/no-custom-config/tests/utils/assets/models/__init__.py +++ b/seed/python-sdk/streaming/no-custom-config/tests/utils/assets/models/__init__.py @@ -5,7 +5,7 @@ from .circle import CircleParams from .object_with_defaults import ObjectWithDefaultsParams from .object_with_optional_field import ObjectWithOptionalFieldParams -from .shape import Shape_CircleParams, Shape_SquareParams, ShapeParams +from .shape import ShapeParams, Shape_CircleParams, Shape_SquareParams from .square import SquareParams from .undiscriminated_shape import UndiscriminatedShapeParams diff --git a/seed/python-sdk/streaming/no-custom-config/tests/utils/assets/models/circle.py b/seed/python-sdk/streaming/no-custom-config/tests/utils/assets/models/circle.py index af7a1bf8a8e..253f12d38b3 100644 --- a/seed/python-sdk/streaming/no-custom-config/tests/utils/assets/models/circle.py +++ b/seed/python-sdk/streaming/no-custom-config/tests/utils/assets/models/circle.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class CircleParams(typing_extensions.TypedDict): - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] diff --git a/seed/python-sdk/streaming/no-custom-config/tests/utils/assets/models/object_with_optional_field.py b/seed/python-sdk/streaming/no-custom-config/tests/utils/assets/models/object_with_optional_field.py index 3ad93d5f305..ebe7dc80547 100644 --- a/seed/python-sdk/streaming/no-custom-config/tests/utils/assets/models/object_with_optional_field.py +++ b/seed/python-sdk/streaming/no-custom-config/tests/utils/assets/models/object_with_optional_field.py @@ -7,8 +7,8 @@ import uuid import typing_extensions -from seed.core.serialization import FieldMetadata +from seed.core.serialization import FieldMetadata from .color import Color from .shape import ShapeParams from .undiscriminated_shape import UndiscriminatedShapeParams @@ -18,16 +18,30 @@ class ObjectWithOptionalFieldParams(typing_extensions.TypedDict): literal: typing.Literal["lit_one"] string: typing_extensions.NotRequired[str] integer: typing_extensions.NotRequired[int] - long_: typing_extensions.NotRequired[typing_extensions.Annotated[int, FieldMetadata(alias="long")]] + long_: typing_extensions.NotRequired[ + typing_extensions.Annotated[int, FieldMetadata(alias="long")] + ] double: typing_extensions.NotRequired[float] - bool_: typing_extensions.NotRequired[typing_extensions.Annotated[bool, FieldMetadata(alias="bool")]] + bool_: typing_extensions.NotRequired[ + typing_extensions.Annotated[bool, FieldMetadata(alias="bool")] + ] datetime: typing_extensions.NotRequired[dt.datetime] date: typing_extensions.NotRequired[dt.date] - uuid_: typing_extensions.NotRequired[typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")]] - base_64: typing_extensions.NotRequired[typing_extensions.Annotated[str, FieldMetadata(alias="base64")]] - list_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")]] - set_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")]] - map_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")]] + uuid_: typing_extensions.NotRequired[ + typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")] + ] + base_64: typing_extensions.NotRequired[ + typing_extensions.Annotated[str, FieldMetadata(alias="base64")] + ] + list_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")] + ] + set_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")] + ] + map_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")] + ] enum: typing_extensions.NotRequired[Color] union: typing_extensions.NotRequired[ShapeParams] second_union: typing_extensions.NotRequired[ShapeParams] diff --git a/seed/python-sdk/streaming/no-custom-config/tests/utils/assets/models/shape.py b/seed/python-sdk/streaming/no-custom-config/tests/utils/assets/models/shape.py index 2c33c877951..816ffc51bdc 100644 --- a/seed/python-sdk/streaming/no-custom-config/tests/utils/assets/models/shape.py +++ b/seed/python-sdk/streaming/no-custom-config/tests/utils/assets/models/shape.py @@ -7,6 +7,7 @@ import typing import typing_extensions + from seed.core.serialization import FieldMetadata @@ -15,13 +16,21 @@ class Base(typing_extensions.TypedDict): class Shape_CircleParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["circle"], FieldMetadata(alias="shapeType")] - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["circle"], FieldMetadata(alias="shapeType") + ] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] class Shape_SquareParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["square"], FieldMetadata(alias="shapeType")] - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["square"], FieldMetadata(alias="shapeType") + ] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] ShapeParams = typing.Union[Shape_CircleParams, Shape_SquareParams] diff --git a/seed/python-sdk/streaming/no-custom-config/tests/utils/assets/models/square.py b/seed/python-sdk/streaming/no-custom-config/tests/utils/assets/models/square.py index b9b7dd319bc..bcf08a723c5 100644 --- a/seed/python-sdk/streaming/no-custom-config/tests/utils/assets/models/square.py +++ b/seed/python-sdk/streaming/no-custom-config/tests/utils/assets/models/square.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class SquareParams(typing_extensions.TypedDict): - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] diff --git a/seed/python-sdk/streaming/no-custom-config/tests/utils/test_http_client.py b/seed/python-sdk/streaming/no-custom-config/tests/utils/test_http_client.py index edd11ca7afb..f5a874a75f3 100644 --- a/seed/python-sdk/streaming/no-custom-config/tests/utils/test_http_client.py +++ b/seed/python-sdk/streaming/no-custom-config/tests/utils/test_http_client.py @@ -9,12 +9,17 @@ def get_request_options() -> RequestOptions: def test_get_json_request_body() -> None: - json_body, data_body = get_request_body(json={"hello": "world"}, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json={"hello": "world"}, data=None, request_options=None, omit=None + ) assert json_body == {"hello": "world"} assert data_body is None json_body_extras, data_body_extras = get_request_body( - json={"goodbye": "world"}, data=None, request_options=get_request_options(), omit=None + json={"goodbye": "world"}, + data=None, + request_options=get_request_options(), + omit=None, ) assert json_body_extras == {"goodbye": "world", "see you": "later"} @@ -22,12 +27,17 @@ def test_get_json_request_body() -> None: def test_get_files_request_body() -> None: - json_body, data_body = get_request_body(json=None, data={"hello": "world"}, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data={"hello": "world"}, request_options=None, omit=None + ) assert data_body == {"hello": "world"} assert json_body is None json_body_extras, data_body_extras = get_request_body( - json=None, data={"goodbye": "world"}, request_options=get_request_options(), omit=None + json=None, + data={"goodbye": "world"}, + request_options=get_request_options(), + omit=None, ) assert data_body_extras == {"goodbye": "world", "see you": "later"} @@ -35,7 +45,9 @@ def test_get_files_request_body() -> None: def test_get_none_request_body() -> None: - json_body, data_body = get_request_body(json=None, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data=None, request_options=None, omit=None + ) assert data_body is None assert json_body is None diff --git a/seed/python-sdk/streaming/no-custom-config/tests/utils/test_query_encoding.py b/seed/python-sdk/streaming/no-custom-config/tests/utils/test_query_encoding.py index 247e1551b46..fbc8f402167 100644 --- a/seed/python-sdk/streaming/no-custom-config/tests/utils/test_query_encoding.py +++ b/seed/python-sdk/streaming/no-custom-config/tests/utils/test_query_encoding.py @@ -4,9 +4,15 @@ def test_query_encoding() -> None: - assert encode_query({"hello world": "hello world"}) == {"hello world": "hello world"} - assert encode_query({"hello_world": {"hello": "world"}}) == {"hello_world[hello]": "world"} - assert encode_query({"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"}) == { + assert encode_query({"hello world": "hello world"}) == { + "hello world": "hello world" + } + assert encode_query({"hello_world": {"hello": "world"}}) == { + "hello_world[hello]": "world" + } + assert encode_query( + {"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"} + ) == { "hello_world[hello][world]": "today", "hello_world[test]": "this", "hi": "there", diff --git a/seed/python-sdk/streaming/no-custom-config/tests/utils/test_serialization.py b/seed/python-sdk/streaming/no-custom-config/tests/utils/test_serialization.py index 58b1ed66e6d..5ca956916dd 100644 --- a/seed/python-sdk/streaming/no-custom-config/tests/utils/test_serialization.py +++ b/seed/python-sdk/streaming/no-custom-config/tests/utils/test_serialization.py @@ -1,10 +1,12 @@ # This file was auto-generated by Fern from our API Definition. -from typing import Any, List +from typing import List, Any -from seed.core.serialization import convert_and_respect_annotation_metadata +from seed.core.serialization import ( + convert_and_respect_annotation_metadata, +) +from .assets.models import ShapeParams, ObjectWithOptionalFieldParams -from .assets.models import ObjectWithOptionalFieldParams, ShapeParams UNION_TEST: ShapeParams = {"radius_measurement": 1.0, "shape_type": "circle", "id": "1"} UNION_TEST_CONVERTED = {"shapeType": "circle", "radiusMeasurement": 1.0, "id": "1"} @@ -18,20 +20,54 @@ def test_convert_and_respect_annotation_metadata() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) - assert converted == {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"} + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) + assert converted == { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + } def test_convert_and_respect_annotation_metadata_in_list() -> None: data: List[ObjectWithOptionalFieldParams] = [ - {"string": "string", "long_": 12345, "bool_": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long_": 67890, "list_": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long_": 12345, + "bool_": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long_": 67890, + "list_": [], + "literal": "lit_one", + "any": "any", + }, ] - converted = convert_and_respect_annotation_metadata(object_=data, annotation=List[ObjectWithOptionalFieldParams]) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=List[ObjectWithOptionalFieldParams] + ) assert converted == [ - {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long": 67890, "list": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long": 67890, + "list": [], + "literal": "lit_one", + "any": "any", + }, ] @@ -43,7 +79,9 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) assert converted == { "string": "string", @@ -55,12 +93,16 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: def test_convert_and_respect_annotation_metadata_in_union() -> None: - converted = convert_and_respect_annotation_metadata(object_=UNION_TEST, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=UNION_TEST, annotation=ShapeParams + ) assert converted == UNION_TEST_CONVERTED def test_convert_and_respect_annotation_metadata_with_empty_object() -> None: data: Any = {} - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ShapeParams + ) assert converted == data diff --git a/seed/python-sdk/streaming/skip-pydantic-validation/pyproject.toml b/seed/python-sdk/streaming/skip-pydantic-validation/pyproject.toml index 8c1b1ca948f..41f6f015bce 100644 --- a/seed/python-sdk/streaming/skip-pydantic-validation/pyproject.toml +++ b/seed/python-sdk/streaming/skip-pydantic-validation/pyproject.toml @@ -43,6 +43,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/python-sdk/streaming/skip-pydantic-validation/src/seed/__init__.py b/seed/python-sdk/streaming/skip-pydantic-validation/src/seed/__init__.py index 8d93d0c1029..04a2311759c 100644 --- a/seed/python-sdk/streaming/skip-pydantic-validation/src/seed/__init__.py +++ b/seed/python-sdk/streaming/skip-pydantic-validation/src/seed/__init__.py @@ -5,4 +5,10 @@ from .dummy import StreamResponse from .version import __version__ -__all__ = ["AsyncSeedStreaming", "SeedStreaming", "StreamResponse", "__version__", "dummy"] +__all__ = [ + "AsyncSeedStreaming", + "SeedStreaming", + "StreamResponse", + "__version__", + "dummy", +] diff --git a/seed/python-sdk/streaming/skip-pydantic-validation/src/seed/client.py b/seed/python-sdk/streaming/skip-pydantic-validation/src/seed/client.py index cb008619005..0395cc355e1 100644 --- a/seed/python-sdk/streaming/skip-pydantic-validation/src/seed/client.py +++ b/seed/python-sdk/streaming/skip-pydantic-validation/src/seed/client.py @@ -1,11 +1,11 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from .dummy.client import AsyncDummyClient, DummyClient +from .core.client_wrapper import SyncClientWrapper +from .dummy.client import DummyClient +from .core.client_wrapper import AsyncClientWrapper +from .dummy.client import AsyncDummyClient class SeedStreaming: @@ -41,14 +41,18 @@ def __init__( base_url: str, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.Client] = None + httpx_client: typing.Optional[httpx.Client] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = SyncClientWrapper( base_url=base_url, httpx_client=httpx_client if httpx_client is not None - else httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.Client( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.Client(timeout=_defaulted_timeout), timeout=_defaulted_timeout, @@ -89,14 +93,18 @@ def __init__( base_url: str, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.AsyncClient] = None + httpx_client: typing.Optional[httpx.AsyncClient] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = AsyncClientWrapper( base_url=base_url, httpx_client=httpx_client if httpx_client is not None - else httpx.AsyncClient(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.AsyncClient( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.AsyncClient(timeout=_defaulted_timeout), timeout=_defaulted_timeout, diff --git a/seed/python-sdk/streaming/skip-pydantic-validation/src/seed/core/api_error.py b/seed/python-sdk/streaming/skip-pydantic-validation/src/seed/core/api_error.py index 2e9fc5431cd..da734b58068 100644 --- a/seed/python-sdk/streaming/skip-pydantic-validation/src/seed/core/api_error.py +++ b/seed/python-sdk/streaming/skip-pydantic-validation/src/seed/core/api_error.py @@ -7,7 +7,9 @@ class ApiError(Exception): status_code: typing.Optional[int] body: typing.Any - def __init__(self, *, status_code: typing.Optional[int] = None, body: typing.Any = None): + def __init__( + self, *, status_code: typing.Optional[int] = None, body: typing.Any = None + ): self.status_code = status_code self.body = body diff --git a/seed/python-sdk/streaming/skip-pydantic-validation/src/seed/core/client_wrapper.py b/seed/python-sdk/streaming/skip-pydantic-validation/src/seed/core/client_wrapper.py index f5a3cbe0a1d..de6ec6dbddd 100644 --- a/seed/python-sdk/streaming/skip-pydantic-validation/src/seed/core/client_wrapper.py +++ b/seed/python-sdk/streaming/skip-pydantic-validation/src/seed/core/client_wrapper.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .http_client import AsyncHttpClient, HttpClient +from .http_client import HttpClient +from .http_client import AsyncHttpClient class BaseClientWrapper: @@ -28,7 +27,13 @@ def get_timeout(self) -> typing.Optional[float]: class SyncClientWrapper(BaseClientWrapper): - def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, httpx_client: httpx.Client): + def __init__( + self, + *, + base_url: str, + timeout: typing.Optional[float] = None, + httpx_client: httpx.Client, + ): super().__init__(base_url=base_url, timeout=timeout) self.httpx_client = HttpClient( httpx_client=httpx_client, @@ -39,7 +44,13 @@ def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, htt class AsyncClientWrapper(BaseClientWrapper): - def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, httpx_client: httpx.AsyncClient): + def __init__( + self, + *, + base_url: str, + timeout: typing.Optional[float] = None, + httpx_client: httpx.AsyncClient, + ): super().__init__(base_url=base_url, timeout=timeout) self.httpx_client = AsyncHttpClient( httpx_client=httpx_client, diff --git a/seed/python-sdk/streaming/skip-pydantic-validation/src/seed/core/datetime_utils.py b/seed/python-sdk/streaming/skip-pydantic-validation/src/seed/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/python-sdk/streaming/skip-pydantic-validation/src/seed/core/datetime_utils.py +++ b/seed/python-sdk/streaming/skip-pydantic-validation/src/seed/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/python-sdk/streaming/skip-pydantic-validation/src/seed/core/file.py b/seed/python-sdk/streaming/skip-pydantic-validation/src/seed/core/file.py index cb0d40bbbf3..6e0f92bfcb1 100644 --- a/seed/python-sdk/streaming/skip-pydantic-validation/src/seed/core/file.py +++ b/seed/python-sdk/streaming/skip-pydantic-validation/src/seed/core/file.py @@ -13,12 +13,17 @@ # (filename, file (or bytes), content_type) typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str]], # (filename, file (or bytes), content_type, headers) - typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str], typing.Mapping[str, str]], + typing.Tuple[ + typing.Optional[str], + FileContent, + typing.Optional[str], + typing.Mapping[str, str], + ], ] def convert_file_dict_to_httpx_tuples( - d: typing.Dict[str, typing.Union[File, typing.List[File]]] + d: typing.Dict[str, typing.Union[File, typing.List[File]]], ) -> typing.List[typing.Tuple[str, File]]: """ The format we use is a list of tuples, where the first element is the diff --git a/seed/python-sdk/streaming/skip-pydantic-validation/src/seed/core/http_client.py b/seed/python-sdk/streaming/skip-pydantic-validation/src/seed/core/http_client.py index 9333d8a7f15..091f71bc185 100644 --- a/seed/python-sdk/streaming/skip-pydantic-validation/src/seed/core/http_client.py +++ b/seed/python-sdk/streaming/skip-pydantic-validation/src/seed/core/http_client.py @@ -77,7 +77,9 @@ def _retry_timeout(response: httpx.Response, retries: int) -> float: return retry_after # Apply exponential backoff, capped at MAX_RETRY_DELAY_SECONDS. - retry_delay = min(INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS) + retry_delay = min( + INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS + ) # Add a randomness / jitter to the retry delay to avoid overwhelming the server with retries. timeout = retry_delay * (1 - 0.25 * random()) @@ -90,7 +92,8 @@ def _should_retry(response: httpx.Response) -> bool: def remove_omit_from_dict( - original: typing.Dict[str, typing.Optional[typing.Any]], omit: typing.Optional[typing.Any] + original: typing.Dict[str, typing.Optional[typing.Any]], + omit: typing.Optional[typing.Any], ) -> typing.Dict[str, typing.Any]: if omit is None: return original @@ -108,7 +111,8 @@ def maybe_filter_request_body( ) -> typing.Optional[typing.Any]: if data is None: return ( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else None ) @@ -118,7 +122,8 @@ def maybe_filter_request_body( data_content = { **(jsonable_encoder(remove_omit_from_dict(data, omit))), # type: ignore **( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else {} ), @@ -162,7 +167,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url def request( @@ -174,8 +181,12 @@ def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -184,11 +195,14 @@ def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) response = self.httpx_client.request( method=method, @@ -198,7 +212,11 @@ def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -209,7 +227,10 @@ def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -222,11 +243,15 @@ def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: time.sleep(_retry_timeout(response=response, retries=retries)) @@ -256,8 +281,12 @@ def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -266,11 +295,14 @@ def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) with self.httpx_client.stream( method=method, @@ -280,7 +312,11 @@ def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -291,7 +327,9 @@ def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -304,7 +342,9 @@ def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream @@ -327,7 +367,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url async def request( @@ -339,8 +381,12 @@ async def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -349,11 +395,14 @@ async def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) # Add the input to each of these and do None-safety checks response = await self.httpx_client.request( @@ -364,7 +413,11 @@ async def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -375,7 +428,10 @@ async def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -388,11 +444,15 @@ async def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: await asyncio.sleep(_retry_timeout(response=response, retries=retries)) @@ -421,8 +481,12 @@ async def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -431,11 +495,14 @@ async def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) async with self.httpx_client.stream( method=method, @@ -445,7 +512,11 @@ async def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -456,7 +527,9 @@ async def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -469,7 +542,9 @@ async def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream diff --git a/seed/python-sdk/streaming/skip-pydantic-validation/src/seed/core/jsonable_encoder.py b/seed/python-sdk/streaming/skip-pydantic-validation/src/seed/core/jsonable_encoder.py index d3fd328fd41..12a8b52fc22 100644 --- a/seed/python-sdk/streaming/skip-pydantic-validation/src/seed/core/jsonable_encoder.py +++ b/seed/python-sdk/streaming/skip-pydantic-validation/src/seed/core/jsonable_encoder.py @@ -19,13 +19,19 @@ import pydantic from .datetime_utils import serialize_datetime -from .pydantic_utilities import IS_PYDANTIC_V2, encode_by_type, to_jsonable_with_fallback +from .pydantic_utilities import ( + IS_PYDANTIC_V2, + encode_by_type, + to_jsonable_with_fallback, +) SetIntStr = Set[Union[int, str]] DictIntStrAny = Dict[Union[int, str], Any] -def jsonable_encoder(obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None) -> Any: +def jsonable_encoder( + obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None +) -> Any: custom_encoder = custom_encoder or {} if custom_encoder: if type(obj) in custom_encoder: diff --git a/seed/python-sdk/streaming/skip-pydantic-validation/src/seed/core/pydantic_utilities.py b/seed/python-sdk/streaming/skip-pydantic-validation/src/seed/core/pydantic_utilities.py index 170a563d6eb..c63935c32a2 100644 --- a/seed/python-sdk/streaming/skip-pydantic-validation/src/seed/core/pydantic_utilities.py +++ b/seed/python-sdk/streaming/skip-pydantic-validation/src/seed/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) # type: ignore # Pydantic v1 diff --git a/seed/python-sdk/streaming/skip-pydantic-validation/src/seed/core/query_encoder.py b/seed/python-sdk/streaming/skip-pydantic-validation/src/seed/core/query_encoder.py index 24076d72ee9..7cb98f52cd7 100644 --- a/seed/python-sdk/streaming/skip-pydantic-validation/src/seed/core/query_encoder.py +++ b/seed/python-sdk/streaming/skip-pydantic-validation/src/seed/core/query_encoder.py @@ -7,7 +7,9 @@ # Flattens dicts to be of the form {"key[subkey][subkey2]": value} where value is not a dict -def traverse_query_dict(dict_flat: Dict[str, Any], key_prefix: Optional[str] = None) -> Dict[str, Any]: +def traverse_query_dict( + dict_flat: Dict[str, Any], key_prefix: Optional[str] = None +) -> Dict[str, Any]: result = {} for k, v in dict_flat.items(): key = f"{key_prefix}[{k}]" if key_prefix is not None else k @@ -30,4 +32,8 @@ def single_query_encoder(query_key: str, query_value: Any) -> Dict[str, Any]: def encode_query(query: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: - return dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) if query is not None else None + return ( + dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) + if query is not None + else None + ) diff --git a/seed/python-sdk/streaming/skip-pydantic-validation/src/seed/core/serialization.py b/seed/python-sdk/streaming/skip-pydantic-validation/src/seed/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/python-sdk/streaming/skip-pydantic-validation/src/seed/core/serialization.py +++ b/seed/python-sdk/streaming/skip-pydantic-validation/src/seed/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/python-sdk/streaming/skip-pydantic-validation/src/seed/core/unchecked_base_model.py b/seed/python-sdk/streaming/skip-pydantic-validation/src/seed/core/unchecked_base_model.py index 401cc513bd1..c5e3ed36f22 100644 --- a/seed/python-sdk/streaming/skip-pydantic-validation/src/seed/core/unchecked_base_model.py +++ b/seed/python-sdk/streaming/skip-pydantic-validation/src/seed/core/unchecked_base_model.py @@ -5,10 +5,11 @@ import typing import uuid -import pydantic import typing_extensions from pydantic_core import PydanticUndefined +import pydantic + from .pydantic_utilities import ( IS_PYDANTIC_V2, ModelField, @@ -35,7 +36,9 @@ def __init__(self, *, discriminant: str) -> None: class UncheckedBaseModel(UniversalBaseModel): if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow" + ) # type: ignore # Pydantic v2 else: class Config: @@ -43,7 +46,9 @@ class Config: @classmethod def model_construct( - cls: typing.Type["Model"], _fields_set: typing.Optional[typing.Set[str]] = None, **values: typing.Any + cls: typing.Type["Model"], + _fields_set: typing.Optional[typing.Set[str]] = None, + **values: typing.Any, ) -> "Model": # Fallback construct function to the specified override below. return cls.construct(_fields_set=_fields_set, **values) @@ -52,7 +57,9 @@ def model_construct( # Implementation taken from: https://github.com/pydantic/pydantic/issues/1168#issuecomment-817742836 @classmethod def construct( - cls: typing.Type["Model"], _fields_set: typing.Optional[typing.Set[str]] = None, **values: typing.Any + cls: typing.Type["Model"], + _fields_set: typing.Optional[typing.Set[str]] = None, + **values: typing.Any, ) -> "Model": m = cls.__new__(cls) fields_values = {} @@ -68,7 +75,9 @@ def construct( # you should always use the NAME of the field to for field_values, etc. # because that's how the object is constructed from a pydantic perspective key = field.alias - if key is None or (key not in values and populate_by_name): # Added this to allow population by field name + if key is None or ( + key not in values and populate_by_name + ): # Added this to allow population by field name key = name if key in values: @@ -78,7 +87,9 @@ def construct( type_ = typing.cast(typing.Type, field.outer_type_) # type: ignore # Pydantic < v1.10.15 fields_values[name] = ( - construct_type(object_=values[key], type_=type_) if type_ is not None else values[key] + construct_type(object_=values[key], type_=type_) + if type_ is not None + else values[key] ) _fields_set.add(name) else: @@ -114,14 +125,18 @@ def construct( return m -def _convert_undiscriminated_union_type(union_type: typing.Type[typing.Any], object_: typing.Any) -> typing.Any: +def _convert_undiscriminated_union_type( + union_type: typing.Type[typing.Any], object_: typing.Any +) -> typing.Any: inner_types = get_args(union_type) if typing.Any in inner_types: return object_ for inner_type in inner_types: try: - if inspect.isclass(inner_type) and issubclass(inner_type, pydantic.BaseModel): + if inspect.isclass(inner_type) and issubclass( + inner_type, pydantic.BaseModel + ): # Attempt a validated parse until one works return parse_obj_as(inner_type, object_) except Exception: @@ -135,7 +150,9 @@ def _convert_undiscriminated_union_type(union_type: typing.Type[typing.Any], obj continue -def _convert_union_type(type_: typing.Type[typing.Any], object_: typing.Any) -> typing.Any: +def _convert_union_type( + type_: typing.Type[typing.Any], object_: typing.Any +) -> typing.Any: base_type = get_origin(type_) or type_ union_type = type_ if base_type == typing_extensions.Annotated: @@ -147,10 +164,15 @@ def _convert_union_type(type_: typing.Type[typing.Any], object_: typing.Any) -> # Cast to the correct type, based on the discriminant for inner_type in get_args(union_type): try: - objects_discriminant = getattr(object_, metadata.discriminant) + objects_discriminant = getattr( + object_, metadata.discriminant + ) except: objects_discriminant = object_[metadata.discriminant] - if inner_type.__fields__[metadata.discriminant].default == objects_discriminant: + if ( + inner_type.__fields__[metadata.discriminant].default + == objects_discriminant + ): return construct_type(object_=object_, type_=inner_type) except Exception: # Allow to fall through to our regular union handling @@ -158,7 +180,9 @@ def _convert_union_type(type_: typing.Type[typing.Any], object_: typing.Any) -> return _convert_undiscriminated_union_type(union_type, object_) -def construct_type(*, type_: typing.Type[typing.Any], object_: typing.Any) -> typing.Any: +def construct_type( + *, type_: typing.Type[typing.Any], object_: typing.Any +) -> typing.Any: """ Here we are essentially creating the same `construct` method in spirit as the above, but for all types, not just Pydantic models. @@ -171,7 +195,9 @@ def construct_type(*, type_: typing.Type[typing.Any], object_: typing.Any) -> ty base_type = get_origin(type_) or type_ is_annotated = base_type == typing_extensions.Annotated maybe_annotation_members = get_args(type_) - is_annotated_union = is_annotated and is_union(get_origin(maybe_annotation_members[0])) + is_annotated_union = is_annotated and is_union( + get_origin(maybe_annotation_members[0]) + ) if base_type == typing.Any: return object_ @@ -182,7 +208,9 @@ def construct_type(*, type_: typing.Type[typing.Any], object_: typing.Any) -> ty key_type, items_type = get_args(type_) d = { - construct_type(object_=key, type_=key_type): construct_type(object_=item, type_=items_type) + construct_type(object_=key, type_=key_type): construct_type( + object_=item, type_=items_type + ) for key, item in object_.items() } return d @@ -263,7 +291,9 @@ def _get_is_populate_by_name(model: typing.Type["Model"]) -> bool: # Pydantic V1 swapped the typing of __fields__'s values from ModelField to FieldInfo # And so we try to handle both V1 cases, as well as V2 (FieldInfo from model.model_fields) -def _get_model_fields(model: typing.Type["Model"]) -> typing.Mapping[str, PydanticField]: +def _get_model_fields( + model: typing.Type["Model"], +) -> typing.Mapping[str, PydanticField]: if IS_PYDANTIC_V2: return model.model_fields # type: ignore # Pydantic v2 else: diff --git a/seed/python-sdk/streaming/skip-pydantic-validation/src/seed/dummy/client.py b/seed/python-sdk/streaming/skip-pydantic-validation/src/seed/dummy/client.py index b3fc1d94d04..0e72a5e6883 100644 --- a/seed/python-sdk/streaming/skip-pydantic-validation/src/seed/dummy/client.py +++ b/seed/python-sdk/streaming/skip-pydantic-validation/src/seed/dummy/client.py @@ -1,14 +1,14 @@ # This file was auto-generated by Fern from our API Definition. -import json import typing -from json.decoder import JSONDecodeError - -from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper +from ..core.client_wrapper import SyncClientWrapper from ..core.request_options import RequestOptions -from ..core.unchecked_base_model import construct_type from .types.stream_response import StreamResponse +from ..core.unchecked_base_model import construct_type +import json +from json.decoder import JSONDecodeError +from ..core.api_error import ApiError +from ..core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -19,7 +19,10 @@ def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper def generate_stream( - self, *, num_events: int, request_options: typing.Optional[RequestOptions] = None + self, + *, + num_events: int, + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Iterator[StreamResponse]: """ Parameters @@ -49,7 +52,10 @@ def generate_stream( with self._client_wrapper.httpx_client.stream( "generate-stream", method="POST", - json={"num_events": num_events, "stream": True}, + json={ + "num_events": num_events, + "stream": True, + }, request_options=request_options, omit=OMIT, ) as _response: @@ -59,7 +65,12 @@ def generate_stream( try: if len(_text) == 0: continue - yield typing.cast(StreamResponse, construct_type(type_=StreamResponse, object_=json.loads(_text))) # type: ignore + yield typing.cast( + StreamResponse, + construct_type( + type_=StreamResponse, object_=json.loads(_text) + ), + ) # type: ignore except: pass return @@ -69,7 +80,12 @@ def generate_stream( raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def generate(self, *, num_events: int, request_options: typing.Optional[RequestOptions] = None) -> StreamResponse: + def generate( + self, + *, + num_events: int, + request_options: typing.Optional[RequestOptions] = None, + ) -> StreamResponse: """ Parameters ---------- @@ -96,13 +112,19 @@ def generate(self, *, num_events: int, request_options: typing.Optional[RequestO _response = self._client_wrapper.httpx_client.request( "generate", method="POST", - json={"num_events": num_events, "stream": False}, + json={ + "num_events": num_events, + "stream": False, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(StreamResponse, construct_type(type_=StreamResponse, object_=_response.json())) # type: ignore + return typing.cast( + StreamResponse, + construct_type(type_=StreamResponse, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -114,7 +136,10 @@ def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper async def generate_stream( - self, *, num_events: int, request_options: typing.Optional[RequestOptions] = None + self, + *, + num_events: int, + request_options: typing.Optional[RequestOptions] = None, ) -> typing.AsyncIterator[StreamResponse]: """ Parameters @@ -152,7 +177,10 @@ async def main() -> None: async with self._client_wrapper.httpx_client.stream( "generate-stream", method="POST", - json={"num_events": num_events, "stream": True}, + json={ + "num_events": num_events, + "stream": True, + }, request_options=request_options, omit=OMIT, ) as _response: @@ -162,7 +190,12 @@ async def main() -> None: try: if len(_text) == 0: continue - yield typing.cast(StreamResponse, construct_type(type_=StreamResponse, object_=json.loads(_text))) # type: ignore + yield typing.cast( + StreamResponse, + construct_type( + type_=StreamResponse, object_=json.loads(_text) + ), + ) # type: ignore except: pass return @@ -173,7 +206,10 @@ async def main() -> None: raise ApiError(status_code=_response.status_code, body=_response_json) async def generate( - self, *, num_events: int, request_options: typing.Optional[RequestOptions] = None + self, + *, + num_events: int, + request_options: typing.Optional[RequestOptions] = None, ) -> StreamResponse: """ Parameters @@ -209,13 +245,19 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( "generate", method="POST", - json={"num_events": num_events, "stream": False}, + json={ + "num_events": num_events, + "stream": False, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(StreamResponse, construct_type(type_=StreamResponse, object_=_response.json())) # type: ignore + return typing.cast( + StreamResponse, + construct_type(type_=StreamResponse, object_=_response.json()), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/streaming/skip-pydantic-validation/src/seed/dummy/types/stream_response.py b/seed/python-sdk/streaming/skip-pydantic-validation/src/seed/dummy/types/stream_response.py index 928a204521f..5c5dca39b24 100644 --- a/seed/python-sdk/streaming/skip-pydantic-validation/src/seed/dummy/types/stream_response.py +++ b/seed/python-sdk/streaming/skip-pydantic-validation/src/seed/dummy/types/stream_response.py @@ -1,11 +1,9 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.unchecked_base_model import UncheckedBaseModel import typing - -import pydantic - from ...core.pydantic_utilities import IS_PYDANTIC_V2 -from ...core.unchecked_base_model import UncheckedBaseModel +import pydantic class StreamResponse(UncheckedBaseModel): @@ -13,7 +11,9 @@ class StreamResponse(UncheckedBaseModel): name: typing.Optional[str] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/streaming/skip-pydantic-validation/src/seed/version.py b/seed/python-sdk/streaming/skip-pydantic-validation/src/seed/version.py index ad0eb823c17..c1691d5b0dd 100644 --- a/seed/python-sdk/streaming/skip-pydantic-validation/src/seed/version.py +++ b/seed/python-sdk/streaming/skip-pydantic-validation/src/seed/version.py @@ -1,4 +1,3 @@ - from importlib import metadata __version__ = metadata.version("fern_streaming") diff --git a/seed/python-sdk/streaming/skip-pydantic-validation/tests/conftest.py b/seed/python-sdk/streaming/skip-pydantic-validation/tests/conftest.py index 45cf3f5003a..5df2bde2264 100644 --- a/seed/python-sdk/streaming/skip-pydantic-validation/tests/conftest.py +++ b/seed/python-sdk/streaming/skip-pydantic-validation/tests/conftest.py @@ -1,9 +1,9 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedStreaming import os - import pytest -from seed import AsyncSeedStreaming, SeedStreaming +from seed import AsyncSeedStreaming @pytest.fixture diff --git a/seed/python-sdk/streaming/skip-pydantic-validation/tests/custom/test_client.py b/seed/python-sdk/streaming/skip-pydantic-validation/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/python-sdk/streaming/skip-pydantic-validation/tests/custom/test_client.py +++ b/seed/python-sdk/streaming/skip-pydantic-validation/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/python-sdk/streaming/skip-pydantic-validation/tests/test_dummy.py b/seed/python-sdk/streaming/skip-pydantic-validation/tests/test_dummy.py index e5a1d2264c2..acd269f5d60 100644 --- a/seed/python-sdk/streaming/skip-pydantic-validation/tests/test_dummy.py +++ b/seed/python-sdk/streaming/skip-pydantic-validation/tests/test_dummy.py @@ -1,13 +1,14 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedStreaming +from seed import AsyncSeedStreaming import typing - -from seed import AsyncSeedStreaming, SeedStreaming - from .utilities import validate_response -async def test_generate(client: SeedStreaming, async_client: AsyncSeedStreaming) -> None: +async def test_generate( + client: SeedStreaming, async_client: AsyncSeedStreaming +) -> None: expected_response: typing.Any = {"id": "id", "name": "name"} expected_types: typing.Any = {"id": None, "name": None} response = client.dummy.generate(num_events=5) diff --git a/seed/python-sdk/streaming/skip-pydantic-validation/tests/utilities.py b/seed/python-sdk/streaming/skip-pydantic-validation/tests/utilities.py index 13da208eb3a..e8f4472564c 100644 --- a/seed/python-sdk/streaming/skip-pydantic-validation/tests/utilities.py +++ b/seed/python-sdk/streaming/skip-pydantic-validation/tests/utilities.py @@ -3,11 +3,14 @@ import typing import uuid -import pydantic from dateutil import parser +import pydantic + -def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> typing.Any: +def cast_field( + json_expectation: typing.Any, type_expectation: typing.Any +) -> typing.Any: # Cast these specific types which come through as string and expect our # models to cast to the correct type. if type_expectation == "uuid": @@ -25,7 +28,9 @@ def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> ty return json_expectation -def validate_field(response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any) -> None: +def validate_field( + response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectation == "no_validate": return @@ -44,7 +49,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(entry_expectation, dict): is_container_of_complex_type = True validate_response( - response=response[idx], json_expectation=ex, type_expectations=entry_expectation + response=response[idx], + json_expectation=ex, + type_expectations=entry_expectation, ) else: cast_json_expectation.append(cast_field(ex, entry_expectation)) @@ -56,7 +63,10 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # if any of the values of the set have a type_expectation of a dict, we're assuming it's a pydantic # model and keeping it a list. if container_expectation != "set" or not any( - map(lambda value: isinstance(value, dict), list(contents_expectation.values())) + map( + lambda value: isinstance(value, dict), + list(contents_expectation.values()), + ) ): json_expectation = cast_field(json_expectation, container_expectation) elif isinstance(type_expectation, tuple): @@ -65,9 +75,15 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(contents_expectation, dict): json_expectation = { cast_field( - key, contents_expectation.get(idx)[0] if contents_expectation.get(idx) is not None else None # type: ignore + key, + contents_expectation.get(idx)[0] + if contents_expectation.get(idx) is not None + else None, # type: ignore ): cast_field( - value, contents_expectation.get(idx)[1] if contents_expectation.get(idx) is not None else None # type: ignore + value, + contents_expectation.get(idx)[1] + if contents_expectation.get(idx) is not None + else None, # type: ignore ) for idx, (key, value) in enumerate(json_expectation.items()) } @@ -86,7 +102,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # Arg type_expectations is a deeply nested structure that matches the response, but with the values replaced with the expected types -def validate_response(response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any) -> None: +def validate_response( + response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectations == "no_validate": return @@ -96,11 +114,17 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e and not isinstance(response, dict) and not issubclass(type(response), pydantic.BaseModel) ): - validate_field(response=response, json_expectation=json_expectation, type_expectation=type_expectations) + validate_field( + response=response, + json_expectation=json_expectation, + type_expectation=type_expectations, + ) return if isinstance(response, list): - assert len(response) == len(json_expectation), "Length mismatch, expected: {0}, Actual: {1}".format( + assert len(response) == len( + json_expectation + ), "Length mismatch, expected: {0}, Actual: {1}".format( len(response), len(json_expectation) ) content_expectation = type_expectations @@ -108,7 +132,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e content_expectation = type_expectations[1] for idx, item in enumerate(response): validate_response( - response=item, json_expectation=json_expectation[idx], type_expectations=content_expectation[idx] + response=item, + json_expectation=json_expectation[idx], + type_expectations=content_expectation[idx], ) else: response_json = response @@ -116,7 +142,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e response_json = response.dict(by_alias=True) for key, value in json_expectation.items(): - assert key in response_json, "Field {0} not found within the response object: {1}".format( + assert ( + key in response_json + ), "Field {0} not found within the response object: {1}".format( key, response_json ) @@ -128,11 +156,19 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e # Otherwise, we're just validating a single field that's a pydantic model. if isinstance(value, dict) and not isinstance(type_expectation, tuple): validate_response( - response=response_json[key], json_expectation=value, type_expectations=type_expectation + response=response_json[key], + json_expectation=value, + type_expectations=type_expectation, ) else: - validate_field(response=response_json[key], json_expectation=value, type_expectation=type_expectation) + validate_field( + response=response_json[key], + json_expectation=value, + type_expectation=type_expectation, + ) # Ensure there are no additional fields here either del response_json[key] - assert len(response_json) == 0, "Additional fields found, expected None: {0}".format(response_json) + assert ( + len(response_json) == 0 + ), "Additional fields found, expected None: {0}".format(response_json) diff --git a/seed/python-sdk/streaming/skip-pydantic-validation/tests/utils/assets/models/__init__.py b/seed/python-sdk/streaming/skip-pydantic-validation/tests/utils/assets/models/__init__.py index 2cf01263529..3a1c852e71e 100644 --- a/seed/python-sdk/streaming/skip-pydantic-validation/tests/utils/assets/models/__init__.py +++ b/seed/python-sdk/streaming/skip-pydantic-validation/tests/utils/assets/models/__init__.py @@ -5,7 +5,7 @@ from .circle import CircleParams from .object_with_defaults import ObjectWithDefaultsParams from .object_with_optional_field import ObjectWithOptionalFieldParams -from .shape import Shape_CircleParams, Shape_SquareParams, ShapeParams +from .shape import ShapeParams, Shape_CircleParams, Shape_SquareParams from .square import SquareParams from .undiscriminated_shape import UndiscriminatedShapeParams diff --git a/seed/python-sdk/streaming/skip-pydantic-validation/tests/utils/assets/models/circle.py b/seed/python-sdk/streaming/skip-pydantic-validation/tests/utils/assets/models/circle.py index af7a1bf8a8e..253f12d38b3 100644 --- a/seed/python-sdk/streaming/skip-pydantic-validation/tests/utils/assets/models/circle.py +++ b/seed/python-sdk/streaming/skip-pydantic-validation/tests/utils/assets/models/circle.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class CircleParams(typing_extensions.TypedDict): - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] diff --git a/seed/python-sdk/streaming/skip-pydantic-validation/tests/utils/assets/models/object_with_optional_field.py b/seed/python-sdk/streaming/skip-pydantic-validation/tests/utils/assets/models/object_with_optional_field.py index 3ad93d5f305..ebe7dc80547 100644 --- a/seed/python-sdk/streaming/skip-pydantic-validation/tests/utils/assets/models/object_with_optional_field.py +++ b/seed/python-sdk/streaming/skip-pydantic-validation/tests/utils/assets/models/object_with_optional_field.py @@ -7,8 +7,8 @@ import uuid import typing_extensions -from seed.core.serialization import FieldMetadata +from seed.core.serialization import FieldMetadata from .color import Color from .shape import ShapeParams from .undiscriminated_shape import UndiscriminatedShapeParams @@ -18,16 +18,30 @@ class ObjectWithOptionalFieldParams(typing_extensions.TypedDict): literal: typing.Literal["lit_one"] string: typing_extensions.NotRequired[str] integer: typing_extensions.NotRequired[int] - long_: typing_extensions.NotRequired[typing_extensions.Annotated[int, FieldMetadata(alias="long")]] + long_: typing_extensions.NotRequired[ + typing_extensions.Annotated[int, FieldMetadata(alias="long")] + ] double: typing_extensions.NotRequired[float] - bool_: typing_extensions.NotRequired[typing_extensions.Annotated[bool, FieldMetadata(alias="bool")]] + bool_: typing_extensions.NotRequired[ + typing_extensions.Annotated[bool, FieldMetadata(alias="bool")] + ] datetime: typing_extensions.NotRequired[dt.datetime] date: typing_extensions.NotRequired[dt.date] - uuid_: typing_extensions.NotRequired[typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")]] - base_64: typing_extensions.NotRequired[typing_extensions.Annotated[str, FieldMetadata(alias="base64")]] - list_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")]] - set_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")]] - map_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")]] + uuid_: typing_extensions.NotRequired[ + typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")] + ] + base_64: typing_extensions.NotRequired[ + typing_extensions.Annotated[str, FieldMetadata(alias="base64")] + ] + list_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")] + ] + set_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")] + ] + map_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")] + ] enum: typing_extensions.NotRequired[Color] union: typing_extensions.NotRequired[ShapeParams] second_union: typing_extensions.NotRequired[ShapeParams] diff --git a/seed/python-sdk/streaming/skip-pydantic-validation/tests/utils/assets/models/shape.py b/seed/python-sdk/streaming/skip-pydantic-validation/tests/utils/assets/models/shape.py index 2c33c877951..816ffc51bdc 100644 --- a/seed/python-sdk/streaming/skip-pydantic-validation/tests/utils/assets/models/shape.py +++ b/seed/python-sdk/streaming/skip-pydantic-validation/tests/utils/assets/models/shape.py @@ -7,6 +7,7 @@ import typing import typing_extensions + from seed.core.serialization import FieldMetadata @@ -15,13 +16,21 @@ class Base(typing_extensions.TypedDict): class Shape_CircleParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["circle"], FieldMetadata(alias="shapeType")] - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["circle"], FieldMetadata(alias="shapeType") + ] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] class Shape_SquareParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["square"], FieldMetadata(alias="shapeType")] - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["square"], FieldMetadata(alias="shapeType") + ] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] ShapeParams = typing.Union[Shape_CircleParams, Shape_SquareParams] diff --git a/seed/python-sdk/streaming/skip-pydantic-validation/tests/utils/assets/models/square.py b/seed/python-sdk/streaming/skip-pydantic-validation/tests/utils/assets/models/square.py index b9b7dd319bc..bcf08a723c5 100644 --- a/seed/python-sdk/streaming/skip-pydantic-validation/tests/utils/assets/models/square.py +++ b/seed/python-sdk/streaming/skip-pydantic-validation/tests/utils/assets/models/square.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class SquareParams(typing_extensions.TypedDict): - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] diff --git a/seed/python-sdk/streaming/skip-pydantic-validation/tests/utils/test_http_client.py b/seed/python-sdk/streaming/skip-pydantic-validation/tests/utils/test_http_client.py index edd11ca7afb..f5a874a75f3 100644 --- a/seed/python-sdk/streaming/skip-pydantic-validation/tests/utils/test_http_client.py +++ b/seed/python-sdk/streaming/skip-pydantic-validation/tests/utils/test_http_client.py @@ -9,12 +9,17 @@ def get_request_options() -> RequestOptions: def test_get_json_request_body() -> None: - json_body, data_body = get_request_body(json={"hello": "world"}, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json={"hello": "world"}, data=None, request_options=None, omit=None + ) assert json_body == {"hello": "world"} assert data_body is None json_body_extras, data_body_extras = get_request_body( - json={"goodbye": "world"}, data=None, request_options=get_request_options(), omit=None + json={"goodbye": "world"}, + data=None, + request_options=get_request_options(), + omit=None, ) assert json_body_extras == {"goodbye": "world", "see you": "later"} @@ -22,12 +27,17 @@ def test_get_json_request_body() -> None: def test_get_files_request_body() -> None: - json_body, data_body = get_request_body(json=None, data={"hello": "world"}, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data={"hello": "world"}, request_options=None, omit=None + ) assert data_body == {"hello": "world"} assert json_body is None json_body_extras, data_body_extras = get_request_body( - json=None, data={"goodbye": "world"}, request_options=get_request_options(), omit=None + json=None, + data={"goodbye": "world"}, + request_options=get_request_options(), + omit=None, ) assert data_body_extras == {"goodbye": "world", "see you": "later"} @@ -35,7 +45,9 @@ def test_get_files_request_body() -> None: def test_get_none_request_body() -> None: - json_body, data_body = get_request_body(json=None, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data=None, request_options=None, omit=None + ) assert data_body is None assert json_body is None diff --git a/seed/python-sdk/streaming/skip-pydantic-validation/tests/utils/test_query_encoding.py b/seed/python-sdk/streaming/skip-pydantic-validation/tests/utils/test_query_encoding.py index 247e1551b46..fbc8f402167 100644 --- a/seed/python-sdk/streaming/skip-pydantic-validation/tests/utils/test_query_encoding.py +++ b/seed/python-sdk/streaming/skip-pydantic-validation/tests/utils/test_query_encoding.py @@ -4,9 +4,15 @@ def test_query_encoding() -> None: - assert encode_query({"hello world": "hello world"}) == {"hello world": "hello world"} - assert encode_query({"hello_world": {"hello": "world"}}) == {"hello_world[hello]": "world"} - assert encode_query({"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"}) == { + assert encode_query({"hello world": "hello world"}) == { + "hello world": "hello world" + } + assert encode_query({"hello_world": {"hello": "world"}}) == { + "hello_world[hello]": "world" + } + assert encode_query( + {"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"} + ) == { "hello_world[hello][world]": "today", "hello_world[test]": "this", "hi": "there", diff --git a/seed/python-sdk/streaming/skip-pydantic-validation/tests/utils/test_serialization.py b/seed/python-sdk/streaming/skip-pydantic-validation/tests/utils/test_serialization.py index 58b1ed66e6d..5ca956916dd 100644 --- a/seed/python-sdk/streaming/skip-pydantic-validation/tests/utils/test_serialization.py +++ b/seed/python-sdk/streaming/skip-pydantic-validation/tests/utils/test_serialization.py @@ -1,10 +1,12 @@ # This file was auto-generated by Fern from our API Definition. -from typing import Any, List +from typing import List, Any -from seed.core.serialization import convert_and_respect_annotation_metadata +from seed.core.serialization import ( + convert_and_respect_annotation_metadata, +) +from .assets.models import ShapeParams, ObjectWithOptionalFieldParams -from .assets.models import ObjectWithOptionalFieldParams, ShapeParams UNION_TEST: ShapeParams = {"radius_measurement": 1.0, "shape_type": "circle", "id": "1"} UNION_TEST_CONVERTED = {"shapeType": "circle", "radiusMeasurement": 1.0, "id": "1"} @@ -18,20 +20,54 @@ def test_convert_and_respect_annotation_metadata() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) - assert converted == {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"} + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) + assert converted == { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + } def test_convert_and_respect_annotation_metadata_in_list() -> None: data: List[ObjectWithOptionalFieldParams] = [ - {"string": "string", "long_": 12345, "bool_": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long_": 67890, "list_": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long_": 12345, + "bool_": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long_": 67890, + "list_": [], + "literal": "lit_one", + "any": "any", + }, ] - converted = convert_and_respect_annotation_metadata(object_=data, annotation=List[ObjectWithOptionalFieldParams]) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=List[ObjectWithOptionalFieldParams] + ) assert converted == [ - {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long": 67890, "list": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long": 67890, + "list": [], + "literal": "lit_one", + "any": "any", + }, ] @@ -43,7 +79,9 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) assert converted == { "string": "string", @@ -55,12 +93,16 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: def test_convert_and_respect_annotation_metadata_in_union() -> None: - converted = convert_and_respect_annotation_metadata(object_=UNION_TEST, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=UNION_TEST, annotation=ShapeParams + ) assert converted == UNION_TEST_CONVERTED def test_convert_and_respect_annotation_metadata_with_empty_object() -> None: data: Any = {} - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ShapeParams + ) assert converted == data diff --git a/seed/python-sdk/trace/src/seed/__init__.py b/seed/python-sdk/trace/src/seed/__init__.py index 0d5fa965614..4f1bd8e2066 100644 --- a/seed/python-sdk/trace/src/seed/__init__.py +++ b/seed/python-sdk/trace/src/seed/__init__.py @@ -1,6 +1,17 @@ # This file was auto-generated by Fern from our API Definition. -from . import admin, commons, homepage, lang_server, migration, playlist, problem, submission, sysprop, v_2 +from . import ( + admin, + commons, + homepage, + lang_server, + migration, + playlist, + problem, + submission, + sysprop, + v_2, +) from .admin import Test, Test_And, Test_Or from .commons import ( BinaryTreeNodeAndTreeValue, diff --git a/seed/python-sdk/trace/src/seed/admin/client.py b/seed/python-sdk/trace/src/seed/admin/client.py index 368f76fcb8d..c0ada4ce96e 100644 --- a/seed/python-sdk/trace/src/seed/admin/client.py +++ b/seed/python-sdk/trace/src/seed/admin/client.py @@ -66,27 +66,43 @@ def update_test_submission_status( f"admin/store-test-submission-status/{jsonable_encoder(submission_id)}", ), params=jsonable_encoder( - request_options.get("additional_query_parameters") if request_options is not None else None + request_options.get("additional_query_parameters") + if request_options is not None + else None ), json=jsonable_encoder(request) - if request_options is None or request_options.get("additional_body_parameters") is None + if request_options is None + or request_options.get("additional_body_parameters") is None else { **jsonable_encoder(request), - **(jsonable_encoder(remove_none_from_dict(request_options.get("additional_body_parameters", {})))), + **( + jsonable_encoder( + remove_none_from_dict( + request_options.get("additional_body_parameters", {}) + ) + ) + ), }, headers=jsonable_encoder( remove_none_from_dict( { **self._client_wrapper.get_headers(), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), timeout=request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self._client_wrapper.get_timeout(), retries=0, - max_retries=request_options.get("max_retries") if request_options is not None else 0, # type: ignore + max_retries=request_options.get("max_retries") + if request_options is not None + else 0, # type: ignore ) if 200 <= _response.status_code < 300: return @@ -142,27 +158,43 @@ def send_test_submission_update( f"admin/store-test-submission-status-v2/{jsonable_encoder(submission_id)}", ), params=jsonable_encoder( - request_options.get("additional_query_parameters") if request_options is not None else None + request_options.get("additional_query_parameters") + if request_options is not None + else None ), json=jsonable_encoder(request) - if request_options is None or request_options.get("additional_body_parameters") is None + if request_options is None + or request_options.get("additional_body_parameters") is None else { **jsonable_encoder(request), - **(jsonable_encoder(remove_none_from_dict(request_options.get("additional_body_parameters", {})))), + **( + jsonable_encoder( + remove_none_from_dict( + request_options.get("additional_body_parameters", {}) + ) + ) + ), }, headers=jsonable_encoder( remove_none_from_dict( { **self._client_wrapper.get_headers(), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), timeout=request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self._client_wrapper.get_timeout(), retries=0, - max_retries=request_options.get("max_retries") if request_options is not None else 0, # type: ignore + max_retries=request_options.get("max_retries") + if request_options is not None + else 0, # type: ignore ) if 200 <= _response.status_code < 300: return @@ -210,27 +242,43 @@ def update_workspace_submission_status( f"admin/store-workspace-submission-status/{jsonable_encoder(submission_id)}", ), params=jsonable_encoder( - request_options.get("additional_query_parameters") if request_options is not None else None + request_options.get("additional_query_parameters") + if request_options is not None + else None ), json=jsonable_encoder(request) - if request_options is None or request_options.get("additional_body_parameters") is None + if request_options is None + or request_options.get("additional_body_parameters") is None else { **jsonable_encoder(request), - **(jsonable_encoder(remove_none_from_dict(request_options.get("additional_body_parameters", {})))), + **( + jsonable_encoder( + remove_none_from_dict( + request_options.get("additional_body_parameters", {}) + ) + ) + ), }, headers=jsonable_encoder( remove_none_from_dict( { **self._client_wrapper.get_headers(), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), timeout=request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self._client_wrapper.get_timeout(), retries=0, - max_retries=request_options.get("max_retries") if request_options is not None else 0, # type: ignore + max_retries=request_options.get("max_retries") + if request_options is not None + else 0, # type: ignore ) if 200 <= _response.status_code < 300: return @@ -289,27 +337,43 @@ def send_workspace_submission_update( f"admin/store-workspace-submission-status-v2/{jsonable_encoder(submission_id)}", ), params=jsonable_encoder( - request_options.get("additional_query_parameters") if request_options is not None else None + request_options.get("additional_query_parameters") + if request_options is not None + else None ), json=jsonable_encoder(request) - if request_options is None or request_options.get("additional_body_parameters") is None + if request_options is None + or request_options.get("additional_body_parameters") is None else { **jsonable_encoder(request), - **(jsonable_encoder(remove_none_from_dict(request_options.get("additional_body_parameters", {})))), + **( + jsonable_encoder( + remove_none_from_dict( + request_options.get("additional_body_parameters", {}) + ) + ) + ), }, headers=jsonable_encoder( remove_none_from_dict( { **self._client_wrapper.get_headers(), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), timeout=request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self._client_wrapper.get_timeout(), retries=0, - max_retries=request_options.get("max_retries") if request_options is not None else 0, # type: ignore + max_retries=request_options.get("max_retries") + if request_options is not None + else 0, # type: ignore ) if 200 <= _response.status_code < 300: return @@ -386,27 +450,45 @@ def store_traced_test_case( f"admin/store-test-trace/submission/{jsonable_encoder(submission_id)}/testCase/{jsonable_encoder(test_case_id)}", ), params=jsonable_encoder( - request_options.get("additional_query_parameters") if request_options is not None else None + request_options.get("additional_query_parameters") + if request_options is not None + else None ), json=jsonable_encoder({"result": result, "traceResponses": trace_responses}) - if request_options is None or request_options.get("additional_body_parameters") is None + if request_options is None + or request_options.get("additional_body_parameters") is None else { - **jsonable_encoder({"result": result, "traceResponses": trace_responses}), - **(jsonable_encoder(remove_none_from_dict(request_options.get("additional_body_parameters", {})))), + **jsonable_encoder( + {"result": result, "traceResponses": trace_responses} + ), + **( + jsonable_encoder( + remove_none_from_dict( + request_options.get("additional_body_parameters", {}) + ) + ) + ), }, headers=jsonable_encoder( remove_none_from_dict( { **self._client_wrapper.get_headers(), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), timeout=request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self._client_wrapper.get_timeout(), retries=0, - max_retries=request_options.get("max_retries") if request_options is not None else 0, # type: ignore + max_retries=request_options.get("max_retries") + if request_options is not None + else 0, # type: ignore ) if 200 <= _response.status_code < 300: return @@ -476,27 +558,43 @@ def store_traced_test_case_v_2( f"admin/store-test-trace-v2/submission/{jsonable_encoder(submission_id)}/testCase/{jsonable_encoder(test_case_id)}", ), params=jsonable_encoder( - request_options.get("additional_query_parameters") if request_options is not None else None + request_options.get("additional_query_parameters") + if request_options is not None + else None ), json=jsonable_encoder(request) - if request_options is None or request_options.get("additional_body_parameters") is None + if request_options is None + or request_options.get("additional_body_parameters") is None else { **jsonable_encoder(request), - **(jsonable_encoder(remove_none_from_dict(request_options.get("additional_body_parameters", {})))), + **( + jsonable_encoder( + remove_none_from_dict( + request_options.get("additional_body_parameters", {}) + ) + ) + ), }, headers=jsonable_encoder( remove_none_from_dict( { **self._client_wrapper.get_headers(), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), timeout=request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self._client_wrapper.get_timeout(), retries=0, - max_retries=request_options.get("max_retries") if request_options is not None else 0, # type: ignore + max_retries=request_options.get("max_retries") + if request_options is not None + else 0, # type: ignore ) if 200 <= _response.status_code < 300: return @@ -571,27 +669,53 @@ def store_traced_workspace( f"admin/store-workspace-trace/submission/{jsonable_encoder(submission_id)}", ), params=jsonable_encoder( - request_options.get("additional_query_parameters") if request_options is not None else None - ), - json=jsonable_encoder({"workspaceRunDetails": workspace_run_details, "traceResponses": trace_responses}) - if request_options is None or request_options.get("additional_body_parameters") is None + request_options.get("additional_query_parameters") + if request_options is not None + else None + ), + json=jsonable_encoder( + { + "workspaceRunDetails": workspace_run_details, + "traceResponses": trace_responses, + } + ) + if request_options is None + or request_options.get("additional_body_parameters") is None else { - **jsonable_encoder({"workspaceRunDetails": workspace_run_details, "traceResponses": trace_responses}), - **(jsonable_encoder(remove_none_from_dict(request_options.get("additional_body_parameters", {})))), + **jsonable_encoder( + { + "workspaceRunDetails": workspace_run_details, + "traceResponses": trace_responses, + } + ), + **( + jsonable_encoder( + remove_none_from_dict( + request_options.get("additional_body_parameters", {}) + ) + ) + ), }, headers=jsonable_encoder( remove_none_from_dict( { **self._client_wrapper.get_headers(), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), timeout=request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self._client_wrapper.get_timeout(), retries=0, - max_retries=request_options.get("max_retries") if request_options is not None else 0, # type: ignore + max_retries=request_options.get("max_retries") + if request_options is not None + else 0, # type: ignore ) if 200 <= _response.status_code < 300: return @@ -657,27 +781,43 @@ def store_traced_workspace_v_2( f"admin/store-workspace-trace-v2/submission/{jsonable_encoder(submission_id)}", ), params=jsonable_encoder( - request_options.get("additional_query_parameters") if request_options is not None else None + request_options.get("additional_query_parameters") + if request_options is not None + else None ), json=jsonable_encoder(request) - if request_options is None or request_options.get("additional_body_parameters") is None + if request_options is None + or request_options.get("additional_body_parameters") is None else { **jsonable_encoder(request), - **(jsonable_encoder(remove_none_from_dict(request_options.get("additional_body_parameters", {})))), + **( + jsonable_encoder( + remove_none_from_dict( + request_options.get("additional_body_parameters", {}) + ) + ) + ), }, headers=jsonable_encoder( remove_none_from_dict( { **self._client_wrapper.get_headers(), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), timeout=request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self._client_wrapper.get_timeout(), retries=0, - max_retries=request_options.get("max_retries") if request_options is not None else 0, # type: ignore + max_retries=request_options.get("max_retries") + if request_options is not None + else 0, # type: ignore ) if 200 <= _response.status_code < 300: return @@ -730,27 +870,43 @@ async def update_test_submission_status( f"admin/store-test-submission-status/{jsonable_encoder(submission_id)}", ), params=jsonable_encoder( - request_options.get("additional_query_parameters") if request_options is not None else None + request_options.get("additional_query_parameters") + if request_options is not None + else None ), json=jsonable_encoder(request) - if request_options is None or request_options.get("additional_body_parameters") is None + if request_options is None + or request_options.get("additional_body_parameters") is None else { **jsonable_encoder(request), - **(jsonable_encoder(remove_none_from_dict(request_options.get("additional_body_parameters", {})))), + **( + jsonable_encoder( + remove_none_from_dict( + request_options.get("additional_body_parameters", {}) + ) + ) + ), }, headers=jsonable_encoder( remove_none_from_dict( { **self._client_wrapper.get_headers(), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), timeout=request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self._client_wrapper.get_timeout(), retries=0, - max_retries=request_options.get("max_retries") if request_options is not None else 0, # type: ignore + max_retries=request_options.get("max_retries") + if request_options is not None + else 0, # type: ignore ) if 200 <= _response.status_code < 300: return @@ -806,27 +962,43 @@ async def send_test_submission_update( f"admin/store-test-submission-status-v2/{jsonable_encoder(submission_id)}", ), params=jsonable_encoder( - request_options.get("additional_query_parameters") if request_options is not None else None + request_options.get("additional_query_parameters") + if request_options is not None + else None ), json=jsonable_encoder(request) - if request_options is None or request_options.get("additional_body_parameters") is None + if request_options is None + or request_options.get("additional_body_parameters") is None else { **jsonable_encoder(request), - **(jsonable_encoder(remove_none_from_dict(request_options.get("additional_body_parameters", {})))), + **( + jsonable_encoder( + remove_none_from_dict( + request_options.get("additional_body_parameters", {}) + ) + ) + ), }, headers=jsonable_encoder( remove_none_from_dict( { **self._client_wrapper.get_headers(), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), timeout=request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self._client_wrapper.get_timeout(), retries=0, - max_retries=request_options.get("max_retries") if request_options is not None else 0, # type: ignore + max_retries=request_options.get("max_retries") + if request_options is not None + else 0, # type: ignore ) if 200 <= _response.status_code < 300: return @@ -874,27 +1046,43 @@ async def update_workspace_submission_status( f"admin/store-workspace-submission-status/{jsonable_encoder(submission_id)}", ), params=jsonable_encoder( - request_options.get("additional_query_parameters") if request_options is not None else None + request_options.get("additional_query_parameters") + if request_options is not None + else None ), json=jsonable_encoder(request) - if request_options is None or request_options.get("additional_body_parameters") is None + if request_options is None + or request_options.get("additional_body_parameters") is None else { **jsonable_encoder(request), - **(jsonable_encoder(remove_none_from_dict(request_options.get("additional_body_parameters", {})))), + **( + jsonable_encoder( + remove_none_from_dict( + request_options.get("additional_body_parameters", {}) + ) + ) + ), }, headers=jsonable_encoder( remove_none_from_dict( { **self._client_wrapper.get_headers(), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), timeout=request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self._client_wrapper.get_timeout(), retries=0, - max_retries=request_options.get("max_retries") if request_options is not None else 0, # type: ignore + max_retries=request_options.get("max_retries") + if request_options is not None + else 0, # type: ignore ) if 200 <= _response.status_code < 300: return @@ -953,27 +1141,43 @@ async def send_workspace_submission_update( f"admin/store-workspace-submission-status-v2/{jsonable_encoder(submission_id)}", ), params=jsonable_encoder( - request_options.get("additional_query_parameters") if request_options is not None else None + request_options.get("additional_query_parameters") + if request_options is not None + else None ), json=jsonable_encoder(request) - if request_options is None or request_options.get("additional_body_parameters") is None + if request_options is None + or request_options.get("additional_body_parameters") is None else { **jsonable_encoder(request), - **(jsonable_encoder(remove_none_from_dict(request_options.get("additional_body_parameters", {})))), + **( + jsonable_encoder( + remove_none_from_dict( + request_options.get("additional_body_parameters", {}) + ) + ) + ), }, headers=jsonable_encoder( remove_none_from_dict( { **self._client_wrapper.get_headers(), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), timeout=request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self._client_wrapper.get_timeout(), retries=0, - max_retries=request_options.get("max_retries") if request_options is not None else 0, # type: ignore + max_retries=request_options.get("max_retries") + if request_options is not None + else 0, # type: ignore ) if 200 <= _response.status_code < 300: return @@ -1050,27 +1254,45 @@ async def store_traced_test_case( f"admin/store-test-trace/submission/{jsonable_encoder(submission_id)}/testCase/{jsonable_encoder(test_case_id)}", ), params=jsonable_encoder( - request_options.get("additional_query_parameters") if request_options is not None else None + request_options.get("additional_query_parameters") + if request_options is not None + else None ), json=jsonable_encoder({"result": result, "traceResponses": trace_responses}) - if request_options is None or request_options.get("additional_body_parameters") is None + if request_options is None + or request_options.get("additional_body_parameters") is None else { - **jsonable_encoder({"result": result, "traceResponses": trace_responses}), - **(jsonable_encoder(remove_none_from_dict(request_options.get("additional_body_parameters", {})))), + **jsonable_encoder( + {"result": result, "traceResponses": trace_responses} + ), + **( + jsonable_encoder( + remove_none_from_dict( + request_options.get("additional_body_parameters", {}) + ) + ) + ), }, headers=jsonable_encoder( remove_none_from_dict( { **self._client_wrapper.get_headers(), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), timeout=request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self._client_wrapper.get_timeout(), retries=0, - max_retries=request_options.get("max_retries") if request_options is not None else 0, # type: ignore + max_retries=request_options.get("max_retries") + if request_options is not None + else 0, # type: ignore ) if 200 <= _response.status_code < 300: return @@ -1140,27 +1362,43 @@ async def store_traced_test_case_v_2( f"admin/store-test-trace-v2/submission/{jsonable_encoder(submission_id)}/testCase/{jsonable_encoder(test_case_id)}", ), params=jsonable_encoder( - request_options.get("additional_query_parameters") if request_options is not None else None + request_options.get("additional_query_parameters") + if request_options is not None + else None ), json=jsonable_encoder(request) - if request_options is None or request_options.get("additional_body_parameters") is None + if request_options is None + or request_options.get("additional_body_parameters") is None else { **jsonable_encoder(request), - **(jsonable_encoder(remove_none_from_dict(request_options.get("additional_body_parameters", {})))), + **( + jsonable_encoder( + remove_none_from_dict( + request_options.get("additional_body_parameters", {}) + ) + ) + ), }, headers=jsonable_encoder( remove_none_from_dict( { **self._client_wrapper.get_headers(), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), timeout=request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self._client_wrapper.get_timeout(), retries=0, - max_retries=request_options.get("max_retries") if request_options is not None else 0, # type: ignore + max_retries=request_options.get("max_retries") + if request_options is not None + else 0, # type: ignore ) if 200 <= _response.status_code < 300: return @@ -1235,27 +1473,53 @@ async def store_traced_workspace( f"admin/store-workspace-trace/submission/{jsonable_encoder(submission_id)}", ), params=jsonable_encoder( - request_options.get("additional_query_parameters") if request_options is not None else None - ), - json=jsonable_encoder({"workspaceRunDetails": workspace_run_details, "traceResponses": trace_responses}) - if request_options is None or request_options.get("additional_body_parameters") is None + request_options.get("additional_query_parameters") + if request_options is not None + else None + ), + json=jsonable_encoder( + { + "workspaceRunDetails": workspace_run_details, + "traceResponses": trace_responses, + } + ) + if request_options is None + or request_options.get("additional_body_parameters") is None else { - **jsonable_encoder({"workspaceRunDetails": workspace_run_details, "traceResponses": trace_responses}), - **(jsonable_encoder(remove_none_from_dict(request_options.get("additional_body_parameters", {})))), + **jsonable_encoder( + { + "workspaceRunDetails": workspace_run_details, + "traceResponses": trace_responses, + } + ), + **( + jsonable_encoder( + remove_none_from_dict( + request_options.get("additional_body_parameters", {}) + ) + ) + ), }, headers=jsonable_encoder( remove_none_from_dict( { **self._client_wrapper.get_headers(), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), timeout=request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self._client_wrapper.get_timeout(), retries=0, - max_retries=request_options.get("max_retries") if request_options is not None else 0, # type: ignore + max_retries=request_options.get("max_retries") + if request_options is not None + else 0, # type: ignore ) if 200 <= _response.status_code < 300: return @@ -1321,27 +1585,43 @@ async def store_traced_workspace_v_2( f"admin/store-workspace-trace-v2/submission/{jsonable_encoder(submission_id)}", ), params=jsonable_encoder( - request_options.get("additional_query_parameters") if request_options is not None else None + request_options.get("additional_query_parameters") + if request_options is not None + else None ), json=jsonable_encoder(request) - if request_options is None or request_options.get("additional_body_parameters") is None + if request_options is None + or request_options.get("additional_body_parameters") is None else { **jsonable_encoder(request), - **(jsonable_encoder(remove_none_from_dict(request_options.get("additional_body_parameters", {})))), + **( + jsonable_encoder( + remove_none_from_dict( + request_options.get("additional_body_parameters", {}) + ) + ) + ), }, headers=jsonable_encoder( remove_none_from_dict( { **self._client_wrapper.get_headers(), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), timeout=request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self._client_wrapper.get_timeout(), retries=0, - max_retries=request_options.get("max_retries") if request_options is not None else 0, # type: ignore + max_retries=request_options.get("max_retries") + if request_options is not None + else 0, # type: ignore ) if 200 <= _response.status_code < 300: return diff --git a/seed/python-sdk/trace/src/seed/client.py b/seed/python-sdk/trace/src/seed/client.py index c8c3f7e8d06..6a2420230be 100644 --- a/seed/python-sdk/trace/src/seed/client.py +++ b/seed/python-sdk/trace/src/seed/client.py @@ -54,16 +54,20 @@ def __init__( token: typing.Optional[typing.Union[str, typing.Callable[[], str]]] = None, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = None, - httpx_client: typing.Optional[httpx.Client] = None + httpx_client: typing.Optional[httpx.Client] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = SyncClientWrapper( base_url=_get_base_url(base_url=base_url, environment=environment), x_random_header=x_random_header, token=token, httpx_client=httpx_client if httpx_client is not None - else httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.Client( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.Client(timeout=_defaulted_timeout), timeout=_defaulted_timeout, @@ -116,16 +120,20 @@ def __init__( token: typing.Optional[typing.Union[str, typing.Callable[[], str]]] = None, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = None, - httpx_client: typing.Optional[httpx.AsyncClient] = None + httpx_client: typing.Optional[httpx.AsyncClient] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = AsyncClientWrapper( base_url=_get_base_url(base_url=base_url, environment=environment), x_random_header=x_random_header, token=token, httpx_client=httpx_client if httpx_client is not None - else httpx.AsyncClient(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.AsyncClient( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.AsyncClient(timeout=_defaulted_timeout), timeout=_defaulted_timeout, @@ -140,10 +148,14 @@ def __init__( self.sysprop = AsyncSyspropClient(client_wrapper=self._client_wrapper) -def _get_base_url(*, base_url: typing.Optional[str] = None, environment: SeedTraceEnvironment) -> str: +def _get_base_url( + *, base_url: typing.Optional[str] = None, environment: SeedTraceEnvironment +) -> str: if base_url is not None: return base_url elif environment is not None: return environment.value else: - raise Exception("Please pass in either base_url or environment to construct the client") + raise Exception( + "Please pass in either base_url or environment to construct the client" + ) diff --git a/seed/python-sdk/trace/src/seed/commons/types/binary_tree_node_and_tree_value.py b/seed/python-sdk/trace/src/seed/commons/types/binary_tree_node_and_tree_value.py index d48d23753aa..96ddf40df9b 100644 --- a/seed/python-sdk/trace/src/seed/commons/types/binary_tree_node_and_tree_value.py +++ b/seed/python-sdk/trace/src/seed/commons/types/binary_tree_node_and_tree_value.py @@ -14,11 +14,19 @@ class BinaryTreeNodeAndTreeValue(pydantic_v1.BaseModel): full_tree: BinaryTreeValue = pydantic_v1.Field(alias="fullTree") def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/commons/types/binary_tree_node_value.py b/seed/python-sdk/trace/src/seed/commons/types/binary_tree_node_value.py index fd6e134552f..84f48aecd59 100644 --- a/seed/python-sdk/trace/src/seed/commons/types/binary_tree_node_value.py +++ b/seed/python-sdk/trace/src/seed/commons/types/binary_tree_node_value.py @@ -15,11 +15,19 @@ class BinaryTreeNodeValue(pydantic_v1.BaseModel): left: typing.Optional[NodeId] = None def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/commons/types/binary_tree_value.py b/seed/python-sdk/trace/src/seed/commons/types/binary_tree_value.py index 9b685091b39..23b457867b0 100644 --- a/seed/python-sdk/trace/src/seed/commons/types/binary_tree_value.py +++ b/seed/python-sdk/trace/src/seed/commons/types/binary_tree_value.py @@ -14,11 +14,19 @@ class BinaryTreeValue(pydantic_v1.BaseModel): nodes: typing.Dict[NodeId, BinaryTreeNodeValue] def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/commons/types/debug_key_value_pairs.py b/seed/python-sdk/trace/src/seed/commons/types/debug_key_value_pairs.py index 33618781c83..6ae401a3dc3 100644 --- a/seed/python-sdk/trace/src/seed/commons/types/debug_key_value_pairs.py +++ b/seed/python-sdk/trace/src/seed/commons/types/debug_key_value_pairs.py @@ -14,11 +14,19 @@ class DebugKeyValuePairs(pydantic_v1.BaseModel): value: DebugVariableValue def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/commons/types/debug_map_value.py b/seed/python-sdk/trace/src/seed/commons/types/debug_map_value.py index 317716325c3..76ba0de6804 100644 --- a/seed/python-sdk/trace/src/seed/commons/types/debug_map_value.py +++ b/seed/python-sdk/trace/src/seed/commons/types/debug_map_value.py @@ -10,14 +10,24 @@ class DebugMapValue(pydantic_v1.BaseModel): - key_value_pairs: typing.List[DebugKeyValuePairs] = pydantic_v1.Field(alias="keyValuePairs") + key_value_pairs: typing.List[DebugKeyValuePairs] = pydantic_v1.Field( + alias="keyValuePairs" + ) def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/commons/types/debug_variable_value.py b/seed/python-sdk/trace/src/seed/commons/types/debug_variable_value.py index 6103c9bef6f..7fa1df89b2a 100644 --- a/seed/python-sdk/trace/src/seed/commons/types/debug_variable_value.py +++ b/seed/python-sdk/trace/src/seed/commons/types/debug_variable_value.py @@ -157,8 +157,12 @@ class Config: from .debug_map_value import DebugMapValue # noqa: E402 DebugVariableValue_MapValue.update_forward_refs( - DebugKeyValuePairs=DebugKeyValuePairs, DebugMapValue=DebugMapValue, DebugVariableValue=DebugVariableValue + DebugKeyValuePairs=DebugKeyValuePairs, + DebugMapValue=DebugMapValue, + DebugVariableValue=DebugVariableValue, ) DebugVariableValue_ListValue.update_forward_refs( - DebugKeyValuePairs=DebugKeyValuePairs, DebugMapValue=DebugMapValue, DebugVariableValue=DebugVariableValue + DebugKeyValuePairs=DebugKeyValuePairs, + DebugMapValue=DebugMapValue, + DebugVariableValue=DebugVariableValue, ) diff --git a/seed/python-sdk/trace/src/seed/commons/types/doubly_linked_list_node_and_list_value.py b/seed/python-sdk/trace/src/seed/commons/types/doubly_linked_list_node_and_list_value.py index 82f782b3ebd..92d74ca3377 100644 --- a/seed/python-sdk/trace/src/seed/commons/types/doubly_linked_list_node_and_list_value.py +++ b/seed/python-sdk/trace/src/seed/commons/types/doubly_linked_list_node_and_list_value.py @@ -14,11 +14,19 @@ class DoublyLinkedListNodeAndListValue(pydantic_v1.BaseModel): full_list: DoublyLinkedListValue = pydantic_v1.Field(alias="fullList") def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/commons/types/doubly_linked_list_node_value.py b/seed/python-sdk/trace/src/seed/commons/types/doubly_linked_list_node_value.py index 24efdc53f47..63c30e2fef5 100644 --- a/seed/python-sdk/trace/src/seed/commons/types/doubly_linked_list_node_value.py +++ b/seed/python-sdk/trace/src/seed/commons/types/doubly_linked_list_node_value.py @@ -15,11 +15,19 @@ class DoublyLinkedListNodeValue(pydantic_v1.BaseModel): prev: typing.Optional[NodeId] = None def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/commons/types/doubly_linked_list_value.py b/seed/python-sdk/trace/src/seed/commons/types/doubly_linked_list_value.py index 9262e25d79c..e9e20974413 100644 --- a/seed/python-sdk/trace/src/seed/commons/types/doubly_linked_list_value.py +++ b/seed/python-sdk/trace/src/seed/commons/types/doubly_linked_list_value.py @@ -14,11 +14,19 @@ class DoublyLinkedListValue(pydantic_v1.BaseModel): nodes: typing.Dict[NodeId, DoublyLinkedListNodeValue] def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/commons/types/file_info.py b/seed/python-sdk/trace/src/seed/commons/types/file_info.py index 6504c25a870..d788b5e18d6 100644 --- a/seed/python-sdk/trace/src/seed/commons/types/file_info.py +++ b/seed/python-sdk/trace/src/seed/commons/types/file_info.py @@ -12,11 +12,19 @@ class FileInfo(pydantic_v1.BaseModel): contents: str def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/commons/types/generic_value.py b/seed/python-sdk/trace/src/seed/commons/types/generic_value.py index 603c483c0a1..cbb5c00161b 100644 --- a/seed/python-sdk/trace/src/seed/commons/types/generic_value.py +++ b/seed/python-sdk/trace/src/seed/commons/types/generic_value.py @@ -8,15 +8,25 @@ class GenericValue(pydantic_v1.BaseModel): - stringified_type: typing.Optional[str] = pydantic_v1.Field(alias="stringifiedType", default=None) + stringified_type: typing.Optional[str] = pydantic_v1.Field( + alias="stringifiedType", default=None + ) stringified_value: str = pydantic_v1.Field(alias="stringifiedValue") def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/commons/types/key_value_pair.py b/seed/python-sdk/trace/src/seed/commons/types/key_value_pair.py index 8264e0f904b..7358094a7ac 100644 --- a/seed/python-sdk/trace/src/seed/commons/types/key_value_pair.py +++ b/seed/python-sdk/trace/src/seed/commons/types/key_value_pair.py @@ -14,11 +14,19 @@ class KeyValuePair(pydantic_v1.BaseModel): value: VariableValue def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/commons/types/list_type.py b/seed/python-sdk/trace/src/seed/commons/types/list_type.py index eeb0036a40e..892046a88d0 100644 --- a/seed/python-sdk/trace/src/seed/commons/types/list_type.py +++ b/seed/python-sdk/trace/src/seed/commons/types/list_type.py @@ -11,17 +11,27 @@ class ListType(pydantic_v1.BaseModel): value_type: VariableType = pydantic_v1.Field(alias="valueType") - is_fixed_length: typing.Optional[bool] = pydantic_v1.Field(alias="isFixedLength", default=None) + is_fixed_length: typing.Optional[bool] = pydantic_v1.Field( + alias="isFixedLength", default=None + ) """ Whether this list is fixed-size (for languages that supports fixed-size lists). Defaults to false. """ def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/commons/types/map_type.py b/seed/python-sdk/trace/src/seed/commons/types/map_type.py index 528e1d8cac5..655c4abf3ba 100644 --- a/seed/python-sdk/trace/src/seed/commons/types/map_type.py +++ b/seed/python-sdk/trace/src/seed/commons/types/map_type.py @@ -14,11 +14,19 @@ class MapType(pydantic_v1.BaseModel): value_type: VariableType = pydantic_v1.Field(alias="valueType") def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/commons/types/map_value.py b/seed/python-sdk/trace/src/seed/commons/types/map_value.py index c3724b3a2ea..4e99e335c3c 100644 --- a/seed/python-sdk/trace/src/seed/commons/types/map_value.py +++ b/seed/python-sdk/trace/src/seed/commons/types/map_value.py @@ -10,14 +10,24 @@ class MapValue(pydantic_v1.BaseModel): - key_value_pairs: typing.List[KeyValuePair] = pydantic_v1.Field(alias="keyValuePairs") + key_value_pairs: typing.List[KeyValuePair] = pydantic_v1.Field( + alias="keyValuePairs" + ) def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/commons/types/singly_linked_list_node_and_list_value.py b/seed/python-sdk/trace/src/seed/commons/types/singly_linked_list_node_and_list_value.py index e7b9f0a7123..47c20cc16f1 100644 --- a/seed/python-sdk/trace/src/seed/commons/types/singly_linked_list_node_and_list_value.py +++ b/seed/python-sdk/trace/src/seed/commons/types/singly_linked_list_node_and_list_value.py @@ -14,11 +14,19 @@ class SinglyLinkedListNodeAndListValue(pydantic_v1.BaseModel): full_list: SinglyLinkedListValue = pydantic_v1.Field(alias="fullList") def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/commons/types/singly_linked_list_node_value.py b/seed/python-sdk/trace/src/seed/commons/types/singly_linked_list_node_value.py index 64da1bd136a..470cc87e2fd 100644 --- a/seed/python-sdk/trace/src/seed/commons/types/singly_linked_list_node_value.py +++ b/seed/python-sdk/trace/src/seed/commons/types/singly_linked_list_node_value.py @@ -14,11 +14,19 @@ class SinglyLinkedListNodeValue(pydantic_v1.BaseModel): next: typing.Optional[NodeId] = None def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/commons/types/singly_linked_list_value.py b/seed/python-sdk/trace/src/seed/commons/types/singly_linked_list_value.py index 0b267e60b7d..69e9beabbf9 100644 --- a/seed/python-sdk/trace/src/seed/commons/types/singly_linked_list_value.py +++ b/seed/python-sdk/trace/src/seed/commons/types/singly_linked_list_value.py @@ -14,11 +14,19 @@ class SinglyLinkedListValue(pydantic_v1.BaseModel): nodes: typing.Dict[NodeId, SinglyLinkedListNodeValue] def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/commons/types/test_case.py b/seed/python-sdk/trace/src/seed/commons/types/test_case.py index 03e14e59a15..b683f2eee60 100644 --- a/seed/python-sdk/trace/src/seed/commons/types/test_case.py +++ b/seed/python-sdk/trace/src/seed/commons/types/test_case.py @@ -13,11 +13,19 @@ class TestCase(pydantic_v1.BaseModel): params: typing.List[VariableValue] def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/commons/types/test_case_with_expected_result.py b/seed/python-sdk/trace/src/seed/commons/types/test_case_with_expected_result.py index 55097630d09..824f0cfba06 100644 --- a/seed/python-sdk/trace/src/seed/commons/types/test_case_with_expected_result.py +++ b/seed/python-sdk/trace/src/seed/commons/types/test_case_with_expected_result.py @@ -14,11 +14,19 @@ class TestCaseWithExpectedResult(pydantic_v1.BaseModel): expected_result: VariableValue = pydantic_v1.Field(alias="expectedResult") def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/commons/types/variable_type.py b/seed/python-sdk/trace/src/seed/commons/types/variable_type.py index 71a04989c47..138b69ba24d 100644 --- a/seed/python-sdk/trace/src/seed/commons/types/variable_type.py +++ b/seed/python-sdk/trace/src/seed/commons/types/variable_type.py @@ -106,5 +106,9 @@ class Config: from .list_type import ListType # noqa: E402 from .map_type import MapType # noqa: E402 -VariableType_ListType.update_forward_refs(ListType=ListType, MapType=MapType, VariableType=VariableType) -VariableType_MapType.update_forward_refs(ListType=ListType, MapType=MapType, VariableType=VariableType) +VariableType_ListType.update_forward_refs( + ListType=ListType, MapType=MapType, VariableType=VariableType +) +VariableType_MapType.update_forward_refs( + ListType=ListType, MapType=MapType, VariableType=VariableType +) diff --git a/seed/python-sdk/trace/src/seed/commons/types/variable_value.py b/seed/python-sdk/trace/src/seed/commons/types/variable_value.py index d2743f6d9b9..983e5ad1c05 100644 --- a/seed/python-sdk/trace/src/seed/commons/types/variable_value.py +++ b/seed/python-sdk/trace/src/seed/commons/types/variable_value.py @@ -132,5 +132,9 @@ class Config: from .key_value_pair import KeyValuePair # noqa: E402 from .map_value import MapValue # noqa: E402 -VariableValue_MapValue.update_forward_refs(KeyValuePair=KeyValuePair, MapValue=MapValue, VariableValue=VariableValue) -VariableValue_ListValue.update_forward_refs(KeyValuePair=KeyValuePair, MapValue=MapValue, VariableValue=VariableValue) +VariableValue_MapValue.update_forward_refs( + KeyValuePair=KeyValuePair, MapValue=MapValue, VariableValue=VariableValue +) +VariableValue_ListValue.update_forward_refs( + KeyValuePair=KeyValuePair, MapValue=MapValue, VariableValue=VariableValue +) diff --git a/seed/python-sdk/trace/src/seed/core/api_error.py b/seed/python-sdk/trace/src/seed/core/api_error.py index 2e9fc5431cd..da734b58068 100644 --- a/seed/python-sdk/trace/src/seed/core/api_error.py +++ b/seed/python-sdk/trace/src/seed/core/api_error.py @@ -7,7 +7,9 @@ class ApiError(Exception): status_code: typing.Optional[int] body: typing.Any - def __init__(self, *, status_code: typing.Optional[int] = None, body: typing.Any = None): + def __init__( + self, *, status_code: typing.Optional[int] = None, body: typing.Any = None + ): self.status_code = status_code self.body = body diff --git a/seed/python-sdk/trace/src/seed/core/client_wrapper.py b/seed/python-sdk/trace/src/seed/core/client_wrapper.py index 7c807ff91cc..51052503b44 100644 --- a/seed/python-sdk/trace/src/seed/core/client_wrapper.py +++ b/seed/python-sdk/trace/src/seed/core/client_wrapper.py @@ -57,7 +57,12 @@ def __init__( timeout: typing.Optional[float] = None, httpx_client: httpx.Client, ): - super().__init__(x_random_header=x_random_header, token=token, base_url=base_url, timeout=timeout) + super().__init__( + x_random_header=x_random_header, + token=token, + base_url=base_url, + timeout=timeout, + ) self.httpx_client = HttpClient(httpx_client=httpx_client) @@ -71,5 +76,10 @@ def __init__( timeout: typing.Optional[float] = None, httpx_client: httpx.AsyncClient, ): - super().__init__(x_random_header=x_random_header, token=token, base_url=base_url, timeout=timeout) + super().__init__( + x_random_header=x_random_header, + token=token, + base_url=base_url, + timeout=timeout, + ) self.httpx_client = AsyncHttpClient(httpx_client=httpx_client) diff --git a/seed/python-sdk/trace/src/seed/core/datetime_utils.py b/seed/python-sdk/trace/src/seed/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/python-sdk/trace/src/seed/core/datetime_utils.py +++ b/seed/python-sdk/trace/src/seed/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/python-sdk/trace/src/seed/core/file.py b/seed/python-sdk/trace/src/seed/core/file.py index cb0d40bbbf3..6e0f92bfcb1 100644 --- a/seed/python-sdk/trace/src/seed/core/file.py +++ b/seed/python-sdk/trace/src/seed/core/file.py @@ -13,12 +13,17 @@ # (filename, file (or bytes), content_type) typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str]], # (filename, file (or bytes), content_type, headers) - typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str], typing.Mapping[str, str]], + typing.Tuple[ + typing.Optional[str], + FileContent, + typing.Optional[str], + typing.Mapping[str, str], + ], ] def convert_file_dict_to_httpx_tuples( - d: typing.Dict[str, typing.Union[File, typing.List[File]]] + d: typing.Dict[str, typing.Union[File, typing.List[File]]], ) -> typing.List[typing.Tuple[str, File]]: """ The format we use is a list of tuples, where the first element is the diff --git a/seed/python-sdk/trace/src/seed/core/http_client.py b/seed/python-sdk/trace/src/seed/core/http_client.py index 4e6877df257..ae8a8f0b32e 100644 --- a/seed/python-sdk/trace/src/seed/core/http_client.py +++ b/seed/python-sdk/trace/src/seed/core/http_client.py @@ -70,7 +70,9 @@ def _retry_timeout(response: httpx.Response, retries: int) -> float: return retry_after # Apply exponential backoff, capped at MAX_RETRY_DELAY_SECONDS. - retry_delay = min(INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS) + retry_delay = min( + INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS + ) # Add a randomness / jitter to the retry delay to avoid overwhelming the server with retries. timeout = retry_delay * (1 - 0.25 * random()) @@ -89,18 +91,30 @@ def __init__(self, *, httpx_client: httpx.Client): # Ensure that the signature of the `request` method is the same as the `httpx.Client.request` method @wraps(httpx.Client.request) def request( - self, *args: typing.Any, max_retries: int = 0, retries: int = 0, **kwargs: typing.Any + self, + *args: typing.Any, + max_retries: int = 0, + retries: int = 0, + **kwargs: typing.Any, ) -> httpx.Response: response = self.httpx_client.request(*args, **kwargs) if _should_retry(response=response): if max_retries > retries: time.sleep(_retry_timeout(response=response, retries=retries)) - return self.request(max_retries=max_retries, retries=retries + 1, *args, **kwargs) + return self.request( + max_retries=max_retries, retries=retries + 1, *args, **kwargs + ) return response @wraps(httpx.Client.stream) @contextmanager - def stream(self, *args: typing.Any, max_retries: int = 0, retries: int = 0, **kwargs: typing.Any) -> typing.Any: + def stream( + self, + *args: typing.Any, + max_retries: int = 0, + retries: int = 0, + **kwargs: typing.Any, + ) -> typing.Any: with self.httpx_client.stream(*args, **kwargs) as stream: yield stream @@ -112,19 +126,29 @@ def __init__(self, *, httpx_client: httpx.AsyncClient): # Ensure that the signature of the `request` method is the same as the `httpx.Client.request` method @wraps(httpx.AsyncClient.request) async def request( - self, *args: typing.Any, max_retries: int = 0, retries: int = 0, **kwargs: typing.Any + self, + *args: typing.Any, + max_retries: int = 0, + retries: int = 0, + **kwargs: typing.Any, ) -> httpx.Response: response = await self.httpx_client.request(*args, **kwargs) if _should_retry(response=response): if max_retries > retries: await asyncio.sleep(_retry_timeout(response=response, retries=retries)) - return await self.request(max_retries=max_retries, retries=retries + 1, *args, **kwargs) + return await self.request( + max_retries=max_retries, retries=retries + 1, *args, **kwargs + ) return response @wraps(httpx.AsyncClient.stream) @asynccontextmanager async def stream( - self, *args: typing.Any, max_retries: int = 0, retries: int = 0, **kwargs: typing.Any + self, + *args: typing.Any, + max_retries: int = 0, + retries: int = 0, + **kwargs: typing.Any, ) -> typing.Any: async with self.httpx_client.stream(*args, **kwargs) as stream: yield stream diff --git a/seed/python-sdk/trace/src/seed/core/jsonable_encoder.py b/seed/python-sdk/trace/src/seed/core/jsonable_encoder.py index 7f482732638..a4a3473ed1e 100644 --- a/seed/python-sdk/trace/src/seed/core/jsonable_encoder.py +++ b/seed/python-sdk/trace/src/seed/core/jsonable_encoder.py @@ -24,18 +24,24 @@ def generate_encoders_by_class_tuples( - type_encoder_map: Dict[Any, Callable[[Any], Any]] + type_encoder_map: Dict[Any, Callable[[Any], Any]], ) -> Dict[Callable[[Any], Any], Tuple[Any, ...]]: - encoders_by_class_tuples: Dict[Callable[[Any], Any], Tuple[Any, ...]] = defaultdict(tuple) + encoders_by_class_tuples: Dict[Callable[[Any], Any], Tuple[Any, ...]] = defaultdict( + tuple + ) for type_, encoder in type_encoder_map.items(): encoders_by_class_tuples[encoder] += (type_,) return encoders_by_class_tuples -encoders_by_class_tuples = generate_encoders_by_class_tuples(pydantic_v1.json.ENCODERS_BY_TYPE) +encoders_by_class_tuples = generate_encoders_by_class_tuples( + pydantic_v1.json.ENCODERS_BY_TYPE +) -def jsonable_encoder(obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None) -> Any: +def jsonable_encoder( + obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None +) -> Any: custom_encoder = custom_encoder or {} if custom_encoder: if type(obj) in custom_encoder: diff --git a/seed/python-sdk/trace/src/seed/homepage/client.py b/seed/python-sdk/trace/src/seed/homepage/client.py index 6291f372b32..bea5ef9c224 100644 --- a/seed/python-sdk/trace/src/seed/homepage/client.py +++ b/seed/python-sdk/trace/src/seed/homepage/client.py @@ -37,23 +37,34 @@ def get_homepage_problems( """ _response = self._client_wrapper.httpx_client.request( "GET", - urllib.parse.urljoin(f"{self._client_wrapper.get_base_url()}/", "homepage-problems"), + urllib.parse.urljoin( + f"{self._client_wrapper.get_base_url()}/", "homepage-problems" + ), params=jsonable_encoder( - request_options.get("additional_query_parameters") if request_options is not None else None + request_options.get("additional_query_parameters") + if request_options is not None + else None ), headers=jsonable_encoder( remove_none_from_dict( { **self._client_wrapper.get_headers(), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), timeout=request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self._client_wrapper.get_timeout(), retries=0, - max_retries=request_options.get("max_retries") if request_options is not None else 0, # type: ignore + max_retries=request_options.get("max_retries") + if request_options is not None + else 0, # type: ignore ) try: _response_json = _response.json() @@ -64,7 +75,10 @@ def get_homepage_problems( raise ApiError(status_code=_response.status_code, body=_response_json) def set_homepage_problems( - self, *, request: typing.Sequence[ProblemId], request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Sequence[ProblemId], + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ Parameters: @@ -84,29 +98,47 @@ def set_homepage_problems( """ _response = self._client_wrapper.httpx_client.request( "POST", - urllib.parse.urljoin(f"{self._client_wrapper.get_base_url()}/", "homepage-problems"), + urllib.parse.urljoin( + f"{self._client_wrapper.get_base_url()}/", "homepage-problems" + ), params=jsonable_encoder( - request_options.get("additional_query_parameters") if request_options is not None else None + request_options.get("additional_query_parameters") + if request_options is not None + else None ), json=jsonable_encoder(request) - if request_options is None or request_options.get("additional_body_parameters") is None + if request_options is None + or request_options.get("additional_body_parameters") is None else { **jsonable_encoder(request), - **(jsonable_encoder(remove_none_from_dict(request_options.get("additional_body_parameters", {})))), + **( + jsonable_encoder( + remove_none_from_dict( + request_options.get("additional_body_parameters", {}) + ) + ) + ), }, headers=jsonable_encoder( remove_none_from_dict( { **self._client_wrapper.get_headers(), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), timeout=request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self._client_wrapper.get_timeout(), retries=0, - max_retries=request_options.get("max_retries") if request_options is not None else 0, # type: ignore + max_retries=request_options.get("max_retries") + if request_options is not None + else 0, # type: ignore ) if 200 <= _response.status_code < 300: return @@ -138,23 +170,34 @@ async def get_homepage_problems( """ _response = await self._client_wrapper.httpx_client.request( "GET", - urllib.parse.urljoin(f"{self._client_wrapper.get_base_url()}/", "homepage-problems"), + urllib.parse.urljoin( + f"{self._client_wrapper.get_base_url()}/", "homepage-problems" + ), params=jsonable_encoder( - request_options.get("additional_query_parameters") if request_options is not None else None + request_options.get("additional_query_parameters") + if request_options is not None + else None ), headers=jsonable_encoder( remove_none_from_dict( { **self._client_wrapper.get_headers(), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), timeout=request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self._client_wrapper.get_timeout(), retries=0, - max_retries=request_options.get("max_retries") if request_options is not None else 0, # type: ignore + max_retries=request_options.get("max_retries") + if request_options is not None + else 0, # type: ignore ) try: _response_json = _response.json() @@ -165,7 +208,10 @@ async def get_homepage_problems( raise ApiError(status_code=_response.status_code, body=_response_json) async def set_homepage_problems( - self, *, request: typing.Sequence[ProblemId], request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Sequence[ProblemId], + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ Parameters: @@ -185,29 +231,47 @@ async def set_homepage_problems( """ _response = await self._client_wrapper.httpx_client.request( "POST", - urllib.parse.urljoin(f"{self._client_wrapper.get_base_url()}/", "homepage-problems"), + urllib.parse.urljoin( + f"{self._client_wrapper.get_base_url()}/", "homepage-problems" + ), params=jsonable_encoder( - request_options.get("additional_query_parameters") if request_options is not None else None + request_options.get("additional_query_parameters") + if request_options is not None + else None ), json=jsonable_encoder(request) - if request_options is None or request_options.get("additional_body_parameters") is None + if request_options is None + or request_options.get("additional_body_parameters") is None else { **jsonable_encoder(request), - **(jsonable_encoder(remove_none_from_dict(request_options.get("additional_body_parameters", {})))), + **( + jsonable_encoder( + remove_none_from_dict( + request_options.get("additional_body_parameters", {}) + ) + ) + ), }, headers=jsonable_encoder( remove_none_from_dict( { **self._client_wrapper.get_headers(), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), timeout=request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self._client_wrapper.get_timeout(), retries=0, - max_retries=request_options.get("max_retries") if request_options is not None else 0, # type: ignore + max_retries=request_options.get("max_retries") + if request_options is not None + else 0, # type: ignore ) if 200 <= _response.status_code < 300: return diff --git a/seed/python-sdk/trace/src/seed/lang_server/types/lang_server_request.py b/seed/python-sdk/trace/src/seed/lang_server/types/lang_server_request.py index f743da1968f..0340b90f0cf 100644 --- a/seed/python-sdk/trace/src/seed/lang_server/types/lang_server_request.py +++ b/seed/python-sdk/trace/src/seed/lang_server/types/lang_server_request.py @@ -11,11 +11,19 @@ class LangServerRequest(pydantic_v1.BaseModel): request: typing.Any def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/lang_server/types/lang_server_response.py b/seed/python-sdk/trace/src/seed/lang_server/types/lang_server_response.py index ff59e91e6fa..5b2502b5c9a 100644 --- a/seed/python-sdk/trace/src/seed/lang_server/types/lang_server_response.py +++ b/seed/python-sdk/trace/src/seed/lang_server/types/lang_server_response.py @@ -11,11 +11,19 @@ class LangServerResponse(pydantic_v1.BaseModel): response: typing.Any def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/migration/client.py b/seed/python-sdk/trace/src/seed/migration/client.py index 615a8a6c072..690ec72ac79 100644 --- a/seed/python-sdk/trace/src/seed/migration/client.py +++ b/seed/python-sdk/trace/src/seed/migration/client.py @@ -18,7 +18,10 @@ def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper def get_attempted_migrations( - self, *, admin_key_header: str, request_options: typing.Optional[RequestOptions] = None + self, + *, + admin_key_header: str, + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[Migration]: """ Parameters: @@ -38,24 +41,35 @@ def get_attempted_migrations( """ _response = self._client_wrapper.httpx_client.request( "GET", - urllib.parse.urljoin(f"{self._client_wrapper.get_base_url()}/", "migration-info/all"), + urllib.parse.urljoin( + f"{self._client_wrapper.get_base_url()}/", "migration-info/all" + ), params=jsonable_encoder( - request_options.get("additional_query_parameters") if request_options is not None else None + request_options.get("additional_query_parameters") + if request_options is not None + else None ), headers=jsonable_encoder( remove_none_from_dict( { **self._client_wrapper.get_headers(), "admin-key-header": str(admin_key_header), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), timeout=request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self._client_wrapper.get_timeout(), retries=0, - max_retries=request_options.get("max_retries") if request_options is not None else 0, # type: ignore + max_retries=request_options.get("max_retries") + if request_options is not None + else 0, # type: ignore ) try: _response_json = _response.json() @@ -71,7 +85,10 @@ def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper async def get_attempted_migrations( - self, *, admin_key_header: str, request_options: typing.Optional[RequestOptions] = None + self, + *, + admin_key_header: str, + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[Migration]: """ Parameters: @@ -91,24 +108,35 @@ async def get_attempted_migrations( """ _response = await self._client_wrapper.httpx_client.request( "GET", - urllib.parse.urljoin(f"{self._client_wrapper.get_base_url()}/", "migration-info/all"), + urllib.parse.urljoin( + f"{self._client_wrapper.get_base_url()}/", "migration-info/all" + ), params=jsonable_encoder( - request_options.get("additional_query_parameters") if request_options is not None else None + request_options.get("additional_query_parameters") + if request_options is not None + else None ), headers=jsonable_encoder( remove_none_from_dict( { **self._client_wrapper.get_headers(), "admin-key-header": str(admin_key_header), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), timeout=request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self._client_wrapper.get_timeout(), retries=0, - max_retries=request_options.get("max_retries") if request_options is not None else 0, # type: ignore + max_retries=request_options.get("max_retries") + if request_options is not None + else 0, # type: ignore ) try: _response_json = _response.json() diff --git a/seed/python-sdk/trace/src/seed/migration/types/migration.py b/seed/python-sdk/trace/src/seed/migration/types/migration.py index b30efb81129..9a86c218dfe 100644 --- a/seed/python-sdk/trace/src/seed/migration/types/migration.py +++ b/seed/python-sdk/trace/src/seed/migration/types/migration.py @@ -13,11 +13,19 @@ class Migration(pydantic_v1.BaseModel): status: MigrationStatus def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/migration/types/migration_status.py b/seed/python-sdk/trace/src/seed/migration/types/migration_status.py index c5a2e76b4af..e14e67e1b5a 100644 --- a/seed/python-sdk/trace/src/seed/migration/types/migration_status.py +++ b/seed/python-sdk/trace/src/seed/migration/types/migration_status.py @@ -2,4 +2,6 @@ import typing -MigrationStatus = typing.Union[typing.Literal["RUNNING", "FAILED", "FINISHED"], typing.Any] +MigrationStatus = typing.Union[ + typing.Literal["RUNNING", "FAILED", "FINISHED"], typing.Any +] diff --git a/seed/python-sdk/trace/src/seed/playlist/client.py b/seed/python-sdk/trace/src/seed/playlist/client.py index 32bf7cc9a11..0b04a3ea3a7 100644 --- a/seed/python-sdk/trace/src/seed/playlist/client.py +++ b/seed/python-sdk/trace/src/seed/playlist/client.py @@ -77,7 +77,8 @@ def create_playlist( _response = self._client_wrapper.httpx_client.request( "POST", urllib.parse.urljoin( - f"{self._client_wrapper.get_base_url()}/", f"v2/playlist/{jsonable_encoder(service_param)}/create" + f"{self._client_wrapper.get_base_url()}/", + f"v2/playlist/{jsonable_encoder(service_param)}/create", ), params=jsonable_encoder( remove_none_from_dict( @@ -95,24 +96,38 @@ def create_playlist( ) ), json=jsonable_encoder(request) - if request_options is None or request_options.get("additional_body_parameters") is None + if request_options is None + or request_options.get("additional_body_parameters") is None else { **jsonable_encoder(request), - **(jsonable_encoder(remove_none_from_dict(request_options.get("additional_body_parameters", {})))), + **( + jsonable_encoder( + remove_none_from_dict( + request_options.get("additional_body_parameters", {}) + ) + ) + ), }, headers=jsonable_encoder( remove_none_from_dict( { **self._client_wrapper.get_headers(), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), timeout=request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self._client_wrapper.get_timeout(), retries=0, - max_retries=request_options.get("max_retries") if request_options is not None else 0, # type: ignore + max_retries=request_options.get("max_retries") + if request_options is not None + else 0, # type: ignore ) try: _response_json = _response.json() @@ -129,7 +144,9 @@ def get_playlists( limit: typing.Optional[int] = None, other_field: str, multi_line_docs: str, - optional_multiple_field: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None, + optional_multiple_field: typing.Optional[ + typing.Union[str, typing.Sequence[str]] + ] = None, multiple_field: typing.Union[str, typing.Sequence[str]], request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[Playlist]: @@ -169,7 +186,8 @@ def get_playlists( _response = self._client_wrapper.httpx_client.request( "GET", urllib.parse.urljoin( - f"{self._client_wrapper.get_base_url()}/", f"v2/playlist/{jsonable_encoder(service_param)}/all" + f"{self._client_wrapper.get_base_url()}/", + f"v2/playlist/{jsonable_encoder(service_param)}/all", ), params=jsonable_encoder( remove_none_from_dict( @@ -191,15 +209,22 @@ def get_playlists( remove_none_from_dict( { **self._client_wrapper.get_headers(), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), timeout=request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self._client_wrapper.get_timeout(), retries=0, - max_retries=request_options.get("max_retries") if request_options is not None else 0, # type: ignore + max_retries=request_options.get("max_retries") + if request_options is not None + else 0, # type: ignore ) try: _response_json = _response.json() @@ -210,7 +235,11 @@ def get_playlists( raise ApiError(status_code=_response.status_code, body=_response_json) def get_playlist( - self, service_param: int, playlist_id: PlaylistId, *, request_options: typing.Optional[RequestOptions] = None + self, + service_param: int, + playlist_id: PlaylistId, + *, + request_options: typing.Optional[RequestOptions] = None, ) -> Playlist: """ Returns a playlist @@ -240,21 +269,30 @@ def get_playlist( f"v2/playlist/{jsonable_encoder(service_param)}/{jsonable_encoder(playlist_id)}", ), params=jsonable_encoder( - request_options.get("additional_query_parameters") if request_options is not None else None + request_options.get("additional_query_parameters") + if request_options is not None + else None ), headers=jsonable_encoder( remove_none_from_dict( { **self._client_wrapper.get_headers(), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), timeout=request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self._client_wrapper.get_timeout(), retries=0, - max_retries=request_options.get("max_retries") if request_options is not None else 0, # type: ignore + max_retries=request_options.get("max_retries") + if request_options is not None + else 0, # type: ignore ) try: _response_json = _response.json() @@ -265,7 +303,9 @@ def get_playlist( if "errorName" in _response_json: if _response_json["errorName"] == "PlaylistIdNotFoundError": raise PlaylistIdNotFoundError( - pydantic_v1.parse_obj_as(PlaylistIdNotFoundErrorBody, _response_json["content"]) # type: ignore + pydantic_v1.parse_obj_as( + PlaylistIdNotFoundErrorBody, _response_json["content"] + ) # type: ignore ) if _response_json["errorName"] == "UnauthorizedError": raise UnauthorizedError() @@ -314,27 +354,43 @@ def update_playlist( f"v2/playlist/{jsonable_encoder(service_param)}/{jsonable_encoder(playlist_id)}", ), params=jsonable_encoder( - request_options.get("additional_query_parameters") if request_options is not None else None + request_options.get("additional_query_parameters") + if request_options is not None + else None ), json=jsonable_encoder(request) - if request_options is None or request_options.get("additional_body_parameters") is None + if request_options is None + or request_options.get("additional_body_parameters") is None else { **jsonable_encoder(request), - **(jsonable_encoder(remove_none_from_dict(request_options.get("additional_body_parameters", {})))), + **( + jsonable_encoder( + remove_none_from_dict( + request_options.get("additional_body_parameters", {}) + ) + ) + ), }, headers=jsonable_encoder( remove_none_from_dict( { **self._client_wrapper.get_headers(), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), timeout=request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self._client_wrapper.get_timeout(), retries=0, - max_retries=request_options.get("max_retries") if request_options is not None else 0, # type: ignore + max_retries=request_options.get("max_retries") + if request_options is not None + else 0, # type: ignore ) try: _response_json = _response.json() @@ -345,12 +401,18 @@ def update_playlist( if "errorName" in _response_json: if _response_json["errorName"] == "PlaylistIdNotFoundError": raise PlaylistIdNotFoundError( - pydantic_v1.parse_obj_as(PlaylistIdNotFoundErrorBody, _response_json["content"]) # type: ignore + pydantic_v1.parse_obj_as( + PlaylistIdNotFoundErrorBody, _response_json["content"] + ) # type: ignore ) raise ApiError(status_code=_response.status_code, body=_response_json) def delete_playlist( - self, service_param: int, playlist_id: PlaylistId, *, request_options: typing.Optional[RequestOptions] = None + self, + service_param: int, + playlist_id: PlaylistId, + *, + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ Deletes a playlist @@ -380,21 +442,30 @@ def delete_playlist( f"v2/playlist/{jsonable_encoder(service_param)}/{jsonable_encoder(playlist_id)}", ), params=jsonable_encoder( - request_options.get("additional_query_parameters") if request_options is not None else None + request_options.get("additional_query_parameters") + if request_options is not None + else None ), headers=jsonable_encoder( remove_none_from_dict( { **self._client_wrapper.get_headers(), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), timeout=request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self._client_wrapper.get_timeout(), retries=0, - max_retries=request_options.get("max_retries") if request_options is not None else 0, # type: ignore + max_retries=request_options.get("max_retries") + if request_options is not None + else 0, # type: ignore ) if 200 <= _response.status_code < 300: return @@ -458,7 +529,8 @@ async def create_playlist( _response = await self._client_wrapper.httpx_client.request( "POST", urllib.parse.urljoin( - f"{self._client_wrapper.get_base_url()}/", f"v2/playlist/{jsonable_encoder(service_param)}/create" + f"{self._client_wrapper.get_base_url()}/", + f"v2/playlist/{jsonable_encoder(service_param)}/create", ), params=jsonable_encoder( remove_none_from_dict( @@ -476,24 +548,38 @@ async def create_playlist( ) ), json=jsonable_encoder(request) - if request_options is None or request_options.get("additional_body_parameters") is None + if request_options is None + or request_options.get("additional_body_parameters") is None else { **jsonable_encoder(request), - **(jsonable_encoder(remove_none_from_dict(request_options.get("additional_body_parameters", {})))), + **( + jsonable_encoder( + remove_none_from_dict( + request_options.get("additional_body_parameters", {}) + ) + ) + ), }, headers=jsonable_encoder( remove_none_from_dict( { **self._client_wrapper.get_headers(), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), timeout=request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self._client_wrapper.get_timeout(), retries=0, - max_retries=request_options.get("max_retries") if request_options is not None else 0, # type: ignore + max_retries=request_options.get("max_retries") + if request_options is not None + else 0, # type: ignore ) try: _response_json = _response.json() @@ -510,7 +596,9 @@ async def get_playlists( limit: typing.Optional[int] = None, other_field: str, multi_line_docs: str, - optional_multiple_field: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None, + optional_multiple_field: typing.Optional[ + typing.Union[str, typing.Sequence[str]] + ] = None, multiple_field: typing.Union[str, typing.Sequence[str]], request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[Playlist]: @@ -550,7 +638,8 @@ async def get_playlists( _response = await self._client_wrapper.httpx_client.request( "GET", urllib.parse.urljoin( - f"{self._client_wrapper.get_base_url()}/", f"v2/playlist/{jsonable_encoder(service_param)}/all" + f"{self._client_wrapper.get_base_url()}/", + f"v2/playlist/{jsonable_encoder(service_param)}/all", ), params=jsonable_encoder( remove_none_from_dict( @@ -572,15 +661,22 @@ async def get_playlists( remove_none_from_dict( { **self._client_wrapper.get_headers(), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), timeout=request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self._client_wrapper.get_timeout(), retries=0, - max_retries=request_options.get("max_retries") if request_options is not None else 0, # type: ignore + max_retries=request_options.get("max_retries") + if request_options is not None + else 0, # type: ignore ) try: _response_json = _response.json() @@ -591,7 +687,11 @@ async def get_playlists( raise ApiError(status_code=_response.status_code, body=_response_json) async def get_playlist( - self, service_param: int, playlist_id: PlaylistId, *, request_options: typing.Optional[RequestOptions] = None + self, + service_param: int, + playlist_id: PlaylistId, + *, + request_options: typing.Optional[RequestOptions] = None, ) -> Playlist: """ Returns a playlist @@ -621,21 +721,30 @@ async def get_playlist( f"v2/playlist/{jsonable_encoder(service_param)}/{jsonable_encoder(playlist_id)}", ), params=jsonable_encoder( - request_options.get("additional_query_parameters") if request_options is not None else None + request_options.get("additional_query_parameters") + if request_options is not None + else None ), headers=jsonable_encoder( remove_none_from_dict( { **self._client_wrapper.get_headers(), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), timeout=request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self._client_wrapper.get_timeout(), retries=0, - max_retries=request_options.get("max_retries") if request_options is not None else 0, # type: ignore + max_retries=request_options.get("max_retries") + if request_options is not None + else 0, # type: ignore ) try: _response_json = _response.json() @@ -646,7 +755,9 @@ async def get_playlist( if "errorName" in _response_json: if _response_json["errorName"] == "PlaylistIdNotFoundError": raise PlaylistIdNotFoundError( - pydantic_v1.parse_obj_as(PlaylistIdNotFoundErrorBody, _response_json["content"]) # type: ignore + pydantic_v1.parse_obj_as( + PlaylistIdNotFoundErrorBody, _response_json["content"] + ) # type: ignore ) if _response_json["errorName"] == "UnauthorizedError": raise UnauthorizedError() @@ -695,27 +806,43 @@ async def update_playlist( f"v2/playlist/{jsonable_encoder(service_param)}/{jsonable_encoder(playlist_id)}", ), params=jsonable_encoder( - request_options.get("additional_query_parameters") if request_options is not None else None + request_options.get("additional_query_parameters") + if request_options is not None + else None ), json=jsonable_encoder(request) - if request_options is None or request_options.get("additional_body_parameters") is None + if request_options is None + or request_options.get("additional_body_parameters") is None else { **jsonable_encoder(request), - **(jsonable_encoder(remove_none_from_dict(request_options.get("additional_body_parameters", {})))), + **( + jsonable_encoder( + remove_none_from_dict( + request_options.get("additional_body_parameters", {}) + ) + ) + ), }, headers=jsonable_encoder( remove_none_from_dict( { **self._client_wrapper.get_headers(), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), timeout=request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self._client_wrapper.get_timeout(), retries=0, - max_retries=request_options.get("max_retries") if request_options is not None else 0, # type: ignore + max_retries=request_options.get("max_retries") + if request_options is not None + else 0, # type: ignore ) try: _response_json = _response.json() @@ -726,12 +853,18 @@ async def update_playlist( if "errorName" in _response_json: if _response_json["errorName"] == "PlaylistIdNotFoundError": raise PlaylistIdNotFoundError( - pydantic_v1.parse_obj_as(PlaylistIdNotFoundErrorBody, _response_json["content"]) # type: ignore + pydantic_v1.parse_obj_as( + PlaylistIdNotFoundErrorBody, _response_json["content"] + ) # type: ignore ) raise ApiError(status_code=_response.status_code, body=_response_json) async def delete_playlist( - self, service_param: int, playlist_id: PlaylistId, *, request_options: typing.Optional[RequestOptions] = None + self, + service_param: int, + playlist_id: PlaylistId, + *, + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ Deletes a playlist @@ -761,21 +894,30 @@ async def delete_playlist( f"v2/playlist/{jsonable_encoder(service_param)}/{jsonable_encoder(playlist_id)}", ), params=jsonable_encoder( - request_options.get("additional_query_parameters") if request_options is not None else None + request_options.get("additional_query_parameters") + if request_options is not None + else None ), headers=jsonable_encoder( remove_none_from_dict( { **self._client_wrapper.get_headers(), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), timeout=request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self._client_wrapper.get_timeout(), retries=0, - max_retries=request_options.get("max_retries") if request_options is not None else 0, # type: ignore + max_retries=request_options.get("max_retries") + if request_options is not None + else 0, # type: ignore ) if 200 <= _response.status_code < 300: return diff --git a/seed/python-sdk/trace/src/seed/playlist/types/__init__.py b/seed/python-sdk/trace/src/seed/playlist/types/__init__.py index d4667234a8a..93239244d73 100644 --- a/seed/python-sdk/trace/src/seed/playlist/types/__init__.py +++ b/seed/python-sdk/trace/src/seed/playlist/types/__init__.py @@ -3,7 +3,10 @@ from .playlist import Playlist from .playlist_create_request import PlaylistCreateRequest from .playlist_id import PlaylistId -from .playlist_id_not_found_error_body import PlaylistIdNotFoundErrorBody, PlaylistIdNotFoundErrorBody_PlaylistId +from .playlist_id_not_found_error_body import ( + PlaylistIdNotFoundErrorBody, + PlaylistIdNotFoundErrorBody_PlaylistId, +) from .reserved_keyword_enum import ReservedKeywordEnum from .update_playlist_request import UpdatePlaylistRequest diff --git a/seed/python-sdk/trace/src/seed/playlist/types/playlist.py b/seed/python-sdk/trace/src/seed/playlist/types/playlist.py index 507ff9aac8c..dffb342a045 100644 --- a/seed/python-sdk/trace/src/seed/playlist/types/playlist.py +++ b/seed/python-sdk/trace/src/seed/playlist/types/playlist.py @@ -15,11 +15,19 @@ class Playlist(PlaylistCreateRequest): owner_id: UserId = pydantic_v1.Field(alias="owner-id") def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/playlist/types/playlist_create_request.py b/seed/python-sdk/trace/src/seed/playlist/types/playlist_create_request.py index 0d8fef82c0e..68021ce8f36 100644 --- a/seed/python-sdk/trace/src/seed/playlist/types/playlist_create_request.py +++ b/seed/python-sdk/trace/src/seed/playlist/types/playlist_create_request.py @@ -13,11 +13,19 @@ class PlaylistCreateRequest(pydantic_v1.BaseModel): problems: typing.List[ProblemId] def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/playlist/types/update_playlist_request.py b/seed/python-sdk/trace/src/seed/playlist/types/update_playlist_request.py index efeb097f434..8be504a7b25 100644 --- a/seed/python-sdk/trace/src/seed/playlist/types/update_playlist_request.py +++ b/seed/python-sdk/trace/src/seed/playlist/types/update_playlist_request.py @@ -16,11 +16,19 @@ class UpdatePlaylistRequest(pydantic_v1.BaseModel): """ def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/problem/client.py b/seed/python-sdk/trace/src/seed/problem/client.py index 89eb915b707..19f6ef17c81 100644 --- a/seed/python-sdk/trace/src/seed/problem/client.py +++ b/seed/python-sdk/trace/src/seed/problem/client.py @@ -27,7 +27,10 @@ def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper def create_problem( - self, *, request: CreateProblemRequest, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: CreateProblemRequest, + request_options: typing.Optional[RequestOptions] = None, ) -> CreateProblemResponse: """ Creates a problem @@ -97,29 +100,47 @@ def create_problem( """ _response = self._client_wrapper.httpx_client.request( "POST", - urllib.parse.urljoin(f"{self._client_wrapper.get_base_url()}/", "problem-crud/create"), + urllib.parse.urljoin( + f"{self._client_wrapper.get_base_url()}/", "problem-crud/create" + ), params=jsonable_encoder( - request_options.get("additional_query_parameters") if request_options is not None else None + request_options.get("additional_query_parameters") + if request_options is not None + else None ), json=jsonable_encoder(request) - if request_options is None or request_options.get("additional_body_parameters") is None + if request_options is None + or request_options.get("additional_body_parameters") is None else { **jsonable_encoder(request), - **(jsonable_encoder(remove_none_from_dict(request_options.get("additional_body_parameters", {})))), + **( + jsonable_encoder( + remove_none_from_dict( + request_options.get("additional_body_parameters", {}) + ) + ) + ), }, headers=jsonable_encoder( remove_none_from_dict( { **self._client_wrapper.get_headers(), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), timeout=request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self._client_wrapper.get_timeout(), retries=0, - max_retries=request_options.get("max_retries") if request_options is not None else 0, # type: ignore + max_retries=request_options.get("max_retries") + if request_options is not None + else 0, # type: ignore ) try: _response_json = _response.json() @@ -208,30 +229,47 @@ def update_problem( _response = self._client_wrapper.httpx_client.request( "POST", urllib.parse.urljoin( - f"{self._client_wrapper.get_base_url()}/", f"problem-crud/update/{jsonable_encoder(problem_id)}" + f"{self._client_wrapper.get_base_url()}/", + f"problem-crud/update/{jsonable_encoder(problem_id)}", ), params=jsonable_encoder( - request_options.get("additional_query_parameters") if request_options is not None else None + request_options.get("additional_query_parameters") + if request_options is not None + else None ), json=jsonable_encoder(request) - if request_options is None or request_options.get("additional_body_parameters") is None + if request_options is None + or request_options.get("additional_body_parameters") is None else { **jsonable_encoder(request), - **(jsonable_encoder(remove_none_from_dict(request_options.get("additional_body_parameters", {})))), + **( + jsonable_encoder( + remove_none_from_dict( + request_options.get("additional_body_parameters", {}) + ) + ) + ), }, headers=jsonable_encoder( remove_none_from_dict( { **self._client_wrapper.get_headers(), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), timeout=request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self._client_wrapper.get_timeout(), retries=0, - max_retries=request_options.get("max_retries") if request_options is not None else 0, # type: ignore + max_retries=request_options.get("max_retries") + if request_options is not None + else 0, # type: ignore ) try: _response_json = _response.json() @@ -241,7 +279,12 @@ def update_problem( return pydantic_v1.parse_obj_as(UpdateProblemResponse, _response_json) # type: ignore raise ApiError(status_code=_response.status_code, body=_response_json) - def delete_problem(self, problem_id: ProblemId, *, request_options: typing.Optional[RequestOptions] = None) -> None: + def delete_problem( + self, + problem_id: ProblemId, + *, + request_options: typing.Optional[RequestOptions] = None, + ) -> None: """ Soft deletes a problem @@ -263,24 +306,34 @@ def delete_problem(self, problem_id: ProblemId, *, request_options: typing.Optio _response = self._client_wrapper.httpx_client.request( "DELETE", urllib.parse.urljoin( - f"{self._client_wrapper.get_base_url()}/", f"problem-crud/delete/{jsonable_encoder(problem_id)}" + f"{self._client_wrapper.get_base_url()}/", + f"problem-crud/delete/{jsonable_encoder(problem_id)}", ), params=jsonable_encoder( - request_options.get("additional_query_parameters") if request_options is not None else None + request_options.get("additional_query_parameters") + if request_options is not None + else None ), headers=jsonable_encoder( remove_none_from_dict( { **self._client_wrapper.get_headers(), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), timeout=request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self._client_wrapper.get_timeout(), retries=0, - max_retries=request_options.get("max_retries") if request_options is not None else 0, # type: ignore + max_retries=request_options.get("max_retries") + if request_options is not None + else 0, # type: ignore ) if 200 <= _response.status_code < 300: return @@ -335,36 +388,69 @@ def get_default_starter_files( """ _response = self._client_wrapper.httpx_client.request( "POST", - urllib.parse.urljoin(f"{self._client_wrapper.get_base_url()}/", "problem-crud/default-starter-files"), + urllib.parse.urljoin( + f"{self._client_wrapper.get_base_url()}/", + "problem-crud/default-starter-files", + ), params=jsonable_encoder( - request_options.get("additional_query_parameters") if request_options is not None else None + request_options.get("additional_query_parameters") + if request_options is not None + else None ), - json=jsonable_encoder({"inputParams": input_params, "outputType": output_type, "methodName": method_name}) - if request_options is None or request_options.get("additional_body_parameters") is None + json=jsonable_encoder( + { + "inputParams": input_params, + "outputType": output_type, + "methodName": method_name, + } + ) + if request_options is None + or request_options.get("additional_body_parameters") is None else { - **jsonable_encoder({"inputParams": input_params, "outputType": output_type, "methodName": method_name}), - **(jsonable_encoder(remove_none_from_dict(request_options.get("additional_body_parameters", {})))), + **jsonable_encoder( + { + "inputParams": input_params, + "outputType": output_type, + "methodName": method_name, + } + ), + **( + jsonable_encoder( + remove_none_from_dict( + request_options.get("additional_body_parameters", {}) + ) + ) + ), }, headers=jsonable_encoder( remove_none_from_dict( { **self._client_wrapper.get_headers(), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), timeout=request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self._client_wrapper.get_timeout(), retries=0, - max_retries=request_options.get("max_retries") if request_options is not None else 0, # type: ignore + max_retries=request_options.get("max_retries") + if request_options is not None + else 0, # type: ignore ) try: _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) if 200 <= _response.status_code < 300: - return pydantic_v1.parse_obj_as(GetDefaultStarterFilesResponse, _response_json) # type: ignore + return pydantic_v1.parse_obj_as( + GetDefaultStarterFilesResponse, _response_json + ) # type: ignore raise ApiError(status_code=_response.status_code, body=_response_json) @@ -373,7 +459,10 @@ def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper async def create_problem( - self, *, request: CreateProblemRequest, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: CreateProblemRequest, + request_options: typing.Optional[RequestOptions] = None, ) -> CreateProblemResponse: """ Creates a problem @@ -443,29 +532,47 @@ async def create_problem( """ _response = await self._client_wrapper.httpx_client.request( "POST", - urllib.parse.urljoin(f"{self._client_wrapper.get_base_url()}/", "problem-crud/create"), + urllib.parse.urljoin( + f"{self._client_wrapper.get_base_url()}/", "problem-crud/create" + ), params=jsonable_encoder( - request_options.get("additional_query_parameters") if request_options is not None else None + request_options.get("additional_query_parameters") + if request_options is not None + else None ), json=jsonable_encoder(request) - if request_options is None or request_options.get("additional_body_parameters") is None + if request_options is None + or request_options.get("additional_body_parameters") is None else { **jsonable_encoder(request), - **(jsonable_encoder(remove_none_from_dict(request_options.get("additional_body_parameters", {})))), + **( + jsonable_encoder( + remove_none_from_dict( + request_options.get("additional_body_parameters", {}) + ) + ) + ), }, headers=jsonable_encoder( remove_none_from_dict( { **self._client_wrapper.get_headers(), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), timeout=request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self._client_wrapper.get_timeout(), retries=0, - max_retries=request_options.get("max_retries") if request_options is not None else 0, # type: ignore + max_retries=request_options.get("max_retries") + if request_options is not None + else 0, # type: ignore ) try: _response_json = _response.json() @@ -554,30 +661,47 @@ async def update_problem( _response = await self._client_wrapper.httpx_client.request( "POST", urllib.parse.urljoin( - f"{self._client_wrapper.get_base_url()}/", f"problem-crud/update/{jsonable_encoder(problem_id)}" + f"{self._client_wrapper.get_base_url()}/", + f"problem-crud/update/{jsonable_encoder(problem_id)}", ), params=jsonable_encoder( - request_options.get("additional_query_parameters") if request_options is not None else None + request_options.get("additional_query_parameters") + if request_options is not None + else None ), json=jsonable_encoder(request) - if request_options is None or request_options.get("additional_body_parameters") is None + if request_options is None + or request_options.get("additional_body_parameters") is None else { **jsonable_encoder(request), - **(jsonable_encoder(remove_none_from_dict(request_options.get("additional_body_parameters", {})))), + **( + jsonable_encoder( + remove_none_from_dict( + request_options.get("additional_body_parameters", {}) + ) + ) + ), }, headers=jsonable_encoder( remove_none_from_dict( { **self._client_wrapper.get_headers(), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), timeout=request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self._client_wrapper.get_timeout(), retries=0, - max_retries=request_options.get("max_retries") if request_options is not None else 0, # type: ignore + max_retries=request_options.get("max_retries") + if request_options is not None + else 0, # type: ignore ) try: _response_json = _response.json() @@ -588,7 +712,10 @@ async def update_problem( raise ApiError(status_code=_response.status_code, body=_response_json) async def delete_problem( - self, problem_id: ProblemId, *, request_options: typing.Optional[RequestOptions] = None + self, + problem_id: ProblemId, + *, + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ Soft deletes a problem @@ -611,24 +738,34 @@ async def delete_problem( _response = await self._client_wrapper.httpx_client.request( "DELETE", urllib.parse.urljoin( - f"{self._client_wrapper.get_base_url()}/", f"problem-crud/delete/{jsonable_encoder(problem_id)}" + f"{self._client_wrapper.get_base_url()}/", + f"problem-crud/delete/{jsonable_encoder(problem_id)}", ), params=jsonable_encoder( - request_options.get("additional_query_parameters") if request_options is not None else None + request_options.get("additional_query_parameters") + if request_options is not None + else None ), headers=jsonable_encoder( remove_none_from_dict( { **self._client_wrapper.get_headers(), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), timeout=request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self._client_wrapper.get_timeout(), retries=0, - max_retries=request_options.get("max_retries") if request_options is not None else 0, # type: ignore + max_retries=request_options.get("max_retries") + if request_options is not None + else 0, # type: ignore ) if 200 <= _response.status_code < 300: return @@ -683,34 +820,67 @@ async def get_default_starter_files( """ _response = await self._client_wrapper.httpx_client.request( "POST", - urllib.parse.urljoin(f"{self._client_wrapper.get_base_url()}/", "problem-crud/default-starter-files"), + urllib.parse.urljoin( + f"{self._client_wrapper.get_base_url()}/", + "problem-crud/default-starter-files", + ), params=jsonable_encoder( - request_options.get("additional_query_parameters") if request_options is not None else None + request_options.get("additional_query_parameters") + if request_options is not None + else None ), - json=jsonable_encoder({"inputParams": input_params, "outputType": output_type, "methodName": method_name}) - if request_options is None or request_options.get("additional_body_parameters") is None + json=jsonable_encoder( + { + "inputParams": input_params, + "outputType": output_type, + "methodName": method_name, + } + ) + if request_options is None + or request_options.get("additional_body_parameters") is None else { - **jsonable_encoder({"inputParams": input_params, "outputType": output_type, "methodName": method_name}), - **(jsonable_encoder(remove_none_from_dict(request_options.get("additional_body_parameters", {})))), + **jsonable_encoder( + { + "inputParams": input_params, + "outputType": output_type, + "methodName": method_name, + } + ), + **( + jsonable_encoder( + remove_none_from_dict( + request_options.get("additional_body_parameters", {}) + ) + ) + ), }, headers=jsonable_encoder( remove_none_from_dict( { **self._client_wrapper.get_headers(), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), timeout=request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self._client_wrapper.get_timeout(), retries=0, - max_retries=request_options.get("max_retries") if request_options is not None else 0, # type: ignore + max_retries=request_options.get("max_retries") + if request_options is not None + else 0, # type: ignore ) try: _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) if 200 <= _response.status_code < 300: - return pydantic_v1.parse_obj_as(GetDefaultStarterFilesResponse, _response_json) # type: ignore + return pydantic_v1.parse_obj_as( + GetDefaultStarterFilesResponse, _response_json + ) # type: ignore raise ApiError(status_code=_response.status_code, body=_response_json) diff --git a/seed/python-sdk/trace/src/seed/problem/types/__init__.py b/seed/python-sdk/trace/src/seed/problem/types/__init__.py index 35e2b592b37..c1dc58af5a4 100644 --- a/seed/python-sdk/trace/src/seed/problem/types/__init__.py +++ b/seed/python-sdk/trace/src/seed/problem/types/__init__.py @@ -2,7 +2,11 @@ from .create_problem_error import CreateProblemError, CreateProblemError_Generic from .create_problem_request import CreateProblemRequest -from .create_problem_response import CreateProblemResponse, CreateProblemResponse_Error, CreateProblemResponse_Success +from .create_problem_response import ( + CreateProblemResponse, + CreateProblemResponse_Error, + CreateProblemResponse_Success, +) from .generic_create_problem_error import GenericCreateProblemError from .get_default_starter_files_response import GetDefaultStarterFilesResponse from .problem_description import ProblemDescription diff --git a/seed/python-sdk/trace/src/seed/problem/types/create_problem_error.py b/seed/python-sdk/trace/src/seed/problem/types/create_problem_error.py index 76b97e460a9..1c8465bf3be 100644 --- a/seed/python-sdk/trace/src/seed/problem/types/create_problem_error.py +++ b/seed/python-sdk/trace/src/seed/problem/types/create_problem_error.py @@ -9,7 +9,9 @@ class CreateProblemError_Generic(GenericCreateProblemError): - error_type: typing.Literal["generic"] = pydantic_v1.Field(alias="_type", default="generic") + error_type: typing.Literal["generic"] = pydantic_v1.Field( + alias="_type", default="generic" + ) class Config: frozen = True diff --git a/seed/python-sdk/trace/src/seed/problem/types/create_problem_request.py b/seed/python-sdk/trace/src/seed/problem/types/create_problem_request.py index 317106e9da5..949cd5e9ff5 100644 --- a/seed/python-sdk/trace/src/seed/problem/types/create_problem_request.py +++ b/seed/python-sdk/trace/src/seed/problem/types/create_problem_request.py @@ -15,19 +15,31 @@ class CreateProblemRequest(pydantic_v1.BaseModel): problem_name: str = pydantic_v1.Field(alias="problemName") - problem_description: ProblemDescription = pydantic_v1.Field(alias="problemDescription") + problem_description: ProblemDescription = pydantic_v1.Field( + alias="problemDescription" + ) files: typing.Dict[Language, ProblemFiles] - input_params: typing.List[VariableTypeAndName] = pydantic_v1.Field(alias="inputParams") + input_params: typing.List[VariableTypeAndName] = pydantic_v1.Field( + alias="inputParams" + ) output_type: VariableType = pydantic_v1.Field(alias="outputType") testcases: typing.List[TestCaseWithExpectedResult] method_name: str = pydantic_v1.Field(alias="methodName") def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/problem/types/create_problem_response.py b/seed/python-sdk/trace/src/seed/problem/types/create_problem_response.py index 7ee134c03aa..5d588c0ca31 100644 --- a/seed/python-sdk/trace/src/seed/problem/types/create_problem_response.py +++ b/seed/python-sdk/trace/src/seed/problem/types/create_problem_response.py @@ -27,4 +27,6 @@ class Config: smart_union = True -CreateProblemResponse = typing.Union[CreateProblemResponse_Success, CreateProblemResponse_Error] +CreateProblemResponse = typing.Union[ + CreateProblemResponse_Success, CreateProblemResponse_Error +] diff --git a/seed/python-sdk/trace/src/seed/problem/types/generic_create_problem_error.py b/seed/python-sdk/trace/src/seed/problem/types/generic_create_problem_error.py index 58c87664e39..ab489f30818 100644 --- a/seed/python-sdk/trace/src/seed/problem/types/generic_create_problem_error.py +++ b/seed/python-sdk/trace/src/seed/problem/types/generic_create_problem_error.py @@ -13,11 +13,19 @@ class GenericCreateProblemError(pydantic_v1.BaseModel): stacktrace: str def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/problem/types/get_default_starter_files_response.py b/seed/python-sdk/trace/src/seed/problem/types/get_default_starter_files_response.py index c353077f1aa..8458d525133 100644 --- a/seed/python-sdk/trace/src/seed/problem/types/get_default_starter_files_response.py +++ b/seed/python-sdk/trace/src/seed/problem/types/get_default_starter_files_response.py @@ -13,11 +13,19 @@ class GetDefaultStarterFilesResponse(pydantic_v1.BaseModel): files: typing.Dict[Language, ProblemFiles] def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/problem/types/problem_description.py b/seed/python-sdk/trace/src/seed/problem/types/problem_description.py index 36c67eac2d3..3962222f946 100644 --- a/seed/python-sdk/trace/src/seed/problem/types/problem_description.py +++ b/seed/python-sdk/trace/src/seed/problem/types/problem_description.py @@ -12,11 +12,19 @@ class ProblemDescription(pydantic_v1.BaseModel): boards: typing.List[ProblemDescriptionBoard] def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/problem/types/problem_description_board.py b/seed/python-sdk/trace/src/seed/problem/types/problem_description_board.py index d2c20c22f8d..b3ffbc39830 100644 --- a/seed/python-sdk/trace/src/seed/problem/types/problem_description_board.py +++ b/seed/python-sdk/trace/src/seed/problem/types/problem_description_board.py @@ -35,6 +35,8 @@ class Config: ProblemDescriptionBoard = typing.Union[ - ProblemDescriptionBoard_Html, ProblemDescriptionBoard_Variable, ProblemDescriptionBoard_TestCaseId + ProblemDescriptionBoard_Html, + ProblemDescriptionBoard_Variable, + ProblemDescriptionBoard_TestCaseId, ] from ...commons.types.variable_value import VariableValue # noqa: E402 diff --git a/seed/python-sdk/trace/src/seed/problem/types/problem_files.py b/seed/python-sdk/trace/src/seed/problem/types/problem_files.py index 8aa6621c7c6..031c8629e4d 100644 --- a/seed/python-sdk/trace/src/seed/problem/types/problem_files.py +++ b/seed/python-sdk/trace/src/seed/problem/types/problem_files.py @@ -13,11 +13,19 @@ class ProblemFiles(pydantic_v1.BaseModel): read_only_files: typing.List[FileInfo] = pydantic_v1.Field(alias="readOnlyFiles") def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/problem/types/problem_info.py b/seed/python-sdk/trace/src/seed/problem/types/problem_info.py index fadcf584299..cce65ae0805 100644 --- a/seed/python-sdk/trace/src/seed/problem/types/problem_info.py +++ b/seed/python-sdk/trace/src/seed/problem/types/problem_info.py @@ -16,22 +16,36 @@ class ProblemInfo(pydantic_v1.BaseModel): problem_id: ProblemId = pydantic_v1.Field(alias="problemId") - problem_description: ProblemDescription = pydantic_v1.Field(alias="problemDescription") + problem_description: ProblemDescription = pydantic_v1.Field( + alias="problemDescription" + ) problem_name: str = pydantic_v1.Field(alias="problemName") problem_version: int = pydantic_v1.Field(alias="problemVersion") files: typing.Dict[Language, ProblemFiles] - input_params: typing.List[VariableTypeAndName] = pydantic_v1.Field(alias="inputParams") + input_params: typing.List[VariableTypeAndName] = pydantic_v1.Field( + alias="inputParams" + ) output_type: VariableType = pydantic_v1.Field(alias="outputType") testcases: typing.List[TestCaseWithExpectedResult] method_name: str = pydantic_v1.Field(alias="methodName") - supports_custom_test_cases: bool = pydantic_v1.Field(alias="supportsCustomTestCases") + supports_custom_test_cases: bool = pydantic_v1.Field( + alias="supportsCustomTestCases" + ) def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/problem/types/update_problem_response.py b/seed/python-sdk/trace/src/seed/problem/types/update_problem_response.py index b5e55bfe40e..013b9c2fecf 100644 --- a/seed/python-sdk/trace/src/seed/problem/types/update_problem_response.py +++ b/seed/python-sdk/trace/src/seed/problem/types/update_problem_response.py @@ -11,11 +11,19 @@ class UpdateProblemResponse(pydantic_v1.BaseModel): problem_version: int = pydantic_v1.Field(alias="problemVersion") def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/problem/types/variable_type_and_name.py b/seed/python-sdk/trace/src/seed/problem/types/variable_type_and_name.py index 32c2c37e302..65f998a4b79 100644 --- a/seed/python-sdk/trace/src/seed/problem/types/variable_type_and_name.py +++ b/seed/python-sdk/trace/src/seed/problem/types/variable_type_and_name.py @@ -13,11 +13,19 @@ class VariableTypeAndName(pydantic_v1.BaseModel): name: str def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/submission/client.py b/seed/python-sdk/trace/src/seed/submission/client.py index e8aa8d813dc..6a8ac0d6f90 100644 --- a/seed/python-sdk/trace/src/seed/submission/client.py +++ b/seed/python-sdk/trace/src/seed/submission/client.py @@ -20,7 +20,10 @@ def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper def create_execution_session( - self, language: Language, *, request_options: typing.Optional[RequestOptions] = None + self, + language: Language, + *, + request_options: typing.Optional[RequestOptions] = None, ) -> ExecutionSessionResponse: """ Returns sessionId and execution server URL for session. Spins up server. @@ -43,27 +46,41 @@ def create_execution_session( _response = self._client_wrapper.httpx_client.request( "POST", urllib.parse.urljoin( - f"{self._client_wrapper.get_base_url()}/", f"sessions/create-session/{jsonable_encoder(language)}" + f"{self._client_wrapper.get_base_url()}/", + f"sessions/create-session/{jsonable_encoder(language)}", ), params=jsonable_encoder( - request_options.get("additional_query_parameters") if request_options is not None else None + request_options.get("additional_query_parameters") + if request_options is not None + else None ), - json=jsonable_encoder(remove_none_from_dict(request_options.get("additional_body_parameters", {}))) + json=jsonable_encoder( + remove_none_from_dict( + request_options.get("additional_body_parameters", {}) + ) + ) if request_options is not None else None, headers=jsonable_encoder( remove_none_from_dict( { **self._client_wrapper.get_headers(), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), timeout=request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self._client_wrapper.get_timeout(), retries=0, - max_retries=request_options.get("max_retries") if request_options is not None else 0, # type: ignore + max_retries=request_options.get("max_retries") + if request_options is not None + else 0, # type: ignore ) try: _response_json = _response.json() @@ -74,7 +91,10 @@ def create_execution_session( raise ApiError(status_code=_response.status_code, body=_response_json) def get_execution_session( - self, session_id: str, *, request_options: typing.Optional[RequestOptions] = None + self, + session_id: str, + *, + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Optional[ExecutionSessionResponse]: """ Returns execution server URL for session. Returns empty if session isn't registered. @@ -96,34 +116,51 @@ def get_execution_session( """ _response = self._client_wrapper.httpx_client.request( "GET", - urllib.parse.urljoin(f"{self._client_wrapper.get_base_url()}/", f"sessions/{jsonable_encoder(session_id)}"), + urllib.parse.urljoin( + f"{self._client_wrapper.get_base_url()}/", + f"sessions/{jsonable_encoder(session_id)}", + ), params=jsonable_encoder( - request_options.get("additional_query_parameters") if request_options is not None else None + request_options.get("additional_query_parameters") + if request_options is not None + else None ), headers=jsonable_encoder( remove_none_from_dict( { **self._client_wrapper.get_headers(), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), timeout=request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self._client_wrapper.get_timeout(), retries=0, - max_retries=request_options.get("max_retries") if request_options is not None else 0, # type: ignore + max_retries=request_options.get("max_retries") + if request_options is not None + else 0, # type: ignore ) try: _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) if 200 <= _response.status_code < 300: - return pydantic_v1.parse_obj_as(typing.Optional[ExecutionSessionResponse], _response_json) # type: ignore + return pydantic_v1.parse_obj_as( + typing.Optional[ExecutionSessionResponse], _response_json + ) # type: ignore raise ApiError(status_code=_response.status_code, body=_response_json) def stop_execution_session( - self, session_id: str, *, request_options: typing.Optional[RequestOptions] = None + self, + session_id: str, + *, + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ Stops execution session. @@ -146,24 +183,34 @@ def stop_execution_session( _response = self._client_wrapper.httpx_client.request( "DELETE", urllib.parse.urljoin( - f"{self._client_wrapper.get_base_url()}/", f"sessions/stop/{jsonable_encoder(session_id)}" + f"{self._client_wrapper.get_base_url()}/", + f"sessions/stop/{jsonable_encoder(session_id)}", ), params=jsonable_encoder( - request_options.get("additional_query_parameters") if request_options is not None else None + request_options.get("additional_query_parameters") + if request_options is not None + else None ), headers=jsonable_encoder( remove_none_from_dict( { **self._client_wrapper.get_headers(), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), timeout=request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self._client_wrapper.get_timeout(), retries=0, - max_retries=request_options.get("max_retries") if request_options is not None else 0, # type: ignore + max_retries=request_options.get("max_retries") + if request_options is not None + else 0, # type: ignore ) if 200 <= _response.status_code < 300: return @@ -190,30 +237,44 @@ def get_execution_sessions_state( """ _response = self._client_wrapper.httpx_client.request( "GET", - urllib.parse.urljoin(f"{self._client_wrapper.get_base_url()}/", "sessions/execution-sessions-state"), + urllib.parse.urljoin( + f"{self._client_wrapper.get_base_url()}/", + "sessions/execution-sessions-state", + ), params=jsonable_encoder( - request_options.get("additional_query_parameters") if request_options is not None else None + request_options.get("additional_query_parameters") + if request_options is not None + else None ), headers=jsonable_encoder( remove_none_from_dict( { **self._client_wrapper.get_headers(), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), timeout=request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self._client_wrapper.get_timeout(), retries=0, - max_retries=request_options.get("max_retries") if request_options is not None else 0, # type: ignore + max_retries=request_options.get("max_retries") + if request_options is not None + else 0, # type: ignore ) try: _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) if 200 <= _response.status_code < 300: - return pydantic_v1.parse_obj_as(GetExecutionSessionStateResponse, _response_json) # type: ignore + return pydantic_v1.parse_obj_as( + GetExecutionSessionStateResponse, _response_json + ) # type: ignore raise ApiError(status_code=_response.status_code, body=_response_json) @@ -222,7 +283,10 @@ def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper async def create_execution_session( - self, language: Language, *, request_options: typing.Optional[RequestOptions] = None + self, + language: Language, + *, + request_options: typing.Optional[RequestOptions] = None, ) -> ExecutionSessionResponse: """ Returns sessionId and execution server URL for session. Spins up server. @@ -245,27 +309,41 @@ async def create_execution_session( _response = await self._client_wrapper.httpx_client.request( "POST", urllib.parse.urljoin( - f"{self._client_wrapper.get_base_url()}/", f"sessions/create-session/{jsonable_encoder(language)}" + f"{self._client_wrapper.get_base_url()}/", + f"sessions/create-session/{jsonable_encoder(language)}", ), params=jsonable_encoder( - request_options.get("additional_query_parameters") if request_options is not None else None + request_options.get("additional_query_parameters") + if request_options is not None + else None ), - json=jsonable_encoder(remove_none_from_dict(request_options.get("additional_body_parameters", {}))) + json=jsonable_encoder( + remove_none_from_dict( + request_options.get("additional_body_parameters", {}) + ) + ) if request_options is not None else None, headers=jsonable_encoder( remove_none_from_dict( { **self._client_wrapper.get_headers(), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), timeout=request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self._client_wrapper.get_timeout(), retries=0, - max_retries=request_options.get("max_retries") if request_options is not None else 0, # type: ignore + max_retries=request_options.get("max_retries") + if request_options is not None + else 0, # type: ignore ) try: _response_json = _response.json() @@ -276,7 +354,10 @@ async def create_execution_session( raise ApiError(status_code=_response.status_code, body=_response_json) async def get_execution_session( - self, session_id: str, *, request_options: typing.Optional[RequestOptions] = None + self, + session_id: str, + *, + request_options: typing.Optional[RequestOptions] = None, ) -> typing.Optional[ExecutionSessionResponse]: """ Returns execution server URL for session. Returns empty if session isn't registered. @@ -298,34 +379,51 @@ async def get_execution_session( """ _response = await self._client_wrapper.httpx_client.request( "GET", - urllib.parse.urljoin(f"{self._client_wrapper.get_base_url()}/", f"sessions/{jsonable_encoder(session_id)}"), + urllib.parse.urljoin( + f"{self._client_wrapper.get_base_url()}/", + f"sessions/{jsonable_encoder(session_id)}", + ), params=jsonable_encoder( - request_options.get("additional_query_parameters") if request_options is not None else None + request_options.get("additional_query_parameters") + if request_options is not None + else None ), headers=jsonable_encoder( remove_none_from_dict( { **self._client_wrapper.get_headers(), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), timeout=request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self._client_wrapper.get_timeout(), retries=0, - max_retries=request_options.get("max_retries") if request_options is not None else 0, # type: ignore + max_retries=request_options.get("max_retries") + if request_options is not None + else 0, # type: ignore ) try: _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) if 200 <= _response.status_code < 300: - return pydantic_v1.parse_obj_as(typing.Optional[ExecutionSessionResponse], _response_json) # type: ignore + return pydantic_v1.parse_obj_as( + typing.Optional[ExecutionSessionResponse], _response_json + ) # type: ignore raise ApiError(status_code=_response.status_code, body=_response_json) async def stop_execution_session( - self, session_id: str, *, request_options: typing.Optional[RequestOptions] = None + self, + session_id: str, + *, + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ Stops execution session. @@ -348,24 +446,34 @@ async def stop_execution_session( _response = await self._client_wrapper.httpx_client.request( "DELETE", urllib.parse.urljoin( - f"{self._client_wrapper.get_base_url()}/", f"sessions/stop/{jsonable_encoder(session_id)}" + f"{self._client_wrapper.get_base_url()}/", + f"sessions/stop/{jsonable_encoder(session_id)}", ), params=jsonable_encoder( - request_options.get("additional_query_parameters") if request_options is not None else None + request_options.get("additional_query_parameters") + if request_options is not None + else None ), headers=jsonable_encoder( remove_none_from_dict( { **self._client_wrapper.get_headers(), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), timeout=request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self._client_wrapper.get_timeout(), retries=0, - max_retries=request_options.get("max_retries") if request_options is not None else 0, # type: ignore + max_retries=request_options.get("max_retries") + if request_options is not None + else 0, # type: ignore ) if 200 <= _response.status_code < 300: return @@ -392,28 +500,42 @@ async def get_execution_sessions_state( """ _response = await self._client_wrapper.httpx_client.request( "GET", - urllib.parse.urljoin(f"{self._client_wrapper.get_base_url()}/", "sessions/execution-sessions-state"), + urllib.parse.urljoin( + f"{self._client_wrapper.get_base_url()}/", + "sessions/execution-sessions-state", + ), params=jsonable_encoder( - request_options.get("additional_query_parameters") if request_options is not None else None + request_options.get("additional_query_parameters") + if request_options is not None + else None ), headers=jsonable_encoder( remove_none_from_dict( { **self._client_wrapper.get_headers(), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), timeout=request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self._client_wrapper.get_timeout(), retries=0, - max_retries=request_options.get("max_retries") if request_options is not None else 0, # type: ignore + max_retries=request_options.get("max_retries") + if request_options is not None + else 0, # type: ignore ) try: _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) if 200 <= _response.status_code < 300: - return pydantic_v1.parse_obj_as(GetExecutionSessionStateResponse, _response_json) # type: ignore + return pydantic_v1.parse_obj_as( + GetExecutionSessionStateResponse, _response_json + ) # type: ignore raise ApiError(status_code=_response.status_code, body=_response_json) diff --git a/seed/python-sdk/trace/src/seed/submission/types/__init__.py b/seed/python-sdk/trace/src/seed/submission/types/__init__.py index 5e3287b03b1..a6e67f79fc9 100644 --- a/seed/python-sdk/trace/src/seed/submission/types/__init__.py +++ b/seed/python-sdk/trace/src/seed/submission/types/__init__.py @@ -1,6 +1,11 @@ # This file was auto-generated by Fern from our API Definition. -from .actual_result import ActualResult, ActualResult_Exception, ActualResult_ExceptionV2, ActualResult_Value +from .actual_result import ( + ActualResult, + ActualResult_Exception, + ActualResult_ExceptionV2, + ActualResult_Value, +) from .building_executor_response import BuildingExecutorResponse from .code_execution_update import ( CodeExecutionUpdate, @@ -18,7 +23,12 @@ ) from .compile_error import CompileError from .custom_test_cases_unsupported import CustomTestCasesUnsupported -from .error_info import ErrorInfo, ErrorInfo_CompileError, ErrorInfo_InternalError, ErrorInfo_RuntimeError +from .error_info import ( + ErrorInfo, + ErrorInfo_CompileError, + ErrorInfo_InternalError, + ErrorInfo_RuntimeError, +) from .errored_response import ErroredResponse from .exception_info import ExceptionInfo from .exception_v_2 import ExceptionV2, ExceptionV2_Generic, ExceptionV2_Timeout @@ -84,12 +94,24 @@ SubmissionStatusForTestCase_GradedV2, SubmissionStatusForTestCase_Traced, ) -from .submission_status_v_2 import SubmissionStatusV2, SubmissionStatusV2_Test, SubmissionStatusV2_Workspace +from .submission_status_v_2 import ( + SubmissionStatusV2, + SubmissionStatusV2_Test, + SubmissionStatusV2_Workspace, +) from .submission_type_enum import SubmissionTypeEnum -from .submission_type_state import SubmissionTypeState, SubmissionTypeState_Test, SubmissionTypeState_Workspace +from .submission_type_state import ( + SubmissionTypeState, + SubmissionTypeState_Test, + SubmissionTypeState_Workspace, +) from .submit_request_v_2 import SubmitRequestV2 from .terminated_response import TerminatedResponse -from .test_case_grade import TestCaseGrade, TestCaseGrade_Hidden, TestCaseGrade_NonHidden +from .test_case_grade import ( + TestCaseGrade, + TestCaseGrade_Hidden, + TestCaseGrade_NonHidden, +) from .test_case_hidden_grade import TestCaseHiddenGrade from .test_case_non_hidden_grade import TestCaseNonHiddenGrade from .test_case_result import TestCaseResult diff --git a/seed/python-sdk/trace/src/seed/submission/types/actual_result.py b/seed/python-sdk/trace/src/seed/submission/types/actual_result.py index c4f553b8591..168474772db 100644 --- a/seed/python-sdk/trace/src/seed/submission/types/actual_result.py +++ b/seed/python-sdk/trace/src/seed/submission/types/actual_result.py @@ -37,5 +37,7 @@ class Config: smart_union = True -ActualResult = typing.Union[ActualResult_Value, ActualResult_Exception, ActualResult_ExceptionV2] +ActualResult = typing.Union[ + ActualResult_Value, ActualResult_Exception, ActualResult_ExceptionV2 +] from ...commons.types.variable_value import VariableValue # noqa: E402 diff --git a/seed/python-sdk/trace/src/seed/submission/types/building_executor_response.py b/seed/python-sdk/trace/src/seed/submission/types/building_executor_response.py index 1f475c39963..4557bf90d43 100644 --- a/seed/python-sdk/trace/src/seed/submission/types/building_executor_response.py +++ b/seed/python-sdk/trace/src/seed/submission/types/building_executor_response.py @@ -14,11 +14,19 @@ class BuildingExecutorResponse(pydantic_v1.BaseModel): status: ExecutionSessionStatus def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/submission/types/compile_error.py b/seed/python-sdk/trace/src/seed/submission/types/compile_error.py index cd2c71e31c8..381da9a5254 100644 --- a/seed/python-sdk/trace/src/seed/submission/types/compile_error.py +++ b/seed/python-sdk/trace/src/seed/submission/types/compile_error.py @@ -11,11 +11,19 @@ class CompileError(pydantic_v1.BaseModel): message: str def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/submission/types/custom_test_cases_unsupported.py b/seed/python-sdk/trace/src/seed/submission/types/custom_test_cases_unsupported.py index d3859633584..9e4d06fa704 100644 --- a/seed/python-sdk/trace/src/seed/submission/types/custom_test_cases_unsupported.py +++ b/seed/python-sdk/trace/src/seed/submission/types/custom_test_cases_unsupported.py @@ -14,11 +14,19 @@ class CustomTestCasesUnsupported(pydantic_v1.BaseModel): submission_id: SubmissionId = pydantic_v1.Field(alias="submissionId") def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/submission/types/error_info.py b/seed/python-sdk/trace/src/seed/submission/types/error_info.py index 042ad913add..d6cbf67c3b2 100644 --- a/seed/python-sdk/trace/src/seed/submission/types/error_info.py +++ b/seed/python-sdk/trace/src/seed/submission/types/error_info.py @@ -39,4 +39,6 @@ class Config: populate_by_name = True -ErrorInfo = typing.Union[ErrorInfo_CompileError, ErrorInfo_RuntimeError, ErrorInfo_InternalError] +ErrorInfo = typing.Union[ + ErrorInfo_CompileError, ErrorInfo_RuntimeError, ErrorInfo_InternalError +] diff --git a/seed/python-sdk/trace/src/seed/submission/types/errored_response.py b/seed/python-sdk/trace/src/seed/submission/types/errored_response.py index 22cd00d916b..41a968cd3ee 100644 --- a/seed/python-sdk/trace/src/seed/submission/types/errored_response.py +++ b/seed/python-sdk/trace/src/seed/submission/types/errored_response.py @@ -14,11 +14,19 @@ class ErroredResponse(pydantic_v1.BaseModel): error_info: ErrorInfo = pydantic_v1.Field(alias="errorInfo") def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/submission/types/exception_info.py b/seed/python-sdk/trace/src/seed/submission/types/exception_info.py index e7cb38f840d..9d529094e76 100644 --- a/seed/python-sdk/trace/src/seed/submission/types/exception_info.py +++ b/seed/python-sdk/trace/src/seed/submission/types/exception_info.py @@ -13,11 +13,19 @@ class ExceptionInfo(pydantic_v1.BaseModel): exception_stacktrace: str = pydantic_v1.Field(alias="exceptionStacktrace") def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/submission/types/execution_session_response.py b/seed/python-sdk/trace/src/seed/submission/types/execution_session_response.py index 32eb7ec212e..ad4c5ec6244 100644 --- a/seed/python-sdk/trace/src/seed/submission/types/execution_session_response.py +++ b/seed/python-sdk/trace/src/seed/submission/types/execution_session_response.py @@ -11,16 +11,26 @@ class ExecutionSessionResponse(pydantic_v1.BaseModel): session_id: str = pydantic_v1.Field(alias="sessionId") - execution_session_url: typing.Optional[str] = pydantic_v1.Field(alias="executionSessionUrl", default=None) + execution_session_url: typing.Optional[str] = pydantic_v1.Field( + alias="executionSessionUrl", default=None + ) language: Language status: ExecutionSessionStatus def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/submission/types/execution_session_state.py b/seed/python-sdk/trace/src/seed/submission/types/execution_session_state.py index 9b194c90e3e..0f552c75379 100644 --- a/seed/python-sdk/trace/src/seed/submission/types/execution_session_state.py +++ b/seed/python-sdk/trace/src/seed/submission/types/execution_session_state.py @@ -10,23 +10,35 @@ class ExecutionSessionState(pydantic_v1.BaseModel): - last_time_contacted: typing.Optional[str] = pydantic_v1.Field(alias="lastTimeContacted", default=None) + last_time_contacted: typing.Optional[str] = pydantic_v1.Field( + alias="lastTimeContacted", default=None + ) session_id: str = pydantic_v1.Field(alias="sessionId") """ The auto-generated session id. Formatted as a uuid. """ is_warm_instance: bool = pydantic_v1.Field(alias="isWarmInstance") - aws_task_id: typing.Optional[str] = pydantic_v1.Field(alias="awsTaskId", default=None) + aws_task_id: typing.Optional[str] = pydantic_v1.Field( + alias="awsTaskId", default=None + ) language: Language status: ExecutionSessionStatus def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/submission/types/existing_submission_executing.py b/seed/python-sdk/trace/src/seed/submission/types/existing_submission_executing.py index ef8a43ba58d..db341d1470c 100644 --- a/seed/python-sdk/trace/src/seed/submission/types/existing_submission_executing.py +++ b/seed/python-sdk/trace/src/seed/submission/types/existing_submission_executing.py @@ -12,11 +12,19 @@ class ExistingSubmissionExecuting(pydantic_v1.BaseModel): submission_id: SubmissionId = pydantic_v1.Field(alias="submissionId") def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/submission/types/expression_location.py b/seed/python-sdk/trace/src/seed/submission/types/expression_location.py index 49792e4bfc4..19758186798 100644 --- a/seed/python-sdk/trace/src/seed/submission/types/expression_location.py +++ b/seed/python-sdk/trace/src/seed/submission/types/expression_location.py @@ -12,11 +12,19 @@ class ExpressionLocation(pydantic_v1.BaseModel): offset: int def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/submission/types/finished_response.py b/seed/python-sdk/trace/src/seed/submission/types/finished_response.py index 1a207da86cd..eda09cd03da 100644 --- a/seed/python-sdk/trace/src/seed/submission/types/finished_response.py +++ b/seed/python-sdk/trace/src/seed/submission/types/finished_response.py @@ -12,11 +12,19 @@ class FinishedResponse(pydantic_v1.BaseModel): submission_id: SubmissionId = pydantic_v1.Field(alias="submissionId") def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/submission/types/get_execution_session_state_response.py b/seed/python-sdk/trace/src/seed/submission/types/get_execution_session_state_response.py index fdf149af068..c33717916e0 100644 --- a/seed/python-sdk/trace/src/seed/submission/types/get_execution_session_state_response.py +++ b/seed/python-sdk/trace/src/seed/submission/types/get_execution_session_state_response.py @@ -10,15 +10,25 @@ class GetExecutionSessionStateResponse(pydantic_v1.BaseModel): states: typing.Dict[str, ExecutionSessionState] - num_warming_instances: typing.Optional[int] = pydantic_v1.Field(alias="numWarmingInstances", default=None) + num_warming_instances: typing.Optional[int] = pydantic_v1.Field( + alias="numWarmingInstances", default=None + ) warming_session_ids: typing.List[str] = pydantic_v1.Field(alias="warmingSessionIds") def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/submission/types/get_submission_state_response.py b/seed/python-sdk/trace/src/seed/submission/types/get_submission_state_response.py index a43b4c1cde0..792c6e122a2 100644 --- a/seed/python-sdk/trace/src/seed/submission/types/get_submission_state_response.py +++ b/seed/python-sdk/trace/src/seed/submission/types/get_submission_state_response.py @@ -10,17 +10,29 @@ class GetSubmissionStateResponse(pydantic_v1.BaseModel): - time_submitted: typing.Optional[dt.datetime] = pydantic_v1.Field(alias="timeSubmitted", default=None) + time_submitted: typing.Optional[dt.datetime] = pydantic_v1.Field( + alias="timeSubmitted", default=None + ) submission: str language: Language - submission_type_state: SubmissionTypeState = pydantic_v1.Field(alias="submissionTypeState") + submission_type_state: SubmissionTypeState = pydantic_v1.Field( + alias="submissionTypeState" + ) def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/submission/types/get_trace_responses_page_request.py b/seed/python-sdk/trace/src/seed/submission/types/get_trace_responses_page_request.py index 32bcf05e2c8..fb92904f161 100644 --- a/seed/python-sdk/trace/src/seed/submission/types/get_trace_responses_page_request.py +++ b/seed/python-sdk/trace/src/seed/submission/types/get_trace_responses_page_request.py @@ -11,11 +11,19 @@ class GetTraceResponsesPageRequest(pydantic_v1.BaseModel): offset: typing.Optional[int] = None def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/submission/types/graded_response.py b/seed/python-sdk/trace/src/seed/submission/types/graded_response.py index 9774f8898f5..e4ea8c69ec8 100644 --- a/seed/python-sdk/trace/src/seed/submission/types/graded_response.py +++ b/seed/python-sdk/trace/src/seed/submission/types/graded_response.py @@ -11,14 +11,24 @@ class GradedResponse(pydantic_v1.BaseModel): submission_id: SubmissionId = pydantic_v1.Field(alias="submissionId") - test_cases: typing.Dict[str, TestCaseResultWithStdout] = pydantic_v1.Field(alias="testCases") + test_cases: typing.Dict[str, TestCaseResultWithStdout] = pydantic_v1.Field( + alias="testCases" + ) def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/submission/types/graded_response_v_2.py b/seed/python-sdk/trace/src/seed/submission/types/graded_response_v_2.py index d5d19db687b..ae176456dab 100644 --- a/seed/python-sdk/trace/src/seed/submission/types/graded_response_v_2.py +++ b/seed/python-sdk/trace/src/seed/submission/types/graded_response_v_2.py @@ -12,14 +12,24 @@ class GradedResponseV2(pydantic_v1.BaseModel): submission_id: SubmissionId = pydantic_v1.Field(alias="submissionId") - test_cases: typing.Dict[TestCaseId, TestCaseGrade] = pydantic_v1.Field(alias="testCases") + test_cases: typing.Dict[TestCaseId, TestCaseGrade] = pydantic_v1.Field( + alias="testCases" + ) def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/submission/types/graded_test_case_update.py b/seed/python-sdk/trace/src/seed/submission/types/graded_test_case_update.py index 5473f0316ef..0b2f6c1c17a 100644 --- a/seed/python-sdk/trace/src/seed/submission/types/graded_test_case_update.py +++ b/seed/python-sdk/trace/src/seed/submission/types/graded_test_case_update.py @@ -14,11 +14,19 @@ class GradedTestCaseUpdate(pydantic_v1.BaseModel): grade: TestCaseGrade def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/submission/types/initialize_problem_request.py b/seed/python-sdk/trace/src/seed/submission/types/initialize_problem_request.py index e90b84ee2ef..9391f8bcdc3 100644 --- a/seed/python-sdk/trace/src/seed/submission/types/initialize_problem_request.py +++ b/seed/python-sdk/trace/src/seed/submission/types/initialize_problem_request.py @@ -10,14 +10,24 @@ class InitializeProblemRequest(pydantic_v1.BaseModel): problem_id: ProblemId = pydantic_v1.Field(alias="problemId") - problem_version: typing.Optional[int] = pydantic_v1.Field(alias="problemVersion", default=None) + problem_version: typing.Optional[int] = pydantic_v1.Field( + alias="problemVersion", default=None + ) def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/submission/types/internal_error.py b/seed/python-sdk/trace/src/seed/submission/types/internal_error.py index 6b6850efbfc..0d39aa7a0c6 100644 --- a/seed/python-sdk/trace/src/seed/submission/types/internal_error.py +++ b/seed/python-sdk/trace/src/seed/submission/types/internal_error.py @@ -12,11 +12,19 @@ class InternalError(pydantic_v1.BaseModel): exception_info: ExceptionInfo = pydantic_v1.Field(alias="exceptionInfo") def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/submission/types/invalid_request_response.py b/seed/python-sdk/trace/src/seed/submission/types/invalid_request_response.py index 6d25f0aa740..b792d9e5417 100644 --- a/seed/python-sdk/trace/src/seed/submission/types/invalid_request_response.py +++ b/seed/python-sdk/trace/src/seed/submission/types/invalid_request_response.py @@ -14,11 +14,19 @@ class InvalidRequestResponse(pydantic_v1.BaseModel): cause: InvalidRequestCause def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/submission/types/lightweight_stackframe_information.py b/seed/python-sdk/trace/src/seed/submission/types/lightweight_stackframe_information.py index b5ff8b5692b..959b3b234b0 100644 --- a/seed/python-sdk/trace/src/seed/submission/types/lightweight_stackframe_information.py +++ b/seed/python-sdk/trace/src/seed/submission/types/lightweight_stackframe_information.py @@ -9,14 +9,24 @@ class LightweightStackframeInformation(pydantic_v1.BaseModel): num_stack_frames: int = pydantic_v1.Field(alias="numStackFrames") - top_stack_frame_method_name: str = pydantic_v1.Field(alias="topStackFrameMethodName") + top_stack_frame_method_name: str = pydantic_v1.Field( + alias="topStackFrameMethodName" + ) def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/submission/types/recorded_response_notification.py b/seed/python-sdk/trace/src/seed/submission/types/recorded_response_notification.py index 5bea65e6e56..60b3a84a950 100644 --- a/seed/python-sdk/trace/src/seed/submission/types/recorded_response_notification.py +++ b/seed/python-sdk/trace/src/seed/submission/types/recorded_response_notification.py @@ -11,14 +11,24 @@ class RecordedResponseNotification(pydantic_v1.BaseModel): submission_id: SubmissionId = pydantic_v1.Field(alias="submissionId") trace_responses_size: int = pydantic_v1.Field(alias="traceResponsesSize") - test_case_id: typing.Optional[str] = pydantic_v1.Field(alias="testCaseId", default=None) + test_case_id: typing.Optional[str] = pydantic_v1.Field( + alias="testCaseId", default=None + ) def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/submission/types/recorded_test_case_update.py b/seed/python-sdk/trace/src/seed/submission/types/recorded_test_case_update.py index e8456b086bc..d197bc276e1 100644 --- a/seed/python-sdk/trace/src/seed/submission/types/recorded_test_case_update.py +++ b/seed/python-sdk/trace/src/seed/submission/types/recorded_test_case_update.py @@ -13,11 +13,19 @@ class RecordedTestCaseUpdate(pydantic_v1.BaseModel): trace_responses_size: int = pydantic_v1.Field(alias="traceResponsesSize") def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/submission/types/recording_response_notification.py b/seed/python-sdk/trace/src/seed/submission/types/recording_response_notification.py index 9df9ea5022c..582438a505d 100644 --- a/seed/python-sdk/trace/src/seed/submission/types/recording_response_notification.py +++ b/seed/python-sdk/trace/src/seed/submission/types/recording_response_notification.py @@ -12,17 +12,31 @@ class RecordingResponseNotification(pydantic_v1.BaseModel): submission_id: SubmissionId = pydantic_v1.Field(alias="submissionId") - test_case_id: typing.Optional[str] = pydantic_v1.Field(alias="testCaseId", default=None) + test_case_id: typing.Optional[str] = pydantic_v1.Field( + alias="testCaseId", default=None + ) line_number: int = pydantic_v1.Field(alias="lineNumber") - lightweight_stack_info: LightweightStackframeInformation = pydantic_v1.Field(alias="lightweightStackInfo") - traced_file: typing.Optional[TracedFile] = pydantic_v1.Field(alias="tracedFile", default=None) + lightweight_stack_info: LightweightStackframeInformation = pydantic_v1.Field( + alias="lightweightStackInfo" + ) + traced_file: typing.Optional[TracedFile] = pydantic_v1.Field( + alias="tracedFile", default=None + ) def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/submission/types/running_response.py b/seed/python-sdk/trace/src/seed/submission/types/running_response.py index b0202ad91e5..1a5cec87b65 100644 --- a/seed/python-sdk/trace/src/seed/submission/types/running_response.py +++ b/seed/python-sdk/trace/src/seed/submission/types/running_response.py @@ -14,11 +14,19 @@ class RunningResponse(pydantic_v1.BaseModel): state: RunningSubmissionState def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/submission/types/runtime_error.py b/seed/python-sdk/trace/src/seed/submission/types/runtime_error.py index 9de8888d93c..8e868e5f7c9 100644 --- a/seed/python-sdk/trace/src/seed/submission/types/runtime_error.py +++ b/seed/python-sdk/trace/src/seed/submission/types/runtime_error.py @@ -11,11 +11,19 @@ class RuntimeError(pydantic_v1.BaseModel): message: str def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/submission/types/scope.py b/seed/python-sdk/trace/src/seed/submission/types/scope.py index 7270669cde0..93c2f5390a1 100644 --- a/seed/python-sdk/trace/src/seed/submission/types/scope.py +++ b/seed/python-sdk/trace/src/seed/submission/types/scope.py @@ -12,11 +12,19 @@ class Scope(pydantic_v1.BaseModel): variables: typing.Dict[str, DebugVariableValue] def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/submission/types/stack_frame.py b/seed/python-sdk/trace/src/seed/submission/types/stack_frame.py index 563054cd632..e640ab50130 100644 --- a/seed/python-sdk/trace/src/seed/submission/types/stack_frame.py +++ b/seed/python-sdk/trace/src/seed/submission/types/stack_frame.py @@ -14,11 +14,19 @@ class StackFrame(pydantic_v1.BaseModel): scopes: typing.List[Scope] def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/submission/types/stack_information.py b/seed/python-sdk/trace/src/seed/submission/types/stack_information.py index 09cfa3757ee..21f1a16a70b 100644 --- a/seed/python-sdk/trace/src/seed/submission/types/stack_information.py +++ b/seed/python-sdk/trace/src/seed/submission/types/stack_information.py @@ -10,14 +10,24 @@ class StackInformation(pydantic_v1.BaseModel): num_stack_frames: int = pydantic_v1.Field(alias="numStackFrames") - top_stack_frame: typing.Optional[StackFrame] = pydantic_v1.Field(alias="topStackFrame", default=None) + top_stack_frame: typing.Optional[StackFrame] = pydantic_v1.Field( + alias="topStackFrame", default=None + ) def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/submission/types/stderr_response.py b/seed/python-sdk/trace/src/seed/submission/types/stderr_response.py index 79e1812ae87..26cfba24bdb 100644 --- a/seed/python-sdk/trace/src/seed/submission/types/stderr_response.py +++ b/seed/python-sdk/trace/src/seed/submission/types/stderr_response.py @@ -13,11 +13,19 @@ class StderrResponse(pydantic_v1.BaseModel): stderr: str def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/submission/types/stdout_response.py b/seed/python-sdk/trace/src/seed/submission/types/stdout_response.py index 36fd543250e..408d5718a7f 100644 --- a/seed/python-sdk/trace/src/seed/submission/types/stdout_response.py +++ b/seed/python-sdk/trace/src/seed/submission/types/stdout_response.py @@ -13,11 +13,19 @@ class StdoutResponse(pydantic_v1.BaseModel): stdout: str def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/submission/types/stop_request.py b/seed/python-sdk/trace/src/seed/submission/types/stop_request.py index 8c19cf84b72..b4284df452b 100644 --- a/seed/python-sdk/trace/src/seed/submission/types/stop_request.py +++ b/seed/python-sdk/trace/src/seed/submission/types/stop_request.py @@ -12,11 +12,19 @@ class StopRequest(pydantic_v1.BaseModel): submission_id: SubmissionId = pydantic_v1.Field(alias="submissionId") def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/submission/types/stopped_response.py b/seed/python-sdk/trace/src/seed/submission/types/stopped_response.py index d4980ceff34..7a69d9dfbce 100644 --- a/seed/python-sdk/trace/src/seed/submission/types/stopped_response.py +++ b/seed/python-sdk/trace/src/seed/submission/types/stopped_response.py @@ -12,11 +12,19 @@ class StoppedResponse(pydantic_v1.BaseModel): submission_id: SubmissionId = pydantic_v1.Field(alias="submissionId") def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/submission/types/submission_file_info.py b/seed/python-sdk/trace/src/seed/submission/types/submission_file_info.py index ee8604b9ae3..9937d17d37f 100644 --- a/seed/python-sdk/trace/src/seed/submission/types/submission_file_info.py +++ b/seed/python-sdk/trace/src/seed/submission/types/submission_file_info.py @@ -13,11 +13,19 @@ class SubmissionFileInfo(pydantic_v1.BaseModel): contents: str def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/submission/types/submission_id_not_found.py b/seed/python-sdk/trace/src/seed/submission/types/submission_id_not_found.py index 6a91218b12f..a86e03ffa9e 100644 --- a/seed/python-sdk/trace/src/seed/submission/types/submission_id_not_found.py +++ b/seed/python-sdk/trace/src/seed/submission/types/submission_id_not_found.py @@ -12,11 +12,19 @@ class SubmissionIdNotFound(pydantic_v1.BaseModel): missing_submission_id: SubmissionId = pydantic_v1.Field(alias="missingSubmissionId") def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/submission/types/submission_status_for_test_case.py b/seed/python-sdk/trace/src/seed/submission/types/submission_status_for_test_case.py index 3d7b4944b30..3250860505a 100644 --- a/seed/python-sdk/trace/src/seed/submission/types/submission_status_for_test_case.py +++ b/seed/python-sdk/trace/src/seed/submission/types/submission_status_for_test_case.py @@ -40,5 +40,7 @@ class Config: SubmissionStatusForTestCase = typing.Union[ - SubmissionStatusForTestCase_Graded, SubmissionStatusForTestCase_GradedV2, SubmissionStatusForTestCase_Traced + SubmissionStatusForTestCase_Graded, + SubmissionStatusForTestCase_GradedV2, + SubmissionStatusForTestCase_Traced, ] diff --git a/seed/python-sdk/trace/src/seed/submission/types/submission_type_state.py b/seed/python-sdk/trace/src/seed/submission/types/submission_type_state.py index 400b23eebd9..b65a2a7be67 100644 --- a/seed/python-sdk/trace/src/seed/submission/types/submission_type_state.py +++ b/seed/python-sdk/trace/src/seed/submission/types/submission_type_state.py @@ -28,4 +28,6 @@ class Config: populate_by_name = True -SubmissionTypeState = typing.Union[SubmissionTypeState_Test, SubmissionTypeState_Workspace] +SubmissionTypeState = typing.Union[ + SubmissionTypeState_Test, SubmissionTypeState_Workspace +] diff --git a/seed/python-sdk/trace/src/seed/submission/types/submit_request_v_2.py b/seed/python-sdk/trace/src/seed/submission/types/submit_request_v_2.py index e1b9663004a..dd50dc70d4f 100644 --- a/seed/python-sdk/trace/src/seed/submission/types/submit_request_v_2.py +++ b/seed/python-sdk/trace/src/seed/submission/types/submit_request_v_2.py @@ -14,17 +14,29 @@ class SubmitRequestV2(pydantic_v1.BaseModel): submission_id: SubmissionId = pydantic_v1.Field(alias="submissionId") language: Language - submission_files: typing.List[SubmissionFileInfo] = pydantic_v1.Field(alias="submissionFiles") + submission_files: typing.List[SubmissionFileInfo] = pydantic_v1.Field( + alias="submissionFiles" + ) problem_id: ProblemId = pydantic_v1.Field(alias="problemId") - problem_version: typing.Optional[int] = pydantic_v1.Field(alias="problemVersion", default=None) + problem_version: typing.Optional[int] = pydantic_v1.Field( + alias="problemVersion", default=None + ) user_id: typing.Optional[str] = pydantic_v1.Field(alias="userId", default=None) def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/submission/types/terminated_response.py b/seed/python-sdk/trace/src/seed/submission/types/terminated_response.py index 33af7568f75..8dacb2d9c9b 100644 --- a/seed/python-sdk/trace/src/seed/submission/types/terminated_response.py +++ b/seed/python-sdk/trace/src/seed/submission/types/terminated_response.py @@ -9,11 +9,19 @@ class TerminatedResponse(pydantic_v1.BaseModel): def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/submission/types/test_case_hidden_grade.py b/seed/python-sdk/trace/src/seed/submission/types/test_case_hidden_grade.py index 246911e8940..30b6bd7d5e4 100644 --- a/seed/python-sdk/trace/src/seed/submission/types/test_case_hidden_grade.py +++ b/seed/python-sdk/trace/src/seed/submission/types/test_case_hidden_grade.py @@ -11,11 +11,19 @@ class TestCaseHiddenGrade(pydantic_v1.BaseModel): passed: bool def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/submission/types/test_case_non_hidden_grade.py b/seed/python-sdk/trace/src/seed/submission/types/test_case_non_hidden_grade.py index 4465c5dbe30..65d7421249f 100644 --- a/seed/python-sdk/trace/src/seed/submission/types/test_case_non_hidden_grade.py +++ b/seed/python-sdk/trace/src/seed/submission/types/test_case_non_hidden_grade.py @@ -11,16 +11,26 @@ class TestCaseNonHiddenGrade(pydantic_v1.BaseModel): passed: bool - actual_result: typing.Optional[VariableValue] = pydantic_v1.Field(alias="actualResult", default=None) + actual_result: typing.Optional[VariableValue] = pydantic_v1.Field( + alias="actualResult", default=None + ) exception: typing.Optional[ExceptionV2] = None stdout: str def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/submission/types/test_case_result.py b/seed/python-sdk/trace/src/seed/submission/types/test_case_result.py index 4c4a797c6b9..27a3e66e4f3 100644 --- a/seed/python-sdk/trace/src/seed/submission/types/test_case_result.py +++ b/seed/python-sdk/trace/src/seed/submission/types/test_case_result.py @@ -15,11 +15,19 @@ class TestCaseResult(pydantic_v1.BaseModel): passed: bool def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/submission/types/test_case_result_with_stdout.py b/seed/python-sdk/trace/src/seed/submission/types/test_case_result_with_stdout.py index 3f2ef4d8398..da93dca9c64 100644 --- a/seed/python-sdk/trace/src/seed/submission/types/test_case_result_with_stdout.py +++ b/seed/python-sdk/trace/src/seed/submission/types/test_case_result_with_stdout.py @@ -13,11 +13,19 @@ class TestCaseResultWithStdout(pydantic_v1.BaseModel): stdout: str def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/submission/types/test_submission_state.py b/seed/python-sdk/trace/src/seed/submission/types/test_submission_state.py index 14908f096e0..22af9a6d0a8 100644 --- a/seed/python-sdk/trace/src/seed/submission/types/test_submission_state.py +++ b/seed/python-sdk/trace/src/seed/submission/types/test_submission_state.py @@ -12,16 +12,28 @@ class TestSubmissionState(pydantic_v1.BaseModel): problem_id: ProblemId = pydantic_v1.Field(alias="problemId") - default_test_cases: typing.List[TestCase] = pydantic_v1.Field(alias="defaultTestCases") - custom_test_cases: typing.List[TestCase] = pydantic_v1.Field(alias="customTestCases") + default_test_cases: typing.List[TestCase] = pydantic_v1.Field( + alias="defaultTestCases" + ) + custom_test_cases: typing.List[TestCase] = pydantic_v1.Field( + alias="customTestCases" + ) status: TestSubmissionStatus def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/submission/types/test_submission_status_v_2.py b/seed/python-sdk/trace/src/seed/submission/types/test_submission_status_v_2.py index 4358d123356..8f1a3077f7f 100644 --- a/seed/python-sdk/trace/src/seed/submission/types/test_submission_status_v_2.py +++ b/seed/python-sdk/trace/src/seed/submission/types/test_submission_status_v_2.py @@ -17,11 +17,19 @@ class TestSubmissionStatusV2(pydantic_v1.BaseModel): problem_info: ProblemInfoV2 = pydantic_v1.Field(alias="problemInfo") def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/submission/types/test_submission_update.py b/seed/python-sdk/trace/src/seed/submission/types/test_submission_update.py index fb63beedd1e..0718bde4cdb 100644 --- a/seed/python-sdk/trace/src/seed/submission/types/test_submission_update.py +++ b/seed/python-sdk/trace/src/seed/submission/types/test_submission_update.py @@ -13,11 +13,19 @@ class TestSubmissionUpdate(pydantic_v1.BaseModel): update_info: TestSubmissionUpdateInfo = pydantic_v1.Field(alias="updateInfo") def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/submission/types/trace_response.py b/seed/python-sdk/trace/src/seed/submission/types/trace_response.py index 3455939562f..9aa7272fc67 100644 --- a/seed/python-sdk/trace/src/seed/submission/types/trace_response.py +++ b/seed/python-sdk/trace/src/seed/submission/types/trace_response.py @@ -14,7 +14,9 @@ class TraceResponse(pydantic_v1.BaseModel): submission_id: SubmissionId = pydantic_v1.Field(alias="submissionId") line_number: int = pydantic_v1.Field(alias="lineNumber") - return_value: typing.Optional[DebugVariableValue] = pydantic_v1.Field(alias="returnValue", default=None) + return_value: typing.Optional[DebugVariableValue] = pydantic_v1.Field( + alias="returnValue", default=None + ) expression_location: typing.Optional[ExpressionLocation] = pydantic_v1.Field( alias="expressionLocation", default=None ) @@ -22,11 +24,19 @@ class TraceResponse(pydantic_v1.BaseModel): stdout: typing.Optional[str] = None def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/submission/types/trace_response_v_2.py b/seed/python-sdk/trace/src/seed/submission/types/trace_response_v_2.py index 665014b5ae5..cf1895c382f 100644 --- a/seed/python-sdk/trace/src/seed/submission/types/trace_response_v_2.py +++ b/seed/python-sdk/trace/src/seed/submission/types/trace_response_v_2.py @@ -16,7 +16,9 @@ class TraceResponseV2(pydantic_v1.BaseModel): submission_id: SubmissionId = pydantic_v1.Field(alias="submissionId") line_number: int = pydantic_v1.Field(alias="lineNumber") file: TracedFile - return_value: typing.Optional[DebugVariableValue] = pydantic_v1.Field(alias="returnValue", default=None) + return_value: typing.Optional[DebugVariableValue] = pydantic_v1.Field( + alias="returnValue", default=None + ) expression_location: typing.Optional[ExpressionLocation] = pydantic_v1.Field( alias="expressionLocation", default=None ) @@ -24,11 +26,19 @@ class TraceResponseV2(pydantic_v1.BaseModel): stdout: typing.Optional[str] = None def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/submission/types/trace_responses_page.py b/seed/python-sdk/trace/src/seed/submission/types/trace_responses_page.py index 48e98116ff5..78bf62a1c71 100644 --- a/seed/python-sdk/trace/src/seed/submission/types/trace_responses_page.py +++ b/seed/python-sdk/trace/src/seed/submission/types/trace_responses_page.py @@ -15,14 +15,24 @@ class TraceResponsesPage(pydantic_v1.BaseModel): The offset is the id of the next trace response to load. """ - trace_responses: typing.List[TraceResponse] = pydantic_v1.Field(alias="traceResponses") + trace_responses: typing.List[TraceResponse] = pydantic_v1.Field( + alias="traceResponses" + ) def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/submission/types/trace_responses_page_v_2.py b/seed/python-sdk/trace/src/seed/submission/types/trace_responses_page_v_2.py index 0c8853bc4c0..e14617508b9 100644 --- a/seed/python-sdk/trace/src/seed/submission/types/trace_responses_page_v_2.py +++ b/seed/python-sdk/trace/src/seed/submission/types/trace_responses_page_v_2.py @@ -15,14 +15,24 @@ class TraceResponsesPageV2(pydantic_v1.BaseModel): The offset is the id of the next trace response to load. """ - trace_responses: typing.List[TraceResponseV2] = pydantic_v1.Field(alias="traceResponses") + trace_responses: typing.List[TraceResponseV2] = pydantic_v1.Field( + alias="traceResponses" + ) def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/submission/types/traced_file.py b/seed/python-sdk/trace/src/seed/submission/types/traced_file.py index a349c17daff..4edcad3d25d 100644 --- a/seed/python-sdk/trace/src/seed/submission/types/traced_file.py +++ b/seed/python-sdk/trace/src/seed/submission/types/traced_file.py @@ -12,11 +12,19 @@ class TracedFile(pydantic_v1.BaseModel): directory: str def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/submission/types/traced_test_case.py b/seed/python-sdk/trace/src/seed/submission/types/traced_test_case.py index d3c1e866371..c11365b1ba3 100644 --- a/seed/python-sdk/trace/src/seed/submission/types/traced_test_case.py +++ b/seed/python-sdk/trace/src/seed/submission/types/traced_test_case.py @@ -13,11 +13,19 @@ class TracedTestCase(pydantic_v1.BaseModel): trace_responses_size: int = pydantic_v1.Field(alias="traceResponsesSize") def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/submission/types/unexpected_language_error.py b/seed/python-sdk/trace/src/seed/submission/types/unexpected_language_error.py index 0907b48ff47..994b52093ac 100644 --- a/seed/python-sdk/trace/src/seed/submission/types/unexpected_language_error.py +++ b/seed/python-sdk/trace/src/seed/submission/types/unexpected_language_error.py @@ -13,11 +13,19 @@ class UnexpectedLanguageError(pydantic_v1.BaseModel): actual_language: Language = pydantic_v1.Field(alias="actualLanguage") def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/submission/types/workspace_files.py b/seed/python-sdk/trace/src/seed/submission/types/workspace_files.py index 82e8b5da491..a1d0a1f8f75 100644 --- a/seed/python-sdk/trace/src/seed/submission/types/workspace_files.py +++ b/seed/python-sdk/trace/src/seed/submission/types/workspace_files.py @@ -13,11 +13,19 @@ class WorkspaceFiles(pydantic_v1.BaseModel): read_only_files: typing.List[FileInfo] = pydantic_v1.Field(alias="readOnlyFiles") def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/submission/types/workspace_ran_response.py b/seed/python-sdk/trace/src/seed/submission/types/workspace_ran_response.py index 0c424989c7f..4ead6330d6e 100644 --- a/seed/python-sdk/trace/src/seed/submission/types/workspace_ran_response.py +++ b/seed/python-sdk/trace/src/seed/submission/types/workspace_ran_response.py @@ -14,11 +14,19 @@ class WorkspaceRanResponse(pydantic_v1.BaseModel): run_details: WorkspaceRunDetails = pydantic_v1.Field(alias="runDetails") def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/submission/types/workspace_run_details.py b/seed/python-sdk/trace/src/seed/submission/types/workspace_run_details.py index f85c2200511..52f6c53bdc7 100644 --- a/seed/python-sdk/trace/src/seed/submission/types/workspace_run_details.py +++ b/seed/python-sdk/trace/src/seed/submission/types/workspace_run_details.py @@ -10,16 +10,26 @@ class WorkspaceRunDetails(pydantic_v1.BaseModel): - exception_v_2: typing.Optional[ExceptionV2] = pydantic_v1.Field(alias="exceptionV2", default=None) + exception_v_2: typing.Optional[ExceptionV2] = pydantic_v1.Field( + alias="exceptionV2", default=None + ) exception: typing.Optional[ExceptionInfo] = None stdout: str def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/submission/types/workspace_starter_files_response.py b/seed/python-sdk/trace/src/seed/submission/types/workspace_starter_files_response.py index 52aab73795c..d5c9daa7f86 100644 --- a/seed/python-sdk/trace/src/seed/submission/types/workspace_starter_files_response.py +++ b/seed/python-sdk/trace/src/seed/submission/types/workspace_starter_files_response.py @@ -13,11 +13,19 @@ class WorkspaceStarterFilesResponse(pydantic_v1.BaseModel): files: typing.Dict[Language, WorkspaceFiles] def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/submission/types/workspace_starter_files_response_v_2.py b/seed/python-sdk/trace/src/seed/submission/types/workspace_starter_files_response_v_2.py index ce6b76705dc..ed4790c9c9f 100644 --- a/seed/python-sdk/trace/src/seed/submission/types/workspace_starter_files_response_v_2.py +++ b/seed/python-sdk/trace/src/seed/submission/types/workspace_starter_files_response_v_2.py @@ -10,14 +10,24 @@ class WorkspaceStarterFilesResponseV2(pydantic_v1.BaseModel): - files_by_language: typing.Dict[Language, Files] = pydantic_v1.Field(alias="filesByLanguage") + files_by_language: typing.Dict[Language, Files] = pydantic_v1.Field( + alias="filesByLanguage" + ) def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/submission/types/workspace_submission_state.py b/seed/python-sdk/trace/src/seed/submission/types/workspace_submission_state.py index 040ccf4d1e6..42964b69b17 100644 --- a/seed/python-sdk/trace/src/seed/submission/types/workspace_submission_state.py +++ b/seed/python-sdk/trace/src/seed/submission/types/workspace_submission_state.py @@ -12,11 +12,19 @@ class WorkspaceSubmissionState(pydantic_v1.BaseModel): status: WorkspaceSubmissionStatus def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/submission/types/workspace_submission_status_v_2.py b/seed/python-sdk/trace/src/seed/submission/types/workspace_submission_status_v_2.py index 6940a8d09e2..f7c5dabf070 100644 --- a/seed/python-sdk/trace/src/seed/submission/types/workspace_submission_status_v_2.py +++ b/seed/python-sdk/trace/src/seed/submission/types/workspace_submission_status_v_2.py @@ -12,11 +12,19 @@ class WorkspaceSubmissionStatusV2(pydantic_v1.BaseModel): updates: typing.List[WorkspaceSubmissionUpdate] def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/submission/types/workspace_submission_update.py b/seed/python-sdk/trace/src/seed/submission/types/workspace_submission_update.py index c16d1bf2973..17b0f500101 100644 --- a/seed/python-sdk/trace/src/seed/submission/types/workspace_submission_update.py +++ b/seed/python-sdk/trace/src/seed/submission/types/workspace_submission_update.py @@ -13,11 +13,19 @@ class WorkspaceSubmissionUpdate(pydantic_v1.BaseModel): update_info: WorkspaceSubmissionUpdateInfo = pydantic_v1.Field(alias="updateInfo") def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/submission/types/workspace_submit_request.py b/seed/python-sdk/trace/src/seed/submission/types/workspace_submit_request.py index 903fa370360..f1acf2c40c7 100644 --- a/seed/python-sdk/trace/src/seed/submission/types/workspace_submit_request.py +++ b/seed/python-sdk/trace/src/seed/submission/types/workspace_submit_request.py @@ -13,15 +13,25 @@ class WorkspaceSubmitRequest(pydantic_v1.BaseModel): submission_id: SubmissionId = pydantic_v1.Field(alias="submissionId") language: Language - submission_files: typing.List[SubmissionFileInfo] = pydantic_v1.Field(alias="submissionFiles") + submission_files: typing.List[SubmissionFileInfo] = pydantic_v1.Field( + alias="submissionFiles" + ) user_id: typing.Optional[str] = pydantic_v1.Field(alias="userId", default=None) def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/submission/types/workspace_traced_update.py b/seed/python-sdk/trace/src/seed/submission/types/workspace_traced_update.py index bef0d2812e4..9eed20c4cad 100644 --- a/seed/python-sdk/trace/src/seed/submission/types/workspace_traced_update.py +++ b/seed/python-sdk/trace/src/seed/submission/types/workspace_traced_update.py @@ -11,11 +11,19 @@ class WorkspaceTracedUpdate(pydantic_v1.BaseModel): trace_responses_size: int = pydantic_v1.Field(alias="traceResponsesSize") def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/sysprop/client.py b/seed/python-sdk/trace/src/seed/sysprop/client.py index f904debbb68..99ca53e8df9 100644 --- a/seed/python-sdk/trace/src/seed/sysprop/client.py +++ b/seed/python-sdk/trace/src/seed/sysprop/client.py @@ -18,7 +18,11 @@ def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper def set_num_warm_instances( - self, language: Language, num_warm_instances: int, *, request_options: typing.Optional[RequestOptions] = None + self, + language: Language, + num_warm_instances: int, + *, + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ Parameters: @@ -46,24 +50,37 @@ def set_num_warm_instances( f"sysprop/num-warm-instances/{jsonable_encoder(language)}/{jsonable_encoder(num_warm_instances)}", ), params=jsonable_encoder( - request_options.get("additional_query_parameters") if request_options is not None else None + request_options.get("additional_query_parameters") + if request_options is not None + else None ), - json=jsonable_encoder(remove_none_from_dict(request_options.get("additional_body_parameters", {}))) + json=jsonable_encoder( + remove_none_from_dict( + request_options.get("additional_body_parameters", {}) + ) + ) if request_options is not None else None, headers=jsonable_encoder( remove_none_from_dict( { **self._client_wrapper.get_headers(), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), timeout=request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self._client_wrapper.get_timeout(), retries=0, - max_retries=request_options.get("max_retries") if request_options is not None else 0, # type: ignore + max_retries=request_options.get("max_retries") + if request_options is not None + else 0, # type: ignore ) if 200 <= _response.status_code < 300: return @@ -90,23 +107,34 @@ def get_num_warm_instances( """ _response = self._client_wrapper.httpx_client.request( "GET", - urllib.parse.urljoin(f"{self._client_wrapper.get_base_url()}/", "sysprop/num-warm-instances"), + urllib.parse.urljoin( + f"{self._client_wrapper.get_base_url()}/", "sysprop/num-warm-instances" + ), params=jsonable_encoder( - request_options.get("additional_query_parameters") if request_options is not None else None + request_options.get("additional_query_parameters") + if request_options is not None + else None ), headers=jsonable_encoder( remove_none_from_dict( { **self._client_wrapper.get_headers(), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), timeout=request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self._client_wrapper.get_timeout(), retries=0, - max_retries=request_options.get("max_retries") if request_options is not None else 0, # type: ignore + max_retries=request_options.get("max_retries") + if request_options is not None + else 0, # type: ignore ) try: _response_json = _response.json() @@ -122,7 +150,11 @@ def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper async def set_num_warm_instances( - self, language: Language, num_warm_instances: int, *, request_options: typing.Optional[RequestOptions] = None + self, + language: Language, + num_warm_instances: int, + *, + request_options: typing.Optional[RequestOptions] = None, ) -> None: """ Parameters: @@ -150,24 +182,37 @@ async def set_num_warm_instances( f"sysprop/num-warm-instances/{jsonable_encoder(language)}/{jsonable_encoder(num_warm_instances)}", ), params=jsonable_encoder( - request_options.get("additional_query_parameters") if request_options is not None else None + request_options.get("additional_query_parameters") + if request_options is not None + else None ), - json=jsonable_encoder(remove_none_from_dict(request_options.get("additional_body_parameters", {}))) + json=jsonable_encoder( + remove_none_from_dict( + request_options.get("additional_body_parameters", {}) + ) + ) if request_options is not None else None, headers=jsonable_encoder( remove_none_from_dict( { **self._client_wrapper.get_headers(), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), timeout=request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self._client_wrapper.get_timeout(), retries=0, - max_retries=request_options.get("max_retries") if request_options is not None else 0, # type: ignore + max_retries=request_options.get("max_retries") + if request_options is not None + else 0, # type: ignore ) if 200 <= _response.status_code < 300: return @@ -194,23 +239,34 @@ async def get_num_warm_instances( """ _response = await self._client_wrapper.httpx_client.request( "GET", - urllib.parse.urljoin(f"{self._client_wrapper.get_base_url()}/", "sysprop/num-warm-instances"), + urllib.parse.urljoin( + f"{self._client_wrapper.get_base_url()}/", "sysprop/num-warm-instances" + ), params=jsonable_encoder( - request_options.get("additional_query_parameters") if request_options is not None else None + request_options.get("additional_query_parameters") + if request_options is not None + else None ), headers=jsonable_encoder( remove_none_from_dict( { **self._client_wrapper.get_headers(), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), timeout=request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self._client_wrapper.get_timeout(), retries=0, - max_retries=request_options.get("max_retries") if request_options is not None else 0, # type: ignore + max_retries=request_options.get("max_retries") + if request_options is not None + else 0, # type: ignore ) try: _response_json = _response.json() diff --git a/seed/python-sdk/trace/src/seed/v_2/client.py b/seed/python-sdk/trace/src/seed/v_2/client.py index 199341d813b..ae6609d43b4 100644 --- a/seed/python-sdk/trace/src/seed/v_2/client.py +++ b/seed/python-sdk/trace/src/seed/v_2/client.py @@ -35,21 +35,30 @@ def test(self, *, request_options: typing.Optional[RequestOptions] = None) -> No "GET", self._client_wrapper.get_base_url(), params=jsonable_encoder( - request_options.get("additional_query_parameters") if request_options is not None else None + request_options.get("additional_query_parameters") + if request_options is not None + else None ), headers=jsonable_encoder( remove_none_from_dict( { **self._client_wrapper.get_headers(), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), timeout=request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self._client_wrapper.get_timeout(), retries=0, - max_retries=request_options.get("max_retries") if request_options is not None else 0, # type: ignore + max_retries=request_options.get("max_retries") + if request_options is not None + else 0, # type: ignore ) if 200 <= _response.status_code < 300: return @@ -66,7 +75,9 @@ def __init__(self, *, client_wrapper: AsyncClientWrapper): self.problem = AsyncProblemClient(client_wrapper=self._client_wrapper) self.v_3 = AsyncV3Client(client_wrapper=self._client_wrapper) - async def test(self, *, request_options: typing.Optional[RequestOptions] = None) -> None: + async def test( + self, *, request_options: typing.Optional[RequestOptions] = None + ) -> None: """ Parameters: - request_options: typing.Optional[RequestOptions]. Request-specific configuration. @@ -83,21 +94,30 @@ async def test(self, *, request_options: typing.Optional[RequestOptions] = None) "GET", self._client_wrapper.get_base_url(), params=jsonable_encoder( - request_options.get("additional_query_parameters") if request_options is not None else None + request_options.get("additional_query_parameters") + if request_options is not None + else None ), headers=jsonable_encoder( remove_none_from_dict( { **self._client_wrapper.get_headers(), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), timeout=request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self._client_wrapper.get_timeout(), retries=0, - max_retries=request_options.get("max_retries") if request_options is not None else 0, # type: ignore + max_retries=request_options.get("max_retries") + if request_options is not None + else 0, # type: ignore ) if 200 <= _response.status_code < 300: return diff --git a/seed/python-sdk/trace/src/seed/v_2/problem/client.py b/seed/python-sdk/trace/src/seed/v_2/problem/client.py index 8081d945022..be9332438dc 100644 --- a/seed/python-sdk/trace/src/seed/v_2/problem/client.py +++ b/seed/python-sdk/trace/src/seed/v_2/problem/client.py @@ -38,33 +38,49 @@ def get_lightweight_problems( """ _response = self._client_wrapper.httpx_client.request( "GET", - urllib.parse.urljoin(f"{self._client_wrapper.get_base_url()}/", "problems-v2/lightweight-problem-info"), + urllib.parse.urljoin( + f"{self._client_wrapper.get_base_url()}/", + "problems-v2/lightweight-problem-info", + ), params=jsonable_encoder( - request_options.get("additional_query_parameters") if request_options is not None else None + request_options.get("additional_query_parameters") + if request_options is not None + else None ), headers=jsonable_encoder( remove_none_from_dict( { **self._client_wrapper.get_headers(), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), timeout=request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self._client_wrapper.get_timeout(), retries=0, - max_retries=request_options.get("max_retries") if request_options is not None else 0, # type: ignore + max_retries=request_options.get("max_retries") + if request_options is not None + else 0, # type: ignore ) try: _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) if 200 <= _response.status_code < 300: - return pydantic_v1.parse_obj_as(typing.List[LightweightProblemInfoV2], _response_json) # type: ignore + return pydantic_v1.parse_obj_as( + typing.List[LightweightProblemInfoV2], _response_json + ) # type: ignore raise ApiError(status_code=_response.status_code, body=_response_json) - def get_problems(self, *, request_options: typing.Optional[RequestOptions] = None) -> typing.List[ProblemInfoV2]: + def get_problems( + self, *, request_options: typing.Optional[RequestOptions] = None + ) -> typing.List[ProblemInfoV2]: """ Returns latest versions of all problems @@ -81,23 +97,34 @@ def get_problems(self, *, request_options: typing.Optional[RequestOptions] = Non """ _response = self._client_wrapper.httpx_client.request( "GET", - urllib.parse.urljoin(f"{self._client_wrapper.get_base_url()}/", "problems-v2/problem-info"), + urllib.parse.urljoin( + f"{self._client_wrapper.get_base_url()}/", "problems-v2/problem-info" + ), params=jsonable_encoder( - request_options.get("additional_query_parameters") if request_options is not None else None + request_options.get("additional_query_parameters") + if request_options is not None + else None ), headers=jsonable_encoder( remove_none_from_dict( { **self._client_wrapper.get_headers(), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), timeout=request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self._client_wrapper.get_timeout(), retries=0, - max_retries=request_options.get("max_retries") if request_options is not None else 0, # type: ignore + max_retries=request_options.get("max_retries") + if request_options is not None + else 0, # type: ignore ) try: _response_json = _response.json() @@ -108,7 +135,10 @@ def get_problems(self, *, request_options: typing.Optional[RequestOptions] = Non raise ApiError(status_code=_response.status_code, body=_response_json) def get_latest_problem( - self, problem_id: ProblemId, *, request_options: typing.Optional[RequestOptions] = None + self, + problem_id: ProblemId, + *, + request_options: typing.Optional[RequestOptions] = None, ) -> ProblemInfoV2: """ Returns latest version of a problem @@ -131,24 +161,34 @@ def get_latest_problem( _response = self._client_wrapper.httpx_client.request( "GET", urllib.parse.urljoin( - f"{self._client_wrapper.get_base_url()}/", f"problems-v2/problem-info/{jsonable_encoder(problem_id)}" + f"{self._client_wrapper.get_base_url()}/", + f"problems-v2/problem-info/{jsonable_encoder(problem_id)}", ), params=jsonable_encoder( - request_options.get("additional_query_parameters") if request_options is not None else None + request_options.get("additional_query_parameters") + if request_options is not None + else None ), headers=jsonable_encoder( remove_none_from_dict( { **self._client_wrapper.get_headers(), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), timeout=request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self._client_wrapper.get_timeout(), retries=0, - max_retries=request_options.get("max_retries") if request_options is not None else 0, # type: ignore + max_retries=request_options.get("max_retries") + if request_options is not None + else 0, # type: ignore ) try: _response_json = _response.json() @@ -159,7 +199,11 @@ def get_latest_problem( raise ApiError(status_code=_response.status_code, body=_response_json) def get_problem_version( - self, problem_id: ProblemId, problem_version: int, *, request_options: typing.Optional[RequestOptions] = None + self, + problem_id: ProblemId, + problem_version: int, + *, + request_options: typing.Optional[RequestOptions] = None, ) -> ProblemInfoV2: """ Returns requested version of a problem @@ -189,21 +233,30 @@ def get_problem_version( f"problems-v2/problem-info/{jsonable_encoder(problem_id)}/version/{jsonable_encoder(problem_version)}", ), params=jsonable_encoder( - request_options.get("additional_query_parameters") if request_options is not None else None + request_options.get("additional_query_parameters") + if request_options is not None + else None ), headers=jsonable_encoder( remove_none_from_dict( { **self._client_wrapper.get_headers(), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), timeout=request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self._client_wrapper.get_timeout(), retries=0, - max_retries=request_options.get("max_retries") if request_options is not None else 0, # type: ignore + max_retries=request_options.get("max_retries") + if request_options is not None + else 0, # type: ignore ) try: _response_json = _response.json() @@ -237,30 +290,44 @@ async def get_lightweight_problems( """ _response = await self._client_wrapper.httpx_client.request( "GET", - urllib.parse.urljoin(f"{self._client_wrapper.get_base_url()}/", "problems-v2/lightweight-problem-info"), + urllib.parse.urljoin( + f"{self._client_wrapper.get_base_url()}/", + "problems-v2/lightweight-problem-info", + ), params=jsonable_encoder( - request_options.get("additional_query_parameters") if request_options is not None else None + request_options.get("additional_query_parameters") + if request_options is not None + else None ), headers=jsonable_encoder( remove_none_from_dict( { **self._client_wrapper.get_headers(), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), timeout=request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self._client_wrapper.get_timeout(), retries=0, - max_retries=request_options.get("max_retries") if request_options is not None else 0, # type: ignore + max_retries=request_options.get("max_retries") + if request_options is not None + else 0, # type: ignore ) try: _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) if 200 <= _response.status_code < 300: - return pydantic_v1.parse_obj_as(typing.List[LightweightProblemInfoV2], _response_json) # type: ignore + return pydantic_v1.parse_obj_as( + typing.List[LightweightProblemInfoV2], _response_json + ) # type: ignore raise ApiError(status_code=_response.status_code, body=_response_json) async def get_problems( @@ -282,23 +349,34 @@ async def get_problems( """ _response = await self._client_wrapper.httpx_client.request( "GET", - urllib.parse.urljoin(f"{self._client_wrapper.get_base_url()}/", "problems-v2/problem-info"), + urllib.parse.urljoin( + f"{self._client_wrapper.get_base_url()}/", "problems-v2/problem-info" + ), params=jsonable_encoder( - request_options.get("additional_query_parameters") if request_options is not None else None + request_options.get("additional_query_parameters") + if request_options is not None + else None ), headers=jsonable_encoder( remove_none_from_dict( { **self._client_wrapper.get_headers(), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), timeout=request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self._client_wrapper.get_timeout(), retries=0, - max_retries=request_options.get("max_retries") if request_options is not None else 0, # type: ignore + max_retries=request_options.get("max_retries") + if request_options is not None + else 0, # type: ignore ) try: _response_json = _response.json() @@ -309,7 +387,10 @@ async def get_problems( raise ApiError(status_code=_response.status_code, body=_response_json) async def get_latest_problem( - self, problem_id: ProblemId, *, request_options: typing.Optional[RequestOptions] = None + self, + problem_id: ProblemId, + *, + request_options: typing.Optional[RequestOptions] = None, ) -> ProblemInfoV2: """ Returns latest version of a problem @@ -332,24 +413,34 @@ async def get_latest_problem( _response = await self._client_wrapper.httpx_client.request( "GET", urllib.parse.urljoin( - f"{self._client_wrapper.get_base_url()}/", f"problems-v2/problem-info/{jsonable_encoder(problem_id)}" + f"{self._client_wrapper.get_base_url()}/", + f"problems-v2/problem-info/{jsonable_encoder(problem_id)}", ), params=jsonable_encoder( - request_options.get("additional_query_parameters") if request_options is not None else None + request_options.get("additional_query_parameters") + if request_options is not None + else None ), headers=jsonable_encoder( remove_none_from_dict( { **self._client_wrapper.get_headers(), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), timeout=request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self._client_wrapper.get_timeout(), retries=0, - max_retries=request_options.get("max_retries") if request_options is not None else 0, # type: ignore + max_retries=request_options.get("max_retries") + if request_options is not None + else 0, # type: ignore ) try: _response_json = _response.json() @@ -360,7 +451,11 @@ async def get_latest_problem( raise ApiError(status_code=_response.status_code, body=_response_json) async def get_problem_version( - self, problem_id: ProblemId, problem_version: int, *, request_options: typing.Optional[RequestOptions] = None + self, + problem_id: ProblemId, + problem_version: int, + *, + request_options: typing.Optional[RequestOptions] = None, ) -> ProblemInfoV2: """ Returns requested version of a problem @@ -390,21 +485,30 @@ async def get_problem_version( f"problems-v2/problem-info/{jsonable_encoder(problem_id)}/version/{jsonable_encoder(problem_version)}", ), params=jsonable_encoder( - request_options.get("additional_query_parameters") if request_options is not None else None + request_options.get("additional_query_parameters") + if request_options is not None + else None ), headers=jsonable_encoder( remove_none_from_dict( { **self._client_wrapper.get_headers(), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), timeout=request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self._client_wrapper.get_timeout(), retries=0, - max_retries=request_options.get("max_retries") if request_options is not None else 0, # type: ignore + max_retries=request_options.get("max_retries") + if request_options is not None + else 0, # type: ignore ) try: _response_json = _response.json() diff --git a/seed/python-sdk/trace/src/seed/v_2/problem/types/__init__.py b/seed/python-sdk/trace/src/seed/v_2/problem/types/__init__.py index b2b1239aeec..94e8654458c 100644 --- a/seed/python-sdk/trace/src/seed/v_2/problem/types/__init__.py +++ b/seed/python-sdk/trace/src/seed/v_2/problem/types/__init__.py @@ -14,7 +14,9 @@ from .file_info_v_2 import FileInfoV2 from .files import Files from .function_implementation import FunctionImplementation -from .function_implementation_for_multiple_languages import FunctionImplementationForMultipleLanguages +from .function_implementation_for_multiple_languages import ( + FunctionImplementationForMultipleLanguages, +) from .function_signature import ( FunctionSignature, FunctionSignature_NonVoid, @@ -27,7 +29,9 @@ from .get_function_signature_request import GetFunctionSignatureRequest from .get_function_signature_response import GetFunctionSignatureResponse from .get_generated_test_case_file_request import GetGeneratedTestCaseFileRequest -from .get_generated_test_case_template_file_request import GetGeneratedTestCaseTemplateFileRequest +from .get_generated_test_case_template_file_request import ( + GetGeneratedTestCaseTemplateFileRequest, +) from .lightweight_problem_info_v_2 import LightweightProblemInfoV2 from .non_void_function_definition import NonVoidFunctionDefinition from .non_void_function_signature import NonVoidFunctionSignature @@ -35,7 +39,11 @@ from .parameter_id import ParameterId from .problem_info_v_2 import ProblemInfoV2 from .test_case_expects import TestCaseExpects -from .test_case_function import TestCaseFunction, TestCaseFunction_Custom, TestCaseFunction_WithActualResult +from .test_case_function import ( + TestCaseFunction, + TestCaseFunction_Custom, + TestCaseFunction_WithActualResult, +) from .test_case_id import TestCaseId from .test_case_implementation import TestCaseImplementation from .test_case_implementation_description import TestCaseImplementationDescription @@ -53,11 +61,17 @@ from .test_case_template import TestCaseTemplate from .test_case_template_id import TestCaseTemplateId from .test_case_v_2 import TestCaseV2 -from .test_case_with_actual_result_implementation import TestCaseWithActualResultImplementation +from .test_case_with_actual_result_implementation import ( + TestCaseWithActualResultImplementation, +) from .void_function_definition import VoidFunctionDefinition -from .void_function_definition_that_takes_actual_result import VoidFunctionDefinitionThatTakesActualResult +from .void_function_definition_that_takes_actual_result import ( + VoidFunctionDefinitionThatTakesActualResult, +) from .void_function_signature import VoidFunctionSignature -from .void_function_signature_that_takes_actual_result import VoidFunctionSignatureThatTakesActualResult +from .void_function_signature_that_takes_actual_result import ( + VoidFunctionSignatureThatTakesActualResult, +) __all__ = [ "AssertCorrectnessCheck", diff --git a/seed/python-sdk/trace/src/seed/v_2/problem/types/assert_correctness_check.py b/seed/python-sdk/trace/src/seed/v_2/problem/types/assert_correctness_check.py index 9ebdb63477b..7c1ce21eed4 100644 --- a/seed/python-sdk/trace/src/seed/v_2/problem/types/assert_correctness_check.py +++ b/seed/python-sdk/trace/src/seed/v_2/problem/types/assert_correctness_check.py @@ -5,7 +5,9 @@ import typing from .deep_equality_correctness_check import DeepEqualityCorrectnessCheck -from .void_function_definition_that_takes_actual_result import VoidFunctionDefinitionThatTakesActualResult +from .void_function_definition_that_takes_actual_result import ( + VoidFunctionDefinitionThatTakesActualResult, +) class AssertCorrectnessCheck_DeepEquality(DeepEqualityCorrectnessCheck): @@ -28,4 +30,6 @@ class Config: populate_by_name = True -AssertCorrectnessCheck = typing.Union[AssertCorrectnessCheck_DeepEquality, AssertCorrectnessCheck_Custom] +AssertCorrectnessCheck = typing.Union[ + AssertCorrectnessCheck_DeepEquality, AssertCorrectnessCheck_Custom +] diff --git a/seed/python-sdk/trace/src/seed/v_2/problem/types/basic_custom_files.py b/seed/python-sdk/trace/src/seed/v_2/problem/types/basic_custom_files.py index eda7a50401a..4e91dcf6c3c 100644 --- a/seed/python-sdk/trace/src/seed/v_2/problem/types/basic_custom_files.py +++ b/seed/python-sdk/trace/src/seed/v_2/problem/types/basic_custom_files.py @@ -14,15 +14,27 @@ class BasicCustomFiles(pydantic_v1.BaseModel): method_name: str = pydantic_v1.Field(alias="methodName") signature: NonVoidFunctionSignature - additional_files: typing.Dict[Language, Files] = pydantic_v1.Field(alias="additionalFiles") - basic_test_case_template: BasicTestCaseTemplate = pydantic_v1.Field(alias="basicTestCaseTemplate") + additional_files: typing.Dict[Language, Files] = pydantic_v1.Field( + alias="additionalFiles" + ) + basic_test_case_template: BasicTestCaseTemplate = pydantic_v1.Field( + alias="basicTestCaseTemplate" + ) def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/v_2/problem/types/basic_test_case_template.py b/seed/python-sdk/trace/src/seed/v_2/problem/types/basic_test_case_template.py index 67ed512fde1..d1656b929a0 100644 --- a/seed/python-sdk/trace/src/seed/v_2/problem/types/basic_test_case_template.py +++ b/seed/python-sdk/trace/src/seed/v_2/problem/types/basic_test_case_template.py @@ -14,14 +14,24 @@ class BasicTestCaseTemplate(pydantic_v1.BaseModel): template_id: TestCaseTemplateId = pydantic_v1.Field(alias="templateId") name: str description: TestCaseImplementationDescription - expected_value_parameter_id: ParameterId = pydantic_v1.Field(alias="expectedValueParameterId") + expected_value_parameter_id: ParameterId = pydantic_v1.Field( + alias="expectedValueParameterId" + ) def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/v_2/problem/types/create_problem_request_v_2.py b/seed/python-sdk/trace/src/seed/v_2/problem/types/create_problem_request_v_2.py index 8a503ad59f7..136e545f00c 100644 --- a/seed/python-sdk/trace/src/seed/v_2/problem/types/create_problem_request_v_2.py +++ b/seed/python-sdk/trace/src/seed/v_2/problem/types/create_problem_request_v_2.py @@ -14,19 +14,33 @@ class CreateProblemRequestV2(pydantic_v1.BaseModel): problem_name: str = pydantic_v1.Field(alias="problemName") - problem_description: ProblemDescription = pydantic_v1.Field(alias="problemDescription") + problem_description: ProblemDescription = pydantic_v1.Field( + alias="problemDescription" + ) custom_files: CustomFiles = pydantic_v1.Field(alias="customFiles") - custom_test_case_templates: typing.List[TestCaseTemplate] = pydantic_v1.Field(alias="customTestCaseTemplates") + custom_test_case_templates: typing.List[TestCaseTemplate] = pydantic_v1.Field( + alias="customTestCaseTemplates" + ) testcases: typing.List[TestCaseV2] - supported_languages: typing.Set[Language] = pydantic_v1.Field(alias="supportedLanguages") + supported_languages: typing.Set[Language] = pydantic_v1.Field( + alias="supportedLanguages" + ) is_public: bool = pydantic_v1.Field(alias="isPublic") def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/v_2/problem/types/deep_equality_correctness_check.py b/seed/python-sdk/trace/src/seed/v_2/problem/types/deep_equality_correctness_check.py index 73c6a448a98..bcd9e8fe90f 100644 --- a/seed/python-sdk/trace/src/seed/v_2/problem/types/deep_equality_correctness_check.py +++ b/seed/python-sdk/trace/src/seed/v_2/problem/types/deep_equality_correctness_check.py @@ -9,14 +9,24 @@ class DeepEqualityCorrectnessCheck(pydantic_v1.BaseModel): - expected_value_parameter_id: ParameterId = pydantic_v1.Field(alias="expectedValueParameterId") + expected_value_parameter_id: ParameterId = pydantic_v1.Field( + alias="expectedValueParameterId" + ) def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/v_2/problem/types/default_provided_file.py b/seed/python-sdk/trace/src/seed/v_2/problem/types/default_provided_file.py index 34d6a507f70..2f682142088 100644 --- a/seed/python-sdk/trace/src/seed/v_2/problem/types/default_provided_file.py +++ b/seed/python-sdk/trace/src/seed/v_2/problem/types/default_provided_file.py @@ -14,11 +14,19 @@ class DefaultProvidedFile(pydantic_v1.BaseModel): related_types: typing.List[VariableType] = pydantic_v1.Field(alias="relatedTypes") def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/v_2/problem/types/file_info_v_2.py b/seed/python-sdk/trace/src/seed/v_2/problem/types/file_info_v_2.py index 84b2fdc17b6..53211eae2fd 100644 --- a/seed/python-sdk/trace/src/seed/v_2/problem/types/file_info_v_2.py +++ b/seed/python-sdk/trace/src/seed/v_2/problem/types/file_info_v_2.py @@ -14,11 +14,19 @@ class FileInfoV2(pydantic_v1.BaseModel): editable: bool def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/v_2/problem/types/files.py b/seed/python-sdk/trace/src/seed/v_2/problem/types/files.py index 70811d96320..71e20840758 100644 --- a/seed/python-sdk/trace/src/seed/v_2/problem/types/files.py +++ b/seed/python-sdk/trace/src/seed/v_2/problem/types/files.py @@ -12,11 +12,19 @@ class Files(pydantic_v1.BaseModel): files: typing.List[FileInfoV2] def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/v_2/problem/types/function_implementation.py b/seed/python-sdk/trace/src/seed/v_2/problem/types/function_implementation.py index 69df6f1b1f9..614acc62204 100644 --- a/seed/python-sdk/trace/src/seed/v_2/problem/types/function_implementation.py +++ b/seed/python-sdk/trace/src/seed/v_2/problem/types/function_implementation.py @@ -12,11 +12,19 @@ class FunctionImplementation(pydantic_v1.BaseModel): imports: typing.Optional[str] = None def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/v_2/problem/types/function_implementation_for_multiple_languages.py b/seed/python-sdk/trace/src/seed/v_2/problem/types/function_implementation_for_multiple_languages.py index 61d1046451e..25816854c45 100644 --- a/seed/python-sdk/trace/src/seed/v_2/problem/types/function_implementation_for_multiple_languages.py +++ b/seed/python-sdk/trace/src/seed/v_2/problem/types/function_implementation_for_multiple_languages.py @@ -10,14 +10,24 @@ class FunctionImplementationForMultipleLanguages(pydantic_v1.BaseModel): - code_by_language: typing.Dict[Language, FunctionImplementation] = pydantic_v1.Field(alias="codeByLanguage") + code_by_language: typing.Dict[Language, FunctionImplementation] = pydantic_v1.Field( + alias="codeByLanguage" + ) def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/v_2/problem/types/function_signature.py b/seed/python-sdk/trace/src/seed/v_2/problem/types/function_signature.py index 8c74dcc76a1..334d588fd60 100644 --- a/seed/python-sdk/trace/src/seed/v_2/problem/types/function_signature.py +++ b/seed/python-sdk/trace/src/seed/v_2/problem/types/function_signature.py @@ -6,7 +6,9 @@ from .non_void_function_signature import NonVoidFunctionSignature from .void_function_signature import VoidFunctionSignature -from .void_function_signature_that_takes_actual_result import VoidFunctionSignatureThatTakesActualResult +from .void_function_signature_that_takes_actual_result import ( + VoidFunctionSignatureThatTakesActualResult, +) class FunctionSignature_Void(VoidFunctionSignature): @@ -29,7 +31,9 @@ class Config: populate_by_name = True -class FunctionSignature_VoidThatTakesActualResult(VoidFunctionSignatureThatTakesActualResult): +class FunctionSignature_VoidThatTakesActualResult( + VoidFunctionSignatureThatTakesActualResult +): type: typing.Literal["voidThatTakesActualResult"] = "voidThatTakesActualResult" class Config: @@ -40,5 +44,7 @@ class Config: FunctionSignature = typing.Union[ - FunctionSignature_Void, FunctionSignature_NonVoid, FunctionSignature_VoidThatTakesActualResult + FunctionSignature_Void, + FunctionSignature_NonVoid, + FunctionSignature_VoidThatTakesActualResult, ] diff --git a/seed/python-sdk/trace/src/seed/v_2/problem/types/generated_files.py b/seed/python-sdk/trace/src/seed/v_2/problem/types/generated_files.py index a3ccd4d8663..54da8e42210 100644 --- a/seed/python-sdk/trace/src/seed/v_2/problem/types/generated_files.py +++ b/seed/python-sdk/trace/src/seed/v_2/problem/types/generated_files.py @@ -10,16 +10,28 @@ class GeneratedFiles(pydantic_v1.BaseModel): - generated_test_case_files: typing.Dict[Language, Files] = pydantic_v1.Field(alias="generatedTestCaseFiles") - generated_template_files: typing.Dict[Language, Files] = pydantic_v1.Field(alias="generatedTemplateFiles") + generated_test_case_files: typing.Dict[Language, Files] = pydantic_v1.Field( + alias="generatedTestCaseFiles" + ) + generated_template_files: typing.Dict[Language, Files] = pydantic_v1.Field( + alias="generatedTemplateFiles" + ) other: typing.Dict[Language, Files] def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/v_2/problem/types/get_basic_solution_file_request.py b/seed/python-sdk/trace/src/seed/v_2/problem/types/get_basic_solution_file_request.py index f9bd4d87984..cc3ba49f107 100644 --- a/seed/python-sdk/trace/src/seed/v_2/problem/types/get_basic_solution_file_request.py +++ b/seed/python-sdk/trace/src/seed/v_2/problem/types/get_basic_solution_file_request.py @@ -13,11 +13,19 @@ class GetBasicSolutionFileRequest(pydantic_v1.BaseModel): signature: NonVoidFunctionSignature def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/v_2/problem/types/get_basic_solution_file_response.py b/seed/python-sdk/trace/src/seed/v_2/problem/types/get_basic_solution_file_response.py index ea499b37838..abccf232635 100644 --- a/seed/python-sdk/trace/src/seed/v_2/problem/types/get_basic_solution_file_response.py +++ b/seed/python-sdk/trace/src/seed/v_2/problem/types/get_basic_solution_file_response.py @@ -10,14 +10,24 @@ class GetBasicSolutionFileResponse(pydantic_v1.BaseModel): - solution_file_by_language: typing.Dict[Language, FileInfoV2] = pydantic_v1.Field(alias="solutionFileByLanguage") + solution_file_by_language: typing.Dict[Language, FileInfoV2] = pydantic_v1.Field( + alias="solutionFileByLanguage" + ) def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/v_2/problem/types/get_function_signature_request.py b/seed/python-sdk/trace/src/seed/v_2/problem/types/get_function_signature_request.py index b7129c52d44..a2789a2b512 100644 --- a/seed/python-sdk/trace/src/seed/v_2/problem/types/get_function_signature_request.py +++ b/seed/python-sdk/trace/src/seed/v_2/problem/types/get_function_signature_request.py @@ -12,11 +12,19 @@ class GetFunctionSignatureRequest(pydantic_v1.BaseModel): function_signature: FunctionSignature = pydantic_v1.Field(alias="functionSignature") def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/v_2/problem/types/get_function_signature_response.py b/seed/python-sdk/trace/src/seed/v_2/problem/types/get_function_signature_response.py index a3d81eb957e..757063e14ac 100644 --- a/seed/python-sdk/trace/src/seed/v_2/problem/types/get_function_signature_response.py +++ b/seed/python-sdk/trace/src/seed/v_2/problem/types/get_function_signature_response.py @@ -9,14 +9,24 @@ class GetFunctionSignatureResponse(pydantic_v1.BaseModel): - function_by_language: typing.Dict[Language, str] = pydantic_v1.Field(alias="functionByLanguage") + function_by_language: typing.Dict[Language, str] = pydantic_v1.Field( + alias="functionByLanguage" + ) def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/v_2/problem/types/get_generated_test_case_file_request.py b/seed/python-sdk/trace/src/seed/v_2/problem/types/get_generated_test_case_file_request.py index bbef1a779cd..2bda6b59a36 100644 --- a/seed/python-sdk/trace/src/seed/v_2/problem/types/get_generated_test_case_file_request.py +++ b/seed/python-sdk/trace/src/seed/v_2/problem/types/get_generated_test_case_file_request.py @@ -14,11 +14,19 @@ class GetGeneratedTestCaseFileRequest(pydantic_v1.BaseModel): test_case: TestCaseV2 = pydantic_v1.Field(alias="testCase") def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/v_2/problem/types/get_generated_test_case_template_file_request.py b/seed/python-sdk/trace/src/seed/v_2/problem/types/get_generated_test_case_template_file_request.py index 28040c7e28f..0d0082805e4 100644 --- a/seed/python-sdk/trace/src/seed/v_2/problem/types/get_generated_test_case_template_file_request.py +++ b/seed/python-sdk/trace/src/seed/v_2/problem/types/get_generated_test_case_template_file_request.py @@ -12,11 +12,19 @@ class GetGeneratedTestCaseTemplateFileRequest(pydantic_v1.BaseModel): template: TestCaseTemplate def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/v_2/problem/types/lightweight_problem_info_v_2.py b/seed/python-sdk/trace/src/seed/v_2/problem/types/lightweight_problem_info_v_2.py index d8b5405b6b2..2ab090f8868 100644 --- a/seed/python-sdk/trace/src/seed/v_2/problem/types/lightweight_problem_info_v_2.py +++ b/seed/python-sdk/trace/src/seed/v_2/problem/types/lightweight_problem_info_v_2.py @@ -16,11 +16,19 @@ class LightweightProblemInfoV2(pydantic_v1.BaseModel): variable_types: typing.List[VariableType] = pydantic_v1.Field(alias="variableTypes") def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/v_2/problem/types/non_void_function_definition.py b/seed/python-sdk/trace/src/seed/v_2/problem/types/non_void_function_definition.py index e81e3d95510..1ced13dcd21 100644 --- a/seed/python-sdk/trace/src/seed/v_2/problem/types/non_void_function_definition.py +++ b/seed/python-sdk/trace/src/seed/v_2/problem/types/non_void_function_definition.py @@ -5,7 +5,9 @@ from ....core.datetime_utils import serialize_datetime from ....core.pydantic_utilities import pydantic_v1 -from .function_implementation_for_multiple_languages import FunctionImplementationForMultipleLanguages +from .function_implementation_for_multiple_languages import ( + FunctionImplementationForMultipleLanguages, +) from .non_void_function_signature import NonVoidFunctionSignature @@ -14,11 +16,19 @@ class NonVoidFunctionDefinition(pydantic_v1.BaseModel): code: FunctionImplementationForMultipleLanguages def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/v_2/problem/types/non_void_function_signature.py b/seed/python-sdk/trace/src/seed/v_2/problem/types/non_void_function_signature.py index 5d7e6f0ddff..4ec7655db47 100644 --- a/seed/python-sdk/trace/src/seed/v_2/problem/types/non_void_function_signature.py +++ b/seed/python-sdk/trace/src/seed/v_2/problem/types/non_void_function_signature.py @@ -14,11 +14,19 @@ class NonVoidFunctionSignature(pydantic_v1.BaseModel): return_type: VariableType = pydantic_v1.Field(alias="returnType") def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/v_2/problem/types/parameter.py b/seed/python-sdk/trace/src/seed/v_2/problem/types/parameter.py index 7e4f9454dbc..2bc97cfce12 100644 --- a/seed/python-sdk/trace/src/seed/v_2/problem/types/parameter.py +++ b/seed/python-sdk/trace/src/seed/v_2/problem/types/parameter.py @@ -15,11 +15,19 @@ class Parameter(pydantic_v1.BaseModel): variable_type: VariableType = pydantic_v1.Field(alias="variableType") def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/v_2/problem/types/problem_info_v_2.py b/seed/python-sdk/trace/src/seed/v_2/problem/types/problem_info_v_2.py index 91e963c4981..e1f45b70c95 100644 --- a/seed/python-sdk/trace/src/seed/v_2/problem/types/problem_info_v_2.py +++ b/seed/python-sdk/trace/src/seed/v_2/problem/types/problem_info_v_2.py @@ -16,22 +16,36 @@ class ProblemInfoV2(pydantic_v1.BaseModel): problem_id: ProblemId = pydantic_v1.Field(alias="problemId") - problem_description: ProblemDescription = pydantic_v1.Field(alias="problemDescription") + problem_description: ProblemDescription = pydantic_v1.Field( + alias="problemDescription" + ) problem_name: str = pydantic_v1.Field(alias="problemName") problem_version: int = pydantic_v1.Field(alias="problemVersion") - supported_languages: typing.Set[Language] = pydantic_v1.Field(alias="supportedLanguages") + supported_languages: typing.Set[Language] = pydantic_v1.Field( + alias="supportedLanguages" + ) custom_files: CustomFiles = pydantic_v1.Field(alias="customFiles") generated_files: GeneratedFiles = pydantic_v1.Field(alias="generatedFiles") - custom_test_case_templates: typing.List[TestCaseTemplate] = pydantic_v1.Field(alias="customTestCaseTemplates") + custom_test_case_templates: typing.List[TestCaseTemplate] = pydantic_v1.Field( + alias="customTestCaseTemplates" + ) testcases: typing.List[TestCaseV2] is_public: bool = pydantic_v1.Field(alias="isPublic") def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/v_2/problem/types/test_case_expects.py b/seed/python-sdk/trace/src/seed/v_2/problem/types/test_case_expects.py index daf83e80c66..80ab1794562 100644 --- a/seed/python-sdk/trace/src/seed/v_2/problem/types/test_case_expects.py +++ b/seed/python-sdk/trace/src/seed/v_2/problem/types/test_case_expects.py @@ -8,14 +8,24 @@ class TestCaseExpects(pydantic_v1.BaseModel): - expected_stdout: typing.Optional[str] = pydantic_v1.Field(alias="expectedStdout", default=None) + expected_stdout: typing.Optional[str] = pydantic_v1.Field( + alias="expectedStdout", default=None + ) def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/v_2/problem/types/test_case_function.py b/seed/python-sdk/trace/src/seed/v_2/problem/types/test_case_function.py index f40bbe8ed89..677a9d239db 100644 --- a/seed/python-sdk/trace/src/seed/v_2/problem/types/test_case_function.py +++ b/seed/python-sdk/trace/src/seed/v_2/problem/types/test_case_function.py @@ -4,7 +4,9 @@ import typing -from .test_case_with_actual_result_implementation import TestCaseWithActualResultImplementation +from .test_case_with_actual_result_implementation import ( + TestCaseWithActualResultImplementation, +) from .void_function_definition import VoidFunctionDefinition @@ -28,4 +30,6 @@ class Config: populate_by_name = True -TestCaseFunction = typing.Union[TestCaseFunction_WithActualResult, TestCaseFunction_Custom] +TestCaseFunction = typing.Union[ + TestCaseFunction_WithActualResult, TestCaseFunction_Custom +] diff --git a/seed/python-sdk/trace/src/seed/v_2/problem/types/test_case_implementation.py b/seed/python-sdk/trace/src/seed/v_2/problem/types/test_case_implementation.py index 1637a276408..38afbf6c094 100644 --- a/seed/python-sdk/trace/src/seed/v_2/problem/types/test_case_implementation.py +++ b/seed/python-sdk/trace/src/seed/v_2/problem/types/test_case_implementation.py @@ -14,11 +14,19 @@ class TestCaseImplementation(pydantic_v1.BaseModel): function: TestCaseFunction def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/v_2/problem/types/test_case_implementation_description.py b/seed/python-sdk/trace/src/seed/v_2/problem/types/test_case_implementation_description.py index 111e28ad9d4..02a916b1b1f 100644 --- a/seed/python-sdk/trace/src/seed/v_2/problem/types/test_case_implementation_description.py +++ b/seed/python-sdk/trace/src/seed/v_2/problem/types/test_case_implementation_description.py @@ -5,18 +5,28 @@ from ....core.datetime_utils import serialize_datetime from ....core.pydantic_utilities import pydantic_v1 -from .test_case_implementation_description_board import TestCaseImplementationDescriptionBoard +from .test_case_implementation_description_board import ( + TestCaseImplementationDescriptionBoard, +) class TestCaseImplementationDescription(pydantic_v1.BaseModel): boards: typing.List[TestCaseImplementationDescriptionBoard] def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/v_2/problem/types/test_case_implementation_description_board.py b/seed/python-sdk/trace/src/seed/v_2/problem/types/test_case_implementation_description_board.py index 5a7367560bf..41156aa6194 100644 --- a/seed/python-sdk/trace/src/seed/v_2/problem/types/test_case_implementation_description_board.py +++ b/seed/python-sdk/trace/src/seed/v_2/problem/types/test_case_implementation_description_board.py @@ -27,5 +27,6 @@ class Config: TestCaseImplementationDescriptionBoard = typing.Union[ - TestCaseImplementationDescriptionBoard_Html, TestCaseImplementationDescriptionBoard_ParamId + TestCaseImplementationDescriptionBoard_Html, + TestCaseImplementationDescriptionBoard_ParamId, ] diff --git a/seed/python-sdk/trace/src/seed/v_2/problem/types/test_case_implementation_reference.py b/seed/python-sdk/trace/src/seed/v_2/problem/types/test_case_implementation_reference.py index a55a8cd0def..aa9731a4644 100644 --- a/seed/python-sdk/trace/src/seed/v_2/problem/types/test_case_implementation_reference.py +++ b/seed/python-sdk/trace/src/seed/v_2/problem/types/test_case_implementation_reference.py @@ -29,5 +29,6 @@ class Config: TestCaseImplementationReference = typing.Union[ - TestCaseImplementationReference_TemplateId, TestCaseImplementationReference_Implementation + TestCaseImplementationReference_TemplateId, + TestCaseImplementationReference_Implementation, ] diff --git a/seed/python-sdk/trace/src/seed/v_2/problem/types/test_case_metadata.py b/seed/python-sdk/trace/src/seed/v_2/problem/types/test_case_metadata.py index d7eca1471b3..67a89dc8a6a 100644 --- a/seed/python-sdk/trace/src/seed/v_2/problem/types/test_case_metadata.py +++ b/seed/python-sdk/trace/src/seed/v_2/problem/types/test_case_metadata.py @@ -14,11 +14,19 @@ class TestCaseMetadata(pydantic_v1.BaseModel): hidden: bool def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/v_2/problem/types/test_case_template.py b/seed/python-sdk/trace/src/seed/v_2/problem/types/test_case_template.py index 5128f3feeb2..abd97c670cf 100644 --- a/seed/python-sdk/trace/src/seed/v_2/problem/types/test_case_template.py +++ b/seed/python-sdk/trace/src/seed/v_2/problem/types/test_case_template.py @@ -15,11 +15,19 @@ class TestCaseTemplate(pydantic_v1.BaseModel): implementation: TestCaseImplementation def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/v_2/problem/types/test_case_v_2.py b/seed/python-sdk/trace/src/seed/v_2/problem/types/test_case_v_2.py index 120770b3577..853919d1911 100644 --- a/seed/python-sdk/trace/src/seed/v_2/problem/types/test_case_v_2.py +++ b/seed/python-sdk/trace/src/seed/v_2/problem/types/test_case_v_2.py @@ -19,11 +19,19 @@ class TestCaseV2(pydantic_v1.BaseModel): expects: typing.Optional[TestCaseExpects] = None def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/v_2/problem/types/test_case_with_actual_result_implementation.py b/seed/python-sdk/trace/src/seed/v_2/problem/types/test_case_with_actual_result_implementation.py index cdd6b3a84df..6f67138ad26 100644 --- a/seed/python-sdk/trace/src/seed/v_2/problem/types/test_case_with_actual_result_implementation.py +++ b/seed/python-sdk/trace/src/seed/v_2/problem/types/test_case_with_actual_result_implementation.py @@ -10,15 +10,27 @@ class TestCaseWithActualResultImplementation(pydantic_v1.BaseModel): - get_actual_result: NonVoidFunctionDefinition = pydantic_v1.Field(alias="getActualResult") - assert_correctness_check: AssertCorrectnessCheck = pydantic_v1.Field(alias="assertCorrectnessCheck") + get_actual_result: NonVoidFunctionDefinition = pydantic_v1.Field( + alias="getActualResult" + ) + assert_correctness_check: AssertCorrectnessCheck = pydantic_v1.Field( + alias="assertCorrectnessCheck" + ) def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/v_2/problem/types/void_function_definition.py b/seed/python-sdk/trace/src/seed/v_2/problem/types/void_function_definition.py index b0487603de1..a39f987cca7 100644 --- a/seed/python-sdk/trace/src/seed/v_2/problem/types/void_function_definition.py +++ b/seed/python-sdk/trace/src/seed/v_2/problem/types/void_function_definition.py @@ -5,7 +5,9 @@ from ....core.datetime_utils import serialize_datetime from ....core.pydantic_utilities import pydantic_v1 -from .function_implementation_for_multiple_languages import FunctionImplementationForMultipleLanguages +from .function_implementation_for_multiple_languages import ( + FunctionImplementationForMultipleLanguages, +) from .parameter import Parameter @@ -14,11 +16,19 @@ class VoidFunctionDefinition(pydantic_v1.BaseModel): code: FunctionImplementationForMultipleLanguages def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/v_2/problem/types/void_function_definition_that_takes_actual_result.py b/seed/python-sdk/trace/src/seed/v_2/problem/types/void_function_definition_that_takes_actual_result.py index 91878d60f5e..191da4fe076 100644 --- a/seed/python-sdk/trace/src/seed/v_2/problem/types/void_function_definition_that_takes_actual_result.py +++ b/seed/python-sdk/trace/src/seed/v_2/problem/types/void_function_definition_that_takes_actual_result.py @@ -5,7 +5,9 @@ from ....core.datetime_utils import serialize_datetime from ....core.pydantic_utilities import pydantic_v1 -from .function_implementation_for_multiple_languages import FunctionImplementationForMultipleLanguages +from .function_implementation_for_multiple_languages import ( + FunctionImplementationForMultipleLanguages, +) from .parameter import Parameter @@ -14,15 +16,25 @@ class VoidFunctionDefinitionThatTakesActualResult(pydantic_v1.BaseModel): The generated signature will include an additional param, actualResult """ - additional_parameters: typing.List[Parameter] = pydantic_v1.Field(alias="additionalParameters") + additional_parameters: typing.List[Parameter] = pydantic_v1.Field( + alias="additionalParameters" + ) code: FunctionImplementationForMultipleLanguages def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/v_2/problem/types/void_function_signature.py b/seed/python-sdk/trace/src/seed/v_2/problem/types/void_function_signature.py index 398d5848dc0..e28da65a575 100644 --- a/seed/python-sdk/trace/src/seed/v_2/problem/types/void_function_signature.py +++ b/seed/python-sdk/trace/src/seed/v_2/problem/types/void_function_signature.py @@ -12,11 +12,19 @@ class VoidFunctionSignature(pydantic_v1.BaseModel): parameters: typing.List[Parameter] def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/v_2/problem/types/void_function_signature_that_takes_actual_result.py b/seed/python-sdk/trace/src/seed/v_2/problem/types/void_function_signature_that_takes_actual_result.py index 6bf61ecdefc..3f82cb20f24 100644 --- a/seed/python-sdk/trace/src/seed/v_2/problem/types/void_function_signature_that_takes_actual_result.py +++ b/seed/python-sdk/trace/src/seed/v_2/problem/types/void_function_signature_that_takes_actual_result.py @@ -14,11 +14,19 @@ class VoidFunctionSignatureThatTakesActualResult(pydantic_v1.BaseModel): actual_result_type: VariableType = pydantic_v1.Field(alias="actualResultType") def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/v_2/v_3/problem/client.py b/seed/python-sdk/trace/src/seed/v_2/v_3/problem/client.py index 3f616a8e218..01587952637 100644 --- a/seed/python-sdk/trace/src/seed/v_2/v_3/problem/client.py +++ b/seed/python-sdk/trace/src/seed/v_2/v_3/problem/client.py @@ -38,33 +38,49 @@ def get_lightweight_problems( """ _response = self._client_wrapper.httpx_client.request( "GET", - urllib.parse.urljoin(f"{self._client_wrapper.get_base_url()}/", "problems-v2/lightweight-problem-info"), + urllib.parse.urljoin( + f"{self._client_wrapper.get_base_url()}/", + "problems-v2/lightweight-problem-info", + ), params=jsonable_encoder( - request_options.get("additional_query_parameters") if request_options is not None else None + request_options.get("additional_query_parameters") + if request_options is not None + else None ), headers=jsonable_encoder( remove_none_from_dict( { **self._client_wrapper.get_headers(), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), timeout=request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self._client_wrapper.get_timeout(), retries=0, - max_retries=request_options.get("max_retries") if request_options is not None else 0, # type: ignore + max_retries=request_options.get("max_retries") + if request_options is not None + else 0, # type: ignore ) try: _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) if 200 <= _response.status_code < 300: - return pydantic_v1.parse_obj_as(typing.List[LightweightProblemInfoV2], _response_json) # type: ignore + return pydantic_v1.parse_obj_as( + typing.List[LightweightProblemInfoV2], _response_json + ) # type: ignore raise ApiError(status_code=_response.status_code, body=_response_json) - def get_problems(self, *, request_options: typing.Optional[RequestOptions] = None) -> typing.List[ProblemInfoV2]: + def get_problems( + self, *, request_options: typing.Optional[RequestOptions] = None + ) -> typing.List[ProblemInfoV2]: """ Returns latest versions of all problems @@ -81,23 +97,34 @@ def get_problems(self, *, request_options: typing.Optional[RequestOptions] = Non """ _response = self._client_wrapper.httpx_client.request( "GET", - urllib.parse.urljoin(f"{self._client_wrapper.get_base_url()}/", "problems-v2/problem-info"), + urllib.parse.urljoin( + f"{self._client_wrapper.get_base_url()}/", "problems-v2/problem-info" + ), params=jsonable_encoder( - request_options.get("additional_query_parameters") if request_options is not None else None + request_options.get("additional_query_parameters") + if request_options is not None + else None ), headers=jsonable_encoder( remove_none_from_dict( { **self._client_wrapper.get_headers(), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), timeout=request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self._client_wrapper.get_timeout(), retries=0, - max_retries=request_options.get("max_retries") if request_options is not None else 0, # type: ignore + max_retries=request_options.get("max_retries") + if request_options is not None + else 0, # type: ignore ) try: _response_json = _response.json() @@ -108,7 +135,10 @@ def get_problems(self, *, request_options: typing.Optional[RequestOptions] = Non raise ApiError(status_code=_response.status_code, body=_response_json) def get_latest_problem( - self, problem_id: ProblemId, *, request_options: typing.Optional[RequestOptions] = None + self, + problem_id: ProblemId, + *, + request_options: typing.Optional[RequestOptions] = None, ) -> ProblemInfoV2: """ Returns latest version of a problem @@ -131,24 +161,34 @@ def get_latest_problem( _response = self._client_wrapper.httpx_client.request( "GET", urllib.parse.urljoin( - f"{self._client_wrapper.get_base_url()}/", f"problems-v2/problem-info/{jsonable_encoder(problem_id)}" + f"{self._client_wrapper.get_base_url()}/", + f"problems-v2/problem-info/{jsonable_encoder(problem_id)}", ), params=jsonable_encoder( - request_options.get("additional_query_parameters") if request_options is not None else None + request_options.get("additional_query_parameters") + if request_options is not None + else None ), headers=jsonable_encoder( remove_none_from_dict( { **self._client_wrapper.get_headers(), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), timeout=request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self._client_wrapper.get_timeout(), retries=0, - max_retries=request_options.get("max_retries") if request_options is not None else 0, # type: ignore + max_retries=request_options.get("max_retries") + if request_options is not None + else 0, # type: ignore ) try: _response_json = _response.json() @@ -159,7 +199,11 @@ def get_latest_problem( raise ApiError(status_code=_response.status_code, body=_response_json) def get_problem_version( - self, problem_id: ProblemId, problem_version: int, *, request_options: typing.Optional[RequestOptions] = None + self, + problem_id: ProblemId, + problem_version: int, + *, + request_options: typing.Optional[RequestOptions] = None, ) -> ProblemInfoV2: """ Returns requested version of a problem @@ -189,21 +233,30 @@ def get_problem_version( f"problems-v2/problem-info/{jsonable_encoder(problem_id)}/version/{jsonable_encoder(problem_version)}", ), params=jsonable_encoder( - request_options.get("additional_query_parameters") if request_options is not None else None + request_options.get("additional_query_parameters") + if request_options is not None + else None ), headers=jsonable_encoder( remove_none_from_dict( { **self._client_wrapper.get_headers(), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), timeout=request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self._client_wrapper.get_timeout(), retries=0, - max_retries=request_options.get("max_retries") if request_options is not None else 0, # type: ignore + max_retries=request_options.get("max_retries") + if request_options is not None + else 0, # type: ignore ) try: _response_json = _response.json() @@ -237,30 +290,44 @@ async def get_lightweight_problems( """ _response = await self._client_wrapper.httpx_client.request( "GET", - urllib.parse.urljoin(f"{self._client_wrapper.get_base_url()}/", "problems-v2/lightweight-problem-info"), + urllib.parse.urljoin( + f"{self._client_wrapper.get_base_url()}/", + "problems-v2/lightweight-problem-info", + ), params=jsonable_encoder( - request_options.get("additional_query_parameters") if request_options is not None else None + request_options.get("additional_query_parameters") + if request_options is not None + else None ), headers=jsonable_encoder( remove_none_from_dict( { **self._client_wrapper.get_headers(), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), timeout=request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self._client_wrapper.get_timeout(), retries=0, - max_retries=request_options.get("max_retries") if request_options is not None else 0, # type: ignore + max_retries=request_options.get("max_retries") + if request_options is not None + else 0, # type: ignore ) try: _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) if 200 <= _response.status_code < 300: - return pydantic_v1.parse_obj_as(typing.List[LightweightProblemInfoV2], _response_json) # type: ignore + return pydantic_v1.parse_obj_as( + typing.List[LightweightProblemInfoV2], _response_json + ) # type: ignore raise ApiError(status_code=_response.status_code, body=_response_json) async def get_problems( @@ -282,23 +349,34 @@ async def get_problems( """ _response = await self._client_wrapper.httpx_client.request( "GET", - urllib.parse.urljoin(f"{self._client_wrapper.get_base_url()}/", "problems-v2/problem-info"), + urllib.parse.urljoin( + f"{self._client_wrapper.get_base_url()}/", "problems-v2/problem-info" + ), params=jsonable_encoder( - request_options.get("additional_query_parameters") if request_options is not None else None + request_options.get("additional_query_parameters") + if request_options is not None + else None ), headers=jsonable_encoder( remove_none_from_dict( { **self._client_wrapper.get_headers(), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), timeout=request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self._client_wrapper.get_timeout(), retries=0, - max_retries=request_options.get("max_retries") if request_options is not None else 0, # type: ignore + max_retries=request_options.get("max_retries") + if request_options is not None + else 0, # type: ignore ) try: _response_json = _response.json() @@ -309,7 +387,10 @@ async def get_problems( raise ApiError(status_code=_response.status_code, body=_response_json) async def get_latest_problem( - self, problem_id: ProblemId, *, request_options: typing.Optional[RequestOptions] = None + self, + problem_id: ProblemId, + *, + request_options: typing.Optional[RequestOptions] = None, ) -> ProblemInfoV2: """ Returns latest version of a problem @@ -332,24 +413,34 @@ async def get_latest_problem( _response = await self._client_wrapper.httpx_client.request( "GET", urllib.parse.urljoin( - f"{self._client_wrapper.get_base_url()}/", f"problems-v2/problem-info/{jsonable_encoder(problem_id)}" + f"{self._client_wrapper.get_base_url()}/", + f"problems-v2/problem-info/{jsonable_encoder(problem_id)}", ), params=jsonable_encoder( - request_options.get("additional_query_parameters") if request_options is not None else None + request_options.get("additional_query_parameters") + if request_options is not None + else None ), headers=jsonable_encoder( remove_none_from_dict( { **self._client_wrapper.get_headers(), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), timeout=request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self._client_wrapper.get_timeout(), retries=0, - max_retries=request_options.get("max_retries") if request_options is not None else 0, # type: ignore + max_retries=request_options.get("max_retries") + if request_options is not None + else 0, # type: ignore ) try: _response_json = _response.json() @@ -360,7 +451,11 @@ async def get_latest_problem( raise ApiError(status_code=_response.status_code, body=_response_json) async def get_problem_version( - self, problem_id: ProblemId, problem_version: int, *, request_options: typing.Optional[RequestOptions] = None + self, + problem_id: ProblemId, + problem_version: int, + *, + request_options: typing.Optional[RequestOptions] = None, ) -> ProblemInfoV2: """ Returns requested version of a problem @@ -390,21 +485,30 @@ async def get_problem_version( f"problems-v2/problem-info/{jsonable_encoder(problem_id)}/version/{jsonable_encoder(problem_version)}", ), params=jsonable_encoder( - request_options.get("additional_query_parameters") if request_options is not None else None + request_options.get("additional_query_parameters") + if request_options is not None + else None ), headers=jsonable_encoder( remove_none_from_dict( { **self._client_wrapper.get_headers(), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), timeout=request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self._client_wrapper.get_timeout(), retries=0, - max_retries=request_options.get("max_retries") if request_options is not None else 0, # type: ignore + max_retries=request_options.get("max_retries") + if request_options is not None + else 0, # type: ignore ) try: _response_json = _response.json() diff --git a/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/__init__.py b/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/__init__.py index b2b1239aeec..94e8654458c 100644 --- a/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/__init__.py +++ b/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/__init__.py @@ -14,7 +14,9 @@ from .file_info_v_2 import FileInfoV2 from .files import Files from .function_implementation import FunctionImplementation -from .function_implementation_for_multiple_languages import FunctionImplementationForMultipleLanguages +from .function_implementation_for_multiple_languages import ( + FunctionImplementationForMultipleLanguages, +) from .function_signature import ( FunctionSignature, FunctionSignature_NonVoid, @@ -27,7 +29,9 @@ from .get_function_signature_request import GetFunctionSignatureRequest from .get_function_signature_response import GetFunctionSignatureResponse from .get_generated_test_case_file_request import GetGeneratedTestCaseFileRequest -from .get_generated_test_case_template_file_request import GetGeneratedTestCaseTemplateFileRequest +from .get_generated_test_case_template_file_request import ( + GetGeneratedTestCaseTemplateFileRequest, +) from .lightweight_problem_info_v_2 import LightweightProblemInfoV2 from .non_void_function_definition import NonVoidFunctionDefinition from .non_void_function_signature import NonVoidFunctionSignature @@ -35,7 +39,11 @@ from .parameter_id import ParameterId from .problem_info_v_2 import ProblemInfoV2 from .test_case_expects import TestCaseExpects -from .test_case_function import TestCaseFunction, TestCaseFunction_Custom, TestCaseFunction_WithActualResult +from .test_case_function import ( + TestCaseFunction, + TestCaseFunction_Custom, + TestCaseFunction_WithActualResult, +) from .test_case_id import TestCaseId from .test_case_implementation import TestCaseImplementation from .test_case_implementation_description import TestCaseImplementationDescription @@ -53,11 +61,17 @@ from .test_case_template import TestCaseTemplate from .test_case_template_id import TestCaseTemplateId from .test_case_v_2 import TestCaseV2 -from .test_case_with_actual_result_implementation import TestCaseWithActualResultImplementation +from .test_case_with_actual_result_implementation import ( + TestCaseWithActualResultImplementation, +) from .void_function_definition import VoidFunctionDefinition -from .void_function_definition_that_takes_actual_result import VoidFunctionDefinitionThatTakesActualResult +from .void_function_definition_that_takes_actual_result import ( + VoidFunctionDefinitionThatTakesActualResult, +) from .void_function_signature import VoidFunctionSignature -from .void_function_signature_that_takes_actual_result import VoidFunctionSignatureThatTakesActualResult +from .void_function_signature_that_takes_actual_result import ( + VoidFunctionSignatureThatTakesActualResult, +) __all__ = [ "AssertCorrectnessCheck", diff --git a/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/assert_correctness_check.py b/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/assert_correctness_check.py index 9ebdb63477b..7c1ce21eed4 100644 --- a/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/assert_correctness_check.py +++ b/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/assert_correctness_check.py @@ -5,7 +5,9 @@ import typing from .deep_equality_correctness_check import DeepEqualityCorrectnessCheck -from .void_function_definition_that_takes_actual_result import VoidFunctionDefinitionThatTakesActualResult +from .void_function_definition_that_takes_actual_result import ( + VoidFunctionDefinitionThatTakesActualResult, +) class AssertCorrectnessCheck_DeepEquality(DeepEqualityCorrectnessCheck): @@ -28,4 +30,6 @@ class Config: populate_by_name = True -AssertCorrectnessCheck = typing.Union[AssertCorrectnessCheck_DeepEquality, AssertCorrectnessCheck_Custom] +AssertCorrectnessCheck = typing.Union[ + AssertCorrectnessCheck_DeepEquality, AssertCorrectnessCheck_Custom +] diff --git a/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/basic_custom_files.py b/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/basic_custom_files.py index 1ad36eeed85..afbe170060c 100644 --- a/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/basic_custom_files.py +++ b/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/basic_custom_files.py @@ -14,15 +14,27 @@ class BasicCustomFiles(pydantic_v1.BaseModel): method_name: str = pydantic_v1.Field(alias="methodName") signature: NonVoidFunctionSignature - additional_files: typing.Dict[Language, Files] = pydantic_v1.Field(alias="additionalFiles") - basic_test_case_template: BasicTestCaseTemplate = pydantic_v1.Field(alias="basicTestCaseTemplate") + additional_files: typing.Dict[Language, Files] = pydantic_v1.Field( + alias="additionalFiles" + ) + basic_test_case_template: BasicTestCaseTemplate = pydantic_v1.Field( + alias="basicTestCaseTemplate" + ) def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/basic_test_case_template.py b/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/basic_test_case_template.py index f8cbaa7bebb..f7e00e1b31e 100644 --- a/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/basic_test_case_template.py +++ b/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/basic_test_case_template.py @@ -14,14 +14,24 @@ class BasicTestCaseTemplate(pydantic_v1.BaseModel): template_id: TestCaseTemplateId = pydantic_v1.Field(alias="templateId") name: str description: TestCaseImplementationDescription - expected_value_parameter_id: ParameterId = pydantic_v1.Field(alias="expectedValueParameterId") + expected_value_parameter_id: ParameterId = pydantic_v1.Field( + alias="expectedValueParameterId" + ) def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/create_problem_request_v_2.py b/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/create_problem_request_v_2.py index 6d726e1e1b8..f3ff8dc110a 100644 --- a/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/create_problem_request_v_2.py +++ b/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/create_problem_request_v_2.py @@ -14,19 +14,33 @@ class CreateProblemRequestV2(pydantic_v1.BaseModel): problem_name: str = pydantic_v1.Field(alias="problemName") - problem_description: ProblemDescription = pydantic_v1.Field(alias="problemDescription") + problem_description: ProblemDescription = pydantic_v1.Field( + alias="problemDescription" + ) custom_files: CustomFiles = pydantic_v1.Field(alias="customFiles") - custom_test_case_templates: typing.List[TestCaseTemplate] = pydantic_v1.Field(alias="customTestCaseTemplates") + custom_test_case_templates: typing.List[TestCaseTemplate] = pydantic_v1.Field( + alias="customTestCaseTemplates" + ) testcases: typing.List[TestCaseV2] - supported_languages: typing.Set[Language] = pydantic_v1.Field(alias="supportedLanguages") + supported_languages: typing.Set[Language] = pydantic_v1.Field( + alias="supportedLanguages" + ) is_public: bool = pydantic_v1.Field(alias="isPublic") def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/deep_equality_correctness_check.py b/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/deep_equality_correctness_check.py index 8ce6b280f25..aa493092566 100644 --- a/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/deep_equality_correctness_check.py +++ b/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/deep_equality_correctness_check.py @@ -9,14 +9,24 @@ class DeepEqualityCorrectnessCheck(pydantic_v1.BaseModel): - expected_value_parameter_id: ParameterId = pydantic_v1.Field(alias="expectedValueParameterId") + expected_value_parameter_id: ParameterId = pydantic_v1.Field( + alias="expectedValueParameterId" + ) def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/default_provided_file.py b/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/default_provided_file.py index f09a2cc45c2..090c09f66b0 100644 --- a/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/default_provided_file.py +++ b/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/default_provided_file.py @@ -14,11 +14,19 @@ class DefaultProvidedFile(pydantic_v1.BaseModel): related_types: typing.List[VariableType] = pydantic_v1.Field(alias="relatedTypes") def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/file_info_v_2.py b/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/file_info_v_2.py index 8ae9721947a..2569f01ae45 100644 --- a/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/file_info_v_2.py +++ b/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/file_info_v_2.py @@ -14,11 +14,19 @@ class FileInfoV2(pydantic_v1.BaseModel): editable: bool def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/files.py b/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/files.py index 24b40b09e72..24afa3fc2e8 100644 --- a/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/files.py +++ b/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/files.py @@ -12,11 +12,19 @@ class Files(pydantic_v1.BaseModel): files: typing.List[FileInfoV2] def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/function_implementation.py b/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/function_implementation.py index c62ebe797e5..1887d7cce56 100644 --- a/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/function_implementation.py +++ b/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/function_implementation.py @@ -12,11 +12,19 @@ class FunctionImplementation(pydantic_v1.BaseModel): imports: typing.Optional[str] = None def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/function_implementation_for_multiple_languages.py b/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/function_implementation_for_multiple_languages.py index ef68c1affc1..510fa073fd5 100644 --- a/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/function_implementation_for_multiple_languages.py +++ b/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/function_implementation_for_multiple_languages.py @@ -10,14 +10,24 @@ class FunctionImplementationForMultipleLanguages(pydantic_v1.BaseModel): - code_by_language: typing.Dict[Language, FunctionImplementation] = pydantic_v1.Field(alias="codeByLanguage") + code_by_language: typing.Dict[Language, FunctionImplementation] = pydantic_v1.Field( + alias="codeByLanguage" + ) def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/function_signature.py b/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/function_signature.py index 8c74dcc76a1..334d588fd60 100644 --- a/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/function_signature.py +++ b/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/function_signature.py @@ -6,7 +6,9 @@ from .non_void_function_signature import NonVoidFunctionSignature from .void_function_signature import VoidFunctionSignature -from .void_function_signature_that_takes_actual_result import VoidFunctionSignatureThatTakesActualResult +from .void_function_signature_that_takes_actual_result import ( + VoidFunctionSignatureThatTakesActualResult, +) class FunctionSignature_Void(VoidFunctionSignature): @@ -29,7 +31,9 @@ class Config: populate_by_name = True -class FunctionSignature_VoidThatTakesActualResult(VoidFunctionSignatureThatTakesActualResult): +class FunctionSignature_VoidThatTakesActualResult( + VoidFunctionSignatureThatTakesActualResult +): type: typing.Literal["voidThatTakesActualResult"] = "voidThatTakesActualResult" class Config: @@ -40,5 +44,7 @@ class Config: FunctionSignature = typing.Union[ - FunctionSignature_Void, FunctionSignature_NonVoid, FunctionSignature_VoidThatTakesActualResult + FunctionSignature_Void, + FunctionSignature_NonVoid, + FunctionSignature_VoidThatTakesActualResult, ] diff --git a/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/generated_files.py b/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/generated_files.py index c218754035a..92b4031b8b3 100644 --- a/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/generated_files.py +++ b/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/generated_files.py @@ -10,16 +10,28 @@ class GeneratedFiles(pydantic_v1.BaseModel): - generated_test_case_files: typing.Dict[Language, Files] = pydantic_v1.Field(alias="generatedTestCaseFiles") - generated_template_files: typing.Dict[Language, Files] = pydantic_v1.Field(alias="generatedTemplateFiles") + generated_test_case_files: typing.Dict[Language, Files] = pydantic_v1.Field( + alias="generatedTestCaseFiles" + ) + generated_template_files: typing.Dict[Language, Files] = pydantic_v1.Field( + alias="generatedTemplateFiles" + ) other: typing.Dict[Language, Files] def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/get_basic_solution_file_request.py b/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/get_basic_solution_file_request.py index 3e0612adddd..44e312e0274 100644 --- a/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/get_basic_solution_file_request.py +++ b/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/get_basic_solution_file_request.py @@ -13,11 +13,19 @@ class GetBasicSolutionFileRequest(pydantic_v1.BaseModel): signature: NonVoidFunctionSignature def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/get_basic_solution_file_response.py b/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/get_basic_solution_file_response.py index 2eb42899c2d..1a876a21d06 100644 --- a/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/get_basic_solution_file_response.py +++ b/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/get_basic_solution_file_response.py @@ -10,14 +10,24 @@ class GetBasicSolutionFileResponse(pydantic_v1.BaseModel): - solution_file_by_language: typing.Dict[Language, FileInfoV2] = pydantic_v1.Field(alias="solutionFileByLanguage") + solution_file_by_language: typing.Dict[Language, FileInfoV2] = pydantic_v1.Field( + alias="solutionFileByLanguage" + ) def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/get_function_signature_request.py b/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/get_function_signature_request.py index e0c9cbeac43..7b03311a2db 100644 --- a/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/get_function_signature_request.py +++ b/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/get_function_signature_request.py @@ -12,11 +12,19 @@ class GetFunctionSignatureRequest(pydantic_v1.BaseModel): function_signature: FunctionSignature = pydantic_v1.Field(alias="functionSignature") def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/get_function_signature_response.py b/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/get_function_signature_response.py index 27a79eedf7a..d48d48ced2a 100644 --- a/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/get_function_signature_response.py +++ b/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/get_function_signature_response.py @@ -9,14 +9,24 @@ class GetFunctionSignatureResponse(pydantic_v1.BaseModel): - function_by_language: typing.Dict[Language, str] = pydantic_v1.Field(alias="functionByLanguage") + function_by_language: typing.Dict[Language, str] = pydantic_v1.Field( + alias="functionByLanguage" + ) def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/get_generated_test_case_file_request.py b/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/get_generated_test_case_file_request.py index 26d93c8c115..4310b98e9b6 100644 --- a/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/get_generated_test_case_file_request.py +++ b/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/get_generated_test_case_file_request.py @@ -14,11 +14,19 @@ class GetGeneratedTestCaseFileRequest(pydantic_v1.BaseModel): test_case: TestCaseV2 = pydantic_v1.Field(alias="testCase") def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/get_generated_test_case_template_file_request.py b/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/get_generated_test_case_template_file_request.py index 8c7a619ab0d..f2fb1d955ab 100644 --- a/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/get_generated_test_case_template_file_request.py +++ b/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/get_generated_test_case_template_file_request.py @@ -12,11 +12,19 @@ class GetGeneratedTestCaseTemplateFileRequest(pydantic_v1.BaseModel): template: TestCaseTemplate def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/lightweight_problem_info_v_2.py b/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/lightweight_problem_info_v_2.py index 5154f9864be..eb8bd03e93b 100644 --- a/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/lightweight_problem_info_v_2.py +++ b/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/lightweight_problem_info_v_2.py @@ -16,11 +16,19 @@ class LightweightProblemInfoV2(pydantic_v1.BaseModel): variable_types: typing.List[VariableType] = pydantic_v1.Field(alias="variableTypes") def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/non_void_function_definition.py b/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/non_void_function_definition.py index f65f1d0e279..583212b06e7 100644 --- a/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/non_void_function_definition.py +++ b/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/non_void_function_definition.py @@ -5,7 +5,9 @@ from .....core.datetime_utils import serialize_datetime from .....core.pydantic_utilities import pydantic_v1 -from .function_implementation_for_multiple_languages import FunctionImplementationForMultipleLanguages +from .function_implementation_for_multiple_languages import ( + FunctionImplementationForMultipleLanguages, +) from .non_void_function_signature import NonVoidFunctionSignature @@ -14,11 +16,19 @@ class NonVoidFunctionDefinition(pydantic_v1.BaseModel): code: FunctionImplementationForMultipleLanguages def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/non_void_function_signature.py b/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/non_void_function_signature.py index c22f43467ff..e837b6de842 100644 --- a/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/non_void_function_signature.py +++ b/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/non_void_function_signature.py @@ -14,11 +14,19 @@ class NonVoidFunctionSignature(pydantic_v1.BaseModel): return_type: VariableType = pydantic_v1.Field(alias="returnType") def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/parameter.py b/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/parameter.py index 7c5b84fdd32..4078a93ebe5 100644 --- a/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/parameter.py +++ b/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/parameter.py @@ -15,11 +15,19 @@ class Parameter(pydantic_v1.BaseModel): variable_type: VariableType = pydantic_v1.Field(alias="variableType") def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/problem_info_v_2.py b/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/problem_info_v_2.py index cf06b683962..c90aad5fcf2 100644 --- a/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/problem_info_v_2.py +++ b/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/problem_info_v_2.py @@ -16,22 +16,36 @@ class ProblemInfoV2(pydantic_v1.BaseModel): problem_id: ProblemId = pydantic_v1.Field(alias="problemId") - problem_description: ProblemDescription = pydantic_v1.Field(alias="problemDescription") + problem_description: ProblemDescription = pydantic_v1.Field( + alias="problemDescription" + ) problem_name: str = pydantic_v1.Field(alias="problemName") problem_version: int = pydantic_v1.Field(alias="problemVersion") - supported_languages: typing.Set[Language] = pydantic_v1.Field(alias="supportedLanguages") + supported_languages: typing.Set[Language] = pydantic_v1.Field( + alias="supportedLanguages" + ) custom_files: CustomFiles = pydantic_v1.Field(alias="customFiles") generated_files: GeneratedFiles = pydantic_v1.Field(alias="generatedFiles") - custom_test_case_templates: typing.List[TestCaseTemplate] = pydantic_v1.Field(alias="customTestCaseTemplates") + custom_test_case_templates: typing.List[TestCaseTemplate] = pydantic_v1.Field( + alias="customTestCaseTemplates" + ) testcases: typing.List[TestCaseV2] is_public: bool = pydantic_v1.Field(alias="isPublic") def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/test_case_expects.py b/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/test_case_expects.py index 5c2a366d6e2..a8dce36caec 100644 --- a/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/test_case_expects.py +++ b/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/test_case_expects.py @@ -8,14 +8,24 @@ class TestCaseExpects(pydantic_v1.BaseModel): - expected_stdout: typing.Optional[str] = pydantic_v1.Field(alias="expectedStdout", default=None) + expected_stdout: typing.Optional[str] = pydantic_v1.Field( + alias="expectedStdout", default=None + ) def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/test_case_function.py b/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/test_case_function.py index f40bbe8ed89..677a9d239db 100644 --- a/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/test_case_function.py +++ b/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/test_case_function.py @@ -4,7 +4,9 @@ import typing -from .test_case_with_actual_result_implementation import TestCaseWithActualResultImplementation +from .test_case_with_actual_result_implementation import ( + TestCaseWithActualResultImplementation, +) from .void_function_definition import VoidFunctionDefinition @@ -28,4 +30,6 @@ class Config: populate_by_name = True -TestCaseFunction = typing.Union[TestCaseFunction_WithActualResult, TestCaseFunction_Custom] +TestCaseFunction = typing.Union[ + TestCaseFunction_WithActualResult, TestCaseFunction_Custom +] diff --git a/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/test_case_implementation.py b/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/test_case_implementation.py index 44cc0dee0a8..fb9ffb0e7c2 100644 --- a/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/test_case_implementation.py +++ b/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/test_case_implementation.py @@ -14,11 +14,19 @@ class TestCaseImplementation(pydantic_v1.BaseModel): function: TestCaseFunction def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/test_case_implementation_description.py b/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/test_case_implementation_description.py index 222e140c257..3bb826523df 100644 --- a/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/test_case_implementation_description.py +++ b/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/test_case_implementation_description.py @@ -5,18 +5,28 @@ from .....core.datetime_utils import serialize_datetime from .....core.pydantic_utilities import pydantic_v1 -from .test_case_implementation_description_board import TestCaseImplementationDescriptionBoard +from .test_case_implementation_description_board import ( + TestCaseImplementationDescriptionBoard, +) class TestCaseImplementationDescription(pydantic_v1.BaseModel): boards: typing.List[TestCaseImplementationDescriptionBoard] def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/test_case_implementation_description_board.py b/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/test_case_implementation_description_board.py index 159fd5b5454..f0f24ddab53 100644 --- a/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/test_case_implementation_description_board.py +++ b/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/test_case_implementation_description_board.py @@ -27,5 +27,6 @@ class Config: TestCaseImplementationDescriptionBoard = typing.Union[ - TestCaseImplementationDescriptionBoard_Html, TestCaseImplementationDescriptionBoard_ParamId + TestCaseImplementationDescriptionBoard_Html, + TestCaseImplementationDescriptionBoard_ParamId, ] diff --git a/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/test_case_implementation_reference.py b/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/test_case_implementation_reference.py index 9aa5ffd3a9c..f854c81d21d 100644 --- a/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/test_case_implementation_reference.py +++ b/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/test_case_implementation_reference.py @@ -29,5 +29,6 @@ class Config: TestCaseImplementationReference = typing.Union[ - TestCaseImplementationReference_TemplateId, TestCaseImplementationReference_Implementation + TestCaseImplementationReference_TemplateId, + TestCaseImplementationReference_Implementation, ] diff --git a/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/test_case_metadata.py b/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/test_case_metadata.py index ccd0084ae1c..b8739748c91 100644 --- a/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/test_case_metadata.py +++ b/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/test_case_metadata.py @@ -14,11 +14,19 @@ class TestCaseMetadata(pydantic_v1.BaseModel): hidden: bool def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/test_case_template.py b/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/test_case_template.py index 0ab4abc5833..4f1879b4bed 100644 --- a/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/test_case_template.py +++ b/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/test_case_template.py @@ -15,11 +15,19 @@ class TestCaseTemplate(pydantic_v1.BaseModel): implementation: TestCaseImplementation def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/test_case_v_2.py b/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/test_case_v_2.py index ffbb2b4c66e..e3c5df000bb 100644 --- a/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/test_case_v_2.py +++ b/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/test_case_v_2.py @@ -19,11 +19,19 @@ class TestCaseV2(pydantic_v1.BaseModel): expects: typing.Optional[TestCaseExpects] = None def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/test_case_with_actual_result_implementation.py b/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/test_case_with_actual_result_implementation.py index 504e5ce8c0f..41821d8db0c 100644 --- a/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/test_case_with_actual_result_implementation.py +++ b/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/test_case_with_actual_result_implementation.py @@ -10,15 +10,27 @@ class TestCaseWithActualResultImplementation(pydantic_v1.BaseModel): - get_actual_result: NonVoidFunctionDefinition = pydantic_v1.Field(alias="getActualResult") - assert_correctness_check: AssertCorrectnessCheck = pydantic_v1.Field(alias="assertCorrectnessCheck") + get_actual_result: NonVoidFunctionDefinition = pydantic_v1.Field( + alias="getActualResult" + ) + assert_correctness_check: AssertCorrectnessCheck = pydantic_v1.Field( + alias="assertCorrectnessCheck" + ) def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/void_function_definition.py b/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/void_function_definition.py index b39de5cc8b6..0c8ac9e56e6 100644 --- a/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/void_function_definition.py +++ b/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/void_function_definition.py @@ -5,7 +5,9 @@ from .....core.datetime_utils import serialize_datetime from .....core.pydantic_utilities import pydantic_v1 -from .function_implementation_for_multiple_languages import FunctionImplementationForMultipleLanguages +from .function_implementation_for_multiple_languages import ( + FunctionImplementationForMultipleLanguages, +) from .parameter import Parameter @@ -14,11 +16,19 @@ class VoidFunctionDefinition(pydantic_v1.BaseModel): code: FunctionImplementationForMultipleLanguages def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/void_function_definition_that_takes_actual_result.py b/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/void_function_definition_that_takes_actual_result.py index bee3a897158..bd2844f80c5 100644 --- a/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/void_function_definition_that_takes_actual_result.py +++ b/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/void_function_definition_that_takes_actual_result.py @@ -5,7 +5,9 @@ from .....core.datetime_utils import serialize_datetime from .....core.pydantic_utilities import pydantic_v1 -from .function_implementation_for_multiple_languages import FunctionImplementationForMultipleLanguages +from .function_implementation_for_multiple_languages import ( + FunctionImplementationForMultipleLanguages, +) from .parameter import Parameter @@ -14,15 +16,25 @@ class VoidFunctionDefinitionThatTakesActualResult(pydantic_v1.BaseModel): The generated signature will include an additional param, actualResult """ - additional_parameters: typing.List[Parameter] = pydantic_v1.Field(alias="additionalParameters") + additional_parameters: typing.List[Parameter] = pydantic_v1.Field( + alias="additionalParameters" + ) code: FunctionImplementationForMultipleLanguages def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/void_function_signature.py b/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/void_function_signature.py index e28f94cb0d3..7059856cd92 100644 --- a/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/void_function_signature.py +++ b/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/void_function_signature.py @@ -12,11 +12,19 @@ class VoidFunctionSignature(pydantic_v1.BaseModel): parameters: typing.List[Parameter] def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/void_function_signature_that_takes_actual_result.py b/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/void_function_signature_that_takes_actual_result.py index cefe9d0a46d..f2f77041c4d 100644 --- a/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/void_function_signature_that_takes_actual_result.py +++ b/seed/python-sdk/trace/src/seed/v_2/v_3/problem/types/void_function_signature_that_takes_actual_result.py @@ -14,11 +14,19 @@ class VoidFunctionSignatureThatTakesActualResult(pydantic_v1.BaseModel): actual_result_type: VariableType = pydantic_v1.Field(alias="actualResultType") def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().dict(**kwargs_with_defaults) class Config: diff --git a/seed/python-sdk/trace/src/seed/version.py b/seed/python-sdk/trace/src/seed/version.py index 3fae08acc44..e4f5d126a8d 100644 --- a/seed/python-sdk/trace/src/seed/version.py +++ b/seed/python-sdk/trace/src/seed/version.py @@ -1,4 +1,3 @@ - from importlib import metadata __version__ = metadata.version("fern_trace") diff --git a/seed/python-sdk/trace/tests/custom/test_client.py b/seed/python-sdk/trace/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/python-sdk/trace/tests/custom/test_client.py +++ b/seed/python-sdk/trace/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/python-sdk/trace/tests/test_admin.py b/seed/python-sdk/trace/tests/test_admin.py index 6e95f124a0e..d0bc2172bc2 100644 --- a/seed/python-sdk/trace/tests/test_admin.py +++ b/seed/python-sdk/trace/tests/test_admin.py @@ -25,57 +25,289 @@ from seed.client import AsyncSeedTrace, SeedTrace -async def test_update_test_submission_status(client: SeedTrace, async_client: AsyncSeedTrace) -> None: +async def test_update_test_submission_status( + client: SeedTrace, async_client: AsyncSeedTrace +) -> None: # Type ignore to avoid mypy complaining about the function not being meant to return a value - assert client.admin.update_test_submission_status(submission_id=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), request=TestSubmissionStatus()) is None # type: ignore[func-returns-value] + assert ( + client.admin.update_test_submission_status( + submission_id=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + request=TestSubmissionStatus(), + ) + is None + ) # type: ignore[func-returns-value] - assert await async_client.admin.update_test_submission_status(submission_id=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), request=TestSubmissionStatus()) is None # type: ignore[func-returns-value] + assert ( + await async_client.admin.update_test_submission_status( + submission_id=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + request=TestSubmissionStatus(), + ) + is None + ) # type: ignore[func-returns-value] -async def test_send_test_submission_update(client: SeedTrace, async_client: AsyncSeedTrace) -> None: +async def test_send_test_submission_update( + client: SeedTrace, async_client: AsyncSeedTrace +) -> None: # Type ignore to avoid mypy complaining about the function not being meant to return a value - assert client.admin.send_test_submission_update(submission_id=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), request=TestSubmissionUpdate(update_time=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), update_info=TestSubmissionUpdateInfo_Running(value="QUEUEING_SUBMISSION"))) is None # type: ignore[func-returns-value] + assert ( + client.admin.send_test_submission_update( + submission_id=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + request=TestSubmissionUpdate( + update_time=datetime.datetime.fromisoformat( + "2024-01-15 09:30:00+00:00" + ), + update_info=TestSubmissionUpdateInfo_Running( + value="QUEUEING_SUBMISSION" + ), + ), + ) + is None + ) # type: ignore[func-returns-value] - assert await async_client.admin.send_test_submission_update(submission_id=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), request=TestSubmissionUpdate(update_time=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), update_info=TestSubmissionUpdateInfo_Running(value="QUEUEING_SUBMISSION"))) is None # type: ignore[func-returns-value] + assert ( + await async_client.admin.send_test_submission_update( + submission_id=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + request=TestSubmissionUpdate( + update_time=datetime.datetime.fromisoformat( + "2024-01-15 09:30:00+00:00" + ), + update_info=TestSubmissionUpdateInfo_Running( + value="QUEUEING_SUBMISSION" + ), + ), + ) + is None + ) # type: ignore[func-returns-value] -async def test_update_workspace_submission_status(client: SeedTrace, async_client: AsyncSeedTrace) -> None: +async def test_update_workspace_submission_status( + client: SeedTrace, async_client: AsyncSeedTrace +) -> None: # Type ignore to avoid mypy complaining about the function not being meant to return a value - assert client.admin.update_workspace_submission_status(submission_id=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), request=WorkspaceSubmissionStatus()) is None # type: ignore[func-returns-value] + assert ( + client.admin.update_workspace_submission_status( + submission_id=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + request=WorkspaceSubmissionStatus(), + ) + is None + ) # type: ignore[func-returns-value] - assert await async_client.admin.update_workspace_submission_status(submission_id=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), request=WorkspaceSubmissionStatus()) is None # type: ignore[func-returns-value] + assert ( + await async_client.admin.update_workspace_submission_status( + submission_id=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + request=WorkspaceSubmissionStatus(), + ) + is None + ) # type: ignore[func-returns-value] -async def test_send_workspace_submission_update(client: SeedTrace, async_client: AsyncSeedTrace) -> None: +async def test_send_workspace_submission_update( + client: SeedTrace, async_client: AsyncSeedTrace +) -> None: # Type ignore to avoid mypy complaining about the function not being meant to return a value - assert client.admin.send_workspace_submission_update(submission_id=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), request=WorkspaceSubmissionUpdate(update_time=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), update_info=WorkspaceSubmissionUpdateInfo_Running(value="QUEUEING_SUBMISSION"))) is None # type: ignore[func-returns-value] + assert ( + client.admin.send_workspace_submission_update( + submission_id=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + request=WorkspaceSubmissionUpdate( + update_time=datetime.datetime.fromisoformat( + "2024-01-15 09:30:00+00:00" + ), + update_info=WorkspaceSubmissionUpdateInfo_Running( + value="QUEUEING_SUBMISSION" + ), + ), + ) + is None + ) # type: ignore[func-returns-value] - assert await async_client.admin.send_workspace_submission_update(submission_id=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), request=WorkspaceSubmissionUpdate(update_time=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), update_info=WorkspaceSubmissionUpdateInfo_Running(value="QUEUEING_SUBMISSION"))) is None # type: ignore[func-returns-value] + assert ( + await async_client.admin.send_workspace_submission_update( + submission_id=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + request=WorkspaceSubmissionUpdate( + update_time=datetime.datetime.fromisoformat( + "2024-01-15 09:30:00+00:00" + ), + update_info=WorkspaceSubmissionUpdateInfo_Running( + value="QUEUEING_SUBMISSION" + ), + ), + ) + is None + ) # type: ignore[func-returns-value] -async def test_store_traced_test_case(client: SeedTrace, async_client: AsyncSeedTrace) -> None: +async def test_store_traced_test_case( + client: SeedTrace, async_client: AsyncSeedTrace +) -> None: # Type ignore to avoid mypy complaining about the function not being meant to return a value - assert client.admin.store_traced_test_case(submission_id=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), test_case_id="string", result=TestCaseResultWithStdout(result=TestCaseResult(), stdout="string"), trace_responses=[TraceResponse(submission_id=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), line_number=1, return_value=DebugVariableValue_IntegerValue(value=1), expression_location=ExpressionLocation(), stack=StackInformation(), stdout="string")]) is None # type: ignore[func-returns-value] + assert ( + client.admin.store_traced_test_case( + submission_id=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + test_case_id="string", + result=TestCaseResultWithStdout(result=TestCaseResult(), stdout="string"), + trace_responses=[ + TraceResponse( + submission_id=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + line_number=1, + return_value=DebugVariableValue_IntegerValue(value=1), + expression_location=ExpressionLocation(), + stack=StackInformation(), + stdout="string", + ) + ], + ) + is None + ) # type: ignore[func-returns-value] - assert await async_client.admin.store_traced_test_case(submission_id=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), test_case_id="string", result=TestCaseResultWithStdout(result=TestCaseResult(), stdout="string"), trace_responses=[TraceResponse(submission_id=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), line_number=1, return_value=DebugVariableValue_IntegerValue(value=1), expression_location=ExpressionLocation(), stack=StackInformation(), stdout="string")]) is None # type: ignore[func-returns-value] + assert ( + await async_client.admin.store_traced_test_case( + submission_id=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + test_case_id="string", + result=TestCaseResultWithStdout(result=TestCaseResult(), stdout="string"), + trace_responses=[ + TraceResponse( + submission_id=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + line_number=1, + return_value=DebugVariableValue_IntegerValue(value=1), + expression_location=ExpressionLocation(), + stack=StackInformation(), + stdout="string", + ) + ], + ) + is None + ) # type: ignore[func-returns-value] -async def test_store_traced_test_case_v_2(client: SeedTrace, async_client: AsyncSeedTrace) -> None: +async def test_store_traced_test_case_v_2( + client: SeedTrace, async_client: AsyncSeedTrace +) -> None: # Type ignore to avoid mypy complaining about the function not being meant to return a value - assert client.admin.store_traced_test_case_v_2(submission_id=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), test_case_id="string", request=[TraceResponseV2(submission_id=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), line_number=1, file=TracedFile(), return_value=DebugVariableValue_IntegerValue(value=1), expression_location=ExpressionLocation(), stack=StackInformation(), stdout="string")]) is None # type: ignore[func-returns-value] + assert ( + client.admin.store_traced_test_case_v_2( + submission_id=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + test_case_id="string", + request=[ + TraceResponseV2( + submission_id=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + line_number=1, + file=TracedFile(), + return_value=DebugVariableValue_IntegerValue(value=1), + expression_location=ExpressionLocation(), + stack=StackInformation(), + stdout="string", + ) + ], + ) + is None + ) # type: ignore[func-returns-value] - assert await async_client.admin.store_traced_test_case_v_2(submission_id=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), test_case_id="string", request=[TraceResponseV2(submission_id=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), line_number=1, file=TracedFile(), return_value=DebugVariableValue_IntegerValue(value=1), expression_location=ExpressionLocation(), stack=StackInformation(), stdout="string")]) is None # type: ignore[func-returns-value] + assert ( + await async_client.admin.store_traced_test_case_v_2( + submission_id=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + test_case_id="string", + request=[ + TraceResponseV2( + submission_id=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + line_number=1, + file=TracedFile(), + return_value=DebugVariableValue_IntegerValue(value=1), + expression_location=ExpressionLocation(), + stack=StackInformation(), + stdout="string", + ) + ], + ) + is None + ) # type: ignore[func-returns-value] -async def test_store_traced_workspace(client: SeedTrace, async_client: AsyncSeedTrace) -> None: +async def test_store_traced_workspace( + client: SeedTrace, async_client: AsyncSeedTrace +) -> None: # Type ignore to avoid mypy complaining about the function not being meant to return a value - assert client.admin.store_traced_workspace(submission_id=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), workspace_run_details=WorkspaceRunDetails(exception_v_2=ExceptionV2_Generic(), exception=ExceptionInfo(), stdout="string"), trace_responses=[TraceResponse(submission_id=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), line_number=1, return_value=DebugVariableValue_IntegerValue(value=1), expression_location=ExpressionLocation(), stack=StackInformation(), stdout="string")]) is None # type: ignore[func-returns-value] + assert ( + client.admin.store_traced_workspace( + submission_id=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + workspace_run_details=WorkspaceRunDetails( + exception_v_2=ExceptionV2_Generic(), + exception=ExceptionInfo(), + stdout="string", + ), + trace_responses=[ + TraceResponse( + submission_id=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + line_number=1, + return_value=DebugVariableValue_IntegerValue(value=1), + expression_location=ExpressionLocation(), + stack=StackInformation(), + stdout="string", + ) + ], + ) + is None + ) # type: ignore[func-returns-value] - assert await async_client.admin.store_traced_workspace(submission_id=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), workspace_run_details=WorkspaceRunDetails(exception_v_2=ExceptionV2_Generic(), exception=ExceptionInfo(), stdout="string"), trace_responses=[TraceResponse(submission_id=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), line_number=1, return_value=DebugVariableValue_IntegerValue(value=1), expression_location=ExpressionLocation(), stack=StackInformation(), stdout="string")]) is None # type: ignore[func-returns-value] + assert ( + await async_client.admin.store_traced_workspace( + submission_id=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + workspace_run_details=WorkspaceRunDetails( + exception_v_2=ExceptionV2_Generic(), + exception=ExceptionInfo(), + stdout="string", + ), + trace_responses=[ + TraceResponse( + submission_id=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + line_number=1, + return_value=DebugVariableValue_IntegerValue(value=1), + expression_location=ExpressionLocation(), + stack=StackInformation(), + stdout="string", + ) + ], + ) + is None + ) # type: ignore[func-returns-value] -async def test_store_traced_workspace_v_2(client: SeedTrace, async_client: AsyncSeedTrace) -> None: +async def test_store_traced_workspace_v_2( + client: SeedTrace, async_client: AsyncSeedTrace +) -> None: # Type ignore to avoid mypy complaining about the function not being meant to return a value - assert client.admin.store_traced_workspace_v_2(submission_id=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), request=[TraceResponseV2(submission_id=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), line_number=1, file=TracedFile(), return_value=DebugVariableValue_IntegerValue(value=1), expression_location=ExpressionLocation(), stack=StackInformation(), stdout="string")]) is None # type: ignore[func-returns-value] + assert ( + client.admin.store_traced_workspace_v_2( + submission_id=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + request=[ + TraceResponseV2( + submission_id=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + line_number=1, + file=TracedFile(), + return_value=DebugVariableValue_IntegerValue(value=1), + expression_location=ExpressionLocation(), + stack=StackInformation(), + stdout="string", + ) + ], + ) + is None + ) # type: ignore[func-returns-value] - assert await async_client.admin.store_traced_workspace_v_2(submission_id=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), request=[TraceResponseV2(submission_id=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), line_number=1, file=TracedFile(), return_value=DebugVariableValue_IntegerValue(value=1), expression_location=ExpressionLocation(), stack=StackInformation(), stdout="string")]) is None # type: ignore[func-returns-value] + assert ( + await async_client.admin.store_traced_workspace_v_2( + submission_id=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + request=[ + TraceResponseV2( + submission_id=uuid.UUID("d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32"), + line_number=1, + file=TracedFile(), + return_value=DebugVariableValue_IntegerValue(value=1), + expression_location=ExpressionLocation(), + stack=StackInformation(), + stdout="string", + ) + ], + ) + is None + ) # type: ignore[func-returns-value] diff --git a/seed/python-sdk/trace/tests/test_homepage.py b/seed/python-sdk/trace/tests/test_homepage.py index 43f1c7b203b..8bebc18c0bf 100644 --- a/seed/python-sdk/trace/tests/test_homepage.py +++ b/seed/python-sdk/trace/tests/test_homepage.py @@ -5,7 +5,9 @@ from .utilities import validate_response -async def test_get_homepage_problems(client: SeedTrace, async_client: AsyncSeedTrace) -> None: +async def test_get_homepage_problems( + client: SeedTrace, async_client: AsyncSeedTrace +) -> None: expected_response = ["string"] expected_types = ("list", {0: None}) response = client.homepage.get_homepage_problems() @@ -15,7 +17,9 @@ async def test_get_homepage_problems(client: SeedTrace, async_client: AsyncSeedT validate_response(async_response, expected_response, expected_types) -async def test_set_homepage_problems(client: SeedTrace, async_client: AsyncSeedTrace) -> None: +async def test_set_homepage_problems( + client: SeedTrace, async_client: AsyncSeedTrace +) -> None: # Type ignore to avoid mypy complaining about the function not being meant to return a value assert client.homepage.set_homepage_problems(request=["string"]) is None # type: ignore[func-returns-value] diff --git a/seed/python-sdk/trace/tests/test_migration.py b/seed/python-sdk/trace/tests/test_migration.py index e46d176da4e..ce485141195 100644 --- a/seed/python-sdk/trace/tests/test_migration.py +++ b/seed/python-sdk/trace/tests/test_migration.py @@ -5,11 +5,15 @@ from .utilities import validate_response -async def test_get_attempted_migrations(client: SeedTrace, async_client: AsyncSeedTrace) -> None: +async def test_get_attempted_migrations( + client: SeedTrace, async_client: AsyncSeedTrace +) -> None: expected_response = [{"name": "string", "status": "RUNNING"}] expected_types = ("list", {0: {"name": None, "status": None}}) response = client.migration.get_attempted_migrations(admin_key_header="string") validate_response(response, expected_response, expected_types) - async_response = await async_client.migration.get_attempted_migrations(admin_key_header="string") + async_response = await async_client.migration.get_attempted_migrations( + admin_key_header="string" + ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/trace/tests/test_playlist.py b/seed/python-sdk/trace/tests/test_playlist.py index 31ebe486bdc..651e36e5966 100644 --- a/seed/python-sdk/trace/tests/test_playlist.py +++ b/seed/python-sdk/trace/tests/test_playlist.py @@ -9,8 +9,18 @@ async def test_create_playlist(client: SeedTrace, async_client: AsyncSeedTrace) -> None: - expected_response = {"playlist_id": "string", "owner-id": "string", "name": "string", "problems": ["string"]} - expected_types = {"playlist_id": None, "owner-id": None, "name": None, "problems": ("list", {0: None})} + expected_response = { + "playlist_id": "string", + "owner-id": "string", + "name": "string", + "problems": ["string"], + } + expected_types = { + "playlist_id": None, + "owner-id": None, + "name": None, + "problems": ("list", {0: None}), + } response = client.playlist.create_playlist( service_param=1, datetime=datetime.datetime.fromisoformat("2024-01-15 09:30:00+00:00"), @@ -29,10 +39,24 @@ async def test_create_playlist(client: SeedTrace, async_client: AsyncSeedTrace) async def test_get_playlists(client: SeedTrace, async_client: AsyncSeedTrace) -> None: - expected_response = [{"playlist_id": "string", "owner-id": "string", "name": "string", "problems": ["string"]}] + expected_response = [ + { + "playlist_id": "string", + "owner-id": "string", + "name": "string", + "problems": ["string"], + } + ] expected_types = ( "list", - {0: {"playlist_id": None, "owner-id": None, "name": None, "problems": ("list", {0: None})}}, + { + 0: { + "playlist_id": None, + "owner-id": None, + "name": None, + "problems": ("list", {0: None}), + } + }, ) response = client.playlist.get_playlists( service_param=1, @@ -56,31 +80,64 @@ async def test_get_playlists(client: SeedTrace, async_client: AsyncSeedTrace) -> async def test_get_playlist(client: SeedTrace, async_client: AsyncSeedTrace) -> None: - expected_response = {"playlist_id": "string", "owner-id": "string", "name": "string", "problems": ["string"]} - expected_types = {"playlist_id": None, "owner-id": None, "name": None, "problems": ("list", {0: None})} + expected_response = { + "playlist_id": "string", + "owner-id": "string", + "name": "string", + "problems": ["string"], + } + expected_types = { + "playlist_id": None, + "owner-id": None, + "name": None, + "problems": ("list", {0: None}), + } response = client.playlist.get_playlist(service_param=1, playlist_id="string") validate_response(response, expected_response, expected_types) - async_response = await async_client.playlist.get_playlist(service_param=1, playlist_id="string") + async_response = await async_client.playlist.get_playlist( + service_param=1, playlist_id="string" + ) validate_response(async_response, expected_response, expected_types) async def test_update_playlist(client: SeedTrace, async_client: AsyncSeedTrace) -> None: - expected_response = {"playlist_id": "string", "owner-id": "string", "name": "string", "problems": ["string"]} - expected_types = {"playlist_id": None, "owner-id": None, "name": None, "problems": ("list", {0: None})} + expected_response = { + "playlist_id": "string", + "owner-id": "string", + "name": "string", + "problems": ["string"], + } + expected_types = { + "playlist_id": None, + "owner-id": None, + "name": None, + "problems": ("list", {0: None}), + } response = client.playlist.update_playlist( - service_param=1, playlist_id="string", request=UpdatePlaylistRequest(name="string", problems=["string"]) + service_param=1, + playlist_id="string", + request=UpdatePlaylistRequest(name="string", problems=["string"]), ) validate_response(response, expected_response, expected_types) async_response = await async_client.playlist.update_playlist( - service_param=1, playlist_id="string", request=UpdatePlaylistRequest(name="string", problems=["string"]) + service_param=1, + playlist_id="string", + request=UpdatePlaylistRequest(name="string", problems=["string"]), ) validate_response(async_response, expected_response, expected_types) async def test_delete_playlist(client: SeedTrace, async_client: AsyncSeedTrace) -> None: # Type ignore to avoid mypy complaining about the function not being meant to return a value - assert client.playlist.delete_playlist(service_param=1, playlist_id="string") is None # type: ignore[func-returns-value] - - assert await async_client.playlist.delete_playlist(service_param=1, playlist_id="string") is None # type: ignore[func-returns-value] + assert ( + client.playlist.delete_playlist(service_param=1, playlist_id="string") is None + ) # type: ignore[func-returns-value] + + assert ( + await async_client.playlist.delete_playlist( + service_param=1, playlist_id="string" + ) + is None + ) # type: ignore[func-returns-value] diff --git a/seed/python-sdk/trace/tests/test_problem.py b/seed/python-sdk/trace/tests/test_problem.py index eba9c3963e0..da4470c2394 100644 --- a/seed/python-sdk/trace/tests/test_problem.py +++ b/seed/python-sdk/trace/tests/test_problem.py @@ -18,23 +18,37 @@ async def test_create_problem(client: SeedTrace, async_client: AsyncSeedTrace) -> None: - expected_response = {"0": "s", "1": "t", "2": "r", "3": "i", "4": "n", "5": "g", "type": "success"} + expected_response = { + "0": "s", + "1": "t", + "2": "r", + "3": "i", + "4": "n", + "5": "g", + "type": "success", + } expected_types = "no_validate" response = client.problem.create_problem( request=CreateProblemRequest( problem_name="string", - problem_description=ProblemDescription(boards=[ProblemDescriptionBoard_Html(value="string")]), + problem_description=ProblemDescription( + boards=[ProblemDescriptionBoard_Html(value="string")] + ), files={ "JAVA": ProblemFiles( solution_file=FileInfo(filename="string", contents="string"), read_only_files=[FileInfo(filename="string", contents="string")], ) }, - input_params=[VariableTypeAndName(variable_type=VariableType(), name="string")], + input_params=[ + VariableTypeAndName(variable_type=VariableType(), name="string") + ], output_type=VariableType(), testcases=[ TestCaseWithExpectedResult( - test_case=TestCase(id="string", params=[VariableValue_IntegerValue(value=1)]), + test_case=TestCase( + id="string", params=[VariableValue_IntegerValue(value=1)] + ), expected_result=VariableValue_IntegerValue(value=1), ) ], @@ -46,18 +60,24 @@ async def test_create_problem(client: SeedTrace, async_client: AsyncSeedTrace) - async_response = await async_client.problem.create_problem( request=CreateProblemRequest( problem_name="string", - problem_description=ProblemDescription(boards=[ProblemDescriptionBoard_Html(value="string")]), + problem_description=ProblemDescription( + boards=[ProblemDescriptionBoard_Html(value="string")] + ), files={ "JAVA": ProblemFiles( solution_file=FileInfo(filename="string", contents="string"), read_only_files=[FileInfo(filename="string", contents="string")], ) }, - input_params=[VariableTypeAndName(variable_type=VariableType(), name="string")], + input_params=[ + VariableTypeAndName(variable_type=VariableType(), name="string") + ], output_type=VariableType(), testcases=[ TestCaseWithExpectedResult( - test_case=TestCase(id="string", params=[VariableValue_IntegerValue(value=1)]), + test_case=TestCase( + id="string", params=[VariableValue_IntegerValue(value=1)] + ), expected_result=VariableValue_IntegerValue(value=1), ) ], @@ -74,18 +94,24 @@ async def test_update_problem(client: SeedTrace, async_client: AsyncSeedTrace) - problem_id="string", request=CreateProblemRequest( problem_name="string", - problem_description=ProblemDescription(boards=[ProblemDescriptionBoard_Html(value="string")]), + problem_description=ProblemDescription( + boards=[ProblemDescriptionBoard_Html(value="string")] + ), files={ "JAVA": ProblemFiles( solution_file=FileInfo(filename="string", contents="string"), read_only_files=[FileInfo(filename="string", contents="string")], ) }, - input_params=[VariableTypeAndName(variable_type=VariableType(), name="string")], + input_params=[ + VariableTypeAndName(variable_type=VariableType(), name="string") + ], output_type=VariableType(), testcases=[ TestCaseWithExpectedResult( - test_case=TestCase(id="string", params=[VariableValue_IntegerValue(value=1)]), + test_case=TestCase( + id="string", params=[VariableValue_IntegerValue(value=1)] + ), expected_result=VariableValue_IntegerValue(value=1), ) ], @@ -98,18 +124,24 @@ async def test_update_problem(client: SeedTrace, async_client: AsyncSeedTrace) - problem_id="string", request=CreateProblemRequest( problem_name="string", - problem_description=ProblemDescription(boards=[ProblemDescriptionBoard_Html(value="string")]), + problem_description=ProblemDescription( + boards=[ProblemDescriptionBoard_Html(value="string")] + ), files={ "JAVA": ProblemFiles( solution_file=FileInfo(filename="string", contents="string"), read_only_files=[FileInfo(filename="string", contents="string")], ) }, - input_params=[VariableTypeAndName(variable_type=VariableType(), name="string")], + input_params=[ + VariableTypeAndName(variable_type=VariableType(), name="string") + ], output_type=VariableType(), testcases=[ TestCaseWithExpectedResult( - test_case=TestCase(id="string", params=[VariableValue_IntegerValue(value=1)]), + test_case=TestCase( + id="string", params=[VariableValue_IntegerValue(value=1)] + ), expected_result=VariableValue_IntegerValue(value=1), ) ], @@ -126,7 +158,9 @@ async def test_delete_problem(client: SeedTrace, async_client: AsyncSeedTrace) - assert await async_client.problem.delete_problem(problem_id="string") is None # type: ignore[func-returns-value] -async def test_get_default_starter_files(client: SeedTrace, async_client: AsyncSeedTrace) -> None: +async def test_get_default_starter_files( + client: SeedTrace, async_client: AsyncSeedTrace +) -> None: expected_response = { "files": { "string": { @@ -143,7 +177,10 @@ async def test_get_default_starter_files(client: SeedTrace, async_client: AsyncS None, { "solutionFile": {"filename": None, "contents": None}, - "readOnlyFiles": ("list", {0: {"filename": None, "contents": None}}), + "readOnlyFiles": ( + "list", + {0: {"filename": None, "contents": None}}, + ), }, ) }, diff --git a/seed/python-sdk/trace/tests/test_submission.py b/seed/python-sdk/trace/tests/test_submission.py index 1e1d7c9cdf6..421d422f3d1 100644 --- a/seed/python-sdk/trace/tests/test_submission.py +++ b/seed/python-sdk/trace/tests/test_submission.py @@ -5,44 +5,69 @@ from .utilities import validate_response -async def test_create_execution_session(client: SeedTrace, async_client: AsyncSeedTrace) -> None: +async def test_create_execution_session( + client: SeedTrace, async_client: AsyncSeedTrace +) -> None: expected_response = { "sessionId": "string", "executionSessionUrl": "string", "language": "JAVA", "status": "CREATING_CONTAINER", } - expected_types = {"sessionId": None, "executionSessionUrl": None, "language": None, "status": None} + expected_types = { + "sessionId": None, + "executionSessionUrl": None, + "language": None, + "status": None, + } response = client.submission.create_execution_session(language="JAVA") validate_response(response, expected_response, expected_types) - async_response = await async_client.submission.create_execution_session(language="JAVA") + async_response = await async_client.submission.create_execution_session( + language="JAVA" + ) validate_response(async_response, expected_response, expected_types) -async def test_get_execution_session(client: SeedTrace, async_client: AsyncSeedTrace) -> None: +async def test_get_execution_session( + client: SeedTrace, async_client: AsyncSeedTrace +) -> None: expected_response = { "sessionId": "string", "executionSessionUrl": "string", "language": "JAVA", "status": "CREATING_CONTAINER", } - expected_types = {"sessionId": None, "executionSessionUrl": None, "language": None, "status": None} + expected_types = { + "sessionId": None, + "executionSessionUrl": None, + "language": None, + "status": None, + } response = client.submission.get_execution_session(session_id="string") validate_response(response, expected_response, expected_types) - async_response = await async_client.submission.get_execution_session(session_id="string") + async_response = await async_client.submission.get_execution_session( + session_id="string" + ) validate_response(async_response, expected_response, expected_types) -async def test_stop_execution_session(client: SeedTrace, async_client: AsyncSeedTrace) -> None: +async def test_stop_execution_session( + client: SeedTrace, async_client: AsyncSeedTrace +) -> None: # Type ignore to avoid mypy complaining about the function not being meant to return a value assert client.submission.stop_execution_session(session_id="string") is None # type: ignore[func-returns-value] - assert await async_client.submission.stop_execution_session(session_id="string") is None # type: ignore[func-returns-value] + assert ( + await async_client.submission.stop_execution_session(session_id="string") + is None + ) # type: ignore[func-returns-value] -async def test_get_execution_sessions_state(client: SeedTrace, async_client: AsyncSeedTrace) -> None: +async def test_get_execution_sessions_state( + client: SeedTrace, async_client: AsyncSeedTrace +) -> None: expected_response = { "states": { "string": { diff --git a/seed/python-sdk/trace/tests/test_sysprop.py b/seed/python-sdk/trace/tests/test_sysprop.py index 8a2768a5ad9..7cabfb43a1e 100644 --- a/seed/python-sdk/trace/tests/test_sysprop.py +++ b/seed/python-sdk/trace/tests/test_sysprop.py @@ -5,14 +5,26 @@ from .utilities import validate_response -async def test_set_num_warm_instances(client: SeedTrace, async_client: AsyncSeedTrace) -> None: +async def test_set_num_warm_instances( + client: SeedTrace, async_client: AsyncSeedTrace +) -> None: # Type ignore to avoid mypy complaining about the function not being meant to return a value - assert client.sysprop.set_num_warm_instances(language="JAVA", num_warm_instances=1) is None # type: ignore[func-returns-value] - - assert await async_client.sysprop.set_num_warm_instances(language="JAVA", num_warm_instances=1) is None # type: ignore[func-returns-value] - - -async def test_get_num_warm_instances(client: SeedTrace, async_client: AsyncSeedTrace) -> None: + assert ( + client.sysprop.set_num_warm_instances(language="JAVA", num_warm_instances=1) + is None + ) # type: ignore[func-returns-value] + + assert ( + await async_client.sysprop.set_num_warm_instances( + language="JAVA", num_warm_instances=1 + ) + is None + ) # type: ignore[func-returns-value] + + +async def test_get_num_warm_instances( + client: SeedTrace, async_client: AsyncSeedTrace +) -> None: expected_response = {"string": 1} expected_types = ("dict", {0: (None, "integer")}) response = client.sysprop.get_num_warm_instances() diff --git a/seed/python-sdk/trace/tests/utilities.py b/seed/python-sdk/trace/tests/utilities.py index 34f0864a553..5b9627095f9 100644 --- a/seed/python-sdk/trace/tests/utilities.py +++ b/seed/python-sdk/trace/tests/utilities.py @@ -8,7 +8,9 @@ from .pydantic_utilities import pydantic_v1 -def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> typing.Any: +def cast_field( + json_expectation: typing.Any, type_expectation: typing.Any +) -> typing.Any: # Cast these specific types which come through as string and expect our # models to cast to the correct type. if type_expectation == "uuid": @@ -26,7 +28,9 @@ def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> ty return json_expectation -def validate_field(response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any) -> None: +def validate_field( + response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectation == "no_validate": return @@ -37,14 +41,22 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe container_expectation = type_expectation[0] contents_expectation = type_expectation[1] json_expectation = [ - cast_field(ex, contents_expectation.get(idx) if isinstance(contents_expectation, dict) else None) + cast_field( + ex, + contents_expectation.get(idx) + if isinstance(contents_expectation, dict) + else None, + ) for idx, ex in enumerate(json_expectation) ] # Note that we explicitly do not allow for sets of pydantic models as they are not hashable, so # if any of the values of the set have a type_expectation of a dict, we're assuming it's a pydantic # model and keeping it a list. if container_expectation != "set" or not any( - map(lambda value: isinstance(value, dict), list(contents_expectation.values())) + map( + lambda value: isinstance(value, dict), + list(contents_expectation.values()), + ) ): json_expectation = cast_field(json_expectation, container_expectation) elif isinstance(type_expectation, tuple): @@ -52,27 +64,43 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe contents_expectation = type_expectation[1] json_expectation = { cast_field( - key, contents_expectation.get(idx)[0] if isinstance(contents_expectation, dict) else None - ): cast_field(value, contents_expectation.get(idx)[1] if isinstance(contents_expectation, dict) else None) + key, + contents_expectation.get(idx)[0] + if isinstance(contents_expectation, dict) + else None, + ): cast_field( + value, + contents_expectation.get(idx)[1] + if isinstance(contents_expectation, dict) + else None, + ) for idx, (key, value) in enumerate(json_expectation.items()) } json_expectation = cast_field(json_expectation, container_expectation) elif type_expectation is not None: json_expectation = cast_field(json_expectation, type_expectation) - assert json_expectation == response, "Primitives found, expected: {0}, Actual: {1}".format( - json_expectation, response - ) + assert ( + json_expectation == response + ), "Primitives found, expected: {0}, Actual: {1}".format(json_expectation, response) # Arg type_expectations is a deeply nested structure that matches the response, but with the values replaced with the expected types -def validate_response(response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any) -> None: +def validate_response( + response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectations == "no_validate": return - if not isinstance(response, dict) and not issubclass(type(response), pydantic_v1.BaseModel): - validate_field(response=response, json_expectation=json_expectation, type_expectation=type_expectations) + if not isinstance(response, dict) and not issubclass( + type(response), pydantic_v1.BaseModel + ): + validate_field( + response=response, + json_expectation=json_expectation, + type_expectation=type_expectations, + ) return response_json = response @@ -80,7 +108,11 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e response_json = response.dict(by_alias=True) for key, value in json_expectation.items(): - assert key in response_json, "Field {0} not found within the response object: {1}".format(key, response_json) + assert ( + key in response_json + ), "Field {0} not found within the response object: {1}".format( + key, response_json + ) type_expectation = None if type_expectations is not None and isinstance(type_expectations, dict): @@ -89,10 +121,20 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e # If your type_expectation is a tuple then you have a container field, process it as such # Otherwise, we're just validating a single field that's a pydantic model. if isinstance(value, dict) and not isinstance(type_expectation, tuple): - validate_response(response=response_json[key], json_expectation=value, type_expectations=type_expectation) + validate_response( + response=response_json[key], + json_expectation=value, + type_expectations=type_expectation, + ) else: - validate_field(response=response_json[key], json_expectation=value, type_expectation=type_expectation) + validate_field( + response=response_json[key], + json_expectation=value, + type_expectation=type_expectation, + ) # Ensure there are no additional fields here either del response_json[key] - assert len(response_json) == 0, "Additional fields found, expected None: {0}".format(response_json) + assert ( + len(response_json) == 0 + ), "Additional fields found, expected None: {0}".format(response_json) diff --git a/seed/python-sdk/trace/tests/v_2/test_problem.py b/seed/python-sdk/trace/tests/v_2/test_problem.py index d744d37750a..417f3397837 100644 --- a/seed/python-sdk/trace/tests/v_2/test_problem.py +++ b/seed/python-sdk/trace/tests/v_2/test_problem.py @@ -5,7 +5,9 @@ from ..utilities import validate_response -async def test_get_lightweight_problems(client: SeedTrace, async_client: AsyncSeedTrace) -> None: +async def test_get_lightweight_problems( + client: SeedTrace, async_client: AsyncSeedTrace +) -> None: expected_response = [ { "problemId": "string", @@ -37,7 +39,17 @@ async def test_get_problems(client: SeedTrace, async_client: AsyncSeedTrace) -> { "problemId": "string", "problemDescription": { - "boards": [{"0": "s", "1": "t", "2": "r", "3": "i", "4": "n", "5": "g", "type": "html"}] + "boards": [ + { + "0": "s", + "1": "t", + "2": "r", + "3": "i", + "4": "n", + "5": "g", + "type": "html", + } + ] }, "problemName": "string", "problemVersion": 1, @@ -73,11 +85,23 @@ async def test_get_problems(client: SeedTrace, async_client: AsyncSeedTrace) -> validate_response(async_response, expected_response, expected_types) -async def test_get_latest_problem(client: SeedTrace, async_client: AsyncSeedTrace) -> None: +async def test_get_latest_problem( + client: SeedTrace, async_client: AsyncSeedTrace +) -> None: expected_response = { "problemId": "string", "problemDescription": { - "boards": [{"0": "s", "1": "t", "2": "r", "3": "i", "4": "n", "5": "g", "type": "html"}] + "boards": [ + { + "0": "s", + "1": "t", + "2": "r", + "3": "i", + "4": "n", + "5": "g", + "type": "html", + } + ] }, "problemName": "string", "problemVersion": 1, @@ -103,15 +127,29 @@ async def test_get_latest_problem(client: SeedTrace, async_client: AsyncSeedTrac response = client.v_2.problem.get_latest_problem(problem_id="string") validate_response(response, expected_response, expected_types) - async_response = await async_client.v_2.problem.get_latest_problem(problem_id="string") + async_response = await async_client.v_2.problem.get_latest_problem( + problem_id="string" + ) validate_response(async_response, expected_response, expected_types) -async def test_get_problem_version(client: SeedTrace, async_client: AsyncSeedTrace) -> None: +async def test_get_problem_version( + client: SeedTrace, async_client: AsyncSeedTrace +) -> None: expected_response = { "problemId": "string", "problemDescription": { - "boards": [{"0": "s", "1": "t", "2": "r", "3": "i", "4": "n", "5": "g", "type": "html"}] + "boards": [ + { + "0": "s", + "1": "t", + "2": "r", + "3": "i", + "4": "n", + "5": "g", + "type": "html", + } + ] }, "problemName": "string", "problemVersion": 1, @@ -134,8 +172,12 @@ async def test_get_problem_version(client: SeedTrace, async_client: AsyncSeedTra "testcases": ("list", {0: {}}), "isPublic": None, } - response = client.v_2.problem.get_problem_version(problem_id="string", problem_version=1) + response = client.v_2.problem.get_problem_version( + problem_id="string", problem_version=1 + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.v_2.problem.get_problem_version(problem_id="string", problem_version=1) + async_response = await async_client.v_2.problem.get_problem_version( + problem_id="string", problem_version=1 + ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/trace/tests/v_2/v_3/test_problem.py b/seed/python-sdk/trace/tests/v_2/v_3/test_problem.py index e3aa84b809e..fa92134aad7 100644 --- a/seed/python-sdk/trace/tests/v_2/v_3/test_problem.py +++ b/seed/python-sdk/trace/tests/v_2/v_3/test_problem.py @@ -5,7 +5,9 @@ from ...utilities import validate_response -async def test_get_lightweight_problems(client: SeedTrace, async_client: AsyncSeedTrace) -> None: +async def test_get_lightweight_problems( + client: SeedTrace, async_client: AsyncSeedTrace +) -> None: expected_response = [ { "problemId": "string", @@ -37,7 +39,17 @@ async def test_get_problems(client: SeedTrace, async_client: AsyncSeedTrace) -> { "problemId": "string", "problemDescription": { - "boards": [{"0": "s", "1": "t", "2": "r", "3": "i", "4": "n", "5": "g", "type": "html"}] + "boards": [ + { + "0": "s", + "1": "t", + "2": "r", + "3": "i", + "4": "n", + "5": "g", + "type": "html", + } + ] }, "problemName": "string", "problemVersion": 1, @@ -73,11 +85,23 @@ async def test_get_problems(client: SeedTrace, async_client: AsyncSeedTrace) -> validate_response(async_response, expected_response, expected_types) -async def test_get_latest_problem(client: SeedTrace, async_client: AsyncSeedTrace) -> None: +async def test_get_latest_problem( + client: SeedTrace, async_client: AsyncSeedTrace +) -> None: expected_response = { "problemId": "string", "problemDescription": { - "boards": [{"0": "s", "1": "t", "2": "r", "3": "i", "4": "n", "5": "g", "type": "html"}] + "boards": [ + { + "0": "s", + "1": "t", + "2": "r", + "3": "i", + "4": "n", + "5": "g", + "type": "html", + } + ] }, "problemName": "string", "problemVersion": 1, @@ -103,15 +127,29 @@ async def test_get_latest_problem(client: SeedTrace, async_client: AsyncSeedTrac response = client.v_2.v_3.problem.get_latest_problem(problem_id="string") validate_response(response, expected_response, expected_types) - async_response = await async_client.v_2.v_3.problem.get_latest_problem(problem_id="string") + async_response = await async_client.v_2.v_3.problem.get_latest_problem( + problem_id="string" + ) validate_response(async_response, expected_response, expected_types) -async def test_get_problem_version(client: SeedTrace, async_client: AsyncSeedTrace) -> None: +async def test_get_problem_version( + client: SeedTrace, async_client: AsyncSeedTrace +) -> None: expected_response = { "problemId": "string", "problemDescription": { - "boards": [{"0": "s", "1": "t", "2": "r", "3": "i", "4": "n", "5": "g", "type": "html"}] + "boards": [ + { + "0": "s", + "1": "t", + "2": "r", + "3": "i", + "4": "n", + "5": "g", + "type": "html", + } + ] }, "problemName": "string", "problemVersion": 1, @@ -134,8 +172,12 @@ async def test_get_problem_version(client: SeedTrace, async_client: AsyncSeedTra "testcases": ("list", {0: {}}), "isPublic": None, } - response = client.v_2.v_3.problem.get_problem_version(problem_id="string", problem_version=1) + response = client.v_2.v_3.problem.get_problem_version( + problem_id="string", problem_version=1 + ) validate_response(response, expected_response, expected_types) - async_response = await async_client.v_2.v_3.problem.get_problem_version(problem_id="string", problem_version=1) + async_response = await async_client.v_2.v_3.problem.get_problem_version( + problem_id="string", problem_version=1 + ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/undiscriminated-unions/pyproject.toml b/seed/python-sdk/undiscriminated-unions/pyproject.toml index fbdf70f568e..bee9f1e52a6 100644 --- a/seed/python-sdk/undiscriminated-unions/pyproject.toml +++ b/seed/python-sdk/undiscriminated-unions/pyproject.toml @@ -43,6 +43,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/python-sdk/undiscriminated-unions/src/seed/client.py b/seed/python-sdk/undiscriminated-unions/src/seed/client.py index 0c5b2ae2478..9ef79be6851 100644 --- a/seed/python-sdk/undiscriminated-unions/src/seed/client.py +++ b/seed/python-sdk/undiscriminated-unions/src/seed/client.py @@ -1,11 +1,11 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from .union.client import AsyncUnionClient, UnionClient +from .core.client_wrapper import SyncClientWrapper +from .union.client import UnionClient +from .core.client_wrapper import AsyncClientWrapper +from .union.client import AsyncUnionClient class SeedUndiscriminatedUnions: @@ -41,14 +41,18 @@ def __init__( base_url: str, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.Client] = None + httpx_client: typing.Optional[httpx.Client] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = SyncClientWrapper( base_url=base_url, httpx_client=httpx_client if httpx_client is not None - else httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.Client( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.Client(timeout=_defaulted_timeout), timeout=_defaulted_timeout, @@ -89,14 +93,18 @@ def __init__( base_url: str, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.AsyncClient] = None + httpx_client: typing.Optional[httpx.AsyncClient] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = AsyncClientWrapper( base_url=base_url, httpx_client=httpx_client if httpx_client is not None - else httpx.AsyncClient(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.AsyncClient( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.AsyncClient(timeout=_defaulted_timeout), timeout=_defaulted_timeout, diff --git a/seed/python-sdk/undiscriminated-unions/src/seed/core/api_error.py b/seed/python-sdk/undiscriminated-unions/src/seed/core/api_error.py index 2e9fc5431cd..da734b58068 100644 --- a/seed/python-sdk/undiscriminated-unions/src/seed/core/api_error.py +++ b/seed/python-sdk/undiscriminated-unions/src/seed/core/api_error.py @@ -7,7 +7,9 @@ class ApiError(Exception): status_code: typing.Optional[int] body: typing.Any - def __init__(self, *, status_code: typing.Optional[int] = None, body: typing.Any = None): + def __init__( + self, *, status_code: typing.Optional[int] = None, body: typing.Any = None + ): self.status_code = status_code self.body = body diff --git a/seed/python-sdk/undiscriminated-unions/src/seed/core/client_wrapper.py b/seed/python-sdk/undiscriminated-unions/src/seed/core/client_wrapper.py index f940f2d4ab4..88e7c6f5b69 100644 --- a/seed/python-sdk/undiscriminated-unions/src/seed/core/client_wrapper.py +++ b/seed/python-sdk/undiscriminated-unions/src/seed/core/client_wrapper.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .http_client import AsyncHttpClient, HttpClient +from .http_client import HttpClient +from .http_client import AsyncHttpClient class BaseClientWrapper: @@ -28,7 +27,13 @@ def get_timeout(self) -> typing.Optional[float]: class SyncClientWrapper(BaseClientWrapper): - def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, httpx_client: httpx.Client): + def __init__( + self, + *, + base_url: str, + timeout: typing.Optional[float] = None, + httpx_client: httpx.Client, + ): super().__init__(base_url=base_url, timeout=timeout) self.httpx_client = HttpClient( httpx_client=httpx_client, @@ -39,7 +44,13 @@ def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, htt class AsyncClientWrapper(BaseClientWrapper): - def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, httpx_client: httpx.AsyncClient): + def __init__( + self, + *, + base_url: str, + timeout: typing.Optional[float] = None, + httpx_client: httpx.AsyncClient, + ): super().__init__(base_url=base_url, timeout=timeout) self.httpx_client = AsyncHttpClient( httpx_client=httpx_client, diff --git a/seed/python-sdk/undiscriminated-unions/src/seed/core/datetime_utils.py b/seed/python-sdk/undiscriminated-unions/src/seed/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/python-sdk/undiscriminated-unions/src/seed/core/datetime_utils.py +++ b/seed/python-sdk/undiscriminated-unions/src/seed/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/python-sdk/undiscriminated-unions/src/seed/core/file.py b/seed/python-sdk/undiscriminated-unions/src/seed/core/file.py index cb0d40bbbf3..6e0f92bfcb1 100644 --- a/seed/python-sdk/undiscriminated-unions/src/seed/core/file.py +++ b/seed/python-sdk/undiscriminated-unions/src/seed/core/file.py @@ -13,12 +13,17 @@ # (filename, file (or bytes), content_type) typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str]], # (filename, file (or bytes), content_type, headers) - typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str], typing.Mapping[str, str]], + typing.Tuple[ + typing.Optional[str], + FileContent, + typing.Optional[str], + typing.Mapping[str, str], + ], ] def convert_file_dict_to_httpx_tuples( - d: typing.Dict[str, typing.Union[File, typing.List[File]]] + d: typing.Dict[str, typing.Union[File, typing.List[File]]], ) -> typing.List[typing.Tuple[str, File]]: """ The format we use is a list of tuples, where the first element is the diff --git a/seed/python-sdk/undiscriminated-unions/src/seed/core/http_client.py b/seed/python-sdk/undiscriminated-unions/src/seed/core/http_client.py index 9333d8a7f15..091f71bc185 100644 --- a/seed/python-sdk/undiscriminated-unions/src/seed/core/http_client.py +++ b/seed/python-sdk/undiscriminated-unions/src/seed/core/http_client.py @@ -77,7 +77,9 @@ def _retry_timeout(response: httpx.Response, retries: int) -> float: return retry_after # Apply exponential backoff, capped at MAX_RETRY_DELAY_SECONDS. - retry_delay = min(INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS) + retry_delay = min( + INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS + ) # Add a randomness / jitter to the retry delay to avoid overwhelming the server with retries. timeout = retry_delay * (1 - 0.25 * random()) @@ -90,7 +92,8 @@ def _should_retry(response: httpx.Response) -> bool: def remove_omit_from_dict( - original: typing.Dict[str, typing.Optional[typing.Any]], omit: typing.Optional[typing.Any] + original: typing.Dict[str, typing.Optional[typing.Any]], + omit: typing.Optional[typing.Any], ) -> typing.Dict[str, typing.Any]: if omit is None: return original @@ -108,7 +111,8 @@ def maybe_filter_request_body( ) -> typing.Optional[typing.Any]: if data is None: return ( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else None ) @@ -118,7 +122,8 @@ def maybe_filter_request_body( data_content = { **(jsonable_encoder(remove_omit_from_dict(data, omit))), # type: ignore **( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else {} ), @@ -162,7 +167,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url def request( @@ -174,8 +181,12 @@ def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -184,11 +195,14 @@ def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) response = self.httpx_client.request( method=method, @@ -198,7 +212,11 @@ def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -209,7 +227,10 @@ def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -222,11 +243,15 @@ def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: time.sleep(_retry_timeout(response=response, retries=retries)) @@ -256,8 +281,12 @@ def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -266,11 +295,14 @@ def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) with self.httpx_client.stream( method=method, @@ -280,7 +312,11 @@ def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -291,7 +327,9 @@ def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -304,7 +342,9 @@ def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream @@ -327,7 +367,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url async def request( @@ -339,8 +381,12 @@ async def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -349,11 +395,14 @@ async def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) # Add the input to each of these and do None-safety checks response = await self.httpx_client.request( @@ -364,7 +413,11 @@ async def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -375,7 +428,10 @@ async def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -388,11 +444,15 @@ async def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: await asyncio.sleep(_retry_timeout(response=response, retries=retries)) @@ -421,8 +481,12 @@ async def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -431,11 +495,14 @@ async def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) async with self.httpx_client.stream( method=method, @@ -445,7 +512,11 @@ async def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -456,7 +527,9 @@ async def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -469,7 +542,9 @@ async def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream diff --git a/seed/python-sdk/undiscriminated-unions/src/seed/core/jsonable_encoder.py b/seed/python-sdk/undiscriminated-unions/src/seed/core/jsonable_encoder.py index d3fd328fd41..12a8b52fc22 100644 --- a/seed/python-sdk/undiscriminated-unions/src/seed/core/jsonable_encoder.py +++ b/seed/python-sdk/undiscriminated-unions/src/seed/core/jsonable_encoder.py @@ -19,13 +19,19 @@ import pydantic from .datetime_utils import serialize_datetime -from .pydantic_utilities import IS_PYDANTIC_V2, encode_by_type, to_jsonable_with_fallback +from .pydantic_utilities import ( + IS_PYDANTIC_V2, + encode_by_type, + to_jsonable_with_fallback, +) SetIntStr = Set[Union[int, str]] DictIntStrAny = Dict[Union[int, str], Any] -def jsonable_encoder(obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None) -> Any: +def jsonable_encoder( + obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None +) -> Any: custom_encoder = custom_encoder or {} if custom_encoder: if type(obj) in custom_encoder: diff --git a/seed/python-sdk/undiscriminated-unions/src/seed/core/pydantic_utilities.py b/seed/python-sdk/undiscriminated-unions/src/seed/core/pydantic_utilities.py index 170a563d6eb..c63935c32a2 100644 --- a/seed/python-sdk/undiscriminated-unions/src/seed/core/pydantic_utilities.py +++ b/seed/python-sdk/undiscriminated-unions/src/seed/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) # type: ignore # Pydantic v1 diff --git a/seed/python-sdk/undiscriminated-unions/src/seed/core/query_encoder.py b/seed/python-sdk/undiscriminated-unions/src/seed/core/query_encoder.py index 24076d72ee9..7cb98f52cd7 100644 --- a/seed/python-sdk/undiscriminated-unions/src/seed/core/query_encoder.py +++ b/seed/python-sdk/undiscriminated-unions/src/seed/core/query_encoder.py @@ -7,7 +7,9 @@ # Flattens dicts to be of the form {"key[subkey][subkey2]": value} where value is not a dict -def traverse_query_dict(dict_flat: Dict[str, Any], key_prefix: Optional[str] = None) -> Dict[str, Any]: +def traverse_query_dict( + dict_flat: Dict[str, Any], key_prefix: Optional[str] = None +) -> Dict[str, Any]: result = {} for k, v in dict_flat.items(): key = f"{key_prefix}[{k}]" if key_prefix is not None else k @@ -30,4 +32,8 @@ def single_query_encoder(query_key: str, query_value: Any) -> Dict[str, Any]: def encode_query(query: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: - return dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) if query is not None else None + return ( + dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) + if query is not None + else None + ) diff --git a/seed/python-sdk/undiscriminated-unions/src/seed/core/serialization.py b/seed/python-sdk/undiscriminated-unions/src/seed/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/python-sdk/undiscriminated-unions/src/seed/core/serialization.py +++ b/seed/python-sdk/undiscriminated-unions/src/seed/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/python-sdk/undiscriminated-unions/src/seed/union/client.py b/seed/python-sdk/undiscriminated-unions/src/seed/union/client.py index 0bbc3d2e856..9956fae1420 100644 --- a/seed/python-sdk/undiscriminated-unions/src/seed/union/client.py +++ b/seed/python-sdk/undiscriminated-unions/src/seed/union/client.py @@ -1,14 +1,14 @@ # This file was auto-generated by Fern from our API Definition. import typing +from ..core.client_wrapper import SyncClientWrapper +from .types.my_union import MyUnion +from ..core.request_options import RequestOptions +from ..core.pydantic_utilities import parse_obj_as from json.decoder import JSONDecodeError - from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.pydantic_utilities import parse_obj_as -from ..core.request_options import RequestOptions from .types.metadata import Metadata -from .types.my_union import MyUnion +from ..core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -18,7 +18,12 @@ class UnionClient: def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper - def get(self, *, request: MyUnion, request_options: typing.Optional[RequestOptions] = None) -> MyUnion: + def get( + self, + *, + request: MyUnion, + request_options: typing.Optional[RequestOptions] = None, + ) -> MyUnion: """ Parameters ---------- @@ -43,17 +48,24 @@ def get(self, *, request: MyUnion, request_options: typing.Optional[RequestOptio ) """ _response = self._client_wrapper.httpx_client.request( - method="POST", json=request, request_options=request_options, omit=OMIT + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(MyUnion, parse_obj_as(type_=MyUnion, object_=_response.json())) # type: ignore + return typing.cast( + MyUnion, parse_obj_as(type_=MyUnion, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def get_metadata(self, *, request_options: typing.Optional[RequestOptions] = None) -> Metadata: + def get_metadata( + self, *, request_options: typing.Optional[RequestOptions] = None + ) -> Metadata: """ Parameters ---------- @@ -73,10 +85,16 @@ def get_metadata(self, *, request_options: typing.Optional[RequestOptions] = Non ) client.union.get_metadata() """ - _response = self._client_wrapper.httpx_client.request("metadata", method="GET", request_options=request_options) + _response = self._client_wrapper.httpx_client.request( + "metadata", + method="GET", + request_options=request_options, + ) try: if 200 <= _response.status_code < 300: - return typing.cast(Metadata, parse_obj_as(type_=Metadata, object_=_response.json())) # type: ignore + return typing.cast( + Metadata, parse_obj_as(type_=Metadata, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -87,7 +105,12 @@ class AsyncUnionClient: def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper - async def get(self, *, request: MyUnion, request_options: typing.Optional[RequestOptions] = None) -> MyUnion: + async def get( + self, + *, + request: MyUnion, + request_options: typing.Optional[RequestOptions] = None, + ) -> MyUnion: """ Parameters ---------- @@ -120,17 +143,24 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - method="POST", json=request, request_options=request_options, omit=OMIT + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(MyUnion, parse_obj_as(type_=MyUnion, object_=_response.json())) # type: ignore + return typing.cast( + MyUnion, parse_obj_as(type_=MyUnion, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - async def get_metadata(self, *, request_options: typing.Optional[RequestOptions] = None) -> Metadata: + async def get_metadata( + self, *, request_options: typing.Optional[RequestOptions] = None + ) -> Metadata: """ Parameters ---------- @@ -159,11 +189,15 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - "metadata", method="GET", request_options=request_options + "metadata", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(Metadata, parse_obj_as(type_=Metadata, object_=_response.json())) # type: ignore + return typing.cast( + Metadata, parse_obj_as(type_=Metadata, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/undiscriminated-unions/src/seed/union/types/key.py b/seed/python-sdk/undiscriminated-unions/src/seed/union/types/key.py index 3c379619874..c143ecf00b2 100644 --- a/seed/python-sdk/undiscriminated-unions/src/seed/union/types/key.py +++ b/seed/python-sdk/undiscriminated-unions/src/seed/union/types/key.py @@ -1,7 +1,6 @@ # This file was auto-generated by Fern from our API Definition. import typing - from .key_type import KeyType Key = typing.Union[KeyType, typing.Literal["default"]] diff --git a/seed/python-sdk/undiscriminated-unions/src/seed/union/types/metadata.py b/seed/python-sdk/undiscriminated-unions/src/seed/union/types/metadata.py index 9d3134f13ad..2c53a1101bc 100644 --- a/seed/python-sdk/undiscriminated-unions/src/seed/union/types/metadata.py +++ b/seed/python-sdk/undiscriminated-unions/src/seed/union/types/metadata.py @@ -1,7 +1,6 @@ # This file was auto-generated by Fern from our API Definition. import typing - from .key import Key """ diff --git a/seed/python-sdk/undiscriminated-unions/src/seed/union/types/my_union.py b/seed/python-sdk/undiscriminated-unions/src/seed/union/types/my_union.py index 6b8c3dae2f4..9a8a6426908 100644 --- a/seed/python-sdk/undiscriminated-unions/src/seed/union/types/my_union.py +++ b/seed/python-sdk/undiscriminated-unions/src/seed/union/types/my_union.py @@ -2,4 +2,11 @@ import typing -MyUnion = typing.Union[str, typing.List[str], int, typing.List[int], typing.List[typing.List[int]], typing.Set[str]] +MyUnion = typing.Union[ + str, + typing.List[str], + int, + typing.List[int], + typing.List[typing.List[int]], + typing.Set[str], +] diff --git a/seed/python-sdk/undiscriminated-unions/src/seed/version.py b/seed/python-sdk/undiscriminated-unions/src/seed/version.py index 61d5e92e497..9d588e6c5fd 100644 --- a/seed/python-sdk/undiscriminated-unions/src/seed/version.py +++ b/seed/python-sdk/undiscriminated-unions/src/seed/version.py @@ -1,4 +1,3 @@ - from importlib import metadata __version__ = metadata.version("fern_undiscriminated-unions") diff --git a/seed/python-sdk/undiscriminated-unions/tests/conftest.py b/seed/python-sdk/undiscriminated-unions/tests/conftest.py index 03084dd81ba..9a775071db0 100644 --- a/seed/python-sdk/undiscriminated-unions/tests/conftest.py +++ b/seed/python-sdk/undiscriminated-unions/tests/conftest.py @@ -1,9 +1,9 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedUndiscriminatedUnions import os - import pytest -from seed import AsyncSeedUndiscriminatedUnions, SeedUndiscriminatedUnions +from seed import AsyncSeedUndiscriminatedUnions @pytest.fixture @@ -13,4 +13,6 @@ def client() -> SeedUndiscriminatedUnions: @pytest.fixture def async_client() -> AsyncSeedUndiscriminatedUnions: - return AsyncSeedUndiscriminatedUnions(base_url=os.getenv("TESTS_BASE_URL", "base_url")) + return AsyncSeedUndiscriminatedUnions( + base_url=os.getenv("TESTS_BASE_URL", "base_url") + ) diff --git a/seed/python-sdk/undiscriminated-unions/tests/custom/test_client.py b/seed/python-sdk/undiscriminated-unions/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/python-sdk/undiscriminated-unions/tests/custom/test_client.py +++ b/seed/python-sdk/undiscriminated-unions/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/python-sdk/undiscriminated-unions/tests/test_union.py b/seed/python-sdk/undiscriminated-unions/tests/test_union.py index 246ca6d6c29..130aaa9300a 100644 --- a/seed/python-sdk/undiscriminated-unions/tests/test_union.py +++ b/seed/python-sdk/undiscriminated-unions/tests/test_union.py @@ -1,13 +1,14 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedUndiscriminatedUnions +from seed import AsyncSeedUndiscriminatedUnions import typing - -from seed import AsyncSeedUndiscriminatedUnions, SeedUndiscriminatedUnions - from .utilities import validate_response -async def test_get(client: SeedUndiscriminatedUnions, async_client: AsyncSeedUndiscriminatedUnions) -> None: +async def test_get( + client: SeedUndiscriminatedUnions, async_client: AsyncSeedUndiscriminatedUnions +) -> None: expected_response: typing.Any = "string" expected_types: typing.Any = None response = client.union.get(request="string") @@ -17,9 +18,18 @@ async def test_get(client: SeedUndiscriminatedUnions, async_client: AsyncSeedUnd validate_response(async_response, expected_response, expected_types) -async def test_get_metadata(client: SeedUndiscriminatedUnions, async_client: AsyncSeedUndiscriminatedUnions) -> None: - expected_response: typing.Any = {"name": "exampleName", "value": "exampleValue", "default": "exampleDefault"} - expected_types: typing.Tuple[typing.Any, typing.Any] = ("dict", {0: (None, None), 1: (None, None), 2: (None, None)}) +async def test_get_metadata( + client: SeedUndiscriminatedUnions, async_client: AsyncSeedUndiscriminatedUnions +) -> None: + expected_response: typing.Any = { + "name": "exampleName", + "value": "exampleValue", + "default": "exampleDefault", + } + expected_types: typing.Tuple[typing.Any, typing.Any] = ( + "dict", + {0: (None, None), 1: (None, None), 2: (None, None)}, + ) response = client.union.get_metadata() validate_response(response, expected_response, expected_types) diff --git a/seed/python-sdk/undiscriminated-unions/tests/utilities.py b/seed/python-sdk/undiscriminated-unions/tests/utilities.py index 13da208eb3a..e8f4472564c 100644 --- a/seed/python-sdk/undiscriminated-unions/tests/utilities.py +++ b/seed/python-sdk/undiscriminated-unions/tests/utilities.py @@ -3,11 +3,14 @@ import typing import uuid -import pydantic from dateutil import parser +import pydantic + -def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> typing.Any: +def cast_field( + json_expectation: typing.Any, type_expectation: typing.Any +) -> typing.Any: # Cast these specific types which come through as string and expect our # models to cast to the correct type. if type_expectation == "uuid": @@ -25,7 +28,9 @@ def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> ty return json_expectation -def validate_field(response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any) -> None: +def validate_field( + response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectation == "no_validate": return @@ -44,7 +49,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(entry_expectation, dict): is_container_of_complex_type = True validate_response( - response=response[idx], json_expectation=ex, type_expectations=entry_expectation + response=response[idx], + json_expectation=ex, + type_expectations=entry_expectation, ) else: cast_json_expectation.append(cast_field(ex, entry_expectation)) @@ -56,7 +63,10 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # if any of the values of the set have a type_expectation of a dict, we're assuming it's a pydantic # model and keeping it a list. if container_expectation != "set" or not any( - map(lambda value: isinstance(value, dict), list(contents_expectation.values())) + map( + lambda value: isinstance(value, dict), + list(contents_expectation.values()), + ) ): json_expectation = cast_field(json_expectation, container_expectation) elif isinstance(type_expectation, tuple): @@ -65,9 +75,15 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(contents_expectation, dict): json_expectation = { cast_field( - key, contents_expectation.get(idx)[0] if contents_expectation.get(idx) is not None else None # type: ignore + key, + contents_expectation.get(idx)[0] + if contents_expectation.get(idx) is not None + else None, # type: ignore ): cast_field( - value, contents_expectation.get(idx)[1] if contents_expectation.get(idx) is not None else None # type: ignore + value, + contents_expectation.get(idx)[1] + if contents_expectation.get(idx) is not None + else None, # type: ignore ) for idx, (key, value) in enumerate(json_expectation.items()) } @@ -86,7 +102,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # Arg type_expectations is a deeply nested structure that matches the response, but with the values replaced with the expected types -def validate_response(response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any) -> None: +def validate_response( + response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectations == "no_validate": return @@ -96,11 +114,17 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e and not isinstance(response, dict) and not issubclass(type(response), pydantic.BaseModel) ): - validate_field(response=response, json_expectation=json_expectation, type_expectation=type_expectations) + validate_field( + response=response, + json_expectation=json_expectation, + type_expectation=type_expectations, + ) return if isinstance(response, list): - assert len(response) == len(json_expectation), "Length mismatch, expected: {0}, Actual: {1}".format( + assert len(response) == len( + json_expectation + ), "Length mismatch, expected: {0}, Actual: {1}".format( len(response), len(json_expectation) ) content_expectation = type_expectations @@ -108,7 +132,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e content_expectation = type_expectations[1] for idx, item in enumerate(response): validate_response( - response=item, json_expectation=json_expectation[idx], type_expectations=content_expectation[idx] + response=item, + json_expectation=json_expectation[idx], + type_expectations=content_expectation[idx], ) else: response_json = response @@ -116,7 +142,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e response_json = response.dict(by_alias=True) for key, value in json_expectation.items(): - assert key in response_json, "Field {0} not found within the response object: {1}".format( + assert ( + key in response_json + ), "Field {0} not found within the response object: {1}".format( key, response_json ) @@ -128,11 +156,19 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e # Otherwise, we're just validating a single field that's a pydantic model. if isinstance(value, dict) and not isinstance(type_expectation, tuple): validate_response( - response=response_json[key], json_expectation=value, type_expectations=type_expectation + response=response_json[key], + json_expectation=value, + type_expectations=type_expectation, ) else: - validate_field(response=response_json[key], json_expectation=value, type_expectation=type_expectation) + validate_field( + response=response_json[key], + json_expectation=value, + type_expectation=type_expectation, + ) # Ensure there are no additional fields here either del response_json[key] - assert len(response_json) == 0, "Additional fields found, expected None: {0}".format(response_json) + assert ( + len(response_json) == 0 + ), "Additional fields found, expected None: {0}".format(response_json) diff --git a/seed/python-sdk/undiscriminated-unions/tests/utils/assets/models/__init__.py b/seed/python-sdk/undiscriminated-unions/tests/utils/assets/models/__init__.py index 2cf01263529..3a1c852e71e 100644 --- a/seed/python-sdk/undiscriminated-unions/tests/utils/assets/models/__init__.py +++ b/seed/python-sdk/undiscriminated-unions/tests/utils/assets/models/__init__.py @@ -5,7 +5,7 @@ from .circle import CircleParams from .object_with_defaults import ObjectWithDefaultsParams from .object_with_optional_field import ObjectWithOptionalFieldParams -from .shape import Shape_CircleParams, Shape_SquareParams, ShapeParams +from .shape import ShapeParams, Shape_CircleParams, Shape_SquareParams from .square import SquareParams from .undiscriminated_shape import UndiscriminatedShapeParams diff --git a/seed/python-sdk/undiscriminated-unions/tests/utils/assets/models/circle.py b/seed/python-sdk/undiscriminated-unions/tests/utils/assets/models/circle.py index af7a1bf8a8e..253f12d38b3 100644 --- a/seed/python-sdk/undiscriminated-unions/tests/utils/assets/models/circle.py +++ b/seed/python-sdk/undiscriminated-unions/tests/utils/assets/models/circle.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class CircleParams(typing_extensions.TypedDict): - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] diff --git a/seed/python-sdk/undiscriminated-unions/tests/utils/assets/models/object_with_optional_field.py b/seed/python-sdk/undiscriminated-unions/tests/utils/assets/models/object_with_optional_field.py index 3ad93d5f305..ebe7dc80547 100644 --- a/seed/python-sdk/undiscriminated-unions/tests/utils/assets/models/object_with_optional_field.py +++ b/seed/python-sdk/undiscriminated-unions/tests/utils/assets/models/object_with_optional_field.py @@ -7,8 +7,8 @@ import uuid import typing_extensions -from seed.core.serialization import FieldMetadata +from seed.core.serialization import FieldMetadata from .color import Color from .shape import ShapeParams from .undiscriminated_shape import UndiscriminatedShapeParams @@ -18,16 +18,30 @@ class ObjectWithOptionalFieldParams(typing_extensions.TypedDict): literal: typing.Literal["lit_one"] string: typing_extensions.NotRequired[str] integer: typing_extensions.NotRequired[int] - long_: typing_extensions.NotRequired[typing_extensions.Annotated[int, FieldMetadata(alias="long")]] + long_: typing_extensions.NotRequired[ + typing_extensions.Annotated[int, FieldMetadata(alias="long")] + ] double: typing_extensions.NotRequired[float] - bool_: typing_extensions.NotRequired[typing_extensions.Annotated[bool, FieldMetadata(alias="bool")]] + bool_: typing_extensions.NotRequired[ + typing_extensions.Annotated[bool, FieldMetadata(alias="bool")] + ] datetime: typing_extensions.NotRequired[dt.datetime] date: typing_extensions.NotRequired[dt.date] - uuid_: typing_extensions.NotRequired[typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")]] - base_64: typing_extensions.NotRequired[typing_extensions.Annotated[str, FieldMetadata(alias="base64")]] - list_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")]] - set_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")]] - map_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")]] + uuid_: typing_extensions.NotRequired[ + typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")] + ] + base_64: typing_extensions.NotRequired[ + typing_extensions.Annotated[str, FieldMetadata(alias="base64")] + ] + list_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")] + ] + set_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")] + ] + map_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")] + ] enum: typing_extensions.NotRequired[Color] union: typing_extensions.NotRequired[ShapeParams] second_union: typing_extensions.NotRequired[ShapeParams] diff --git a/seed/python-sdk/undiscriminated-unions/tests/utils/assets/models/shape.py b/seed/python-sdk/undiscriminated-unions/tests/utils/assets/models/shape.py index 2c33c877951..816ffc51bdc 100644 --- a/seed/python-sdk/undiscriminated-unions/tests/utils/assets/models/shape.py +++ b/seed/python-sdk/undiscriminated-unions/tests/utils/assets/models/shape.py @@ -7,6 +7,7 @@ import typing import typing_extensions + from seed.core.serialization import FieldMetadata @@ -15,13 +16,21 @@ class Base(typing_extensions.TypedDict): class Shape_CircleParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["circle"], FieldMetadata(alias="shapeType")] - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["circle"], FieldMetadata(alias="shapeType") + ] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] class Shape_SquareParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["square"], FieldMetadata(alias="shapeType")] - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["square"], FieldMetadata(alias="shapeType") + ] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] ShapeParams = typing.Union[Shape_CircleParams, Shape_SquareParams] diff --git a/seed/python-sdk/undiscriminated-unions/tests/utils/assets/models/square.py b/seed/python-sdk/undiscriminated-unions/tests/utils/assets/models/square.py index b9b7dd319bc..bcf08a723c5 100644 --- a/seed/python-sdk/undiscriminated-unions/tests/utils/assets/models/square.py +++ b/seed/python-sdk/undiscriminated-unions/tests/utils/assets/models/square.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class SquareParams(typing_extensions.TypedDict): - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] diff --git a/seed/python-sdk/undiscriminated-unions/tests/utils/test_http_client.py b/seed/python-sdk/undiscriminated-unions/tests/utils/test_http_client.py index edd11ca7afb..f5a874a75f3 100644 --- a/seed/python-sdk/undiscriminated-unions/tests/utils/test_http_client.py +++ b/seed/python-sdk/undiscriminated-unions/tests/utils/test_http_client.py @@ -9,12 +9,17 @@ def get_request_options() -> RequestOptions: def test_get_json_request_body() -> None: - json_body, data_body = get_request_body(json={"hello": "world"}, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json={"hello": "world"}, data=None, request_options=None, omit=None + ) assert json_body == {"hello": "world"} assert data_body is None json_body_extras, data_body_extras = get_request_body( - json={"goodbye": "world"}, data=None, request_options=get_request_options(), omit=None + json={"goodbye": "world"}, + data=None, + request_options=get_request_options(), + omit=None, ) assert json_body_extras == {"goodbye": "world", "see you": "later"} @@ -22,12 +27,17 @@ def test_get_json_request_body() -> None: def test_get_files_request_body() -> None: - json_body, data_body = get_request_body(json=None, data={"hello": "world"}, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data={"hello": "world"}, request_options=None, omit=None + ) assert data_body == {"hello": "world"} assert json_body is None json_body_extras, data_body_extras = get_request_body( - json=None, data={"goodbye": "world"}, request_options=get_request_options(), omit=None + json=None, + data={"goodbye": "world"}, + request_options=get_request_options(), + omit=None, ) assert data_body_extras == {"goodbye": "world", "see you": "later"} @@ -35,7 +45,9 @@ def test_get_files_request_body() -> None: def test_get_none_request_body() -> None: - json_body, data_body = get_request_body(json=None, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data=None, request_options=None, omit=None + ) assert data_body is None assert json_body is None diff --git a/seed/python-sdk/undiscriminated-unions/tests/utils/test_query_encoding.py b/seed/python-sdk/undiscriminated-unions/tests/utils/test_query_encoding.py index 247e1551b46..fbc8f402167 100644 --- a/seed/python-sdk/undiscriminated-unions/tests/utils/test_query_encoding.py +++ b/seed/python-sdk/undiscriminated-unions/tests/utils/test_query_encoding.py @@ -4,9 +4,15 @@ def test_query_encoding() -> None: - assert encode_query({"hello world": "hello world"}) == {"hello world": "hello world"} - assert encode_query({"hello_world": {"hello": "world"}}) == {"hello_world[hello]": "world"} - assert encode_query({"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"}) == { + assert encode_query({"hello world": "hello world"}) == { + "hello world": "hello world" + } + assert encode_query({"hello_world": {"hello": "world"}}) == { + "hello_world[hello]": "world" + } + assert encode_query( + {"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"} + ) == { "hello_world[hello][world]": "today", "hello_world[test]": "this", "hi": "there", diff --git a/seed/python-sdk/undiscriminated-unions/tests/utils/test_serialization.py b/seed/python-sdk/undiscriminated-unions/tests/utils/test_serialization.py index 58b1ed66e6d..5ca956916dd 100644 --- a/seed/python-sdk/undiscriminated-unions/tests/utils/test_serialization.py +++ b/seed/python-sdk/undiscriminated-unions/tests/utils/test_serialization.py @@ -1,10 +1,12 @@ # This file was auto-generated by Fern from our API Definition. -from typing import Any, List +from typing import List, Any -from seed.core.serialization import convert_and_respect_annotation_metadata +from seed.core.serialization import ( + convert_and_respect_annotation_metadata, +) +from .assets.models import ShapeParams, ObjectWithOptionalFieldParams -from .assets.models import ObjectWithOptionalFieldParams, ShapeParams UNION_TEST: ShapeParams = {"radius_measurement": 1.0, "shape_type": "circle", "id": "1"} UNION_TEST_CONVERTED = {"shapeType": "circle", "radiusMeasurement": 1.0, "id": "1"} @@ -18,20 +20,54 @@ def test_convert_and_respect_annotation_metadata() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) - assert converted == {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"} + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) + assert converted == { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + } def test_convert_and_respect_annotation_metadata_in_list() -> None: data: List[ObjectWithOptionalFieldParams] = [ - {"string": "string", "long_": 12345, "bool_": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long_": 67890, "list_": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long_": 12345, + "bool_": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long_": 67890, + "list_": [], + "literal": "lit_one", + "any": "any", + }, ] - converted = convert_and_respect_annotation_metadata(object_=data, annotation=List[ObjectWithOptionalFieldParams]) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=List[ObjectWithOptionalFieldParams] + ) assert converted == [ - {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long": 67890, "list": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long": 67890, + "list": [], + "literal": "lit_one", + "any": "any", + }, ] @@ -43,7 +79,9 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) assert converted == { "string": "string", @@ -55,12 +93,16 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: def test_convert_and_respect_annotation_metadata_in_union() -> None: - converted = convert_and_respect_annotation_metadata(object_=UNION_TEST, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=UNION_TEST, annotation=ShapeParams + ) assert converted == UNION_TEST_CONVERTED def test_convert_and_respect_annotation_metadata_with_empty_object() -> None: data: Any = {} - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ShapeParams + ) assert converted == data diff --git a/seed/python-sdk/unions/no-custom-config/pyproject.toml b/seed/python-sdk/unions/no-custom-config/pyproject.toml index 94ea983b951..74156e62e47 100644 --- a/seed/python-sdk/unions/no-custom-config/pyproject.toml +++ b/seed/python-sdk/unions/no-custom-config/pyproject.toml @@ -43,6 +43,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/python-sdk/unions/no-custom-config/src/seed/client.py b/seed/python-sdk/unions/no-custom-config/src/seed/client.py index 58cb9526d55..7f926f5e347 100644 --- a/seed/python-sdk/unions/no-custom-config/src/seed/client.py +++ b/seed/python-sdk/unions/no-custom-config/src/seed/client.py @@ -1,11 +1,11 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from .union.client import AsyncUnionClient, UnionClient +from .core.client_wrapper import SyncClientWrapper +from .union.client import UnionClient +from .core.client_wrapper import AsyncClientWrapper +from .union.client import AsyncUnionClient class SeedUnions: @@ -41,14 +41,18 @@ def __init__( base_url: str, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.Client] = None + httpx_client: typing.Optional[httpx.Client] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = SyncClientWrapper( base_url=base_url, httpx_client=httpx_client if httpx_client is not None - else httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.Client( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.Client(timeout=_defaulted_timeout), timeout=_defaulted_timeout, @@ -89,14 +93,18 @@ def __init__( base_url: str, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.AsyncClient] = None + httpx_client: typing.Optional[httpx.AsyncClient] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = AsyncClientWrapper( base_url=base_url, httpx_client=httpx_client if httpx_client is not None - else httpx.AsyncClient(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.AsyncClient( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.AsyncClient(timeout=_defaulted_timeout), timeout=_defaulted_timeout, diff --git a/seed/python-sdk/unions/no-custom-config/src/seed/core/api_error.py b/seed/python-sdk/unions/no-custom-config/src/seed/core/api_error.py index 2e9fc5431cd..da734b58068 100644 --- a/seed/python-sdk/unions/no-custom-config/src/seed/core/api_error.py +++ b/seed/python-sdk/unions/no-custom-config/src/seed/core/api_error.py @@ -7,7 +7,9 @@ class ApiError(Exception): status_code: typing.Optional[int] body: typing.Any - def __init__(self, *, status_code: typing.Optional[int] = None, body: typing.Any = None): + def __init__( + self, *, status_code: typing.Optional[int] = None, body: typing.Any = None + ): self.status_code = status_code self.body = body diff --git a/seed/python-sdk/unions/no-custom-config/src/seed/core/client_wrapper.py b/seed/python-sdk/unions/no-custom-config/src/seed/core/client_wrapper.py index a12ded4d812..951aaa210f2 100644 --- a/seed/python-sdk/unions/no-custom-config/src/seed/core/client_wrapper.py +++ b/seed/python-sdk/unions/no-custom-config/src/seed/core/client_wrapper.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .http_client import AsyncHttpClient, HttpClient +from .http_client import HttpClient +from .http_client import AsyncHttpClient class BaseClientWrapper: @@ -28,7 +27,13 @@ def get_timeout(self) -> typing.Optional[float]: class SyncClientWrapper(BaseClientWrapper): - def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, httpx_client: httpx.Client): + def __init__( + self, + *, + base_url: str, + timeout: typing.Optional[float] = None, + httpx_client: httpx.Client, + ): super().__init__(base_url=base_url, timeout=timeout) self.httpx_client = HttpClient( httpx_client=httpx_client, @@ -39,7 +44,13 @@ def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, htt class AsyncClientWrapper(BaseClientWrapper): - def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, httpx_client: httpx.AsyncClient): + def __init__( + self, + *, + base_url: str, + timeout: typing.Optional[float] = None, + httpx_client: httpx.AsyncClient, + ): super().__init__(base_url=base_url, timeout=timeout) self.httpx_client = AsyncHttpClient( httpx_client=httpx_client, diff --git a/seed/python-sdk/unions/no-custom-config/src/seed/core/datetime_utils.py b/seed/python-sdk/unions/no-custom-config/src/seed/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/python-sdk/unions/no-custom-config/src/seed/core/datetime_utils.py +++ b/seed/python-sdk/unions/no-custom-config/src/seed/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/python-sdk/unions/no-custom-config/src/seed/core/file.py b/seed/python-sdk/unions/no-custom-config/src/seed/core/file.py index cb0d40bbbf3..6e0f92bfcb1 100644 --- a/seed/python-sdk/unions/no-custom-config/src/seed/core/file.py +++ b/seed/python-sdk/unions/no-custom-config/src/seed/core/file.py @@ -13,12 +13,17 @@ # (filename, file (or bytes), content_type) typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str]], # (filename, file (or bytes), content_type, headers) - typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str], typing.Mapping[str, str]], + typing.Tuple[ + typing.Optional[str], + FileContent, + typing.Optional[str], + typing.Mapping[str, str], + ], ] def convert_file_dict_to_httpx_tuples( - d: typing.Dict[str, typing.Union[File, typing.List[File]]] + d: typing.Dict[str, typing.Union[File, typing.List[File]]], ) -> typing.List[typing.Tuple[str, File]]: """ The format we use is a list of tuples, where the first element is the diff --git a/seed/python-sdk/unions/no-custom-config/src/seed/core/http_client.py b/seed/python-sdk/unions/no-custom-config/src/seed/core/http_client.py index 9333d8a7f15..091f71bc185 100644 --- a/seed/python-sdk/unions/no-custom-config/src/seed/core/http_client.py +++ b/seed/python-sdk/unions/no-custom-config/src/seed/core/http_client.py @@ -77,7 +77,9 @@ def _retry_timeout(response: httpx.Response, retries: int) -> float: return retry_after # Apply exponential backoff, capped at MAX_RETRY_DELAY_SECONDS. - retry_delay = min(INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS) + retry_delay = min( + INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS + ) # Add a randomness / jitter to the retry delay to avoid overwhelming the server with retries. timeout = retry_delay * (1 - 0.25 * random()) @@ -90,7 +92,8 @@ def _should_retry(response: httpx.Response) -> bool: def remove_omit_from_dict( - original: typing.Dict[str, typing.Optional[typing.Any]], omit: typing.Optional[typing.Any] + original: typing.Dict[str, typing.Optional[typing.Any]], + omit: typing.Optional[typing.Any], ) -> typing.Dict[str, typing.Any]: if omit is None: return original @@ -108,7 +111,8 @@ def maybe_filter_request_body( ) -> typing.Optional[typing.Any]: if data is None: return ( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else None ) @@ -118,7 +122,8 @@ def maybe_filter_request_body( data_content = { **(jsonable_encoder(remove_omit_from_dict(data, omit))), # type: ignore **( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else {} ), @@ -162,7 +167,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url def request( @@ -174,8 +181,12 @@ def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -184,11 +195,14 @@ def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) response = self.httpx_client.request( method=method, @@ -198,7 +212,11 @@ def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -209,7 +227,10 @@ def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -222,11 +243,15 @@ def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: time.sleep(_retry_timeout(response=response, retries=retries)) @@ -256,8 +281,12 @@ def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -266,11 +295,14 @@ def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) with self.httpx_client.stream( method=method, @@ -280,7 +312,11 @@ def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -291,7 +327,9 @@ def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -304,7 +342,9 @@ def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream @@ -327,7 +367,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url async def request( @@ -339,8 +381,12 @@ async def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -349,11 +395,14 @@ async def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) # Add the input to each of these and do None-safety checks response = await self.httpx_client.request( @@ -364,7 +413,11 @@ async def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -375,7 +428,10 @@ async def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -388,11 +444,15 @@ async def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: await asyncio.sleep(_retry_timeout(response=response, retries=retries)) @@ -421,8 +481,12 @@ async def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -431,11 +495,14 @@ async def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) async with self.httpx_client.stream( method=method, @@ -445,7 +512,11 @@ async def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -456,7 +527,9 @@ async def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -469,7 +542,9 @@ async def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream diff --git a/seed/python-sdk/unions/no-custom-config/src/seed/core/jsonable_encoder.py b/seed/python-sdk/unions/no-custom-config/src/seed/core/jsonable_encoder.py index d3fd328fd41..12a8b52fc22 100644 --- a/seed/python-sdk/unions/no-custom-config/src/seed/core/jsonable_encoder.py +++ b/seed/python-sdk/unions/no-custom-config/src/seed/core/jsonable_encoder.py @@ -19,13 +19,19 @@ import pydantic from .datetime_utils import serialize_datetime -from .pydantic_utilities import IS_PYDANTIC_V2, encode_by_type, to_jsonable_with_fallback +from .pydantic_utilities import ( + IS_PYDANTIC_V2, + encode_by_type, + to_jsonable_with_fallback, +) SetIntStr = Set[Union[int, str]] DictIntStrAny = Dict[Union[int, str], Any] -def jsonable_encoder(obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None) -> Any: +def jsonable_encoder( + obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None +) -> Any: custom_encoder = custom_encoder or {} if custom_encoder: if type(obj) in custom_encoder: diff --git a/seed/python-sdk/unions/no-custom-config/src/seed/core/pydantic_utilities.py b/seed/python-sdk/unions/no-custom-config/src/seed/core/pydantic_utilities.py index 170a563d6eb..c63935c32a2 100644 --- a/seed/python-sdk/unions/no-custom-config/src/seed/core/pydantic_utilities.py +++ b/seed/python-sdk/unions/no-custom-config/src/seed/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) # type: ignore # Pydantic v1 diff --git a/seed/python-sdk/unions/no-custom-config/src/seed/core/query_encoder.py b/seed/python-sdk/unions/no-custom-config/src/seed/core/query_encoder.py index 24076d72ee9..7cb98f52cd7 100644 --- a/seed/python-sdk/unions/no-custom-config/src/seed/core/query_encoder.py +++ b/seed/python-sdk/unions/no-custom-config/src/seed/core/query_encoder.py @@ -7,7 +7,9 @@ # Flattens dicts to be of the form {"key[subkey][subkey2]": value} where value is not a dict -def traverse_query_dict(dict_flat: Dict[str, Any], key_prefix: Optional[str] = None) -> Dict[str, Any]: +def traverse_query_dict( + dict_flat: Dict[str, Any], key_prefix: Optional[str] = None +) -> Dict[str, Any]: result = {} for k, v in dict_flat.items(): key = f"{key_prefix}[{k}]" if key_prefix is not None else k @@ -30,4 +32,8 @@ def single_query_encoder(query_key: str, query_value: Any) -> Dict[str, Any]: def encode_query(query: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: - return dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) if query is not None else None + return ( + dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) + if query is not None + else None + ) diff --git a/seed/python-sdk/unions/no-custom-config/src/seed/core/serialization.py b/seed/python-sdk/unions/no-custom-config/src/seed/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/python-sdk/unions/no-custom-config/src/seed/core/serialization.py +++ b/seed/python-sdk/unions/no-custom-config/src/seed/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/python-sdk/unions/no-custom-config/src/seed/types/types/__init__.py b/seed/python-sdk/unions/no-custom-config/src/seed/types/types/__init__.py index 42d3faa423c..cb9ecd1e17f 100644 --- a/seed/python-sdk/unions/no-custom-config/src/seed/types/types/__init__.py +++ b/seed/python-sdk/unions/no-custom-config/src/seed/types/types/__init__.py @@ -9,13 +9,37 @@ UnionWithBaseProperties_Integer, UnionWithBaseProperties_String, ) -from .union_with_discriminant import UnionWithDiscriminant, UnionWithDiscriminant_Bar, UnionWithDiscriminant_Foo +from .union_with_discriminant import ( + UnionWithDiscriminant, + UnionWithDiscriminant_Bar, + UnionWithDiscriminant_Foo, +) from .union_with_literal import UnionWithLiteral, UnionWithLiteral_Fern -from .union_with_optional_time import UnionWithOptionalTime, UnionWithOptionalTime_Date, UnionWithOptionalTime_Dateimte -from .union_with_primitive import UnionWithPrimitive, UnionWithPrimitive_Integer, UnionWithPrimitive_String -from .union_with_single_element import UnionWithSingleElement, UnionWithSingleElement_Foo -from .union_with_time import UnionWithTime, UnionWithTime_Date, UnionWithTime_Datetime, UnionWithTime_Value -from .union_with_unknown import UnionWithUnknown, UnionWithUnknown_Foo, UnionWithUnknown_Unknown +from .union_with_optional_time import ( + UnionWithOptionalTime, + UnionWithOptionalTime_Date, + UnionWithOptionalTime_Dateimte, +) +from .union_with_primitive import ( + UnionWithPrimitive, + UnionWithPrimitive_Integer, + UnionWithPrimitive_String, +) +from .union_with_single_element import ( + UnionWithSingleElement, + UnionWithSingleElement_Foo, +) +from .union_with_time import ( + UnionWithTime, + UnionWithTime_Date, + UnionWithTime_Datetime, + UnionWithTime_Value, +) +from .union_with_unknown import ( + UnionWithUnknown, + UnionWithUnknown_Foo, + UnionWithUnknown_Unknown, +) from .union_without_key import UnionWithoutKey, UnionWithoutKey_Bar, UnionWithoutKey_Foo __all__ = [ diff --git a/seed/python-sdk/unions/no-custom-config/src/seed/types/types/bar.py b/seed/python-sdk/unions/no-custom-config/src/seed/types/types/bar.py index 34796fe719f..71aa92ba94d 100644 --- a/seed/python-sdk/unions/no-custom-config/src/seed/types/types/bar.py +++ b/seed/python-sdk/unions/no-custom-config/src/seed/types/types/bar.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class Bar(UniversalBaseModel): name: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/unions/no-custom-config/src/seed/types/types/foo.py b/seed/python-sdk/unions/no-custom-config/src/seed/types/types/foo.py index 9da151d9182..882153c67b4 100644 --- a/seed/python-sdk/unions/no-custom-config/src/seed/types/types/foo.py +++ b/seed/python-sdk/unions/no-custom-config/src/seed/types/types/foo.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class Foo(UniversalBaseModel): name: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/unions/no-custom-config/src/seed/types/types/union.py b/seed/python-sdk/unions/no-custom-config/src/seed/types/types/union.py index eac4c535312..b7644b67202 100644 --- a/seed/python-sdk/unions/no-custom-config/src/seed/types/types/union.py +++ b/seed/python-sdk/unions/no-custom-config/src/seed/types/types/union.py @@ -1,14 +1,12 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ...core.pydantic_utilities import UniversalBaseModel +from .foo import Foo import typing - +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel from .bar import Bar -from .foo import Foo class Union_Foo(UniversalBaseModel): @@ -16,7 +14,9 @@ class Union_Foo(UniversalBaseModel): type: typing.Literal["foo"] = "foo" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + frozen=True + ) # type: ignore # Pydantic v2 else: class Config: @@ -29,7 +29,9 @@ class Union_Bar(UniversalBaseModel): type: typing.Literal["bar"] = "bar" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/unions/no-custom-config/src/seed/types/types/union_with_base_properties.py b/seed/python-sdk/unions/no-custom-config/src/seed/types/types/union_with_base_properties.py index 90112e9f723..4a05db65865 100644 --- a/seed/python-sdk/unions/no-custom-config/src/seed/types/types/union_with_base_properties.py +++ b/seed/python-sdk/unions/no-custom-config/src/seed/types/types/union_with_base_properties.py @@ -1,19 +1,19 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class Base(UniversalBaseModel): id: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: @@ -27,7 +27,9 @@ class UnionWithBaseProperties_Integer(Base): type: typing.Literal["integer"] = "integer" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + frozen=True + ) # type: ignore # Pydantic v2 else: class Config: @@ -40,7 +42,9 @@ class UnionWithBaseProperties_String(Base): type: typing.Literal["string"] = "string" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + frozen=True + ) # type: ignore # Pydantic v2 else: class Config: @@ -53,7 +57,9 @@ class UnionWithBaseProperties_Foo(Base): name: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: @@ -63,5 +69,7 @@ class Config: UnionWithBaseProperties = typing.Union[ - UnionWithBaseProperties_Integer, UnionWithBaseProperties_String, UnionWithBaseProperties_Foo + UnionWithBaseProperties_Integer, + UnionWithBaseProperties_String, + UnionWithBaseProperties_Foo, ] diff --git a/seed/python-sdk/unions/no-custom-config/src/seed/types/types/union_with_discriminant.py b/seed/python-sdk/unions/no-custom-config/src/seed/types/types/union_with_discriminant.py index 0805f2a5148..3c473f96e5a 100644 --- a/seed/python-sdk/unions/no-custom-config/src/seed/types/types/union_with_discriminant.py +++ b/seed/python-sdk/unions/no-custom-config/src/seed/types/types/union_with_discriminant.py @@ -1,14 +1,12 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ...core.pydantic_utilities import UniversalBaseModel +from .foo import Foo import typing - import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 from .bar import Bar -from .foo import Foo class UnionWithDiscriminant_Foo(UniversalBaseModel): @@ -16,7 +14,9 @@ class UnionWithDiscriminant_Foo(UniversalBaseModel): type: typing.Literal["foo"] = pydantic.Field(alias="_type", default="foo") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + frozen=True + ) # type: ignore # Pydantic v2 else: class Config: @@ -29,7 +29,9 @@ class UnionWithDiscriminant_Bar(UniversalBaseModel): type: typing.Literal["bar"] = pydantic.Field(alias="_type", default="bar") if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + frozen=True + ) # type: ignore # Pydantic v2 else: class Config: @@ -37,4 +39,6 @@ class Config: smart_union = True -UnionWithDiscriminant = typing.Union[UnionWithDiscriminant_Foo, UnionWithDiscriminant_Bar] +UnionWithDiscriminant = typing.Union[ + UnionWithDiscriminant_Foo, UnionWithDiscriminant_Bar +] diff --git a/seed/python-sdk/unions/no-custom-config/src/seed/types/types/union_with_literal.py b/seed/python-sdk/unions/no-custom-config/src/seed/types/types/union_with_literal.py index 529f691119d..ed8089779e6 100644 --- a/seed/python-sdk/unions/no-custom-config/src/seed/types/types/union_with_literal.py +++ b/seed/python-sdk/unions/no-custom-config/src/seed/types/types/union_with_literal.py @@ -1,19 +1,19 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ...core.pydantic_utilities import UniversalBaseModel import typing - +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class Base(UniversalBaseModel): base: typing.Literal["base"] = "base" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: @@ -27,7 +27,9 @@ class UnionWithLiteral_Fern(Base): type: typing.Literal["fern"] = "fern" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/unions/no-custom-config/src/seed/types/types/union_with_optional_time.py b/seed/python-sdk/unions/no-custom-config/src/seed/types/types/union_with_optional_time.py index 98590c7689d..44033943c54 100644 --- a/seed/python-sdk/unions/no-custom-config/src/seed/types/types/union_with_optional_time.py +++ b/seed/python-sdk/unions/no-custom-config/src/seed/types/types/union_with_optional_time.py @@ -1,21 +1,21 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - -import datetime as dt +from ...core.pydantic_utilities import UniversalBaseModel import typing - +import datetime as dt +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class UnionWithOptionalTime_Date(UniversalBaseModel): value: typing.Optional[dt.date] = None type: typing.Literal["date"] = "date" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + frozen=True + ) # type: ignore # Pydantic v2 else: class Config: @@ -28,7 +28,9 @@ class UnionWithOptionalTime_Dateimte(UniversalBaseModel): type: typing.Literal["dateimte"] = "dateimte" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + frozen=True + ) # type: ignore # Pydantic v2 else: class Config: @@ -36,4 +38,6 @@ class Config: smart_union = True -UnionWithOptionalTime = typing.Union[UnionWithOptionalTime_Date, UnionWithOptionalTime_Dateimte] +UnionWithOptionalTime = typing.Union[ + UnionWithOptionalTime_Date, UnionWithOptionalTime_Dateimte +] diff --git a/seed/python-sdk/unions/no-custom-config/src/seed/types/types/union_with_primitive.py b/seed/python-sdk/unions/no-custom-config/src/seed/types/types/union_with_primitive.py index b2f5fee0c23..060d0a0aa64 100644 --- a/seed/python-sdk/unions/no-custom-config/src/seed/types/types/union_with_primitive.py +++ b/seed/python-sdk/unions/no-custom-config/src/seed/types/types/union_with_primitive.py @@ -1,20 +1,20 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ...core.pydantic_utilities import UniversalBaseModel import typing - +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class UnionWithPrimitive_Integer(UniversalBaseModel): value: int type: typing.Literal["integer"] = "integer" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + frozen=True + ) # type: ignore # Pydantic v2 else: class Config: @@ -27,7 +27,9 @@ class UnionWithPrimitive_String(UniversalBaseModel): type: typing.Literal["string"] = "string" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/unions/no-custom-config/src/seed/types/types/union_with_single_element.py b/seed/python-sdk/unions/no-custom-config/src/seed/types/types/union_with_single_element.py index 959171ebbc5..ed63060f85e 100644 --- a/seed/python-sdk/unions/no-custom-config/src/seed/types/types/union_with_single_element.py +++ b/seed/python-sdk/unions/no-custom-config/src/seed/types/types/union_with_single_element.py @@ -1,20 +1,20 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ...core.pydantic_utilities import UniversalBaseModel import typing - +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class UnionWithSingleElement_Foo(UniversalBaseModel): type: typing.Literal["foo"] = "foo" name: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/unions/no-custom-config/src/seed/types/types/union_with_time.py b/seed/python-sdk/unions/no-custom-config/src/seed/types/types/union_with_time.py index 65749cc6e6b..1aea298aca8 100644 --- a/seed/python-sdk/unions/no-custom-config/src/seed/types/types/union_with_time.py +++ b/seed/python-sdk/unions/no-custom-config/src/seed/types/types/union_with_time.py @@ -1,13 +1,11 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - -import datetime as dt +from ...core.pydantic_utilities import UniversalBaseModel import typing - +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel +import datetime as dt class UnionWithTime_Value(UniversalBaseModel): @@ -15,7 +13,9 @@ class UnionWithTime_Value(UniversalBaseModel): type: typing.Literal["value"] = "value" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + frozen=True + ) # type: ignore # Pydantic v2 else: class Config: @@ -28,7 +28,9 @@ class UnionWithTime_Date(UniversalBaseModel): type: typing.Literal["date"] = "date" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + frozen=True + ) # type: ignore # Pydantic v2 else: class Config: @@ -41,7 +43,9 @@ class UnionWithTime_Datetime(UniversalBaseModel): type: typing.Literal["datetime"] = "datetime" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + frozen=True + ) # type: ignore # Pydantic v2 else: class Config: @@ -49,4 +53,6 @@ class Config: smart_union = True -UnionWithTime = typing.Union[UnionWithTime_Value, UnionWithTime_Date, UnionWithTime_Datetime] +UnionWithTime = typing.Union[ + UnionWithTime_Value, UnionWithTime_Date, UnionWithTime_Datetime +] diff --git a/seed/python-sdk/unions/no-custom-config/src/seed/types/types/union_with_unknown.py b/seed/python-sdk/unions/no-custom-config/src/seed/types/types/union_with_unknown.py index c46597e8dab..9026b0b09db 100644 --- a/seed/python-sdk/unions/no-custom-config/src/seed/types/types/union_with_unknown.py +++ b/seed/python-sdk/unions/no-custom-config/src/seed/types/types/union_with_unknown.py @@ -1,20 +1,20 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ...core.pydantic_utilities import UniversalBaseModel import typing - +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class UnionWithUnknown_Foo(UniversalBaseModel): type: typing.Literal["foo"] = "foo" name: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: @@ -27,7 +27,9 @@ class UnionWithUnknown_Unknown(UniversalBaseModel): type: typing.Literal["unknown"] = "unknown" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/unions/no-custom-config/src/seed/types/types/union_without_key.py b/seed/python-sdk/unions/no-custom-config/src/seed/types/types/union_without_key.py index 434651af87c..9953d746ad7 100644 --- a/seed/python-sdk/unions/no-custom-config/src/seed/types/types/union_without_key.py +++ b/seed/python-sdk/unions/no-custom-config/src/seed/types/types/union_without_key.py @@ -1,20 +1,20 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ...core.pydantic_utilities import UniversalBaseModel import typing - +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class UnionWithoutKey_Foo(UniversalBaseModel): type: typing.Literal["foo"] = "foo" name: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: @@ -28,7 +28,9 @@ class UnionWithoutKey_Bar(UniversalBaseModel): name: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/unions/no-custom-config/src/seed/union/__init__.py b/seed/python-sdk/unions/no-custom-config/src/seed/union/__init__.py index d1d8208f67a..1f01ebd1aa5 100644 --- a/seed/python-sdk/unions/no-custom-config/src/seed/union/__init__.py +++ b/seed/python-sdk/unions/no-custom-config/src/seed/union/__init__.py @@ -2,4 +2,11 @@ from .types import Circle, GetShapeRequest, Shape, Shape_Circle, Shape_Square, Square -__all__ = ["Circle", "GetShapeRequest", "Shape", "Shape_Circle", "Shape_Square", "Square"] +__all__ = [ + "Circle", + "GetShapeRequest", + "Shape", + "Shape_Circle", + "Shape_Square", + "Square", +] diff --git a/seed/python-sdk/unions/no-custom-config/src/seed/union/client.py b/seed/python-sdk/unions/no-custom-config/src/seed/union/client.py index 15d8abca9bd..f9f656bce2f 100644 --- a/seed/python-sdk/unions/no-custom-config/src/seed/union/client.py +++ b/seed/python-sdk/unions/no-custom-config/src/seed/union/client.py @@ -1,14 +1,14 @@ # This file was auto-generated by Fern from our API Definition. import typing -from json.decoder import JSONDecodeError - -from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.jsonable_encoder import jsonable_encoder -from ..core.pydantic_utilities import parse_obj_as +from ..core.client_wrapper import SyncClientWrapper from ..core.request_options import RequestOptions from .types.shape import Shape +from ..core.jsonable_encoder import jsonable_encoder +from ..core.pydantic_utilities import parse_obj_as +from json.decoder import JSONDecodeError +from ..core.api_error import ApiError +from ..core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -18,7 +18,9 @@ class UnionClient: def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper - def get(self, id: str, *, request_options: typing.Optional[RequestOptions] = None) -> Shape: + def get( + self, id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> Shape: """ Parameters ---------- @@ -43,17 +45,23 @@ def get(self, id: str, *, request_options: typing.Optional[RequestOptions] = Non ) """ _response = self._client_wrapper.httpx_client.request( - f"{jsonable_encoder(id)}", method="GET", request_options=request_options + f"{jsonable_encoder(id)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(Shape, parse_obj_as(type_=Shape, object_=_response.json())) # type: ignore + return typing.cast( + Shape, parse_obj_as(type_=Shape, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def update(self, *, request: Shape, request_options: typing.Optional[RequestOptions] = None) -> bool: + def update( + self, *, request: Shape, request_options: typing.Optional[RequestOptions] = None + ) -> bool: """ Parameters ---------- @@ -82,11 +90,16 @@ def update(self, *, request: Shape, request_options: typing.Optional[RequestOpti ) """ _response = self._client_wrapper.httpx_client.request( - method="PATCH", json=request, request_options=request_options, omit=OMIT + method="PATCH", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -97,7 +110,9 @@ class AsyncUnionClient: def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper - async def get(self, id: str, *, request_options: typing.Optional[RequestOptions] = None) -> Shape: + async def get( + self, id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> Shape: """ Parameters ---------- @@ -130,17 +145,23 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - f"{jsonable_encoder(id)}", method="GET", request_options=request_options + f"{jsonable_encoder(id)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(Shape, parse_obj_as(type_=Shape, object_=_response.json())) # type: ignore + return typing.cast( + Shape, parse_obj_as(type_=Shape, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - async def update(self, *, request: Shape, request_options: typing.Optional[RequestOptions] = None) -> bool: + async def update( + self, *, request: Shape, request_options: typing.Optional[RequestOptions] = None + ) -> bool: """ Parameters ---------- @@ -177,11 +198,16 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - method="PATCH", json=request, request_options=request_options, omit=OMIT + method="PATCH", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/unions/no-custom-config/src/seed/union/types/__init__.py b/seed/python-sdk/unions/no-custom-config/src/seed/union/types/__init__.py index 37b403a91b5..4664e28cf75 100644 --- a/seed/python-sdk/unions/no-custom-config/src/seed/union/types/__init__.py +++ b/seed/python-sdk/unions/no-custom-config/src/seed/union/types/__init__.py @@ -5,4 +5,11 @@ from .shape import Shape, Shape_Circle, Shape_Square from .square import Square -__all__ = ["Circle", "GetShapeRequest", "Shape", "Shape_Circle", "Shape_Square", "Square"] +__all__ = [ + "Circle", + "GetShapeRequest", + "Shape", + "Shape_Circle", + "Shape_Square", + "Square", +] diff --git a/seed/python-sdk/unions/no-custom-config/src/seed/union/types/circle.py b/seed/python-sdk/unions/no-custom-config/src/seed/union/types/circle.py index 731e80d192e..722e1e9d2e2 100644 --- a/seed/python-sdk/unions/no-custom-config/src/seed/union/types/circle.py +++ b/seed/python-sdk/unions/no-custom-config/src/seed/union/types/circle.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class Circle(UniversalBaseModel): radius: float if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/unions/no-custom-config/src/seed/union/types/get_shape_request.py b/seed/python-sdk/unions/no-custom-config/src/seed/union/types/get_shape_request.py index 7ac528833a5..94ef3c3ae3e 100644 --- a/seed/python-sdk/unions/no-custom-config/src/seed/union/types/get_shape_request.py +++ b/seed/python-sdk/unions/no-custom-config/src/seed/union/types/get_shape_request.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class GetShapeRequest(UniversalBaseModel): id: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/unions/no-custom-config/src/seed/union/types/shape.py b/seed/python-sdk/unions/no-custom-config/src/seed/union/types/shape.py index ad9a8872fed..4018b4c8702 100644 --- a/seed/python-sdk/unions/no-custom-config/src/seed/union/types/shape.py +++ b/seed/python-sdk/unions/no-custom-config/src/seed/union/types/shape.py @@ -1,19 +1,19 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class Base(UniversalBaseModel): id: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: @@ -27,7 +27,9 @@ class Shape_Circle(Base): radius: float if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: @@ -41,7 +43,9 @@ class Shape_Square(Base): length: float if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/unions/no-custom-config/src/seed/union/types/square.py b/seed/python-sdk/unions/no-custom-config/src/seed/union/types/square.py index 6494abdd14d..f7368d88e79 100644 --- a/seed/python-sdk/unions/no-custom-config/src/seed/union/types/square.py +++ b/seed/python-sdk/unions/no-custom-config/src/seed/union/types/square.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class Square(UniversalBaseModel): length: float if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/unions/no-custom-config/src/seed/version.py b/seed/python-sdk/unions/no-custom-config/src/seed/version.py index 123bebe735d..7b884a244da 100644 --- a/seed/python-sdk/unions/no-custom-config/src/seed/version.py +++ b/seed/python-sdk/unions/no-custom-config/src/seed/version.py @@ -1,4 +1,3 @@ - from importlib import metadata __version__ = metadata.version("fern_unions") diff --git a/seed/python-sdk/unions/no-custom-config/tests/conftest.py b/seed/python-sdk/unions/no-custom-config/tests/conftest.py index 7c6e0d163e9..c564db371c3 100644 --- a/seed/python-sdk/unions/no-custom-config/tests/conftest.py +++ b/seed/python-sdk/unions/no-custom-config/tests/conftest.py @@ -1,9 +1,9 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedUnions import os - import pytest -from seed import AsyncSeedUnions, SeedUnions +from seed import AsyncSeedUnions @pytest.fixture diff --git a/seed/python-sdk/unions/no-custom-config/tests/custom/test_client.py b/seed/python-sdk/unions/no-custom-config/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/python-sdk/unions/no-custom-config/tests/custom/test_client.py +++ b/seed/python-sdk/unions/no-custom-config/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/python-sdk/unions/no-custom-config/tests/test_union.py b/seed/python-sdk/unions/no-custom-config/tests/test_union.py index b5a8cf50108..8855e52bf1e 100644 --- a/seed/python-sdk/unions/no-custom-config/tests/test_union.py +++ b/seed/python-sdk/unions/no-custom-config/tests/test_union.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedUnions +from seed import AsyncSeedUnions import typing - -from seed import AsyncSeedUnions, SeedUnions -from seed.union import Shape_Circle - from .utilities import validate_response +from seed.union import Shape_Circle async def test_get(client: SeedUnions, async_client: AsyncSeedUnions) -> None: @@ -24,5 +23,7 @@ async def test_update(client: SeedUnions, async_client: AsyncSeedUnions) -> None response = client.union.update(request=Shape_Circle(id="string", radius=1.1)) validate_response(response, expected_response, expected_types) - async_response = await async_client.union.update(request=Shape_Circle(id="string", radius=1.1)) + async_response = await async_client.union.update( + request=Shape_Circle(id="string", radius=1.1) + ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/unions/no-custom-config/tests/utilities.py b/seed/python-sdk/unions/no-custom-config/tests/utilities.py index 13da208eb3a..e8f4472564c 100644 --- a/seed/python-sdk/unions/no-custom-config/tests/utilities.py +++ b/seed/python-sdk/unions/no-custom-config/tests/utilities.py @@ -3,11 +3,14 @@ import typing import uuid -import pydantic from dateutil import parser +import pydantic + -def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> typing.Any: +def cast_field( + json_expectation: typing.Any, type_expectation: typing.Any +) -> typing.Any: # Cast these specific types which come through as string and expect our # models to cast to the correct type. if type_expectation == "uuid": @@ -25,7 +28,9 @@ def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> ty return json_expectation -def validate_field(response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any) -> None: +def validate_field( + response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectation == "no_validate": return @@ -44,7 +49,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(entry_expectation, dict): is_container_of_complex_type = True validate_response( - response=response[idx], json_expectation=ex, type_expectations=entry_expectation + response=response[idx], + json_expectation=ex, + type_expectations=entry_expectation, ) else: cast_json_expectation.append(cast_field(ex, entry_expectation)) @@ -56,7 +63,10 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # if any of the values of the set have a type_expectation of a dict, we're assuming it's a pydantic # model and keeping it a list. if container_expectation != "set" or not any( - map(lambda value: isinstance(value, dict), list(contents_expectation.values())) + map( + lambda value: isinstance(value, dict), + list(contents_expectation.values()), + ) ): json_expectation = cast_field(json_expectation, container_expectation) elif isinstance(type_expectation, tuple): @@ -65,9 +75,15 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(contents_expectation, dict): json_expectation = { cast_field( - key, contents_expectation.get(idx)[0] if contents_expectation.get(idx) is not None else None # type: ignore + key, + contents_expectation.get(idx)[0] + if contents_expectation.get(idx) is not None + else None, # type: ignore ): cast_field( - value, contents_expectation.get(idx)[1] if contents_expectation.get(idx) is not None else None # type: ignore + value, + contents_expectation.get(idx)[1] + if contents_expectation.get(idx) is not None + else None, # type: ignore ) for idx, (key, value) in enumerate(json_expectation.items()) } @@ -86,7 +102,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # Arg type_expectations is a deeply nested structure that matches the response, but with the values replaced with the expected types -def validate_response(response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any) -> None: +def validate_response( + response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectations == "no_validate": return @@ -96,11 +114,17 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e and not isinstance(response, dict) and not issubclass(type(response), pydantic.BaseModel) ): - validate_field(response=response, json_expectation=json_expectation, type_expectation=type_expectations) + validate_field( + response=response, + json_expectation=json_expectation, + type_expectation=type_expectations, + ) return if isinstance(response, list): - assert len(response) == len(json_expectation), "Length mismatch, expected: {0}, Actual: {1}".format( + assert len(response) == len( + json_expectation + ), "Length mismatch, expected: {0}, Actual: {1}".format( len(response), len(json_expectation) ) content_expectation = type_expectations @@ -108,7 +132,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e content_expectation = type_expectations[1] for idx, item in enumerate(response): validate_response( - response=item, json_expectation=json_expectation[idx], type_expectations=content_expectation[idx] + response=item, + json_expectation=json_expectation[idx], + type_expectations=content_expectation[idx], ) else: response_json = response @@ -116,7 +142,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e response_json = response.dict(by_alias=True) for key, value in json_expectation.items(): - assert key in response_json, "Field {0} not found within the response object: {1}".format( + assert ( + key in response_json + ), "Field {0} not found within the response object: {1}".format( key, response_json ) @@ -128,11 +156,19 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e # Otherwise, we're just validating a single field that's a pydantic model. if isinstance(value, dict) and not isinstance(type_expectation, tuple): validate_response( - response=response_json[key], json_expectation=value, type_expectations=type_expectation + response=response_json[key], + json_expectation=value, + type_expectations=type_expectation, ) else: - validate_field(response=response_json[key], json_expectation=value, type_expectation=type_expectation) + validate_field( + response=response_json[key], + json_expectation=value, + type_expectation=type_expectation, + ) # Ensure there are no additional fields here either del response_json[key] - assert len(response_json) == 0, "Additional fields found, expected None: {0}".format(response_json) + assert ( + len(response_json) == 0 + ), "Additional fields found, expected None: {0}".format(response_json) diff --git a/seed/python-sdk/unions/no-custom-config/tests/utils/assets/models/__init__.py b/seed/python-sdk/unions/no-custom-config/tests/utils/assets/models/__init__.py index 2cf01263529..3a1c852e71e 100644 --- a/seed/python-sdk/unions/no-custom-config/tests/utils/assets/models/__init__.py +++ b/seed/python-sdk/unions/no-custom-config/tests/utils/assets/models/__init__.py @@ -5,7 +5,7 @@ from .circle import CircleParams from .object_with_defaults import ObjectWithDefaultsParams from .object_with_optional_field import ObjectWithOptionalFieldParams -from .shape import Shape_CircleParams, Shape_SquareParams, ShapeParams +from .shape import ShapeParams, Shape_CircleParams, Shape_SquareParams from .square import SquareParams from .undiscriminated_shape import UndiscriminatedShapeParams diff --git a/seed/python-sdk/unions/no-custom-config/tests/utils/assets/models/circle.py b/seed/python-sdk/unions/no-custom-config/tests/utils/assets/models/circle.py index af7a1bf8a8e..253f12d38b3 100644 --- a/seed/python-sdk/unions/no-custom-config/tests/utils/assets/models/circle.py +++ b/seed/python-sdk/unions/no-custom-config/tests/utils/assets/models/circle.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class CircleParams(typing_extensions.TypedDict): - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] diff --git a/seed/python-sdk/unions/no-custom-config/tests/utils/assets/models/object_with_optional_field.py b/seed/python-sdk/unions/no-custom-config/tests/utils/assets/models/object_with_optional_field.py index 3ad93d5f305..ebe7dc80547 100644 --- a/seed/python-sdk/unions/no-custom-config/tests/utils/assets/models/object_with_optional_field.py +++ b/seed/python-sdk/unions/no-custom-config/tests/utils/assets/models/object_with_optional_field.py @@ -7,8 +7,8 @@ import uuid import typing_extensions -from seed.core.serialization import FieldMetadata +from seed.core.serialization import FieldMetadata from .color import Color from .shape import ShapeParams from .undiscriminated_shape import UndiscriminatedShapeParams @@ -18,16 +18,30 @@ class ObjectWithOptionalFieldParams(typing_extensions.TypedDict): literal: typing.Literal["lit_one"] string: typing_extensions.NotRequired[str] integer: typing_extensions.NotRequired[int] - long_: typing_extensions.NotRequired[typing_extensions.Annotated[int, FieldMetadata(alias="long")]] + long_: typing_extensions.NotRequired[ + typing_extensions.Annotated[int, FieldMetadata(alias="long")] + ] double: typing_extensions.NotRequired[float] - bool_: typing_extensions.NotRequired[typing_extensions.Annotated[bool, FieldMetadata(alias="bool")]] + bool_: typing_extensions.NotRequired[ + typing_extensions.Annotated[bool, FieldMetadata(alias="bool")] + ] datetime: typing_extensions.NotRequired[dt.datetime] date: typing_extensions.NotRequired[dt.date] - uuid_: typing_extensions.NotRequired[typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")]] - base_64: typing_extensions.NotRequired[typing_extensions.Annotated[str, FieldMetadata(alias="base64")]] - list_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")]] - set_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")]] - map_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")]] + uuid_: typing_extensions.NotRequired[ + typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")] + ] + base_64: typing_extensions.NotRequired[ + typing_extensions.Annotated[str, FieldMetadata(alias="base64")] + ] + list_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")] + ] + set_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")] + ] + map_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")] + ] enum: typing_extensions.NotRequired[Color] union: typing_extensions.NotRequired[ShapeParams] second_union: typing_extensions.NotRequired[ShapeParams] diff --git a/seed/python-sdk/unions/no-custom-config/tests/utils/assets/models/shape.py b/seed/python-sdk/unions/no-custom-config/tests/utils/assets/models/shape.py index 2c33c877951..816ffc51bdc 100644 --- a/seed/python-sdk/unions/no-custom-config/tests/utils/assets/models/shape.py +++ b/seed/python-sdk/unions/no-custom-config/tests/utils/assets/models/shape.py @@ -7,6 +7,7 @@ import typing import typing_extensions + from seed.core.serialization import FieldMetadata @@ -15,13 +16,21 @@ class Base(typing_extensions.TypedDict): class Shape_CircleParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["circle"], FieldMetadata(alias="shapeType")] - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["circle"], FieldMetadata(alias="shapeType") + ] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] class Shape_SquareParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["square"], FieldMetadata(alias="shapeType")] - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["square"], FieldMetadata(alias="shapeType") + ] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] ShapeParams = typing.Union[Shape_CircleParams, Shape_SquareParams] diff --git a/seed/python-sdk/unions/no-custom-config/tests/utils/assets/models/square.py b/seed/python-sdk/unions/no-custom-config/tests/utils/assets/models/square.py index b9b7dd319bc..bcf08a723c5 100644 --- a/seed/python-sdk/unions/no-custom-config/tests/utils/assets/models/square.py +++ b/seed/python-sdk/unions/no-custom-config/tests/utils/assets/models/square.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class SquareParams(typing_extensions.TypedDict): - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] diff --git a/seed/python-sdk/unions/no-custom-config/tests/utils/test_http_client.py b/seed/python-sdk/unions/no-custom-config/tests/utils/test_http_client.py index edd11ca7afb..f5a874a75f3 100644 --- a/seed/python-sdk/unions/no-custom-config/tests/utils/test_http_client.py +++ b/seed/python-sdk/unions/no-custom-config/tests/utils/test_http_client.py @@ -9,12 +9,17 @@ def get_request_options() -> RequestOptions: def test_get_json_request_body() -> None: - json_body, data_body = get_request_body(json={"hello": "world"}, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json={"hello": "world"}, data=None, request_options=None, omit=None + ) assert json_body == {"hello": "world"} assert data_body is None json_body_extras, data_body_extras = get_request_body( - json={"goodbye": "world"}, data=None, request_options=get_request_options(), omit=None + json={"goodbye": "world"}, + data=None, + request_options=get_request_options(), + omit=None, ) assert json_body_extras == {"goodbye": "world", "see you": "later"} @@ -22,12 +27,17 @@ def test_get_json_request_body() -> None: def test_get_files_request_body() -> None: - json_body, data_body = get_request_body(json=None, data={"hello": "world"}, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data={"hello": "world"}, request_options=None, omit=None + ) assert data_body == {"hello": "world"} assert json_body is None json_body_extras, data_body_extras = get_request_body( - json=None, data={"goodbye": "world"}, request_options=get_request_options(), omit=None + json=None, + data={"goodbye": "world"}, + request_options=get_request_options(), + omit=None, ) assert data_body_extras == {"goodbye": "world", "see you": "later"} @@ -35,7 +45,9 @@ def test_get_files_request_body() -> None: def test_get_none_request_body() -> None: - json_body, data_body = get_request_body(json=None, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data=None, request_options=None, omit=None + ) assert data_body is None assert json_body is None diff --git a/seed/python-sdk/unions/no-custom-config/tests/utils/test_query_encoding.py b/seed/python-sdk/unions/no-custom-config/tests/utils/test_query_encoding.py index 247e1551b46..fbc8f402167 100644 --- a/seed/python-sdk/unions/no-custom-config/tests/utils/test_query_encoding.py +++ b/seed/python-sdk/unions/no-custom-config/tests/utils/test_query_encoding.py @@ -4,9 +4,15 @@ def test_query_encoding() -> None: - assert encode_query({"hello world": "hello world"}) == {"hello world": "hello world"} - assert encode_query({"hello_world": {"hello": "world"}}) == {"hello_world[hello]": "world"} - assert encode_query({"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"}) == { + assert encode_query({"hello world": "hello world"}) == { + "hello world": "hello world" + } + assert encode_query({"hello_world": {"hello": "world"}}) == { + "hello_world[hello]": "world" + } + assert encode_query( + {"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"} + ) == { "hello_world[hello][world]": "today", "hello_world[test]": "this", "hi": "there", diff --git a/seed/python-sdk/unions/no-custom-config/tests/utils/test_serialization.py b/seed/python-sdk/unions/no-custom-config/tests/utils/test_serialization.py index 58b1ed66e6d..5ca956916dd 100644 --- a/seed/python-sdk/unions/no-custom-config/tests/utils/test_serialization.py +++ b/seed/python-sdk/unions/no-custom-config/tests/utils/test_serialization.py @@ -1,10 +1,12 @@ # This file was auto-generated by Fern from our API Definition. -from typing import Any, List +from typing import List, Any -from seed.core.serialization import convert_and_respect_annotation_metadata +from seed.core.serialization import ( + convert_and_respect_annotation_metadata, +) +from .assets.models import ShapeParams, ObjectWithOptionalFieldParams -from .assets.models import ObjectWithOptionalFieldParams, ShapeParams UNION_TEST: ShapeParams = {"radius_measurement": 1.0, "shape_type": "circle", "id": "1"} UNION_TEST_CONVERTED = {"shapeType": "circle", "radiusMeasurement": 1.0, "id": "1"} @@ -18,20 +20,54 @@ def test_convert_and_respect_annotation_metadata() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) - assert converted == {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"} + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) + assert converted == { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + } def test_convert_and_respect_annotation_metadata_in_list() -> None: data: List[ObjectWithOptionalFieldParams] = [ - {"string": "string", "long_": 12345, "bool_": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long_": 67890, "list_": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long_": 12345, + "bool_": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long_": 67890, + "list_": [], + "literal": "lit_one", + "any": "any", + }, ] - converted = convert_and_respect_annotation_metadata(object_=data, annotation=List[ObjectWithOptionalFieldParams]) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=List[ObjectWithOptionalFieldParams] + ) assert converted == [ - {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long": 67890, "list": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long": 67890, + "list": [], + "literal": "lit_one", + "any": "any", + }, ] @@ -43,7 +79,9 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) assert converted == { "string": "string", @@ -55,12 +93,16 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: def test_convert_and_respect_annotation_metadata_in_union() -> None: - converted = convert_and_respect_annotation_metadata(object_=UNION_TEST, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=UNION_TEST, annotation=ShapeParams + ) assert converted == UNION_TEST_CONVERTED def test_convert_and_respect_annotation_metadata_with_empty_object() -> None: data: Any = {} - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ShapeParams + ) assert converted == data diff --git a/seed/python-sdk/unions/tests/custom/test_client.py b/seed/python-sdk/unions/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/python-sdk/unions/tests/custom/test_client.py +++ b/seed/python-sdk/unions/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/python-sdk/unions/tests/test_union.py b/seed/python-sdk/unions/tests/test_union.py index c1a6a71a56c..dfdb5c7335e 100644 --- a/seed/python-sdk/unions/tests/test_union.py +++ b/seed/python-sdk/unions/tests/test_union.py @@ -24,5 +24,7 @@ async def test_update(client: SeedUnions, async_client: AsyncSeedUnions) -> None response = client.union.update(request=Shape_Circle(id="string", radius=1.1)) validate_response(response, expected_response, expected_types) - async_response = await async_client.union.update(request=Shape_Circle(id="string", radius=1.1)) + async_response = await async_client.union.update( + request=Shape_Circle(id="string", radius=1.1) + ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/unions/tests/utilities.py b/seed/python-sdk/unions/tests/utilities.py index 402ee790bb8..27ae3c99b93 100644 --- a/seed/python-sdk/unions/tests/utilities.py +++ b/seed/python-sdk/unions/tests/utilities.py @@ -14,7 +14,9 @@ import pydantic as pydantic_v1 # type: ignore # nopycln: import -def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> typing.Any: +def cast_field( + json_expectation: typing.Any, type_expectation: typing.Any +) -> typing.Any: # Cast these specific types which come through as string and expect our # models to cast to the correct type. if type_expectation == "uuid": @@ -32,7 +34,9 @@ def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> ty return json_expectation -def validate_field(response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any) -> None: +def validate_field( + response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectation == "no_validate": return @@ -51,7 +55,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(entry_expectation, dict): is_container_of_complex_type = True validate_response( - response=response[idx], json_expectation=ex, type_expectations=entry_expectation + response=response[idx], + json_expectation=ex, + type_expectations=entry_expectation, ) else: cast_json_expectation.append(cast_field(ex, entry_expectation)) @@ -63,7 +69,10 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # if any of the values of the set have a type_expectation of a dict, we're assuming it's a pydantic # model and keeping it a list. if container_expectation != "set" or not any( - map(lambda value: isinstance(value, dict), list(contents_expectation.values())) + map( + lambda value: isinstance(value, dict), + list(contents_expectation.values()), + ) ): json_expectation = cast_field(json_expectation, container_expectation) elif isinstance(type_expectation, tuple): @@ -72,9 +81,15 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(contents_expectation, dict): json_expectation = { cast_field( - key, contents_expectation.get(idx)[0] if contents_expectation.get(idx) is not None else None # type: ignore + key, + contents_expectation.get(idx)[0] + if contents_expectation.get(idx) is not None + else None, # type: ignore ): cast_field( - value, contents_expectation.get(idx)[1] if contents_expectation.get(idx) is not None else None # type: ignore + value, + contents_expectation.get(idx)[1] + if contents_expectation.get(idx) is not None + else None, # type: ignore ) for idx, (key, value) in enumerate(json_expectation.items()) } @@ -85,19 +100,29 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # When dealing with containers of models, etc. we're validating them implicitly, so no need to check the resultant list if not is_container_of_complex_type: - assert json_expectation == response, "Primitives found, expected: {0}, Actual: {1}".format( + assert ( + json_expectation == response + ), "Primitives found, expected: {0}, Actual: {1}".format( json_expectation, response ) # Arg type_expectations is a deeply nested structure that matches the response, but with the values replaced with the expected types -def validate_response(response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any) -> None: +def validate_response( + response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectations == "no_validate": return - if not isinstance(response, dict) and not issubclass(type(response), pydantic_v1.BaseModel): - validate_field(response=response, json_expectation=json_expectation, type_expectation=type_expectations) + if not isinstance(response, dict) and not issubclass( + type(response), pydantic_v1.BaseModel + ): + validate_field( + response=response, + json_expectation=json_expectation, + type_expectation=type_expectations, + ) return response_json = response @@ -105,7 +130,11 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e response_json = response.dict(by_alias=True) for key, value in json_expectation.items(): - assert key in response_json, "Field {0} not found within the response object: {1}".format(key, response_json) + assert ( + key in response_json + ), "Field {0} not found within the response object: {1}".format( + key, response_json + ) type_expectation = None if type_expectations is not None and isinstance(type_expectations, dict): @@ -114,10 +143,20 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e # If your type_expectation is a tuple then you have a container field, process it as such # Otherwise, we're just validating a single field that's a pydantic model. if isinstance(value, dict) and not isinstance(type_expectation, tuple): - validate_response(response=response_json[key], json_expectation=value, type_expectations=type_expectation) + validate_response( + response=response_json[key], + json_expectation=value, + type_expectations=type_expectation, + ) else: - validate_field(response=response_json[key], json_expectation=value, type_expectation=type_expectation) + validate_field( + response=response_json[key], + json_expectation=value, + type_expectation=type_expectation, + ) # Ensure there are no additional fields here either del response_json[key] - assert len(response_json) == 0, "Additional fields found, expected None: {0}".format(response_json) + assert ( + len(response_json) == 0 + ), "Additional fields found, expected None: {0}".format(response_json) diff --git a/seed/python-sdk/unions/union-utils/pyproject.toml b/seed/python-sdk/unions/union-utils/pyproject.toml index 94ea983b951..74156e62e47 100644 --- a/seed/python-sdk/unions/union-utils/pyproject.toml +++ b/seed/python-sdk/unions/union-utils/pyproject.toml @@ -43,6 +43,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/python-sdk/unions/union-utils/src/seed/client.py b/seed/python-sdk/unions/union-utils/src/seed/client.py index 58cb9526d55..7f926f5e347 100644 --- a/seed/python-sdk/unions/union-utils/src/seed/client.py +++ b/seed/python-sdk/unions/union-utils/src/seed/client.py @@ -1,11 +1,11 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from .union.client import AsyncUnionClient, UnionClient +from .core.client_wrapper import SyncClientWrapper +from .union.client import UnionClient +from .core.client_wrapper import AsyncClientWrapper +from .union.client import AsyncUnionClient class SeedUnions: @@ -41,14 +41,18 @@ def __init__( base_url: str, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.Client] = None + httpx_client: typing.Optional[httpx.Client] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = SyncClientWrapper( base_url=base_url, httpx_client=httpx_client if httpx_client is not None - else httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.Client( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.Client(timeout=_defaulted_timeout), timeout=_defaulted_timeout, @@ -89,14 +93,18 @@ def __init__( base_url: str, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.AsyncClient] = None + httpx_client: typing.Optional[httpx.AsyncClient] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = AsyncClientWrapper( base_url=base_url, httpx_client=httpx_client if httpx_client is not None - else httpx.AsyncClient(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.AsyncClient( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.AsyncClient(timeout=_defaulted_timeout), timeout=_defaulted_timeout, diff --git a/seed/python-sdk/unions/union-utils/src/seed/core/api_error.py b/seed/python-sdk/unions/union-utils/src/seed/core/api_error.py index 2e9fc5431cd..da734b58068 100644 --- a/seed/python-sdk/unions/union-utils/src/seed/core/api_error.py +++ b/seed/python-sdk/unions/union-utils/src/seed/core/api_error.py @@ -7,7 +7,9 @@ class ApiError(Exception): status_code: typing.Optional[int] body: typing.Any - def __init__(self, *, status_code: typing.Optional[int] = None, body: typing.Any = None): + def __init__( + self, *, status_code: typing.Optional[int] = None, body: typing.Any = None + ): self.status_code = status_code self.body = body diff --git a/seed/python-sdk/unions/union-utils/src/seed/core/client_wrapper.py b/seed/python-sdk/unions/union-utils/src/seed/core/client_wrapper.py index a12ded4d812..951aaa210f2 100644 --- a/seed/python-sdk/unions/union-utils/src/seed/core/client_wrapper.py +++ b/seed/python-sdk/unions/union-utils/src/seed/core/client_wrapper.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .http_client import AsyncHttpClient, HttpClient +from .http_client import HttpClient +from .http_client import AsyncHttpClient class BaseClientWrapper: @@ -28,7 +27,13 @@ def get_timeout(self) -> typing.Optional[float]: class SyncClientWrapper(BaseClientWrapper): - def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, httpx_client: httpx.Client): + def __init__( + self, + *, + base_url: str, + timeout: typing.Optional[float] = None, + httpx_client: httpx.Client, + ): super().__init__(base_url=base_url, timeout=timeout) self.httpx_client = HttpClient( httpx_client=httpx_client, @@ -39,7 +44,13 @@ def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, htt class AsyncClientWrapper(BaseClientWrapper): - def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, httpx_client: httpx.AsyncClient): + def __init__( + self, + *, + base_url: str, + timeout: typing.Optional[float] = None, + httpx_client: httpx.AsyncClient, + ): super().__init__(base_url=base_url, timeout=timeout) self.httpx_client = AsyncHttpClient( httpx_client=httpx_client, diff --git a/seed/python-sdk/unions/union-utils/src/seed/core/datetime_utils.py b/seed/python-sdk/unions/union-utils/src/seed/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/python-sdk/unions/union-utils/src/seed/core/datetime_utils.py +++ b/seed/python-sdk/unions/union-utils/src/seed/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/python-sdk/unions/union-utils/src/seed/core/file.py b/seed/python-sdk/unions/union-utils/src/seed/core/file.py index cb0d40bbbf3..6e0f92bfcb1 100644 --- a/seed/python-sdk/unions/union-utils/src/seed/core/file.py +++ b/seed/python-sdk/unions/union-utils/src/seed/core/file.py @@ -13,12 +13,17 @@ # (filename, file (or bytes), content_type) typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str]], # (filename, file (or bytes), content_type, headers) - typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str], typing.Mapping[str, str]], + typing.Tuple[ + typing.Optional[str], + FileContent, + typing.Optional[str], + typing.Mapping[str, str], + ], ] def convert_file_dict_to_httpx_tuples( - d: typing.Dict[str, typing.Union[File, typing.List[File]]] + d: typing.Dict[str, typing.Union[File, typing.List[File]]], ) -> typing.List[typing.Tuple[str, File]]: """ The format we use is a list of tuples, where the first element is the diff --git a/seed/python-sdk/unions/union-utils/src/seed/core/http_client.py b/seed/python-sdk/unions/union-utils/src/seed/core/http_client.py index 9333d8a7f15..091f71bc185 100644 --- a/seed/python-sdk/unions/union-utils/src/seed/core/http_client.py +++ b/seed/python-sdk/unions/union-utils/src/seed/core/http_client.py @@ -77,7 +77,9 @@ def _retry_timeout(response: httpx.Response, retries: int) -> float: return retry_after # Apply exponential backoff, capped at MAX_RETRY_DELAY_SECONDS. - retry_delay = min(INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS) + retry_delay = min( + INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS + ) # Add a randomness / jitter to the retry delay to avoid overwhelming the server with retries. timeout = retry_delay * (1 - 0.25 * random()) @@ -90,7 +92,8 @@ def _should_retry(response: httpx.Response) -> bool: def remove_omit_from_dict( - original: typing.Dict[str, typing.Optional[typing.Any]], omit: typing.Optional[typing.Any] + original: typing.Dict[str, typing.Optional[typing.Any]], + omit: typing.Optional[typing.Any], ) -> typing.Dict[str, typing.Any]: if omit is None: return original @@ -108,7 +111,8 @@ def maybe_filter_request_body( ) -> typing.Optional[typing.Any]: if data is None: return ( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else None ) @@ -118,7 +122,8 @@ def maybe_filter_request_body( data_content = { **(jsonable_encoder(remove_omit_from_dict(data, omit))), # type: ignore **( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else {} ), @@ -162,7 +167,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url def request( @@ -174,8 +181,12 @@ def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -184,11 +195,14 @@ def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) response = self.httpx_client.request( method=method, @@ -198,7 +212,11 @@ def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -209,7 +227,10 @@ def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -222,11 +243,15 @@ def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: time.sleep(_retry_timeout(response=response, retries=retries)) @@ -256,8 +281,12 @@ def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -266,11 +295,14 @@ def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) with self.httpx_client.stream( method=method, @@ -280,7 +312,11 @@ def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -291,7 +327,9 @@ def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -304,7 +342,9 @@ def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream @@ -327,7 +367,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url async def request( @@ -339,8 +381,12 @@ async def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -349,11 +395,14 @@ async def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) # Add the input to each of these and do None-safety checks response = await self.httpx_client.request( @@ -364,7 +413,11 @@ async def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -375,7 +428,10 @@ async def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -388,11 +444,15 @@ async def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: await asyncio.sleep(_retry_timeout(response=response, retries=retries)) @@ -421,8 +481,12 @@ async def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -431,11 +495,14 @@ async def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) async with self.httpx_client.stream( method=method, @@ -445,7 +512,11 @@ async def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -456,7 +527,9 @@ async def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -469,7 +542,9 @@ async def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream diff --git a/seed/python-sdk/unions/union-utils/src/seed/core/jsonable_encoder.py b/seed/python-sdk/unions/union-utils/src/seed/core/jsonable_encoder.py index d3fd328fd41..12a8b52fc22 100644 --- a/seed/python-sdk/unions/union-utils/src/seed/core/jsonable_encoder.py +++ b/seed/python-sdk/unions/union-utils/src/seed/core/jsonable_encoder.py @@ -19,13 +19,19 @@ import pydantic from .datetime_utils import serialize_datetime -from .pydantic_utilities import IS_PYDANTIC_V2, encode_by_type, to_jsonable_with_fallback +from .pydantic_utilities import ( + IS_PYDANTIC_V2, + encode_by_type, + to_jsonable_with_fallback, +) SetIntStr = Set[Union[int, str]] DictIntStrAny = Dict[Union[int, str], Any] -def jsonable_encoder(obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None) -> Any: +def jsonable_encoder( + obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None +) -> Any: custom_encoder = custom_encoder or {} if custom_encoder: if type(obj) in custom_encoder: diff --git a/seed/python-sdk/unions/union-utils/src/seed/core/pydantic_utilities.py b/seed/python-sdk/unions/union-utils/src/seed/core/pydantic_utilities.py index 170a563d6eb..c63935c32a2 100644 --- a/seed/python-sdk/unions/union-utils/src/seed/core/pydantic_utilities.py +++ b/seed/python-sdk/unions/union-utils/src/seed/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) # type: ignore # Pydantic v1 diff --git a/seed/python-sdk/unions/union-utils/src/seed/core/query_encoder.py b/seed/python-sdk/unions/union-utils/src/seed/core/query_encoder.py index 24076d72ee9..7cb98f52cd7 100644 --- a/seed/python-sdk/unions/union-utils/src/seed/core/query_encoder.py +++ b/seed/python-sdk/unions/union-utils/src/seed/core/query_encoder.py @@ -7,7 +7,9 @@ # Flattens dicts to be of the form {"key[subkey][subkey2]": value} where value is not a dict -def traverse_query_dict(dict_flat: Dict[str, Any], key_prefix: Optional[str] = None) -> Dict[str, Any]: +def traverse_query_dict( + dict_flat: Dict[str, Any], key_prefix: Optional[str] = None +) -> Dict[str, Any]: result = {} for k, v in dict_flat.items(): key = f"{key_prefix}[{k}]" if key_prefix is not None else k @@ -30,4 +32,8 @@ def single_query_encoder(query_key: str, query_value: Any) -> Dict[str, Any]: def encode_query(query: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: - return dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) if query is not None else None + return ( + dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) + if query is not None + else None + ) diff --git a/seed/python-sdk/unions/union-utils/src/seed/core/serialization.py b/seed/python-sdk/unions/union-utils/src/seed/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/python-sdk/unions/union-utils/src/seed/core/serialization.py +++ b/seed/python-sdk/unions/union-utils/src/seed/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/python-sdk/unions/union-utils/src/seed/types/types/bar.py b/seed/python-sdk/unions/union-utils/src/seed/types/types/bar.py index 34796fe719f..71aa92ba94d 100644 --- a/seed/python-sdk/unions/union-utils/src/seed/types/types/bar.py +++ b/seed/python-sdk/unions/union-utils/src/seed/types/types/bar.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class Bar(UniversalBaseModel): name: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/unions/union-utils/src/seed/types/types/foo.py b/seed/python-sdk/unions/union-utils/src/seed/types/types/foo.py index 9da151d9182..882153c67b4 100644 --- a/seed/python-sdk/unions/union-utils/src/seed/types/types/foo.py +++ b/seed/python-sdk/unions/union-utils/src/seed/types/types/foo.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class Foo(UniversalBaseModel): name: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/unions/union-utils/src/seed/types/types/union.py b/seed/python-sdk/unions/union-utils/src/seed/types/types/union.py index 9c54c38efa9..3ad3fa12770 100644 --- a/seed/python-sdk/unions/union-utils/src/seed/types/types/union.py +++ b/seed/python-sdk/unions/union-utils/src/seed/types/types/union.py @@ -1,15 +1,15 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from .foo import Foo as types_types_foo_Foo +from ...core.pydantic_utilities import IS_PYDANTIC_V2 +from .bar import Bar as types_types_bar_Bar +from ...core.pydantic_utilities import UniversalRootModel import typing - -import pydantic import typing_extensions - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel, UniversalRootModel, update_forward_refs -from .bar import Bar as types_types_bar_Bar -from .foo import Foo as types_types_foo_Foo +import pydantic +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import update_forward_refs T_Result = typing.TypeVar("T_Result") @@ -36,11 +36,12 @@ class Union(UniversalRootModel): factory: typing.ClassVar[_Factory] = _Factory() if IS_PYDANTIC_V2: - root: typing_extensions.Annotated[typing.Union[_Union.Foo, _Union.Bar], pydantic.Field(discriminator="type")] + root: typing_extensions.Annotated[ + typing.Union[_Union.Foo, _Union.Bar], pydantic.Field(discriminator="type") + ] def get_as_union(self) -> typing.Union[_Union.Foo, _Union.Bar]: return self.root - else: __root__: typing_extensions.Annotated[ typing.Union[_Union.Foo, _Union.Bar], pydantic.Field(discriminator="type") @@ -67,7 +68,9 @@ class Foo(UniversalBaseModel): foo: types_types_foo_Foo if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + frozen=True + ) # type: ignore # Pydantic v2 else: class Config: @@ -79,7 +82,9 @@ class Bar(UniversalBaseModel): bar: types_types_bar_Bar if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/unions/union-utils/src/seed/types/types/union_with_base_properties.py b/seed/python-sdk/unions/union-utils/src/seed/types/types/union_with_base_properties.py index c0a32377825..8967c652eb9 100644 --- a/seed/python-sdk/unions/union-utils/src/seed/types/types/union_with_base_properties.py +++ b/seed/python-sdk/unions/union-utils/src/seed/types/types/union_with_base_properties.py @@ -1,14 +1,14 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ...core.pydantic_utilities import IS_PYDANTIC_V2 +from .foo import Foo as types_types_foo_Foo +from ...core.pydantic_utilities import UniversalRootModel import typing - -import pydantic import typing_extensions - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel, UniversalRootModel, update_forward_refs -from .foo import Foo as types_types_foo_Foo +import pydantic +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import update_forward_refs T_Result = typing.TypeVar("T_Result") @@ -16,24 +16,36 @@ class _Factory: def integer(self, value: int) -> UnionWithBaseProperties: if IS_PYDANTIC_V2: - return UnionWithBaseProperties(root=_UnionWithBaseProperties.Integer(type="integer", value=value)) + return UnionWithBaseProperties( + root=_UnionWithBaseProperties.Integer(type="integer", value=value) + ) else: - return UnionWithBaseProperties(__root__=_UnionWithBaseProperties.Integer(type="integer", value=value)) + return UnionWithBaseProperties( + __root__=_UnionWithBaseProperties.Integer(type="integer", value=value) + ) def string(self, value: str) -> UnionWithBaseProperties: if IS_PYDANTIC_V2: - return UnionWithBaseProperties(root=_UnionWithBaseProperties.String(type="string", value=value)) + return UnionWithBaseProperties( + root=_UnionWithBaseProperties.String(type="string", value=value) + ) else: - return UnionWithBaseProperties(__root__=_UnionWithBaseProperties.String(type="string", value=value)) + return UnionWithBaseProperties( + __root__=_UnionWithBaseProperties.String(type="string", value=value) + ) def foo(self, value: types_types_foo_Foo) -> UnionWithBaseProperties: if IS_PYDANTIC_V2: return UnionWithBaseProperties( - root=_UnionWithBaseProperties.Foo(**value.dict(exclude_unset=True), type="foo") + root=_UnionWithBaseProperties.Foo( + **value.dict(exclude_unset=True), type="foo" + ) ) else: return UnionWithBaseProperties( - __root__=_UnionWithBaseProperties.Foo(**value.dict(exclude_unset=True), type="foo") + __root__=_UnionWithBaseProperties.Foo( + **value.dict(exclude_unset=True), type="foo" + ) ) @@ -43,7 +55,9 @@ class UnionWithBaseProperties(UniversalRootModel): if IS_PYDANTIC_V2: root: typing_extensions.Annotated[ typing.Union[ - _UnionWithBaseProperties.Integer, _UnionWithBaseProperties.String, _UnionWithBaseProperties.Foo + _UnionWithBaseProperties.Integer, + _UnionWithBaseProperties.String, + _UnionWithBaseProperties.Foo, ], pydantic.Field(discriminator="type"), ] @@ -51,14 +65,17 @@ class UnionWithBaseProperties(UniversalRootModel): def get_as_union( self, ) -> typing.Union[ - _UnionWithBaseProperties.Integer, _UnionWithBaseProperties.String, _UnionWithBaseProperties.Foo + _UnionWithBaseProperties.Integer, + _UnionWithBaseProperties.String, + _UnionWithBaseProperties.Foo, ]: return self.root - else: __root__: typing_extensions.Annotated[ typing.Union[ - _UnionWithBaseProperties.Integer, _UnionWithBaseProperties.String, _UnionWithBaseProperties.Foo + _UnionWithBaseProperties.Integer, + _UnionWithBaseProperties.String, + _UnionWithBaseProperties.Foo, ], pydantic.Field(discriminator="type"), ] @@ -66,7 +83,9 @@ def get_as_union( def get_as_union( self, ) -> typing.Union[ - _UnionWithBaseProperties.Integer, _UnionWithBaseProperties.String, _UnionWithBaseProperties.Foo + _UnionWithBaseProperties.Integer, + _UnionWithBaseProperties.String, + _UnionWithBaseProperties.Foo, ]: return self.__root__ @@ -82,7 +101,11 @@ def visit( if unioned_value.type == "string": return string(unioned_value.value) if unioned_value.type == "foo": - return foo(types_types_foo_Foo(**unioned_value.dict(exclude_unset=True, exclude={"type"}))) + return foo( + types_types_foo_Foo( + **unioned_value.dict(exclude_unset=True, exclude={"type"}) + ) + ) class _UnionWithBaseProperties: @@ -91,7 +114,9 @@ class Integer(UniversalBaseModel): value: int if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + frozen=True + ) # type: ignore # Pydantic v2 else: class Config: @@ -103,7 +128,9 @@ class String(UniversalBaseModel): value: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + frozen=True + ) # type: ignore # Pydantic v2 else: class Config: @@ -114,7 +141,9 @@ class Foo(types_types_foo_Foo): type: typing.Literal["foo"] = "foo" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/unions/union-utils/src/seed/types/types/union_with_discriminant.py b/seed/python-sdk/unions/union-utils/src/seed/types/types/union_with_discriminant.py index 2bb03915a48..9e8e44b0d6a 100644 --- a/seed/python-sdk/unions/union-utils/src/seed/types/types/union_with_discriminant.py +++ b/seed/python-sdk/unions/union-utils/src/seed/types/types/union_with_discriminant.py @@ -1,15 +1,15 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from .foo import Foo as types_types_foo_Foo +from ...core.pydantic_utilities import IS_PYDANTIC_V2 +from .bar import Bar as types_types_bar_Bar +from ...core.pydantic_utilities import UniversalRootModel import typing - -import pydantic import typing_extensions - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel, UniversalRootModel, update_forward_refs -from .bar import Bar as types_types_bar_Bar -from .foo import Foo as types_types_foo_Foo +import pydantic +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import update_forward_refs T_Result = typing.TypeVar("T_Result") @@ -17,15 +17,23 @@ class _Factory: def foo(self, value: types_types_foo_Foo) -> UnionWithDiscriminant: if IS_PYDANTIC_V2: - return UnionWithDiscriminant(root=_UnionWithDiscriminant.Foo(type="foo", foo=value)) + return UnionWithDiscriminant( + root=_UnionWithDiscriminant.Foo(type="foo", foo=value) + ) else: - return UnionWithDiscriminant(__root__=_UnionWithDiscriminant.Foo(type="foo", foo=value)) + return UnionWithDiscriminant( + __root__=_UnionWithDiscriminant.Foo(type="foo", foo=value) + ) def bar(self, value: types_types_bar_Bar) -> UnionWithDiscriminant: if IS_PYDANTIC_V2: - return UnionWithDiscriminant(root=_UnionWithDiscriminant.Bar(type="bar", bar=value)) + return UnionWithDiscriminant( + root=_UnionWithDiscriminant.Bar(type="bar", bar=value) + ) else: - return UnionWithDiscriminant(__root__=_UnionWithDiscriminant.Bar(type="bar", bar=value)) + return UnionWithDiscriminant( + __root__=_UnionWithDiscriminant.Bar(type="bar", bar=value) + ) class UnionWithDiscriminant(UniversalRootModel): @@ -33,18 +41,23 @@ class UnionWithDiscriminant(UniversalRootModel): if IS_PYDANTIC_V2: root: typing_extensions.Annotated[ - typing.Union[_UnionWithDiscriminant.Foo, _UnionWithDiscriminant.Bar], pydantic.Field(discriminator="type") + typing.Union[_UnionWithDiscriminant.Foo, _UnionWithDiscriminant.Bar], + pydantic.Field(discriminator="type"), ] - def get_as_union(self) -> typing.Union[_UnionWithDiscriminant.Foo, _UnionWithDiscriminant.Bar]: + def get_as_union( + self, + ) -> typing.Union[_UnionWithDiscriminant.Foo, _UnionWithDiscriminant.Bar]: return self.root - else: __root__: typing_extensions.Annotated[ - typing.Union[_UnionWithDiscriminant.Foo, _UnionWithDiscriminant.Bar], pydantic.Field(discriminator="type") + typing.Union[_UnionWithDiscriminant.Foo, _UnionWithDiscriminant.Bar], + pydantic.Field(discriminator="type"), ] - def get_as_union(self) -> typing.Union[_UnionWithDiscriminant.Foo, _UnionWithDiscriminant.Bar]: + def get_as_union( + self, + ) -> typing.Union[_UnionWithDiscriminant.Foo, _UnionWithDiscriminant.Bar]: return self.__root__ def visit( @@ -65,7 +78,9 @@ class Foo(UniversalBaseModel): foo: types_types_foo_Foo if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + frozen=True + ) # type: ignore # Pydantic v2 else: class Config: @@ -77,7 +92,9 @@ class Bar(UniversalBaseModel): bar: types_types_bar_Bar if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/unions/union-utils/src/seed/types/types/union_with_literal.py b/seed/python-sdk/unions/union-utils/src/seed/types/types/union_with_literal.py index 23495b76178..ef81c8b8622 100644 --- a/seed/python-sdk/unions/union-utils/src/seed/types/types/union_with_literal.py +++ b/seed/python-sdk/unions/union-utils/src/seed/types/types/union_with_literal.py @@ -1,12 +1,12 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - import typing - +from ...core.pydantic_utilities import IS_PYDANTIC_V2 +from ...core.pydantic_utilities import UniversalRootModel +from ...core.pydantic_utilities import UniversalBaseModel import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel, UniversalRootModel, update_forward_refs +from ...core.pydantic_utilities import update_forward_refs T_Result = typing.TypeVar("T_Result") @@ -14,9 +14,13 @@ class _Factory: def fern(self, value: typing.Literal["fern"]) -> UnionWithLiteral: if IS_PYDANTIC_V2: - return UnionWithLiteral(root=_UnionWithLiteral.Fern(type="fern", value=value)) + return UnionWithLiteral( + root=_UnionWithLiteral.Fern(type="fern", value=value) + ) else: - return UnionWithLiteral(__root__=_UnionWithLiteral.Fern(type="fern", value=value)) + return UnionWithLiteral( + __root__=_UnionWithLiteral.Fern(type="fern", value=value) + ) class UnionWithLiteral(UniversalRootModel): @@ -27,14 +31,15 @@ class UnionWithLiteral(UniversalRootModel): def get_as_union(self) -> typing.Union[_UnionWithLiteral.Fern]: return self.root - else: __root__: typing.Union[_UnionWithLiteral.Fern] def get_as_union(self) -> typing.Union[_UnionWithLiteral.Fern]: return self.__root__ - def visit(self, fern: typing.Callable[[typing.Literal["fern"]], T_Result]) -> T_Result: + def visit( + self, fern: typing.Callable[[typing.Literal["fern"]], T_Result] + ) -> T_Result: unioned_value = self.get_as_union() if unioned_value.type == "fern": return fern(unioned_value.value) @@ -46,7 +51,9 @@ class Fern(UniversalBaseModel): value: typing.Literal["fern"] if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/unions/union-utils/src/seed/types/types/union_with_optional_time.py b/seed/python-sdk/unions/union-utils/src/seed/types/types/union_with_optional_time.py index 02a40803098..0c139a338fd 100644 --- a/seed/python-sdk/unions/union-utils/src/seed/types/types/union_with_optional_time.py +++ b/seed/python-sdk/unions/union-utils/src/seed/types/types/union_with_optional_time.py @@ -1,14 +1,14 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - -import datetime as dt import typing - -import pydantic +import datetime as dt +from ...core.pydantic_utilities import IS_PYDANTIC_V2 +from ...core.pydantic_utilities import UniversalRootModel import typing_extensions - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel, UniversalRootModel, update_forward_refs +import pydantic +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import update_forward_refs T_Result = typing.TypeVar("T_Result") @@ -16,15 +16,23 @@ class _Factory: def date(self, value: typing.Optional[dt.date]) -> UnionWithOptionalTime: if IS_PYDANTIC_V2: - return UnionWithOptionalTime(root=_UnionWithOptionalTime.Date(type="date", value=value)) + return UnionWithOptionalTime( + root=_UnionWithOptionalTime.Date(type="date", value=value) + ) else: - return UnionWithOptionalTime(__root__=_UnionWithOptionalTime.Date(type="date", value=value)) + return UnionWithOptionalTime( + __root__=_UnionWithOptionalTime.Date(type="date", value=value) + ) def dateimte(self, value: typing.Optional[dt.datetime]) -> UnionWithOptionalTime: if IS_PYDANTIC_V2: - return UnionWithOptionalTime(root=_UnionWithOptionalTime.Dateimte(type="dateimte", value=value)) + return UnionWithOptionalTime( + root=_UnionWithOptionalTime.Dateimte(type="dateimte", value=value) + ) else: - return UnionWithOptionalTime(__root__=_UnionWithOptionalTime.Dateimte(type="dateimte", value=value)) + return UnionWithOptionalTime( + __root__=_UnionWithOptionalTime.Dateimte(type="dateimte", value=value) + ) class UnionWithOptionalTime(UniversalRootModel): @@ -36,16 +44,19 @@ class UnionWithOptionalTime(UniversalRootModel): pydantic.Field(discriminator="type"), ] - def get_as_union(self) -> typing.Union[_UnionWithOptionalTime.Date, _UnionWithOptionalTime.Dateimte]: + def get_as_union( + self, + ) -> typing.Union[_UnionWithOptionalTime.Date, _UnionWithOptionalTime.Dateimte]: return self.root - else: __root__: typing_extensions.Annotated[ typing.Union[_UnionWithOptionalTime.Date, _UnionWithOptionalTime.Dateimte], pydantic.Field(discriminator="type"), ] - def get_as_union(self) -> typing.Union[_UnionWithOptionalTime.Date, _UnionWithOptionalTime.Dateimte]: + def get_as_union( + self, + ) -> typing.Union[_UnionWithOptionalTime.Date, _UnionWithOptionalTime.Dateimte]: return self.__root__ def visit( @@ -66,7 +77,9 @@ class Date(UniversalBaseModel): value: typing.Optional[dt.date] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + frozen=True + ) # type: ignore # Pydantic v2 else: class Config: @@ -78,7 +91,9 @@ class Dateimte(UniversalBaseModel): value: typing.Optional[dt.datetime] = None if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/unions/union-utils/src/seed/types/types/union_with_primitive.py b/seed/python-sdk/unions/union-utils/src/seed/types/types/union_with_primitive.py index a2a05f9db77..17e2c55eff0 100644 --- a/seed/python-sdk/unions/union-utils/src/seed/types/types/union_with_primitive.py +++ b/seed/python-sdk/unions/union-utils/src/seed/types/types/union_with_primitive.py @@ -1,13 +1,13 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ...core.pydantic_utilities import IS_PYDANTIC_V2 +from ...core.pydantic_utilities import UniversalRootModel import typing - -import pydantic import typing_extensions - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel, UniversalRootModel, update_forward_refs +import pydantic +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import update_forward_refs T_Result = typing.TypeVar("T_Result") @@ -15,15 +15,23 @@ class _Factory: def integer(self, value: int) -> UnionWithPrimitive: if IS_PYDANTIC_V2: - return UnionWithPrimitive(root=_UnionWithPrimitive.Integer(type="integer", value=value)) + return UnionWithPrimitive( + root=_UnionWithPrimitive.Integer(type="integer", value=value) + ) else: - return UnionWithPrimitive(__root__=_UnionWithPrimitive.Integer(type="integer", value=value)) + return UnionWithPrimitive( + __root__=_UnionWithPrimitive.Integer(type="integer", value=value) + ) def string(self, value: str) -> UnionWithPrimitive: if IS_PYDANTIC_V2: - return UnionWithPrimitive(root=_UnionWithPrimitive.String(type="string", value=value)) + return UnionWithPrimitive( + root=_UnionWithPrimitive.String(type="string", value=value) + ) else: - return UnionWithPrimitive(__root__=_UnionWithPrimitive.String(type="string", value=value)) + return UnionWithPrimitive( + __root__=_UnionWithPrimitive.String(type="string", value=value) + ) class UnionWithPrimitive(UniversalRootModel): @@ -31,21 +39,30 @@ class UnionWithPrimitive(UniversalRootModel): if IS_PYDANTIC_V2: root: typing_extensions.Annotated[ - typing.Union[_UnionWithPrimitive.Integer, _UnionWithPrimitive.String], pydantic.Field(discriminator="type") + typing.Union[_UnionWithPrimitive.Integer, _UnionWithPrimitive.String], + pydantic.Field(discriminator="type"), ] - def get_as_union(self) -> typing.Union[_UnionWithPrimitive.Integer, _UnionWithPrimitive.String]: + def get_as_union( + self, + ) -> typing.Union[_UnionWithPrimitive.Integer, _UnionWithPrimitive.String]: return self.root - else: __root__: typing_extensions.Annotated[ - typing.Union[_UnionWithPrimitive.Integer, _UnionWithPrimitive.String], pydantic.Field(discriminator="type") + typing.Union[_UnionWithPrimitive.Integer, _UnionWithPrimitive.String], + pydantic.Field(discriminator="type"), ] - def get_as_union(self) -> typing.Union[_UnionWithPrimitive.Integer, _UnionWithPrimitive.String]: + def get_as_union( + self, + ) -> typing.Union[_UnionWithPrimitive.Integer, _UnionWithPrimitive.String]: return self.__root__ - def visit(self, integer: typing.Callable[[int], T_Result], string: typing.Callable[[str], T_Result]) -> T_Result: + def visit( + self, + integer: typing.Callable[[int], T_Result], + string: typing.Callable[[str], T_Result], + ) -> T_Result: unioned_value = self.get_as_union() if unioned_value.type == "integer": return integer(unioned_value.value) @@ -59,7 +76,9 @@ class Integer(UniversalBaseModel): value: int if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + frozen=True + ) # type: ignore # Pydantic v2 else: class Config: @@ -71,7 +90,9 @@ class String(UniversalBaseModel): value: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/unions/union-utils/src/seed/types/types/union_with_single_element.py b/seed/python-sdk/unions/union-utils/src/seed/types/types/union_with_single_element.py index 3eb08b9e2c7..61dd4f6f83e 100644 --- a/seed/python-sdk/unions/union-utils/src/seed/types/types/union_with_single_element.py +++ b/seed/python-sdk/unions/union-utils/src/seed/types/types/union_with_single_element.py @@ -1,13 +1,12 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from .foo import Foo as types_types_foo_Foo +from ...core.pydantic_utilities import IS_PYDANTIC_V2 +from ...core.pydantic_utilities import UniversalRootModel import typing - import pydantic - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalRootModel, update_forward_refs -from .foo import Foo as types_types_foo_Foo +from ...core.pydantic_utilities import update_forward_refs T_Result = typing.TypeVar("T_Result") @@ -16,11 +15,15 @@ class _Factory: def foo(self, value: types_types_foo_Foo) -> UnionWithSingleElement: if IS_PYDANTIC_V2: return UnionWithSingleElement( - root=_UnionWithSingleElement.Foo(**value.dict(exclude_unset=True), type="foo") + root=_UnionWithSingleElement.Foo( + **value.dict(exclude_unset=True), type="foo" + ) ) else: return UnionWithSingleElement( - __root__=_UnionWithSingleElement.Foo(**value.dict(exclude_unset=True), type="foo") + __root__=_UnionWithSingleElement.Foo( + **value.dict(exclude_unset=True), type="foo" + ) ) @@ -32,7 +35,6 @@ class UnionWithSingleElement(UniversalRootModel): def get_as_union(self) -> typing.Union[_UnionWithSingleElement.Foo]: return self.root - else: __root__: typing.Union[_UnionWithSingleElement.Foo] @@ -42,7 +44,11 @@ def get_as_union(self) -> typing.Union[_UnionWithSingleElement.Foo]: def visit(self, foo: typing.Callable[[types_types_foo_Foo], T_Result]) -> T_Result: unioned_value = self.get_as_union() if unioned_value.type == "foo": - return foo(types_types_foo_Foo(**unioned_value.dict(exclude_unset=True, exclude={"type"}))) + return foo( + types_types_foo_Foo( + **unioned_value.dict(exclude_unset=True, exclude={"type"}) + ) + ) class _UnionWithSingleElement: @@ -50,7 +56,9 @@ class Foo(types_types_foo_Foo): type: typing.Literal["foo"] = "foo" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/unions/union-utils/src/seed/types/types/union_with_time.py b/seed/python-sdk/unions/union-utils/src/seed/types/types/union_with_time.py index e0650a9bcfa..4c6ce43dd2e 100644 --- a/seed/python-sdk/unions/union-utils/src/seed/types/types/union_with_time.py +++ b/seed/python-sdk/unions/union-utils/src/seed/types/types/union_with_time.py @@ -1,14 +1,14 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import datetime as dt +from ...core.pydantic_utilities import UniversalRootModel import typing - -import pydantic import typing_extensions - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel, UniversalRootModel, update_forward_refs +import pydantic +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import update_forward_refs T_Result = typing.TypeVar("T_Result") @@ -18,7 +18,9 @@ def value(self, value: int) -> UnionWithTime: if IS_PYDANTIC_V2: return UnionWithTime(root=_UnionWithTime.Value(type="value", value=value)) else: - return UnionWithTime(__root__=_UnionWithTime.Value(type="value", value=value)) + return UnionWithTime( + __root__=_UnionWithTime.Value(type="value", value=value) + ) def date(self, value: dt.date) -> UnionWithTime: if IS_PYDANTIC_V2: @@ -28,9 +30,13 @@ def date(self, value: dt.date) -> UnionWithTime: def datetime(self, value: dt.datetime) -> UnionWithTime: if IS_PYDANTIC_V2: - return UnionWithTime(root=_UnionWithTime.Datetime(type="datetime", value=value)) + return UnionWithTime( + root=_UnionWithTime.Datetime(type="datetime", value=value) + ) else: - return UnionWithTime(__root__=_UnionWithTime.Datetime(type="datetime", value=value)) + return UnionWithTime( + __root__=_UnionWithTime.Datetime(type="datetime", value=value) + ) class UnionWithTime(UniversalRootModel): @@ -38,20 +44,31 @@ class UnionWithTime(UniversalRootModel): if IS_PYDANTIC_V2: root: typing_extensions.Annotated[ - typing.Union[_UnionWithTime.Value, _UnionWithTime.Date, _UnionWithTime.Datetime], + typing.Union[ + _UnionWithTime.Value, _UnionWithTime.Date, _UnionWithTime.Datetime + ], pydantic.Field(discriminator="type"), ] - def get_as_union(self) -> typing.Union[_UnionWithTime.Value, _UnionWithTime.Date, _UnionWithTime.Datetime]: + def get_as_union( + self, + ) -> typing.Union[ + _UnionWithTime.Value, _UnionWithTime.Date, _UnionWithTime.Datetime + ]: return self.root - else: __root__: typing_extensions.Annotated[ - typing.Union[_UnionWithTime.Value, _UnionWithTime.Date, _UnionWithTime.Datetime], + typing.Union[ + _UnionWithTime.Value, _UnionWithTime.Date, _UnionWithTime.Datetime + ], pydantic.Field(discriminator="type"), ] - def get_as_union(self) -> typing.Union[_UnionWithTime.Value, _UnionWithTime.Date, _UnionWithTime.Datetime]: + def get_as_union( + self, + ) -> typing.Union[ + _UnionWithTime.Value, _UnionWithTime.Date, _UnionWithTime.Datetime + ]: return self.__root__ def visit( @@ -75,7 +92,9 @@ class Value(UniversalBaseModel): value: int if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + frozen=True + ) # type: ignore # Pydantic v2 else: class Config: @@ -87,7 +106,9 @@ class Date(UniversalBaseModel): value: dt.date if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + frozen=True + ) # type: ignore # Pydantic v2 else: class Config: @@ -99,7 +120,9 @@ class Datetime(UniversalBaseModel): value: dt.datetime if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/unions/union-utils/src/seed/types/types/union_with_unknown.py b/seed/python-sdk/unions/union-utils/src/seed/types/types/union_with_unknown.py index 868d9a76b6c..16bf0bbe105 100644 --- a/seed/python-sdk/unions/union-utils/src/seed/types/types/union_with_unknown.py +++ b/seed/python-sdk/unions/union-utils/src/seed/types/types/union_with_unknown.py @@ -1,14 +1,14 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from .foo import Foo as types_types_foo_Foo +from ...core.pydantic_utilities import IS_PYDANTIC_V2 +from ...core.pydantic_utilities import UniversalRootModel import typing - -import pydantic import typing_extensions - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel, UniversalRootModel, update_forward_refs -from .foo import Foo as types_types_foo_Foo +import pydantic +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import update_forward_refs T_Result = typing.TypeVar("T_Result") @@ -16,9 +16,15 @@ class _Factory: def foo(self, value: types_types_foo_Foo) -> UnionWithUnknown: if IS_PYDANTIC_V2: - return UnionWithUnknown(root=_UnionWithUnknown.Foo(**value.dict(exclude_unset=True), type="foo")) + return UnionWithUnknown( + root=_UnionWithUnknown.Foo(**value.dict(exclude_unset=True), type="foo") + ) else: - return UnionWithUnknown(__root__=_UnionWithUnknown.Foo(**value.dict(exclude_unset=True), type="foo")) + return UnionWithUnknown( + __root__=_UnionWithUnknown.Foo( + **value.dict(exclude_unset=True), type="foo" + ) + ) def unknown(self) -> UnionWithUnknown: if IS_PYDANTIC_V2: @@ -32,26 +38,37 @@ class UnionWithUnknown(UniversalRootModel): if IS_PYDANTIC_V2: root: typing_extensions.Annotated[ - typing.Union[_UnionWithUnknown.Foo, _UnionWithUnknown.Unknown], pydantic.Field(discriminator="type") + typing.Union[_UnionWithUnknown.Foo, _UnionWithUnknown.Unknown], + pydantic.Field(discriminator="type"), ] - def get_as_union(self) -> typing.Union[_UnionWithUnknown.Foo, _UnionWithUnknown.Unknown]: + def get_as_union( + self, + ) -> typing.Union[_UnionWithUnknown.Foo, _UnionWithUnknown.Unknown]: return self.root - else: __root__: typing_extensions.Annotated[ - typing.Union[_UnionWithUnknown.Foo, _UnionWithUnknown.Unknown], pydantic.Field(discriminator="type") + typing.Union[_UnionWithUnknown.Foo, _UnionWithUnknown.Unknown], + pydantic.Field(discriminator="type"), ] - def get_as_union(self) -> typing.Union[_UnionWithUnknown.Foo, _UnionWithUnknown.Unknown]: + def get_as_union( + self, + ) -> typing.Union[_UnionWithUnknown.Foo, _UnionWithUnknown.Unknown]: return self.__root__ def visit( - self, foo: typing.Callable[[types_types_foo_Foo], T_Result], unknown: typing.Callable[[], T_Result] + self, + foo: typing.Callable[[types_types_foo_Foo], T_Result], + unknown: typing.Callable[[], T_Result], ) -> T_Result: unioned_value = self.get_as_union() if unioned_value.type == "foo": - return foo(types_types_foo_Foo(**unioned_value.dict(exclude_unset=True, exclude={"type"}))) + return foo( + types_types_foo_Foo( + **unioned_value.dict(exclude_unset=True, exclude={"type"}) + ) + ) if unioned_value.type == "unknown": return unknown() @@ -61,7 +78,9 @@ class Foo(types_types_foo_Foo): type: typing.Literal["foo"] = "foo" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + frozen=True + ) # type: ignore # Pydantic v2 else: class Config: @@ -72,7 +91,9 @@ class Unknown(UniversalBaseModel): type: typing.Literal["unknown"] = "unknown" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/unions/union-utils/src/seed/types/types/union_without_key.py b/seed/python-sdk/unions/union-utils/src/seed/types/types/union_without_key.py index 88385aa10a2..2ed746429da 100644 --- a/seed/python-sdk/unions/union-utils/src/seed/types/types/union_without_key.py +++ b/seed/python-sdk/unions/union-utils/src/seed/types/types/union_without_key.py @@ -1,15 +1,14 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - +from .foo import Foo as types_types_foo_Foo +from ...core.pydantic_utilities import IS_PYDANTIC_V2 +from .bar import Bar as types_types_bar_Bar +from ...core.pydantic_utilities import UniversalRootModel import typing - -import pydantic import typing_extensions - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalRootModel, update_forward_refs -from .bar import Bar as types_types_bar_Bar -from .foo import Foo as types_types_foo_Foo +import pydantic +from ...core.pydantic_utilities import update_forward_refs T_Result = typing.TypeVar("T_Result") @@ -17,15 +16,27 @@ class _Factory: def foo(self, value: types_types_foo_Foo) -> UnionWithoutKey: if IS_PYDANTIC_V2: - return UnionWithoutKey(root=_UnionWithoutKey.Foo(**value.dict(exclude_unset=True), type="foo")) + return UnionWithoutKey( + root=_UnionWithoutKey.Foo(**value.dict(exclude_unset=True), type="foo") + ) else: - return UnionWithoutKey(__root__=_UnionWithoutKey.Foo(**value.dict(exclude_unset=True), type="foo")) + return UnionWithoutKey( + __root__=_UnionWithoutKey.Foo( + **value.dict(exclude_unset=True), type="foo" + ) + ) def bar(self, value: types_types_bar_Bar) -> UnionWithoutKey: if IS_PYDANTIC_V2: - return UnionWithoutKey(root=_UnionWithoutKey.Bar(**value.dict(exclude_unset=True), type="bar")) + return UnionWithoutKey( + root=_UnionWithoutKey.Bar(**value.dict(exclude_unset=True), type="bar") + ) else: - return UnionWithoutKey(__root__=_UnionWithoutKey.Bar(**value.dict(exclude_unset=True), type="bar")) + return UnionWithoutKey( + __root__=_UnionWithoutKey.Bar( + **value.dict(exclude_unset=True), type="bar" + ) + ) class UnionWithoutKey(UniversalRootModel): @@ -33,18 +44,23 @@ class UnionWithoutKey(UniversalRootModel): if IS_PYDANTIC_V2: root: typing_extensions.Annotated[ - typing.Union[_UnionWithoutKey.Foo, _UnionWithoutKey.Bar], pydantic.Field(discriminator="type") + typing.Union[_UnionWithoutKey.Foo, _UnionWithoutKey.Bar], + pydantic.Field(discriminator="type"), ] - def get_as_union(self) -> typing.Union[_UnionWithoutKey.Foo, _UnionWithoutKey.Bar]: + def get_as_union( + self, + ) -> typing.Union[_UnionWithoutKey.Foo, _UnionWithoutKey.Bar]: return self.root - else: __root__: typing_extensions.Annotated[ - typing.Union[_UnionWithoutKey.Foo, _UnionWithoutKey.Bar], pydantic.Field(discriminator="type") + typing.Union[_UnionWithoutKey.Foo, _UnionWithoutKey.Bar], + pydantic.Field(discriminator="type"), ] - def get_as_union(self) -> typing.Union[_UnionWithoutKey.Foo, _UnionWithoutKey.Bar]: + def get_as_union( + self, + ) -> typing.Union[_UnionWithoutKey.Foo, _UnionWithoutKey.Bar]: return self.__root__ def visit( @@ -54,9 +70,17 @@ def visit( ) -> T_Result: unioned_value = self.get_as_union() if unioned_value.type == "foo": - return foo(types_types_foo_Foo(**unioned_value.dict(exclude_unset=True, exclude={"type"}))) + return foo( + types_types_foo_Foo( + **unioned_value.dict(exclude_unset=True, exclude={"type"}) + ) + ) if unioned_value.type == "bar": - return bar(types_types_bar_Bar(**unioned_value.dict(exclude_unset=True, exclude={"type"}))) + return bar( + types_types_bar_Bar( + **unioned_value.dict(exclude_unset=True, exclude={"type"}) + ) + ) class _UnionWithoutKey: @@ -64,7 +88,9 @@ class Foo(types_types_foo_Foo): type: typing.Literal["foo"] = "foo" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + frozen=True + ) # type: ignore # Pydantic v2 else: class Config: @@ -75,7 +101,9 @@ class Bar(types_types_bar_Bar): type: typing.Literal["bar"] = "bar" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/unions/union-utils/src/seed/union/client.py b/seed/python-sdk/unions/union-utils/src/seed/union/client.py index 15d8abca9bd..f9f656bce2f 100644 --- a/seed/python-sdk/unions/union-utils/src/seed/union/client.py +++ b/seed/python-sdk/unions/union-utils/src/seed/union/client.py @@ -1,14 +1,14 @@ # This file was auto-generated by Fern from our API Definition. import typing -from json.decoder import JSONDecodeError - -from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.jsonable_encoder import jsonable_encoder -from ..core.pydantic_utilities import parse_obj_as +from ..core.client_wrapper import SyncClientWrapper from ..core.request_options import RequestOptions from .types.shape import Shape +from ..core.jsonable_encoder import jsonable_encoder +from ..core.pydantic_utilities import parse_obj_as +from json.decoder import JSONDecodeError +from ..core.api_error import ApiError +from ..core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -18,7 +18,9 @@ class UnionClient: def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper - def get(self, id: str, *, request_options: typing.Optional[RequestOptions] = None) -> Shape: + def get( + self, id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> Shape: """ Parameters ---------- @@ -43,17 +45,23 @@ def get(self, id: str, *, request_options: typing.Optional[RequestOptions] = Non ) """ _response = self._client_wrapper.httpx_client.request( - f"{jsonable_encoder(id)}", method="GET", request_options=request_options + f"{jsonable_encoder(id)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(Shape, parse_obj_as(type_=Shape, object_=_response.json())) # type: ignore + return typing.cast( + Shape, parse_obj_as(type_=Shape, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def update(self, *, request: Shape, request_options: typing.Optional[RequestOptions] = None) -> bool: + def update( + self, *, request: Shape, request_options: typing.Optional[RequestOptions] = None + ) -> bool: """ Parameters ---------- @@ -82,11 +90,16 @@ def update(self, *, request: Shape, request_options: typing.Optional[RequestOpti ) """ _response = self._client_wrapper.httpx_client.request( - method="PATCH", json=request, request_options=request_options, omit=OMIT + method="PATCH", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -97,7 +110,9 @@ class AsyncUnionClient: def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper - async def get(self, id: str, *, request_options: typing.Optional[RequestOptions] = None) -> Shape: + async def get( + self, id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> Shape: """ Parameters ---------- @@ -130,17 +145,23 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - f"{jsonable_encoder(id)}", method="GET", request_options=request_options + f"{jsonable_encoder(id)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(Shape, parse_obj_as(type_=Shape, object_=_response.json())) # type: ignore + return typing.cast( + Shape, parse_obj_as(type_=Shape, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - async def update(self, *, request: Shape, request_options: typing.Optional[RequestOptions] = None) -> bool: + async def update( + self, *, request: Shape, request_options: typing.Optional[RequestOptions] = None + ) -> bool: """ Parameters ---------- @@ -177,11 +198,16 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - method="PATCH", json=request, request_options=request_options, omit=OMIT + method="PATCH", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(bool, parse_obj_as(type_=bool, object_=_response.json())) # type: ignore + return typing.cast( + bool, parse_obj_as(type_=bool, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/unions/union-utils/src/seed/union/types/circle.py b/seed/python-sdk/unions/union-utils/src/seed/union/types/circle.py index 731e80d192e..722e1e9d2e2 100644 --- a/seed/python-sdk/unions/union-utils/src/seed/union/types/circle.py +++ b/seed/python-sdk/unions/union-utils/src/seed/union/types/circle.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class Circle(UniversalBaseModel): radius: float if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/unions/union-utils/src/seed/union/types/get_shape_request.py b/seed/python-sdk/unions/union-utils/src/seed/union/types/get_shape_request.py index 7ac528833a5..94ef3c3ae3e 100644 --- a/seed/python-sdk/unions/union-utils/src/seed/union/types/get_shape_request.py +++ b/seed/python-sdk/unions/union-utils/src/seed/union/types/get_shape_request.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class GetShapeRequest(UniversalBaseModel): id: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/unions/union-utils/src/seed/union/types/shape.py b/seed/python-sdk/unions/union-utils/src/seed/union/types/shape.py index fb9b8ed7292..90d37cc308d 100644 --- a/seed/python-sdk/unions/union-utils/src/seed/union/types/shape.py +++ b/seed/python-sdk/unions/union-utils/src/seed/union/types/shape.py @@ -1,15 +1,14 @@ # This file was auto-generated by Fern from our API Definition. from __future__ import annotations - -import typing - -import pydantic -import typing_extensions - -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalRootModel, update_forward_refs from .circle import Circle as union_types_circle_Circle +from ...core.pydantic_utilities import IS_PYDANTIC_V2 from .square import Square as union_types_square_Square +from ...core.pydantic_utilities import UniversalRootModel +import typing +import typing_extensions +import pydantic +from ...core.pydantic_utilities import update_forward_refs T_Result = typing.TypeVar("T_Result") @@ -17,15 +16,23 @@ class _Factory: def circle(self, value: union_types_circle_Circle) -> Shape: if IS_PYDANTIC_V2: - return Shape(root=_Shape.Circle(**value.dict(exclude_unset=True), type="circle")) + return Shape( + root=_Shape.Circle(**value.dict(exclude_unset=True), type="circle") + ) else: - return Shape(__root__=_Shape.Circle(**value.dict(exclude_unset=True), type="circle")) + return Shape( + __root__=_Shape.Circle(**value.dict(exclude_unset=True), type="circle") + ) def square(self, value: union_types_square_Square) -> Shape: if IS_PYDANTIC_V2: - return Shape(root=_Shape.Square(**value.dict(exclude_unset=True), type="square")) + return Shape( + root=_Shape.Square(**value.dict(exclude_unset=True), type="square") + ) else: - return Shape(__root__=_Shape.Square(**value.dict(exclude_unset=True), type="square")) + return Shape( + __root__=_Shape.Square(**value.dict(exclude_unset=True), type="square") + ) class Shape(UniversalRootModel): @@ -33,15 +40,16 @@ class Shape(UniversalRootModel): if IS_PYDANTIC_V2: root: typing_extensions.Annotated[ - typing.Union[_Shape.Circle, _Shape.Square], pydantic.Field(discriminator="type") + typing.Union[_Shape.Circle, _Shape.Square], + pydantic.Field(discriminator="type"), ] def get_as_union(self) -> typing.Union[_Shape.Circle, _Shape.Square]: return self.root - else: __root__: typing_extensions.Annotated[ - typing.Union[_Shape.Circle, _Shape.Square], pydantic.Field(discriminator="type") + typing.Union[_Shape.Circle, _Shape.Square], + pydantic.Field(discriminator="type"), ] def get_as_union(self) -> typing.Union[_Shape.Circle, _Shape.Square]: @@ -54,9 +62,17 @@ def visit( ) -> T_Result: unioned_value = self.get_as_union() if unioned_value.type == "circle": - return circle(union_types_circle_Circle(**unioned_value.dict(exclude_unset=True, exclude={"type"}))) + return circle( + union_types_circle_Circle( + **unioned_value.dict(exclude_unset=True, exclude={"type"}) + ) + ) if unioned_value.type == "square": - return square(union_types_square_Square(**unioned_value.dict(exclude_unset=True, exclude={"type"}))) + return square( + union_types_square_Square( + **unioned_value.dict(exclude_unset=True, exclude={"type"}) + ) + ) class _Shape: @@ -64,7 +80,9 @@ class Circle(union_types_circle_Circle): type: typing.Literal["circle"] = "circle" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + frozen=True + ) # type: ignore # Pydantic v2 else: class Config: @@ -75,7 +93,9 @@ class Square(union_types_square_Square): type: typing.Literal["square"] = "square" if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/unions/union-utils/src/seed/union/types/square.py b/seed/python-sdk/unions/union-utils/src/seed/union/types/square.py index 6494abdd14d..f7368d88e79 100644 --- a/seed/python-sdk/unions/union-utils/src/seed/union/types/square.py +++ b/seed/python-sdk/unions/union-utils/src/seed/union/types/square.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class Square(UniversalBaseModel): length: float if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/unions/union-utils/src/seed/version.py b/seed/python-sdk/unions/union-utils/src/seed/version.py index 123bebe735d..7b884a244da 100644 --- a/seed/python-sdk/unions/union-utils/src/seed/version.py +++ b/seed/python-sdk/unions/union-utils/src/seed/version.py @@ -1,4 +1,3 @@ - from importlib import metadata __version__ = metadata.version("fern_unions") diff --git a/seed/python-sdk/unions/union-utils/tests/conftest.py b/seed/python-sdk/unions/union-utils/tests/conftest.py index 7c6e0d163e9..c564db371c3 100644 --- a/seed/python-sdk/unions/union-utils/tests/conftest.py +++ b/seed/python-sdk/unions/union-utils/tests/conftest.py @@ -1,9 +1,9 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedUnions import os - import pytest -from seed import AsyncSeedUnions, SeedUnions +from seed import AsyncSeedUnions @pytest.fixture diff --git a/seed/python-sdk/unions/union-utils/tests/custom/test_client.py b/seed/python-sdk/unions/union-utils/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/python-sdk/unions/union-utils/tests/custom/test_client.py +++ b/seed/python-sdk/unions/union-utils/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/python-sdk/unions/union-utils/tests/test_union.py b/seed/python-sdk/unions/union-utils/tests/test_union.py index b5a8cf50108..8855e52bf1e 100644 --- a/seed/python-sdk/unions/union-utils/tests/test_union.py +++ b/seed/python-sdk/unions/union-utils/tests/test_union.py @@ -1,11 +1,10 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedUnions +from seed import AsyncSeedUnions import typing - -from seed import AsyncSeedUnions, SeedUnions -from seed.union import Shape_Circle - from .utilities import validate_response +from seed.union import Shape_Circle async def test_get(client: SeedUnions, async_client: AsyncSeedUnions) -> None: @@ -24,5 +23,7 @@ async def test_update(client: SeedUnions, async_client: AsyncSeedUnions) -> None response = client.union.update(request=Shape_Circle(id="string", radius=1.1)) validate_response(response, expected_response, expected_types) - async_response = await async_client.union.update(request=Shape_Circle(id="string", radius=1.1)) + async_response = await async_client.union.update( + request=Shape_Circle(id="string", radius=1.1) + ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/unions/union-utils/tests/utilities.py b/seed/python-sdk/unions/union-utils/tests/utilities.py index 13da208eb3a..e8f4472564c 100644 --- a/seed/python-sdk/unions/union-utils/tests/utilities.py +++ b/seed/python-sdk/unions/union-utils/tests/utilities.py @@ -3,11 +3,14 @@ import typing import uuid -import pydantic from dateutil import parser +import pydantic + -def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> typing.Any: +def cast_field( + json_expectation: typing.Any, type_expectation: typing.Any +) -> typing.Any: # Cast these specific types which come through as string and expect our # models to cast to the correct type. if type_expectation == "uuid": @@ -25,7 +28,9 @@ def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> ty return json_expectation -def validate_field(response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any) -> None: +def validate_field( + response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectation == "no_validate": return @@ -44,7 +49,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(entry_expectation, dict): is_container_of_complex_type = True validate_response( - response=response[idx], json_expectation=ex, type_expectations=entry_expectation + response=response[idx], + json_expectation=ex, + type_expectations=entry_expectation, ) else: cast_json_expectation.append(cast_field(ex, entry_expectation)) @@ -56,7 +63,10 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # if any of the values of the set have a type_expectation of a dict, we're assuming it's a pydantic # model and keeping it a list. if container_expectation != "set" or not any( - map(lambda value: isinstance(value, dict), list(contents_expectation.values())) + map( + lambda value: isinstance(value, dict), + list(contents_expectation.values()), + ) ): json_expectation = cast_field(json_expectation, container_expectation) elif isinstance(type_expectation, tuple): @@ -65,9 +75,15 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(contents_expectation, dict): json_expectation = { cast_field( - key, contents_expectation.get(idx)[0] if contents_expectation.get(idx) is not None else None # type: ignore + key, + contents_expectation.get(idx)[0] + if contents_expectation.get(idx) is not None + else None, # type: ignore ): cast_field( - value, contents_expectation.get(idx)[1] if contents_expectation.get(idx) is not None else None # type: ignore + value, + contents_expectation.get(idx)[1] + if contents_expectation.get(idx) is not None + else None, # type: ignore ) for idx, (key, value) in enumerate(json_expectation.items()) } @@ -86,7 +102,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # Arg type_expectations is a deeply nested structure that matches the response, but with the values replaced with the expected types -def validate_response(response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any) -> None: +def validate_response( + response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectations == "no_validate": return @@ -96,11 +114,17 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e and not isinstance(response, dict) and not issubclass(type(response), pydantic.BaseModel) ): - validate_field(response=response, json_expectation=json_expectation, type_expectation=type_expectations) + validate_field( + response=response, + json_expectation=json_expectation, + type_expectation=type_expectations, + ) return if isinstance(response, list): - assert len(response) == len(json_expectation), "Length mismatch, expected: {0}, Actual: {1}".format( + assert len(response) == len( + json_expectation + ), "Length mismatch, expected: {0}, Actual: {1}".format( len(response), len(json_expectation) ) content_expectation = type_expectations @@ -108,7 +132,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e content_expectation = type_expectations[1] for idx, item in enumerate(response): validate_response( - response=item, json_expectation=json_expectation[idx], type_expectations=content_expectation[idx] + response=item, + json_expectation=json_expectation[idx], + type_expectations=content_expectation[idx], ) else: response_json = response @@ -116,7 +142,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e response_json = response.dict(by_alias=True) for key, value in json_expectation.items(): - assert key in response_json, "Field {0} not found within the response object: {1}".format( + assert ( + key in response_json + ), "Field {0} not found within the response object: {1}".format( key, response_json ) @@ -128,11 +156,19 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e # Otherwise, we're just validating a single field that's a pydantic model. if isinstance(value, dict) and not isinstance(type_expectation, tuple): validate_response( - response=response_json[key], json_expectation=value, type_expectations=type_expectation + response=response_json[key], + json_expectation=value, + type_expectations=type_expectation, ) else: - validate_field(response=response_json[key], json_expectation=value, type_expectation=type_expectation) + validate_field( + response=response_json[key], + json_expectation=value, + type_expectation=type_expectation, + ) # Ensure there are no additional fields here either del response_json[key] - assert len(response_json) == 0, "Additional fields found, expected None: {0}".format(response_json) + assert ( + len(response_json) == 0 + ), "Additional fields found, expected None: {0}".format(response_json) diff --git a/seed/python-sdk/unions/union-utils/tests/utils/assets/models/__init__.py b/seed/python-sdk/unions/union-utils/tests/utils/assets/models/__init__.py index 2cf01263529..3a1c852e71e 100644 --- a/seed/python-sdk/unions/union-utils/tests/utils/assets/models/__init__.py +++ b/seed/python-sdk/unions/union-utils/tests/utils/assets/models/__init__.py @@ -5,7 +5,7 @@ from .circle import CircleParams from .object_with_defaults import ObjectWithDefaultsParams from .object_with_optional_field import ObjectWithOptionalFieldParams -from .shape import Shape_CircleParams, Shape_SquareParams, ShapeParams +from .shape import ShapeParams, Shape_CircleParams, Shape_SquareParams from .square import SquareParams from .undiscriminated_shape import UndiscriminatedShapeParams diff --git a/seed/python-sdk/unions/union-utils/tests/utils/assets/models/circle.py b/seed/python-sdk/unions/union-utils/tests/utils/assets/models/circle.py index af7a1bf8a8e..253f12d38b3 100644 --- a/seed/python-sdk/unions/union-utils/tests/utils/assets/models/circle.py +++ b/seed/python-sdk/unions/union-utils/tests/utils/assets/models/circle.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class CircleParams(typing_extensions.TypedDict): - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] diff --git a/seed/python-sdk/unions/union-utils/tests/utils/assets/models/object_with_optional_field.py b/seed/python-sdk/unions/union-utils/tests/utils/assets/models/object_with_optional_field.py index 3ad93d5f305..ebe7dc80547 100644 --- a/seed/python-sdk/unions/union-utils/tests/utils/assets/models/object_with_optional_field.py +++ b/seed/python-sdk/unions/union-utils/tests/utils/assets/models/object_with_optional_field.py @@ -7,8 +7,8 @@ import uuid import typing_extensions -from seed.core.serialization import FieldMetadata +from seed.core.serialization import FieldMetadata from .color import Color from .shape import ShapeParams from .undiscriminated_shape import UndiscriminatedShapeParams @@ -18,16 +18,30 @@ class ObjectWithOptionalFieldParams(typing_extensions.TypedDict): literal: typing.Literal["lit_one"] string: typing_extensions.NotRequired[str] integer: typing_extensions.NotRequired[int] - long_: typing_extensions.NotRequired[typing_extensions.Annotated[int, FieldMetadata(alias="long")]] + long_: typing_extensions.NotRequired[ + typing_extensions.Annotated[int, FieldMetadata(alias="long")] + ] double: typing_extensions.NotRequired[float] - bool_: typing_extensions.NotRequired[typing_extensions.Annotated[bool, FieldMetadata(alias="bool")]] + bool_: typing_extensions.NotRequired[ + typing_extensions.Annotated[bool, FieldMetadata(alias="bool")] + ] datetime: typing_extensions.NotRequired[dt.datetime] date: typing_extensions.NotRequired[dt.date] - uuid_: typing_extensions.NotRequired[typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")]] - base_64: typing_extensions.NotRequired[typing_extensions.Annotated[str, FieldMetadata(alias="base64")]] - list_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")]] - set_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")]] - map_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")]] + uuid_: typing_extensions.NotRequired[ + typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")] + ] + base_64: typing_extensions.NotRequired[ + typing_extensions.Annotated[str, FieldMetadata(alias="base64")] + ] + list_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")] + ] + set_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")] + ] + map_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")] + ] enum: typing_extensions.NotRequired[Color] union: typing_extensions.NotRequired[ShapeParams] second_union: typing_extensions.NotRequired[ShapeParams] diff --git a/seed/python-sdk/unions/union-utils/tests/utils/assets/models/shape.py b/seed/python-sdk/unions/union-utils/tests/utils/assets/models/shape.py index 2c33c877951..816ffc51bdc 100644 --- a/seed/python-sdk/unions/union-utils/tests/utils/assets/models/shape.py +++ b/seed/python-sdk/unions/union-utils/tests/utils/assets/models/shape.py @@ -7,6 +7,7 @@ import typing import typing_extensions + from seed.core.serialization import FieldMetadata @@ -15,13 +16,21 @@ class Base(typing_extensions.TypedDict): class Shape_CircleParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["circle"], FieldMetadata(alias="shapeType")] - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["circle"], FieldMetadata(alias="shapeType") + ] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] class Shape_SquareParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["square"], FieldMetadata(alias="shapeType")] - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["square"], FieldMetadata(alias="shapeType") + ] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] ShapeParams = typing.Union[Shape_CircleParams, Shape_SquareParams] diff --git a/seed/python-sdk/unions/union-utils/tests/utils/assets/models/square.py b/seed/python-sdk/unions/union-utils/tests/utils/assets/models/square.py index b9b7dd319bc..bcf08a723c5 100644 --- a/seed/python-sdk/unions/union-utils/tests/utils/assets/models/square.py +++ b/seed/python-sdk/unions/union-utils/tests/utils/assets/models/square.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class SquareParams(typing_extensions.TypedDict): - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] diff --git a/seed/python-sdk/unions/union-utils/tests/utils/test_http_client.py b/seed/python-sdk/unions/union-utils/tests/utils/test_http_client.py index edd11ca7afb..f5a874a75f3 100644 --- a/seed/python-sdk/unions/union-utils/tests/utils/test_http_client.py +++ b/seed/python-sdk/unions/union-utils/tests/utils/test_http_client.py @@ -9,12 +9,17 @@ def get_request_options() -> RequestOptions: def test_get_json_request_body() -> None: - json_body, data_body = get_request_body(json={"hello": "world"}, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json={"hello": "world"}, data=None, request_options=None, omit=None + ) assert json_body == {"hello": "world"} assert data_body is None json_body_extras, data_body_extras = get_request_body( - json={"goodbye": "world"}, data=None, request_options=get_request_options(), omit=None + json={"goodbye": "world"}, + data=None, + request_options=get_request_options(), + omit=None, ) assert json_body_extras == {"goodbye": "world", "see you": "later"} @@ -22,12 +27,17 @@ def test_get_json_request_body() -> None: def test_get_files_request_body() -> None: - json_body, data_body = get_request_body(json=None, data={"hello": "world"}, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data={"hello": "world"}, request_options=None, omit=None + ) assert data_body == {"hello": "world"} assert json_body is None json_body_extras, data_body_extras = get_request_body( - json=None, data={"goodbye": "world"}, request_options=get_request_options(), omit=None + json=None, + data={"goodbye": "world"}, + request_options=get_request_options(), + omit=None, ) assert data_body_extras == {"goodbye": "world", "see you": "later"} @@ -35,7 +45,9 @@ def test_get_files_request_body() -> None: def test_get_none_request_body() -> None: - json_body, data_body = get_request_body(json=None, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data=None, request_options=None, omit=None + ) assert data_body is None assert json_body is None diff --git a/seed/python-sdk/unions/union-utils/tests/utils/test_query_encoding.py b/seed/python-sdk/unions/union-utils/tests/utils/test_query_encoding.py index 247e1551b46..fbc8f402167 100644 --- a/seed/python-sdk/unions/union-utils/tests/utils/test_query_encoding.py +++ b/seed/python-sdk/unions/union-utils/tests/utils/test_query_encoding.py @@ -4,9 +4,15 @@ def test_query_encoding() -> None: - assert encode_query({"hello world": "hello world"}) == {"hello world": "hello world"} - assert encode_query({"hello_world": {"hello": "world"}}) == {"hello_world[hello]": "world"} - assert encode_query({"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"}) == { + assert encode_query({"hello world": "hello world"}) == { + "hello world": "hello world" + } + assert encode_query({"hello_world": {"hello": "world"}}) == { + "hello_world[hello]": "world" + } + assert encode_query( + {"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"} + ) == { "hello_world[hello][world]": "today", "hello_world[test]": "this", "hi": "there", diff --git a/seed/python-sdk/unions/union-utils/tests/utils/test_serialization.py b/seed/python-sdk/unions/union-utils/tests/utils/test_serialization.py index 58b1ed66e6d..5ca956916dd 100644 --- a/seed/python-sdk/unions/union-utils/tests/utils/test_serialization.py +++ b/seed/python-sdk/unions/union-utils/tests/utils/test_serialization.py @@ -1,10 +1,12 @@ # This file was auto-generated by Fern from our API Definition. -from typing import Any, List +from typing import List, Any -from seed.core.serialization import convert_and_respect_annotation_metadata +from seed.core.serialization import ( + convert_and_respect_annotation_metadata, +) +from .assets.models import ShapeParams, ObjectWithOptionalFieldParams -from .assets.models import ObjectWithOptionalFieldParams, ShapeParams UNION_TEST: ShapeParams = {"radius_measurement": 1.0, "shape_type": "circle", "id": "1"} UNION_TEST_CONVERTED = {"shapeType": "circle", "radiusMeasurement": 1.0, "id": "1"} @@ -18,20 +20,54 @@ def test_convert_and_respect_annotation_metadata() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) - assert converted == {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"} + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) + assert converted == { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + } def test_convert_and_respect_annotation_metadata_in_list() -> None: data: List[ObjectWithOptionalFieldParams] = [ - {"string": "string", "long_": 12345, "bool_": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long_": 67890, "list_": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long_": 12345, + "bool_": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long_": 67890, + "list_": [], + "literal": "lit_one", + "any": "any", + }, ] - converted = convert_and_respect_annotation_metadata(object_=data, annotation=List[ObjectWithOptionalFieldParams]) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=List[ObjectWithOptionalFieldParams] + ) assert converted == [ - {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long": 67890, "list": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long": 67890, + "list": [], + "literal": "lit_one", + "any": "any", + }, ] @@ -43,7 +79,9 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) assert converted == { "string": "string", @@ -55,12 +93,16 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: def test_convert_and_respect_annotation_metadata_in_union() -> None: - converted = convert_and_respect_annotation_metadata(object_=UNION_TEST, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=UNION_TEST, annotation=ShapeParams + ) assert converted == UNION_TEST_CONVERTED def test_convert_and_respect_annotation_metadata_with_empty_object() -> None: data: Any = {} - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ShapeParams + ) assert converted == data diff --git a/seed/python-sdk/unions/union_utils/src/seed/client.py b/seed/python-sdk/unions/union_utils/src/seed/client.py index afb1fe53a25..3bb7957b58c 100644 --- a/seed/python-sdk/unions/union_utils/src/seed/client.py +++ b/seed/python-sdk/unions/union_utils/src/seed/client.py @@ -41,14 +41,18 @@ def __init__( base_url: str, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.Client] = None + httpx_client: typing.Optional[httpx.Client] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = SyncClientWrapper( base_url=base_url, httpx_client=httpx_client if httpx_client is not None - else httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.Client( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.Client(timeout=_defaulted_timeout), timeout=_defaulted_timeout, @@ -89,14 +93,18 @@ def __init__( base_url: str, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.AsyncClient] = None + httpx_client: typing.Optional[httpx.AsyncClient] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = AsyncClientWrapper( base_url=base_url, httpx_client=httpx_client if httpx_client is not None - else httpx.AsyncClient(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.AsyncClient( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.AsyncClient(timeout=_defaulted_timeout), timeout=_defaulted_timeout, diff --git a/seed/python-sdk/unions/union_utils/src/seed/core/api_error.py b/seed/python-sdk/unions/union_utils/src/seed/core/api_error.py index 2e9fc5431cd..da734b58068 100644 --- a/seed/python-sdk/unions/union_utils/src/seed/core/api_error.py +++ b/seed/python-sdk/unions/union_utils/src/seed/core/api_error.py @@ -7,7 +7,9 @@ class ApiError(Exception): status_code: typing.Optional[int] body: typing.Any - def __init__(self, *, status_code: typing.Optional[int] = None, body: typing.Any = None): + def __init__( + self, *, status_code: typing.Optional[int] = None, body: typing.Any = None + ): self.status_code = status_code self.body = body diff --git a/seed/python-sdk/unions/union_utils/src/seed/core/client_wrapper.py b/seed/python-sdk/unions/union_utils/src/seed/core/client_wrapper.py index a12ded4d812..818d8bfe143 100644 --- a/seed/python-sdk/unions/union_utils/src/seed/core/client_wrapper.py +++ b/seed/python-sdk/unions/union_utils/src/seed/core/client_wrapper.py @@ -28,7 +28,13 @@ def get_timeout(self) -> typing.Optional[float]: class SyncClientWrapper(BaseClientWrapper): - def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, httpx_client: httpx.Client): + def __init__( + self, + *, + base_url: str, + timeout: typing.Optional[float] = None, + httpx_client: httpx.Client, + ): super().__init__(base_url=base_url, timeout=timeout) self.httpx_client = HttpClient( httpx_client=httpx_client, @@ -39,7 +45,13 @@ def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, htt class AsyncClientWrapper(BaseClientWrapper): - def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, httpx_client: httpx.AsyncClient): + def __init__( + self, + *, + base_url: str, + timeout: typing.Optional[float] = None, + httpx_client: httpx.AsyncClient, + ): super().__init__(base_url=base_url, timeout=timeout) self.httpx_client = AsyncHttpClient( httpx_client=httpx_client, diff --git a/seed/python-sdk/unions/union_utils/src/seed/core/datetime_utils.py b/seed/python-sdk/unions/union_utils/src/seed/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/python-sdk/unions/union_utils/src/seed/core/datetime_utils.py +++ b/seed/python-sdk/unions/union_utils/src/seed/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/python-sdk/unions/union_utils/src/seed/core/file.py b/seed/python-sdk/unions/union_utils/src/seed/core/file.py index cb0d40bbbf3..6e0f92bfcb1 100644 --- a/seed/python-sdk/unions/union_utils/src/seed/core/file.py +++ b/seed/python-sdk/unions/union_utils/src/seed/core/file.py @@ -13,12 +13,17 @@ # (filename, file (or bytes), content_type) typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str]], # (filename, file (or bytes), content_type, headers) - typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str], typing.Mapping[str, str]], + typing.Tuple[ + typing.Optional[str], + FileContent, + typing.Optional[str], + typing.Mapping[str, str], + ], ] def convert_file_dict_to_httpx_tuples( - d: typing.Dict[str, typing.Union[File, typing.List[File]]] + d: typing.Dict[str, typing.Union[File, typing.List[File]]], ) -> typing.List[typing.Tuple[str, File]]: """ The format we use is a list of tuples, where the first element is the diff --git a/seed/python-sdk/unions/union_utils/src/seed/core/http_client.py b/seed/python-sdk/unions/union_utils/src/seed/core/http_client.py index 8f8f6777085..5fc426e214a 100644 --- a/seed/python-sdk/unions/union_utils/src/seed/core/http_client.py +++ b/seed/python-sdk/unions/union_utils/src/seed/core/http_client.py @@ -76,7 +76,9 @@ def _retry_timeout(response: httpx.Response, retries: int) -> float: return retry_after # Apply exponential backoff, capped at MAX_RETRY_DELAY_SECONDS. - retry_delay = min(INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS) + retry_delay = min( + INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS + ) # Add a randomness / jitter to the retry delay to avoid overwhelming the server with retries. timeout = retry_delay * (1 - 0.25 * random()) @@ -89,7 +91,8 @@ def _should_retry(response: httpx.Response) -> bool: def remove_omit_from_dict( - original: typing.Dict[str, typing.Optional[typing.Any]], omit: typing.Optional[typing.Any] + original: typing.Dict[str, typing.Optional[typing.Any]], + omit: typing.Optional[typing.Any], ) -> typing.Dict[str, typing.Any]: if omit is None: return original @@ -138,7 +141,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url def request( @@ -150,8 +155,12 @@ def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -160,7 +169,8 @@ def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) @@ -172,7 +182,11 @@ def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -183,7 +197,9 @@ def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -196,11 +212,15 @@ def request( json=maybe_filter_request_body(json, request_options, omit), data=maybe_filter_request_body(data, request_options, omit), content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: time.sleep(_retry_timeout(response=response, retries=retries)) @@ -230,8 +250,12 @@ def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -240,7 +264,8 @@ def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) @@ -252,7 +277,11 @@ def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -263,7 +292,9 @@ def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -276,7 +307,9 @@ def stream( json=maybe_filter_request_body(json, request_options, omit), data=maybe_filter_request_body(data, request_options, omit), content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream @@ -299,7 +332,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url async def request( @@ -311,8 +346,12 @@ async def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -321,7 +360,8 @@ async def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) @@ -334,7 +374,11 @@ async def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -345,7 +389,9 @@ async def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -358,11 +404,15 @@ async def request( json=maybe_filter_request_body(json, request_options, omit), data=maybe_filter_request_body(data, request_options, omit), content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: await asyncio.sleep(_retry_timeout(response=response, retries=retries)) @@ -391,8 +441,12 @@ async def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -401,7 +455,8 @@ async def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) @@ -413,7 +468,11 @@ async def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -424,7 +483,9 @@ async def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -437,7 +498,9 @@ async def stream( json=maybe_filter_request_body(json, request_options, omit), data=maybe_filter_request_body(data, request_options, omit), content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream diff --git a/seed/python-sdk/unions/union_utils/src/seed/core/jsonable_encoder.py b/seed/python-sdk/unions/union_utils/src/seed/core/jsonable_encoder.py index 7f482732638..a4a3473ed1e 100644 --- a/seed/python-sdk/unions/union_utils/src/seed/core/jsonable_encoder.py +++ b/seed/python-sdk/unions/union_utils/src/seed/core/jsonable_encoder.py @@ -24,18 +24,24 @@ def generate_encoders_by_class_tuples( - type_encoder_map: Dict[Any, Callable[[Any], Any]] + type_encoder_map: Dict[Any, Callable[[Any], Any]], ) -> Dict[Callable[[Any], Any], Tuple[Any, ...]]: - encoders_by_class_tuples: Dict[Callable[[Any], Any], Tuple[Any, ...]] = defaultdict(tuple) + encoders_by_class_tuples: Dict[Callable[[Any], Any], Tuple[Any, ...]] = defaultdict( + tuple + ) for type_, encoder in type_encoder_map.items(): encoders_by_class_tuples[encoder] += (type_,) return encoders_by_class_tuples -encoders_by_class_tuples = generate_encoders_by_class_tuples(pydantic_v1.json.ENCODERS_BY_TYPE) +encoders_by_class_tuples = generate_encoders_by_class_tuples( + pydantic_v1.json.ENCODERS_BY_TYPE +) -def jsonable_encoder(obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None) -> Any: +def jsonable_encoder( + obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None +) -> Any: custom_encoder = custom_encoder or {} if custom_encoder: if type(obj) in custom_encoder: diff --git a/seed/python-sdk/unions/union_utils/src/seed/core/query_encoder.py b/seed/python-sdk/unions/union_utils/src/seed/core/query_encoder.py index 1f5f766b4a0..069633086ae 100644 --- a/seed/python-sdk/unions/union_utils/src/seed/core/query_encoder.py +++ b/seed/python-sdk/unions/union_utils/src/seed/core/query_encoder.py @@ -7,7 +7,9 @@ # Flattens dicts to be of the form {"key[subkey][subkey2]": value} where value is not a dict -def traverse_query_dict(dict_flat: Dict[str, Any], key_prefix: Optional[str] = None) -> Dict[str, Any]: +def traverse_query_dict( + dict_flat: Dict[str, Any], key_prefix: Optional[str] = None +) -> Dict[str, Any]: result = {} for k, v in dict_flat.items(): key = f"{key_prefix}[{k}]" if key_prefix is not None else k @@ -30,4 +32,8 @@ def single_query_encoder(query_key: str, query_value: Any) -> Dict[str, Any]: def encode_query(query: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: - return dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) if query is not None else None + return ( + dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) + if query is not None + else None + ) diff --git a/seed/python-sdk/unions/union_utils/src/seed/types/types/bar.py b/seed/python-sdk/unions/union_utils/src/seed/types/types/bar.py index 801ee184403..1faf58f5a4c 100644 --- a/seed/python-sdk/unions/union_utils/src/seed/types/types/bar.py +++ b/seed/python-sdk/unions/union_utils/src/seed/types/types/bar.py @@ -11,15 +11,28 @@ class Bar(pydantic_v1.BaseModel): name: str def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) class Config: diff --git a/seed/python-sdk/unions/union_utils/src/seed/types/types/foo.py b/seed/python-sdk/unions/union_utils/src/seed/types/types/foo.py index 5167cab0e13..d77b241d561 100644 --- a/seed/python-sdk/unions/union_utils/src/seed/types/types/foo.py +++ b/seed/python-sdk/unions/union_utils/src/seed/types/types/foo.py @@ -11,15 +11,28 @@ class Foo(pydantic_v1.BaseModel): name: str def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) class Config: diff --git a/seed/python-sdk/unions/union_utils/src/seed/types/types/union.py b/seed/python-sdk/unions/union_utils/src/seed/types/types/union.py index 82c405c4307..56a9ed0e0cb 100644 --- a/seed/python-sdk/unions/union_utils/src/seed/types/types/union.py +++ b/seed/python-sdk/unions/union_utils/src/seed/types/types/union.py @@ -43,18 +43,33 @@ def visit( if self.__root__.type == "bar": return bar(self.__root__.bar) - __root__: typing_extensions.Annotated[typing.Union[_Union.Foo, _Union.Bar], pydantic_v1.Field(discriminator="type")] + __root__: typing_extensions.Annotated[ + typing.Union[_Union.Foo, _Union.Bar], pydantic_v1.Field(discriminator="type") + ] def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) class Config: diff --git a/seed/python-sdk/unions/union_utils/src/seed/types/types/union_with_base_properties.py b/seed/python-sdk/unions/union_utils/src/seed/types/types/union_with_base_properties.py index 09d3f1ffc25..d520da634a7 100644 --- a/seed/python-sdk/unions/union_utils/src/seed/types/types/union_with_base_properties.py +++ b/seed/python-sdk/unions/union_utils/src/seed/types/types/union_with_base_properties.py @@ -16,14 +16,20 @@ class _Factory: def integer(self, value: int) -> UnionWithBaseProperties: - return UnionWithBaseProperties(__root__=_UnionWithBaseProperties.Integer(type="integer", value=value)) + return UnionWithBaseProperties( + __root__=_UnionWithBaseProperties.Integer(type="integer", value=value) + ) def string(self, value: str) -> UnionWithBaseProperties: - return UnionWithBaseProperties(__root__=_UnionWithBaseProperties.String(type="string", value=value)) + return UnionWithBaseProperties( + __root__=_UnionWithBaseProperties.String(type="string", value=value) + ) def foo(self, value: types_types_foo_Foo) -> UnionWithBaseProperties: return UnionWithBaseProperties( - __root__=_UnionWithBaseProperties.Foo(**value.dict(exclude_unset=True), type="foo") + __root__=_UnionWithBaseProperties.Foo( + **value.dict(exclude_unset=True), type="foo" + ) ) @@ -32,7 +38,11 @@ class UnionWithBaseProperties(pydantic_v1.BaseModel): def get_as_union( self, - ) -> typing.Union[_UnionWithBaseProperties.Integer, _UnionWithBaseProperties.String, _UnionWithBaseProperties.Foo]: + ) -> typing.Union[ + _UnionWithBaseProperties.Integer, + _UnionWithBaseProperties.String, + _UnionWithBaseProperties.Foo, + ]: return self.__root__ def visit( @@ -46,23 +56,44 @@ def visit( if self.__root__.type == "string": return string(self.__root__.value) if self.__root__.type == "foo": - return foo(types_types_foo_Foo(**self.__root__.dict(exclude_unset=True, exclude={"type"}))) + return foo( + types_types_foo_Foo( + **self.__root__.dict(exclude_unset=True, exclude={"type"}) + ) + ) __root__: typing_extensions.Annotated[ - typing.Union[_UnionWithBaseProperties.Integer, _UnionWithBaseProperties.String, _UnionWithBaseProperties.Foo], + typing.Union[ + _UnionWithBaseProperties.Integer, + _UnionWithBaseProperties.String, + _UnionWithBaseProperties.Foo, + ], pydantic_v1.Field(discriminator="type"), ] def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) class Config: diff --git a/seed/python-sdk/unions/union_utils/src/seed/types/types/union_with_discriminant.py b/seed/python-sdk/unions/union_utils/src/seed/types/types/union_with_discriminant.py index eedaa459342..443834e9c80 100644 --- a/seed/python-sdk/unions/union_utils/src/seed/types/types/union_with_discriminant.py +++ b/seed/python-sdk/unions/union_utils/src/seed/types/types/union_with_discriminant.py @@ -17,16 +17,22 @@ class _Factory: def foo(self, value: types_types_foo_Foo) -> UnionWithDiscriminant: - return UnionWithDiscriminant(__root__=_UnionWithDiscriminant.Foo(type="foo", foo=value)) + return UnionWithDiscriminant( + __root__=_UnionWithDiscriminant.Foo(type="foo", foo=value) + ) def bar(self, value: types_types_bar_Bar) -> UnionWithDiscriminant: - return UnionWithDiscriminant(__root__=_UnionWithDiscriminant.Bar(type="bar", bar=value)) + return UnionWithDiscriminant( + __root__=_UnionWithDiscriminant.Bar(type="bar", bar=value) + ) class UnionWithDiscriminant(pydantic_v1.BaseModel): factory: typing.ClassVar[_Factory] = _Factory() - def get_as_union(self) -> typing.Union[_UnionWithDiscriminant.Foo, _UnionWithDiscriminant.Bar]: + def get_as_union( + self, + ) -> typing.Union[_UnionWithDiscriminant.Foo, _UnionWithDiscriminant.Bar]: return self.__root__ def visit( @@ -40,19 +46,33 @@ def visit( return bar(self.__root__.bar) __root__: typing_extensions.Annotated[ - typing.Union[_UnionWithDiscriminant.Foo, _UnionWithDiscriminant.Bar], pydantic_v1.Field(discriminator="type") + typing.Union[_UnionWithDiscriminant.Foo, _UnionWithDiscriminant.Bar], + pydantic_v1.Field(discriminator="type"), ] def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) class Config: diff --git a/seed/python-sdk/unions/union_utils/src/seed/types/types/union_with_literal.py b/seed/python-sdk/unions/union_utils/src/seed/types/types/union_with_literal.py index f6a2cc73e16..1f7a4945ed1 100644 --- a/seed/python-sdk/unions/union_utils/src/seed/types/types/union_with_literal.py +++ b/seed/python-sdk/unions/union_utils/src/seed/types/types/union_with_literal.py @@ -13,7 +13,9 @@ class _Factory: def fern(self, value: typing.Literal["fern"]) -> UnionWithLiteral: - return UnionWithLiteral(__root__=_UnionWithLiteral.Fern(type="fern", value=value)) + return UnionWithLiteral( + __root__=_UnionWithLiteral.Fern(type="fern", value=value) + ) class UnionWithLiteral(pydantic_v1.BaseModel): @@ -22,22 +24,37 @@ class UnionWithLiteral(pydantic_v1.BaseModel): def get_as_union(self) -> _UnionWithLiteral.Fern: return self.__root__ - def visit(self, fern: typing.Callable[[typing.Literal["fern"]], T_Result]) -> T_Result: + def visit( + self, fern: typing.Callable[[typing.Literal["fern"]], T_Result] + ) -> T_Result: if self.__root__.type == "fern": return fern(self.__root__.value) __root__: _UnionWithLiteral.Fern def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) class Config: diff --git a/seed/python-sdk/unions/union_utils/src/seed/types/types/union_with_optional_time.py b/seed/python-sdk/unions/union_utils/src/seed/types/types/union_with_optional_time.py index eeed6f1277c..9ca1dd862e6 100644 --- a/seed/python-sdk/unions/union_utils/src/seed/types/types/union_with_optional_time.py +++ b/seed/python-sdk/unions/union_utils/src/seed/types/types/union_with_optional_time.py @@ -15,16 +15,22 @@ class _Factory: def date(self, value: typing.Optional[dt.date]) -> UnionWithOptionalTime: - return UnionWithOptionalTime(__root__=_UnionWithOptionalTime.Date(type="date", value=value)) + return UnionWithOptionalTime( + __root__=_UnionWithOptionalTime.Date(type="date", value=value) + ) def dateimte(self, value: typing.Optional[dt.datetime]) -> UnionWithOptionalTime: - return UnionWithOptionalTime(__root__=_UnionWithOptionalTime.Dateimte(type="dateimte", value=value)) + return UnionWithOptionalTime( + __root__=_UnionWithOptionalTime.Dateimte(type="dateimte", value=value) + ) class UnionWithOptionalTime(pydantic_v1.BaseModel): factory: typing.ClassVar[_Factory] = _Factory() - def get_as_union(self) -> typing.Union[_UnionWithOptionalTime.Date, _UnionWithOptionalTime.Dateimte]: + def get_as_union( + self, + ) -> typing.Union[_UnionWithOptionalTime.Date, _UnionWithOptionalTime.Dateimte]: return self.__root__ def visit( @@ -43,15 +49,28 @@ def visit( ] def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) class Config: diff --git a/seed/python-sdk/unions/union_utils/src/seed/types/types/union_with_primitive.py b/seed/python-sdk/unions/union_utils/src/seed/types/types/union_with_primitive.py index 73281c20ca5..a76f3df2201 100644 --- a/seed/python-sdk/unions/union_utils/src/seed/types/types/union_with_primitive.py +++ b/seed/python-sdk/unions/union_utils/src/seed/types/types/union_with_primitive.py @@ -15,38 +15,62 @@ class _Factory: def integer(self, value: int) -> UnionWithPrimitive: - return UnionWithPrimitive(__root__=_UnionWithPrimitive.Integer(type="integer", value=value)) + return UnionWithPrimitive( + __root__=_UnionWithPrimitive.Integer(type="integer", value=value) + ) def string(self, value: str) -> UnionWithPrimitive: - return UnionWithPrimitive(__root__=_UnionWithPrimitive.String(type="string", value=value)) + return UnionWithPrimitive( + __root__=_UnionWithPrimitive.String(type="string", value=value) + ) class UnionWithPrimitive(pydantic_v1.BaseModel): factory: typing.ClassVar[_Factory] = _Factory() - def get_as_union(self) -> typing.Union[_UnionWithPrimitive.Integer, _UnionWithPrimitive.String]: + def get_as_union( + self, + ) -> typing.Union[_UnionWithPrimitive.Integer, _UnionWithPrimitive.String]: return self.__root__ - def visit(self, integer: typing.Callable[[int], T_Result], string: typing.Callable[[str], T_Result]) -> T_Result: + def visit( + self, + integer: typing.Callable[[int], T_Result], + string: typing.Callable[[str], T_Result], + ) -> T_Result: if self.__root__.type == "integer": return integer(self.__root__.value) if self.__root__.type == "string": return string(self.__root__.value) __root__: typing_extensions.Annotated[ - typing.Union[_UnionWithPrimitive.Integer, _UnionWithPrimitive.String], pydantic_v1.Field(discriminator="type") + typing.Union[_UnionWithPrimitive.Integer, _UnionWithPrimitive.String], + pydantic_v1.Field(discriminator="type"), ] def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) class Config: diff --git a/seed/python-sdk/unions/union_utils/src/seed/types/types/union_with_single_element.py b/seed/python-sdk/unions/union_utils/src/seed/types/types/union_with_single_element.py index c645b9f4fa3..cf00d7b7966 100644 --- a/seed/python-sdk/unions/union_utils/src/seed/types/types/union_with_single_element.py +++ b/seed/python-sdk/unions/union_utils/src/seed/types/types/union_with_single_element.py @@ -15,7 +15,9 @@ class _Factory: def foo(self, value: types_types_foo_Foo) -> UnionWithSingleElement: return UnionWithSingleElement( - __root__=_UnionWithSingleElement.Foo(**value.dict(exclude_unset=True), type="foo") + __root__=_UnionWithSingleElement.Foo( + **value.dict(exclude_unset=True), type="foo" + ) ) @@ -27,20 +29,37 @@ def get_as_union(self) -> _UnionWithSingleElement.Foo: def visit(self, foo: typing.Callable[[types_types_foo_Foo], T_Result]) -> T_Result: if self.__root__.type == "foo": - return foo(types_types_foo_Foo(**self.__root__.dict(exclude_unset=True, exclude={"type"}))) + return foo( + types_types_foo_Foo( + **self.__root__.dict(exclude_unset=True, exclude={"type"}) + ) + ) __root__: _UnionWithSingleElement.Foo def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) class Config: diff --git a/seed/python-sdk/unions/union_utils/src/seed/types/types/union_with_time.py b/seed/python-sdk/unions/union_utils/src/seed/types/types/union_with_time.py index 0da378b2d43..66311a5d29b 100644 --- a/seed/python-sdk/unions/union_utils/src/seed/types/types/union_with_time.py +++ b/seed/python-sdk/unions/union_utils/src/seed/types/types/union_with_time.py @@ -21,13 +21,19 @@ def date(self, value: dt.date) -> UnionWithTime: return UnionWithTime(__root__=_UnionWithTime.Date(type="date", value=value)) def datetime(self, value: dt.datetime) -> UnionWithTime: - return UnionWithTime(__root__=_UnionWithTime.Datetime(type="datetime", value=value)) + return UnionWithTime( + __root__=_UnionWithTime.Datetime(type="datetime", value=value) + ) class UnionWithTime(pydantic_v1.BaseModel): factory: typing.ClassVar[_Factory] = _Factory() - def get_as_union(self) -> typing.Union[_UnionWithTime.Value, _UnionWithTime.Date, _UnionWithTime.Datetime]: + def get_as_union( + self, + ) -> typing.Union[ + _UnionWithTime.Value, _UnionWithTime.Date, _UnionWithTime.Datetime + ]: return self.__root__ def visit( @@ -44,20 +50,35 @@ def visit( return datetime(self.__root__.value) __root__: typing_extensions.Annotated[ - typing.Union[_UnionWithTime.Value, _UnionWithTime.Date, _UnionWithTime.Datetime], + typing.Union[ + _UnionWithTime.Value, _UnionWithTime.Date, _UnionWithTime.Datetime + ], pydantic_v1.Field(discriminator="type"), ] def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) class Config: diff --git a/seed/python-sdk/unions/union_utils/src/seed/types/types/union_with_unknown.py b/seed/python-sdk/unions/union_utils/src/seed/types/types/union_with_unknown.py index 1672bbdc4a2..2e7aa8e3b83 100644 --- a/seed/python-sdk/unions/union_utils/src/seed/types/types/union_with_unknown.py +++ b/seed/python-sdk/unions/union_utils/src/seed/types/types/union_with_unknown.py @@ -16,7 +16,9 @@ class _Factory: def foo(self, value: types_types_foo_Foo) -> UnionWithUnknown: - return UnionWithUnknown(__root__=_UnionWithUnknown.Foo(**value.dict(exclude_unset=True), type="foo")) + return UnionWithUnknown( + __root__=_UnionWithUnknown.Foo(**value.dict(exclude_unset=True), type="foo") + ) def unknown(self) -> UnionWithUnknown: return UnionWithUnknown(__root__=_UnionWithUnknown.Unknown(type="unknown")) @@ -25,31 +27,53 @@ def unknown(self) -> UnionWithUnknown: class UnionWithUnknown(pydantic_v1.BaseModel): factory: typing.ClassVar[_Factory] = _Factory() - def get_as_union(self) -> typing.Union[_UnionWithUnknown.Foo, _UnionWithUnknown.Unknown]: + def get_as_union( + self, + ) -> typing.Union[_UnionWithUnknown.Foo, _UnionWithUnknown.Unknown]: return self.__root__ def visit( - self, foo: typing.Callable[[types_types_foo_Foo], T_Result], unknown: typing.Callable[[], T_Result] + self, + foo: typing.Callable[[types_types_foo_Foo], T_Result], + unknown: typing.Callable[[], T_Result], ) -> T_Result: if self.__root__.type == "foo": - return foo(types_types_foo_Foo(**self.__root__.dict(exclude_unset=True, exclude={"type"}))) + return foo( + types_types_foo_Foo( + **self.__root__.dict(exclude_unset=True, exclude={"type"}) + ) + ) if self.__root__.type == "unknown": return unknown() __root__: typing_extensions.Annotated[ - typing.Union[_UnionWithUnknown.Foo, _UnionWithUnknown.Unknown], pydantic_v1.Field(discriminator="type") + typing.Union[_UnionWithUnknown.Foo, _UnionWithUnknown.Unknown], + pydantic_v1.Field(discriminator="type"), ] def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) class Config: diff --git a/seed/python-sdk/unions/union_utils/src/seed/types/types/union_without_key.py b/seed/python-sdk/unions/union_utils/src/seed/types/types/union_without_key.py index c0510fd1e6e..261619c2a47 100644 --- a/seed/python-sdk/unions/union_utils/src/seed/types/types/union_without_key.py +++ b/seed/python-sdk/unions/union_utils/src/seed/types/types/union_without_key.py @@ -17,10 +17,14 @@ class _Factory: def foo(self, value: types_types_foo_Foo) -> UnionWithoutKey: - return UnionWithoutKey(__root__=_UnionWithoutKey.Foo(**value.dict(exclude_unset=True), type="foo")) + return UnionWithoutKey( + __root__=_UnionWithoutKey.Foo(**value.dict(exclude_unset=True), type="foo") + ) def bar(self, value: types_types_bar_Bar) -> UnionWithoutKey: - return UnionWithoutKey(__root__=_UnionWithoutKey.Bar(**value.dict(exclude_unset=True), type="bar")) + return UnionWithoutKey( + __root__=_UnionWithoutKey.Bar(**value.dict(exclude_unset=True), type="bar") + ) class UnionWithoutKey(pydantic_v1.BaseModel): @@ -35,24 +39,46 @@ def visit( bar: typing.Callable[[types_types_bar_Bar], T_Result], ) -> T_Result: if self.__root__.type == "foo": - return foo(types_types_foo_Foo(**self.__root__.dict(exclude_unset=True, exclude={"type"}))) + return foo( + types_types_foo_Foo( + **self.__root__.dict(exclude_unset=True, exclude={"type"}) + ) + ) if self.__root__.type == "bar": - return bar(types_types_bar_Bar(**self.__root__.dict(exclude_unset=True, exclude={"type"}))) + return bar( + types_types_bar_Bar( + **self.__root__.dict(exclude_unset=True, exclude={"type"}) + ) + ) __root__: typing_extensions.Annotated[ - typing.Union[_UnionWithoutKey.Foo, _UnionWithoutKey.Bar], pydantic_v1.Field(discriminator="type") + typing.Union[_UnionWithoutKey.Foo, _UnionWithoutKey.Bar], + pydantic_v1.Field(discriminator="type"), ] def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) class Config: diff --git a/seed/python-sdk/unions/union_utils/src/seed/union/client.py b/seed/python-sdk/unions/union_utils/src/seed/union/client.py index 4edd47080c0..76feae2ae4c 100644 --- a/seed/python-sdk/unions/union_utils/src/seed/union/client.py +++ b/seed/python-sdk/unions/union_utils/src/seed/union/client.py @@ -18,7 +18,9 @@ class UnionClient: def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper - def get(self, id: str, *, request_options: typing.Optional[RequestOptions] = None) -> Shape: + def get( + self, id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> Shape: """ Parameters ---------- @@ -53,7 +55,9 @@ def get(self, id: str, *, request_options: typing.Optional[RequestOptions] = Non raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - def update(self, *, request: Shape, request_options: typing.Optional[RequestOptions] = None) -> bool: + def update( + self, *, request: Shape, request_options: typing.Optional[RequestOptions] = None + ) -> bool: """ Parameters ---------- @@ -97,7 +101,9 @@ class AsyncUnionClient: def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper - async def get(self, id: str, *, request_options: typing.Optional[RequestOptions] = None) -> Shape: + async def get( + self, id: str, *, request_options: typing.Optional[RequestOptions] = None + ) -> Shape: """ Parameters ---------- @@ -132,7 +138,9 @@ async def get(self, id: str, *, request_options: typing.Optional[RequestOptions] raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) - async def update(self, *, request: Shape, request_options: typing.Optional[RequestOptions] = None) -> bool: + async def update( + self, *, request: Shape, request_options: typing.Optional[RequestOptions] = None + ) -> bool: """ Parameters ---------- diff --git a/seed/python-sdk/unions/union_utils/src/seed/union/types/circle.py b/seed/python-sdk/unions/union_utils/src/seed/union/types/circle.py index e02dff86132..eb6c8d5635f 100644 --- a/seed/python-sdk/unions/union_utils/src/seed/union/types/circle.py +++ b/seed/python-sdk/unions/union_utils/src/seed/union/types/circle.py @@ -11,15 +11,28 @@ class Circle(pydantic_v1.BaseModel): radius: float def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) class Config: diff --git a/seed/python-sdk/unions/union_utils/src/seed/union/types/get_shape_request.py b/seed/python-sdk/unions/union_utils/src/seed/union/types/get_shape_request.py index 243ffb5d4b1..98c07587769 100644 --- a/seed/python-sdk/unions/union_utils/src/seed/union/types/get_shape_request.py +++ b/seed/python-sdk/unions/union_utils/src/seed/union/types/get_shape_request.py @@ -11,15 +11,28 @@ class GetShapeRequest(pydantic_v1.BaseModel): id: str def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) class Config: diff --git a/seed/python-sdk/unions/union_utils/src/seed/union/types/shape.py b/seed/python-sdk/unions/union_utils/src/seed/union/types/shape.py index ab5f3986589..778c265aa78 100644 --- a/seed/python-sdk/unions/union_utils/src/seed/union/types/shape.py +++ b/seed/python-sdk/unions/union_utils/src/seed/union/types/shape.py @@ -17,10 +17,14 @@ class _Factory: def circle(self, value: union_types_circle_Circle) -> Shape: - return Shape(__root__=_Shape.Circle(**value.dict(exclude_unset=True), type="circle")) + return Shape( + __root__=_Shape.Circle(**value.dict(exclude_unset=True), type="circle") + ) def square(self, value: union_types_square_Square) -> Shape: - return Shape(__root__=_Shape.Square(**value.dict(exclude_unset=True), type="square")) + return Shape( + __root__=_Shape.Square(**value.dict(exclude_unset=True), type="square") + ) class Shape(pydantic_v1.BaseModel): @@ -35,24 +39,46 @@ def visit( square: typing.Callable[[union_types_square_Square], T_Result], ) -> T_Result: if self.__root__.type == "circle": - return circle(union_types_circle_Circle(**self.__root__.dict(exclude_unset=True, exclude={"type"}))) + return circle( + union_types_circle_Circle( + **self.__root__.dict(exclude_unset=True, exclude={"type"}) + ) + ) if self.__root__.type == "square": - return square(union_types_square_Square(**self.__root__.dict(exclude_unset=True, exclude={"type"}))) + return square( + union_types_square_Square( + **self.__root__.dict(exclude_unset=True, exclude={"type"}) + ) + ) __root__: typing_extensions.Annotated[ - typing.Union[_Shape.Circle, _Shape.Square], pydantic_v1.Field(discriminator="type") + typing.Union[_Shape.Circle, _Shape.Square], + pydantic_v1.Field(discriminator="type"), ] def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) class Config: diff --git a/seed/python-sdk/unions/union_utils/src/seed/union/types/square.py b/seed/python-sdk/unions/union_utils/src/seed/union/types/square.py index 1c011016588..32a14671dd8 100644 --- a/seed/python-sdk/unions/union_utils/src/seed/union/types/square.py +++ b/seed/python-sdk/unions/union_utils/src/seed/union/types/square.py @@ -11,15 +11,28 @@ class Square(pydantic_v1.BaseModel): length: float def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) class Config: diff --git a/seed/python-sdk/unions/union_utils/src/seed/version.py b/seed/python-sdk/unions/union_utils/src/seed/version.py index 123bebe735d..7b884a244da 100644 --- a/seed/python-sdk/unions/union_utils/src/seed/version.py +++ b/seed/python-sdk/unions/union_utils/src/seed/version.py @@ -1,4 +1,3 @@ - from importlib import metadata __version__ = metadata.version("fern_unions") diff --git a/seed/python-sdk/unions/union_utils/tests/custom/test_client.py b/seed/python-sdk/unions/union_utils/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/python-sdk/unions/union_utils/tests/custom/test_client.py +++ b/seed/python-sdk/unions/union_utils/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/python-sdk/unions/union_utils/tests/test_union.py b/seed/python-sdk/unions/union_utils/tests/test_union.py index c1a6a71a56c..dfdb5c7335e 100644 --- a/seed/python-sdk/unions/union_utils/tests/test_union.py +++ b/seed/python-sdk/unions/union_utils/tests/test_union.py @@ -24,5 +24,7 @@ async def test_update(client: SeedUnions, async_client: AsyncSeedUnions) -> None response = client.union.update(request=Shape_Circle(id="string", radius=1.1)) validate_response(response, expected_response, expected_types) - async_response = await async_client.union.update(request=Shape_Circle(id="string", radius=1.1)) + async_response = await async_client.union.update( + request=Shape_Circle(id="string", radius=1.1) + ) validate_response(async_response, expected_response, expected_types) diff --git a/seed/python-sdk/unions/union_utils/tests/utilities.py b/seed/python-sdk/unions/union_utils/tests/utilities.py index 402ee790bb8..27ae3c99b93 100644 --- a/seed/python-sdk/unions/union_utils/tests/utilities.py +++ b/seed/python-sdk/unions/union_utils/tests/utilities.py @@ -14,7 +14,9 @@ import pydantic as pydantic_v1 # type: ignore # nopycln: import -def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> typing.Any: +def cast_field( + json_expectation: typing.Any, type_expectation: typing.Any +) -> typing.Any: # Cast these specific types which come through as string and expect our # models to cast to the correct type. if type_expectation == "uuid": @@ -32,7 +34,9 @@ def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> ty return json_expectation -def validate_field(response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any) -> None: +def validate_field( + response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectation == "no_validate": return @@ -51,7 +55,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(entry_expectation, dict): is_container_of_complex_type = True validate_response( - response=response[idx], json_expectation=ex, type_expectations=entry_expectation + response=response[idx], + json_expectation=ex, + type_expectations=entry_expectation, ) else: cast_json_expectation.append(cast_field(ex, entry_expectation)) @@ -63,7 +69,10 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # if any of the values of the set have a type_expectation of a dict, we're assuming it's a pydantic # model and keeping it a list. if container_expectation != "set" or not any( - map(lambda value: isinstance(value, dict), list(contents_expectation.values())) + map( + lambda value: isinstance(value, dict), + list(contents_expectation.values()), + ) ): json_expectation = cast_field(json_expectation, container_expectation) elif isinstance(type_expectation, tuple): @@ -72,9 +81,15 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(contents_expectation, dict): json_expectation = { cast_field( - key, contents_expectation.get(idx)[0] if contents_expectation.get(idx) is not None else None # type: ignore + key, + contents_expectation.get(idx)[0] + if contents_expectation.get(idx) is not None + else None, # type: ignore ): cast_field( - value, contents_expectation.get(idx)[1] if contents_expectation.get(idx) is not None else None # type: ignore + value, + contents_expectation.get(idx)[1] + if contents_expectation.get(idx) is not None + else None, # type: ignore ) for idx, (key, value) in enumerate(json_expectation.items()) } @@ -85,19 +100,29 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # When dealing with containers of models, etc. we're validating them implicitly, so no need to check the resultant list if not is_container_of_complex_type: - assert json_expectation == response, "Primitives found, expected: {0}, Actual: {1}".format( + assert ( + json_expectation == response + ), "Primitives found, expected: {0}, Actual: {1}".format( json_expectation, response ) # Arg type_expectations is a deeply nested structure that matches the response, but with the values replaced with the expected types -def validate_response(response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any) -> None: +def validate_response( + response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectations == "no_validate": return - if not isinstance(response, dict) and not issubclass(type(response), pydantic_v1.BaseModel): - validate_field(response=response, json_expectation=json_expectation, type_expectation=type_expectations) + if not isinstance(response, dict) and not issubclass( + type(response), pydantic_v1.BaseModel + ): + validate_field( + response=response, + json_expectation=json_expectation, + type_expectation=type_expectations, + ) return response_json = response @@ -105,7 +130,11 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e response_json = response.dict(by_alias=True) for key, value in json_expectation.items(): - assert key in response_json, "Field {0} not found within the response object: {1}".format(key, response_json) + assert ( + key in response_json + ), "Field {0} not found within the response object: {1}".format( + key, response_json + ) type_expectation = None if type_expectations is not None and isinstance(type_expectations, dict): @@ -114,10 +143,20 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e # If your type_expectation is a tuple then you have a container field, process it as such # Otherwise, we're just validating a single field that's a pydantic model. if isinstance(value, dict) and not isinstance(type_expectation, tuple): - validate_response(response=response_json[key], json_expectation=value, type_expectations=type_expectation) + validate_response( + response=response_json[key], + json_expectation=value, + type_expectations=type_expectation, + ) else: - validate_field(response=response_json[key], json_expectation=value, type_expectation=type_expectation) + validate_field( + response=response_json[key], + json_expectation=value, + type_expectation=type_expectation, + ) # Ensure there are no additional fields here either del response_json[key] - assert len(response_json) == 0, "Additional fields found, expected None: {0}".format(response_json) + assert ( + len(response_json) == 0 + ), "Additional fields found, expected None: {0}".format(response_json) diff --git a/seed/python-sdk/unknown/pyproject.toml b/seed/python-sdk/unknown/pyproject.toml index a73ec4113a0..fc2c7c00c82 100644 --- a/seed/python-sdk/unknown/pyproject.toml +++ b/seed/python-sdk/unknown/pyproject.toml @@ -43,6 +43,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/python-sdk/unknown/src/seed/__init__.py b/seed/python-sdk/unknown/src/seed/__init__.py index 3112ec636b1..f3a0165b68a 100644 --- a/seed/python-sdk/unknown/src/seed/__init__.py +++ b/seed/python-sdk/unknown/src/seed/__init__.py @@ -5,4 +5,11 @@ from .unknown import MyAlias, MyObject from .version import __version__ -__all__ = ["AsyncSeedUnknownAsAny", "MyAlias", "MyObject", "SeedUnknownAsAny", "__version__", "unknown"] +__all__ = [ + "AsyncSeedUnknownAsAny", + "MyAlias", + "MyObject", + "SeedUnknownAsAny", + "__version__", + "unknown", +] diff --git a/seed/python-sdk/unknown/src/seed/client.py b/seed/python-sdk/unknown/src/seed/client.py index 1ef0fca1cde..7515e411f8c 100644 --- a/seed/python-sdk/unknown/src/seed/client.py +++ b/seed/python-sdk/unknown/src/seed/client.py @@ -1,11 +1,11 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from .unknown.client import AsyncUnknownClient, UnknownClient +from .core.client_wrapper import SyncClientWrapper +from .unknown.client import UnknownClient +from .core.client_wrapper import AsyncClientWrapper +from .unknown.client import AsyncUnknownClient class SeedUnknownAsAny: @@ -41,14 +41,18 @@ def __init__( base_url: str, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.Client] = None + httpx_client: typing.Optional[httpx.Client] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = SyncClientWrapper( base_url=base_url, httpx_client=httpx_client if httpx_client is not None - else httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.Client( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.Client(timeout=_defaulted_timeout), timeout=_defaulted_timeout, @@ -89,14 +93,18 @@ def __init__( base_url: str, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.AsyncClient] = None + httpx_client: typing.Optional[httpx.AsyncClient] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = AsyncClientWrapper( base_url=base_url, httpx_client=httpx_client if httpx_client is not None - else httpx.AsyncClient(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.AsyncClient( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.AsyncClient(timeout=_defaulted_timeout), timeout=_defaulted_timeout, diff --git a/seed/python-sdk/unknown/src/seed/core/api_error.py b/seed/python-sdk/unknown/src/seed/core/api_error.py index 2e9fc5431cd..da734b58068 100644 --- a/seed/python-sdk/unknown/src/seed/core/api_error.py +++ b/seed/python-sdk/unknown/src/seed/core/api_error.py @@ -7,7 +7,9 @@ class ApiError(Exception): status_code: typing.Optional[int] body: typing.Any - def __init__(self, *, status_code: typing.Optional[int] = None, body: typing.Any = None): + def __init__( + self, *, status_code: typing.Optional[int] = None, body: typing.Any = None + ): self.status_code = status_code self.body = body diff --git a/seed/python-sdk/unknown/src/seed/core/client_wrapper.py b/seed/python-sdk/unknown/src/seed/core/client_wrapper.py index 12e235ac7e0..29b038abd4d 100644 --- a/seed/python-sdk/unknown/src/seed/core/client_wrapper.py +++ b/seed/python-sdk/unknown/src/seed/core/client_wrapper.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .http_client import AsyncHttpClient, HttpClient +from .http_client import HttpClient +from .http_client import AsyncHttpClient class BaseClientWrapper: @@ -28,7 +27,13 @@ def get_timeout(self) -> typing.Optional[float]: class SyncClientWrapper(BaseClientWrapper): - def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, httpx_client: httpx.Client): + def __init__( + self, + *, + base_url: str, + timeout: typing.Optional[float] = None, + httpx_client: httpx.Client, + ): super().__init__(base_url=base_url, timeout=timeout) self.httpx_client = HttpClient( httpx_client=httpx_client, @@ -39,7 +44,13 @@ def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, htt class AsyncClientWrapper(BaseClientWrapper): - def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, httpx_client: httpx.AsyncClient): + def __init__( + self, + *, + base_url: str, + timeout: typing.Optional[float] = None, + httpx_client: httpx.AsyncClient, + ): super().__init__(base_url=base_url, timeout=timeout) self.httpx_client = AsyncHttpClient( httpx_client=httpx_client, diff --git a/seed/python-sdk/unknown/src/seed/core/datetime_utils.py b/seed/python-sdk/unknown/src/seed/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/python-sdk/unknown/src/seed/core/datetime_utils.py +++ b/seed/python-sdk/unknown/src/seed/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/python-sdk/unknown/src/seed/core/file.py b/seed/python-sdk/unknown/src/seed/core/file.py index cb0d40bbbf3..6e0f92bfcb1 100644 --- a/seed/python-sdk/unknown/src/seed/core/file.py +++ b/seed/python-sdk/unknown/src/seed/core/file.py @@ -13,12 +13,17 @@ # (filename, file (or bytes), content_type) typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str]], # (filename, file (or bytes), content_type, headers) - typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str], typing.Mapping[str, str]], + typing.Tuple[ + typing.Optional[str], + FileContent, + typing.Optional[str], + typing.Mapping[str, str], + ], ] def convert_file_dict_to_httpx_tuples( - d: typing.Dict[str, typing.Union[File, typing.List[File]]] + d: typing.Dict[str, typing.Union[File, typing.List[File]]], ) -> typing.List[typing.Tuple[str, File]]: """ The format we use is a list of tuples, where the first element is the diff --git a/seed/python-sdk/unknown/src/seed/core/http_client.py b/seed/python-sdk/unknown/src/seed/core/http_client.py index 9333d8a7f15..091f71bc185 100644 --- a/seed/python-sdk/unknown/src/seed/core/http_client.py +++ b/seed/python-sdk/unknown/src/seed/core/http_client.py @@ -77,7 +77,9 @@ def _retry_timeout(response: httpx.Response, retries: int) -> float: return retry_after # Apply exponential backoff, capped at MAX_RETRY_DELAY_SECONDS. - retry_delay = min(INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS) + retry_delay = min( + INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS + ) # Add a randomness / jitter to the retry delay to avoid overwhelming the server with retries. timeout = retry_delay * (1 - 0.25 * random()) @@ -90,7 +92,8 @@ def _should_retry(response: httpx.Response) -> bool: def remove_omit_from_dict( - original: typing.Dict[str, typing.Optional[typing.Any]], omit: typing.Optional[typing.Any] + original: typing.Dict[str, typing.Optional[typing.Any]], + omit: typing.Optional[typing.Any], ) -> typing.Dict[str, typing.Any]: if omit is None: return original @@ -108,7 +111,8 @@ def maybe_filter_request_body( ) -> typing.Optional[typing.Any]: if data is None: return ( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else None ) @@ -118,7 +122,8 @@ def maybe_filter_request_body( data_content = { **(jsonable_encoder(remove_omit_from_dict(data, omit))), # type: ignore **( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else {} ), @@ -162,7 +167,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url def request( @@ -174,8 +181,12 @@ def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -184,11 +195,14 @@ def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) response = self.httpx_client.request( method=method, @@ -198,7 +212,11 @@ def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -209,7 +227,10 @@ def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -222,11 +243,15 @@ def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: time.sleep(_retry_timeout(response=response, retries=retries)) @@ -256,8 +281,12 @@ def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -266,11 +295,14 @@ def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) with self.httpx_client.stream( method=method, @@ -280,7 +312,11 @@ def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -291,7 +327,9 @@ def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -304,7 +342,9 @@ def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream @@ -327,7 +367,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url async def request( @@ -339,8 +381,12 @@ async def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -349,11 +395,14 @@ async def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) # Add the input to each of these and do None-safety checks response = await self.httpx_client.request( @@ -364,7 +413,11 @@ async def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -375,7 +428,10 @@ async def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -388,11 +444,15 @@ async def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: await asyncio.sleep(_retry_timeout(response=response, retries=retries)) @@ -421,8 +481,12 @@ async def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -431,11 +495,14 @@ async def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) async with self.httpx_client.stream( method=method, @@ -445,7 +512,11 @@ async def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -456,7 +527,9 @@ async def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -469,7 +542,9 @@ async def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream diff --git a/seed/python-sdk/unknown/src/seed/core/jsonable_encoder.py b/seed/python-sdk/unknown/src/seed/core/jsonable_encoder.py index d3fd328fd41..12a8b52fc22 100644 --- a/seed/python-sdk/unknown/src/seed/core/jsonable_encoder.py +++ b/seed/python-sdk/unknown/src/seed/core/jsonable_encoder.py @@ -19,13 +19,19 @@ import pydantic from .datetime_utils import serialize_datetime -from .pydantic_utilities import IS_PYDANTIC_V2, encode_by_type, to_jsonable_with_fallback +from .pydantic_utilities import ( + IS_PYDANTIC_V2, + encode_by_type, + to_jsonable_with_fallback, +) SetIntStr = Set[Union[int, str]] DictIntStrAny = Dict[Union[int, str], Any] -def jsonable_encoder(obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None) -> Any: +def jsonable_encoder( + obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None +) -> Any: custom_encoder = custom_encoder or {} if custom_encoder: if type(obj) in custom_encoder: diff --git a/seed/python-sdk/unknown/src/seed/core/pydantic_utilities.py b/seed/python-sdk/unknown/src/seed/core/pydantic_utilities.py index 170a563d6eb..c63935c32a2 100644 --- a/seed/python-sdk/unknown/src/seed/core/pydantic_utilities.py +++ b/seed/python-sdk/unknown/src/seed/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) # type: ignore # Pydantic v1 diff --git a/seed/python-sdk/unknown/src/seed/core/query_encoder.py b/seed/python-sdk/unknown/src/seed/core/query_encoder.py index 24076d72ee9..7cb98f52cd7 100644 --- a/seed/python-sdk/unknown/src/seed/core/query_encoder.py +++ b/seed/python-sdk/unknown/src/seed/core/query_encoder.py @@ -7,7 +7,9 @@ # Flattens dicts to be of the form {"key[subkey][subkey2]": value} where value is not a dict -def traverse_query_dict(dict_flat: Dict[str, Any], key_prefix: Optional[str] = None) -> Dict[str, Any]: +def traverse_query_dict( + dict_flat: Dict[str, Any], key_prefix: Optional[str] = None +) -> Dict[str, Any]: result = {} for k, v in dict_flat.items(): key = f"{key_prefix}[{k}]" if key_prefix is not None else k @@ -30,4 +32,8 @@ def single_query_encoder(query_key: str, query_value: Any) -> Dict[str, Any]: def encode_query(query: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: - return dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) if query is not None else None + return ( + dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) + if query is not None + else None + ) diff --git a/seed/python-sdk/unknown/src/seed/core/serialization.py b/seed/python-sdk/unknown/src/seed/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/python-sdk/unknown/src/seed/core/serialization.py +++ b/seed/python-sdk/unknown/src/seed/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/python-sdk/unknown/src/seed/unknown/client.py b/seed/python-sdk/unknown/src/seed/unknown/client.py index 22926ec91dd..98f0706f205 100644 --- a/seed/python-sdk/unknown/src/seed/unknown/client.py +++ b/seed/python-sdk/unknown/src/seed/unknown/client.py @@ -1,12 +1,12 @@ # This file was auto-generated by Fern from our API Definition. import typing +from ..core.client_wrapper import SyncClientWrapper +from ..core.request_options import RequestOptions +from ..core.pydantic_utilities import parse_obj_as from json.decoder import JSONDecodeError - from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.pydantic_utilities import parse_obj_as -from ..core.request_options import RequestOptions +from ..core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -17,7 +17,10 @@ def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper def post( - self, *, request: typing.Any, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Any, + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[typing.Any]: """ Parameters @@ -43,11 +46,19 @@ def post( ) """ _response = self._client_wrapper.httpx_client.request( - method="POST", json=request, request_options=request_options, omit=OMIT + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.List[typing.Any], parse_obj_as(type_=typing.List[typing.Any], object_=_response.json())) # type: ignore + return typing.cast( + typing.List[typing.Any], + parse_obj_as( + type_=typing.List[typing.Any], object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -59,7 +70,10 @@ def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper async def post( - self, *, request: typing.Any, request_options: typing.Optional[RequestOptions] = None + self, + *, + request: typing.Any, + request_options: typing.Optional[RequestOptions] = None, ) -> typing.List[typing.Any]: """ Parameters @@ -93,11 +107,19 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - method="POST", json=request, request_options=request_options, omit=OMIT + method="POST", + json=request, + request_options=request_options, + omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(typing.List[typing.Any], parse_obj_as(type_=typing.List[typing.Any], object_=_response.json())) # type: ignore + return typing.cast( + typing.List[typing.Any], + parse_obj_as( + type_=typing.List[typing.Any], object_=_response.json() + ), + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/unknown/src/seed/unknown/types/my_object.py b/seed/python-sdk/unknown/src/seed/unknown/types/my_object.py index a5c7cc10c24..184f559c67d 100644 --- a/seed/python-sdk/unknown/src/seed/unknown/types/my_object.py +++ b/seed/python-sdk/unknown/src/seed/unknown/types/my_object.py @@ -1,17 +1,18 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel import typing - +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel - class MyObject(UniversalBaseModel): unknown: typing.Any if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/unknown/src/seed/version.py b/seed/python-sdk/unknown/src/seed/version.py index 43d8c2d9f9a..0880db3083b 100644 --- a/seed/python-sdk/unknown/src/seed/version.py +++ b/seed/python-sdk/unknown/src/seed/version.py @@ -1,4 +1,3 @@ - from importlib import metadata __version__ = metadata.version("fern_unknown") diff --git a/seed/python-sdk/unknown/tests/conftest.py b/seed/python-sdk/unknown/tests/conftest.py index 41ff3ac52a1..7f831aa4594 100644 --- a/seed/python-sdk/unknown/tests/conftest.py +++ b/seed/python-sdk/unknown/tests/conftest.py @@ -1,9 +1,9 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedUnknownAsAny import os - import pytest -from seed import AsyncSeedUnknownAsAny, SeedUnknownAsAny +from seed import AsyncSeedUnknownAsAny @pytest.fixture diff --git a/seed/python-sdk/unknown/tests/custom/test_client.py b/seed/python-sdk/unknown/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/python-sdk/unknown/tests/custom/test_client.py +++ b/seed/python-sdk/unknown/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/python-sdk/unknown/tests/test_unknown.py b/seed/python-sdk/unknown/tests/test_unknown.py index 80ad10fa813..5eea7bbd02a 100644 --- a/seed/python-sdk/unknown/tests/test_unknown.py +++ b/seed/python-sdk/unknown/tests/test_unknown.py @@ -1,13 +1,14 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedUnknownAsAny +from seed import AsyncSeedUnknownAsAny import typing - -from seed import AsyncSeedUnknownAsAny, SeedUnknownAsAny - from .utilities import validate_response -async def test_post(client: SeedUnknownAsAny, async_client: AsyncSeedUnknownAsAny) -> None: +async def test_post( + client: SeedUnknownAsAny, async_client: AsyncSeedUnknownAsAny +) -> None: expected_response: typing.Any = [{"key": "value"}] expected_types: typing.Tuple[typing.Any, typing.Any] = ("list", {0: None}) response = client.unknown.post(request={"key": "value"}) diff --git a/seed/python-sdk/unknown/tests/utilities.py b/seed/python-sdk/unknown/tests/utilities.py index 13da208eb3a..e8f4472564c 100644 --- a/seed/python-sdk/unknown/tests/utilities.py +++ b/seed/python-sdk/unknown/tests/utilities.py @@ -3,11 +3,14 @@ import typing import uuid -import pydantic from dateutil import parser +import pydantic + -def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> typing.Any: +def cast_field( + json_expectation: typing.Any, type_expectation: typing.Any +) -> typing.Any: # Cast these specific types which come through as string and expect our # models to cast to the correct type. if type_expectation == "uuid": @@ -25,7 +28,9 @@ def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> ty return json_expectation -def validate_field(response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any) -> None: +def validate_field( + response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectation == "no_validate": return @@ -44,7 +49,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(entry_expectation, dict): is_container_of_complex_type = True validate_response( - response=response[idx], json_expectation=ex, type_expectations=entry_expectation + response=response[idx], + json_expectation=ex, + type_expectations=entry_expectation, ) else: cast_json_expectation.append(cast_field(ex, entry_expectation)) @@ -56,7 +63,10 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # if any of the values of the set have a type_expectation of a dict, we're assuming it's a pydantic # model and keeping it a list. if container_expectation != "set" or not any( - map(lambda value: isinstance(value, dict), list(contents_expectation.values())) + map( + lambda value: isinstance(value, dict), + list(contents_expectation.values()), + ) ): json_expectation = cast_field(json_expectation, container_expectation) elif isinstance(type_expectation, tuple): @@ -65,9 +75,15 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(contents_expectation, dict): json_expectation = { cast_field( - key, contents_expectation.get(idx)[0] if contents_expectation.get(idx) is not None else None # type: ignore + key, + contents_expectation.get(idx)[0] + if contents_expectation.get(idx) is not None + else None, # type: ignore ): cast_field( - value, contents_expectation.get(idx)[1] if contents_expectation.get(idx) is not None else None # type: ignore + value, + contents_expectation.get(idx)[1] + if contents_expectation.get(idx) is not None + else None, # type: ignore ) for idx, (key, value) in enumerate(json_expectation.items()) } @@ -86,7 +102,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # Arg type_expectations is a deeply nested structure that matches the response, but with the values replaced with the expected types -def validate_response(response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any) -> None: +def validate_response( + response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectations == "no_validate": return @@ -96,11 +114,17 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e and not isinstance(response, dict) and not issubclass(type(response), pydantic.BaseModel) ): - validate_field(response=response, json_expectation=json_expectation, type_expectation=type_expectations) + validate_field( + response=response, + json_expectation=json_expectation, + type_expectation=type_expectations, + ) return if isinstance(response, list): - assert len(response) == len(json_expectation), "Length mismatch, expected: {0}, Actual: {1}".format( + assert len(response) == len( + json_expectation + ), "Length mismatch, expected: {0}, Actual: {1}".format( len(response), len(json_expectation) ) content_expectation = type_expectations @@ -108,7 +132,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e content_expectation = type_expectations[1] for idx, item in enumerate(response): validate_response( - response=item, json_expectation=json_expectation[idx], type_expectations=content_expectation[idx] + response=item, + json_expectation=json_expectation[idx], + type_expectations=content_expectation[idx], ) else: response_json = response @@ -116,7 +142,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e response_json = response.dict(by_alias=True) for key, value in json_expectation.items(): - assert key in response_json, "Field {0} not found within the response object: {1}".format( + assert ( + key in response_json + ), "Field {0} not found within the response object: {1}".format( key, response_json ) @@ -128,11 +156,19 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e # Otherwise, we're just validating a single field that's a pydantic model. if isinstance(value, dict) and not isinstance(type_expectation, tuple): validate_response( - response=response_json[key], json_expectation=value, type_expectations=type_expectation + response=response_json[key], + json_expectation=value, + type_expectations=type_expectation, ) else: - validate_field(response=response_json[key], json_expectation=value, type_expectation=type_expectation) + validate_field( + response=response_json[key], + json_expectation=value, + type_expectation=type_expectation, + ) # Ensure there are no additional fields here either del response_json[key] - assert len(response_json) == 0, "Additional fields found, expected None: {0}".format(response_json) + assert ( + len(response_json) == 0 + ), "Additional fields found, expected None: {0}".format(response_json) diff --git a/seed/python-sdk/unknown/tests/utils/assets/models/__init__.py b/seed/python-sdk/unknown/tests/utils/assets/models/__init__.py index 2cf01263529..3a1c852e71e 100644 --- a/seed/python-sdk/unknown/tests/utils/assets/models/__init__.py +++ b/seed/python-sdk/unknown/tests/utils/assets/models/__init__.py @@ -5,7 +5,7 @@ from .circle import CircleParams from .object_with_defaults import ObjectWithDefaultsParams from .object_with_optional_field import ObjectWithOptionalFieldParams -from .shape import Shape_CircleParams, Shape_SquareParams, ShapeParams +from .shape import ShapeParams, Shape_CircleParams, Shape_SquareParams from .square import SquareParams from .undiscriminated_shape import UndiscriminatedShapeParams diff --git a/seed/python-sdk/unknown/tests/utils/assets/models/circle.py b/seed/python-sdk/unknown/tests/utils/assets/models/circle.py index af7a1bf8a8e..253f12d38b3 100644 --- a/seed/python-sdk/unknown/tests/utils/assets/models/circle.py +++ b/seed/python-sdk/unknown/tests/utils/assets/models/circle.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class CircleParams(typing_extensions.TypedDict): - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] diff --git a/seed/python-sdk/unknown/tests/utils/assets/models/object_with_optional_field.py b/seed/python-sdk/unknown/tests/utils/assets/models/object_with_optional_field.py index 3ad93d5f305..ebe7dc80547 100644 --- a/seed/python-sdk/unknown/tests/utils/assets/models/object_with_optional_field.py +++ b/seed/python-sdk/unknown/tests/utils/assets/models/object_with_optional_field.py @@ -7,8 +7,8 @@ import uuid import typing_extensions -from seed.core.serialization import FieldMetadata +from seed.core.serialization import FieldMetadata from .color import Color from .shape import ShapeParams from .undiscriminated_shape import UndiscriminatedShapeParams @@ -18,16 +18,30 @@ class ObjectWithOptionalFieldParams(typing_extensions.TypedDict): literal: typing.Literal["lit_one"] string: typing_extensions.NotRequired[str] integer: typing_extensions.NotRequired[int] - long_: typing_extensions.NotRequired[typing_extensions.Annotated[int, FieldMetadata(alias="long")]] + long_: typing_extensions.NotRequired[ + typing_extensions.Annotated[int, FieldMetadata(alias="long")] + ] double: typing_extensions.NotRequired[float] - bool_: typing_extensions.NotRequired[typing_extensions.Annotated[bool, FieldMetadata(alias="bool")]] + bool_: typing_extensions.NotRequired[ + typing_extensions.Annotated[bool, FieldMetadata(alias="bool")] + ] datetime: typing_extensions.NotRequired[dt.datetime] date: typing_extensions.NotRequired[dt.date] - uuid_: typing_extensions.NotRequired[typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")]] - base_64: typing_extensions.NotRequired[typing_extensions.Annotated[str, FieldMetadata(alias="base64")]] - list_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")]] - set_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")]] - map_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")]] + uuid_: typing_extensions.NotRequired[ + typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")] + ] + base_64: typing_extensions.NotRequired[ + typing_extensions.Annotated[str, FieldMetadata(alias="base64")] + ] + list_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")] + ] + set_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")] + ] + map_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")] + ] enum: typing_extensions.NotRequired[Color] union: typing_extensions.NotRequired[ShapeParams] second_union: typing_extensions.NotRequired[ShapeParams] diff --git a/seed/python-sdk/unknown/tests/utils/assets/models/shape.py b/seed/python-sdk/unknown/tests/utils/assets/models/shape.py index 2c33c877951..816ffc51bdc 100644 --- a/seed/python-sdk/unknown/tests/utils/assets/models/shape.py +++ b/seed/python-sdk/unknown/tests/utils/assets/models/shape.py @@ -7,6 +7,7 @@ import typing import typing_extensions + from seed.core.serialization import FieldMetadata @@ -15,13 +16,21 @@ class Base(typing_extensions.TypedDict): class Shape_CircleParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["circle"], FieldMetadata(alias="shapeType")] - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["circle"], FieldMetadata(alias="shapeType") + ] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] class Shape_SquareParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["square"], FieldMetadata(alias="shapeType")] - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["square"], FieldMetadata(alias="shapeType") + ] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] ShapeParams = typing.Union[Shape_CircleParams, Shape_SquareParams] diff --git a/seed/python-sdk/unknown/tests/utils/assets/models/square.py b/seed/python-sdk/unknown/tests/utils/assets/models/square.py index b9b7dd319bc..bcf08a723c5 100644 --- a/seed/python-sdk/unknown/tests/utils/assets/models/square.py +++ b/seed/python-sdk/unknown/tests/utils/assets/models/square.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class SquareParams(typing_extensions.TypedDict): - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] diff --git a/seed/python-sdk/unknown/tests/utils/test_http_client.py b/seed/python-sdk/unknown/tests/utils/test_http_client.py index edd11ca7afb..f5a874a75f3 100644 --- a/seed/python-sdk/unknown/tests/utils/test_http_client.py +++ b/seed/python-sdk/unknown/tests/utils/test_http_client.py @@ -9,12 +9,17 @@ def get_request_options() -> RequestOptions: def test_get_json_request_body() -> None: - json_body, data_body = get_request_body(json={"hello": "world"}, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json={"hello": "world"}, data=None, request_options=None, omit=None + ) assert json_body == {"hello": "world"} assert data_body is None json_body_extras, data_body_extras = get_request_body( - json={"goodbye": "world"}, data=None, request_options=get_request_options(), omit=None + json={"goodbye": "world"}, + data=None, + request_options=get_request_options(), + omit=None, ) assert json_body_extras == {"goodbye": "world", "see you": "later"} @@ -22,12 +27,17 @@ def test_get_json_request_body() -> None: def test_get_files_request_body() -> None: - json_body, data_body = get_request_body(json=None, data={"hello": "world"}, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data={"hello": "world"}, request_options=None, omit=None + ) assert data_body == {"hello": "world"} assert json_body is None json_body_extras, data_body_extras = get_request_body( - json=None, data={"goodbye": "world"}, request_options=get_request_options(), omit=None + json=None, + data={"goodbye": "world"}, + request_options=get_request_options(), + omit=None, ) assert data_body_extras == {"goodbye": "world", "see you": "later"} @@ -35,7 +45,9 @@ def test_get_files_request_body() -> None: def test_get_none_request_body() -> None: - json_body, data_body = get_request_body(json=None, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data=None, request_options=None, omit=None + ) assert data_body is None assert json_body is None diff --git a/seed/python-sdk/unknown/tests/utils/test_query_encoding.py b/seed/python-sdk/unknown/tests/utils/test_query_encoding.py index 247e1551b46..fbc8f402167 100644 --- a/seed/python-sdk/unknown/tests/utils/test_query_encoding.py +++ b/seed/python-sdk/unknown/tests/utils/test_query_encoding.py @@ -4,9 +4,15 @@ def test_query_encoding() -> None: - assert encode_query({"hello world": "hello world"}) == {"hello world": "hello world"} - assert encode_query({"hello_world": {"hello": "world"}}) == {"hello_world[hello]": "world"} - assert encode_query({"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"}) == { + assert encode_query({"hello world": "hello world"}) == { + "hello world": "hello world" + } + assert encode_query({"hello_world": {"hello": "world"}}) == { + "hello_world[hello]": "world" + } + assert encode_query( + {"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"} + ) == { "hello_world[hello][world]": "today", "hello_world[test]": "this", "hi": "there", diff --git a/seed/python-sdk/unknown/tests/utils/test_serialization.py b/seed/python-sdk/unknown/tests/utils/test_serialization.py index 58b1ed66e6d..5ca956916dd 100644 --- a/seed/python-sdk/unknown/tests/utils/test_serialization.py +++ b/seed/python-sdk/unknown/tests/utils/test_serialization.py @@ -1,10 +1,12 @@ # This file was auto-generated by Fern from our API Definition. -from typing import Any, List +from typing import List, Any -from seed.core.serialization import convert_and_respect_annotation_metadata +from seed.core.serialization import ( + convert_and_respect_annotation_metadata, +) +from .assets.models import ShapeParams, ObjectWithOptionalFieldParams -from .assets.models import ObjectWithOptionalFieldParams, ShapeParams UNION_TEST: ShapeParams = {"radius_measurement": 1.0, "shape_type": "circle", "id": "1"} UNION_TEST_CONVERTED = {"shapeType": "circle", "radiusMeasurement": 1.0, "id": "1"} @@ -18,20 +20,54 @@ def test_convert_and_respect_annotation_metadata() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) - assert converted == {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"} + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) + assert converted == { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + } def test_convert_and_respect_annotation_metadata_in_list() -> None: data: List[ObjectWithOptionalFieldParams] = [ - {"string": "string", "long_": 12345, "bool_": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long_": 67890, "list_": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long_": 12345, + "bool_": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long_": 67890, + "list_": [], + "literal": "lit_one", + "any": "any", + }, ] - converted = convert_and_respect_annotation_metadata(object_=data, annotation=List[ObjectWithOptionalFieldParams]) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=List[ObjectWithOptionalFieldParams] + ) assert converted == [ - {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long": 67890, "list": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long": 67890, + "list": [], + "literal": "lit_one", + "any": "any", + }, ] @@ -43,7 +79,9 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) assert converted == { "string": "string", @@ -55,12 +93,16 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: def test_convert_and_respect_annotation_metadata_in_union() -> None: - converted = convert_and_respect_annotation_metadata(object_=UNION_TEST, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=UNION_TEST, annotation=ShapeParams + ) assert converted == UNION_TEST_CONVERTED def test_convert_and_respect_annotation_metadata_with_empty_object() -> None: data: Any = {} - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ShapeParams + ) assert converted == data diff --git a/seed/python-sdk/validation/no-custom-config/pyproject.toml b/seed/python-sdk/validation/no-custom-config/pyproject.toml index c2ab3b9a3dc..baaabff02ec 100644 --- a/seed/python-sdk/validation/no-custom-config/pyproject.toml +++ b/seed/python-sdk/validation/no-custom-config/pyproject.toml @@ -43,6 +43,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/python-sdk/validation/no-custom-config/src/seed/client.py b/seed/python-sdk/validation/no-custom-config/src/seed/client.py index 179bdb97193..81a1bae40a2 100644 --- a/seed/python-sdk/validation/no-custom-config/src/seed/client.py +++ b/seed/python-sdk/validation/no-custom-config/src/seed/client.py @@ -1,16 +1,15 @@ # This file was auto-generated by Fern from our API Definition. import typing -from json.decoder import JSONDecodeError - import httpx - -from .core.api_error import ApiError -from .core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from .core.pydantic_utilities import parse_obj_as -from .core.request_options import RequestOptions +from .core.client_wrapper import SyncClientWrapper from .types.shape import Shape +from .core.request_options import RequestOptions from .types.type import Type +from .core.pydantic_utilities import parse_obj_as +from json.decoder import JSONDecodeError +from .core.api_error import ApiError +from .core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -49,14 +48,18 @@ def __init__( base_url: str, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.Client] = None + httpx_client: typing.Optional[httpx.Client] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = SyncClientWrapper( base_url=base_url, httpx_client=httpx_client if httpx_client is not None - else httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.Client( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.Client(timeout=_defaulted_timeout), timeout=_defaulted_timeout, @@ -69,7 +72,7 @@ def create( even: int, name: str, shape: Shape, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> Type: """ Parameters @@ -106,20 +109,32 @@ def create( _response = self._client_wrapper.httpx_client.request( "create", method="POST", - json={"decimal": decimal, "even": even, "name": name, "shape": shape}, + json={ + "decimal": decimal, + "even": even, + "name": name, + "shape": shape, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(Type, parse_obj_as(type_=Type, object_=_response.json())) # type: ignore + return typing.cast( + Type, parse_obj_as(type_=Type, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) def get( - self, *, decimal: float, even: int, name: str, request_options: typing.Optional[RequestOptions] = None + self, + *, + decimal: float, + even: int, + name: str, + request_options: typing.Optional[RequestOptions] = None, ) -> Type: """ Parameters @@ -151,11 +166,19 @@ def get( ) """ _response = self._client_wrapper.httpx_client.request( - method="GET", params={"decimal": decimal, "even": even, "name": name}, request_options=request_options + method="GET", + params={ + "decimal": decimal, + "even": even, + "name": name, + }, + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(Type, parse_obj_as(type_=Type, object_=_response.json())) # type: ignore + return typing.cast( + Type, parse_obj_as(type_=Type, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -195,14 +218,18 @@ def __init__( base_url: str, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.AsyncClient] = None + httpx_client: typing.Optional[httpx.AsyncClient] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = AsyncClientWrapper( base_url=base_url, httpx_client=httpx_client if httpx_client is not None - else httpx.AsyncClient(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.AsyncClient( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.AsyncClient(timeout=_defaulted_timeout), timeout=_defaulted_timeout, @@ -215,7 +242,7 @@ async def create( even: int, name: str, shape: Shape, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> Type: """ Parameters @@ -260,20 +287,32 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( "create", method="POST", - json={"decimal": decimal, "even": even, "name": name, "shape": shape}, + json={ + "decimal": decimal, + "even": even, + "name": name, + "shape": shape, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(Type, parse_obj_as(type_=Type, object_=_response.json())) # type: ignore + return typing.cast( + Type, parse_obj_as(type_=Type, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) raise ApiError(status_code=_response.status_code, body=_response_json) async def get( - self, *, decimal: float, even: int, name: str, request_options: typing.Optional[RequestOptions] = None + self, + *, + decimal: float, + even: int, + name: str, + request_options: typing.Optional[RequestOptions] = None, ) -> Type: """ Parameters @@ -313,11 +352,19 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - method="GET", params={"decimal": decimal, "even": even, "name": name}, request_options=request_options + method="GET", + params={ + "decimal": decimal, + "even": even, + "name": name, + }, + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(Type, parse_obj_as(type_=Type, object_=_response.json())) # type: ignore + return typing.cast( + Type, parse_obj_as(type_=Type, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/validation/no-custom-config/src/seed/core/api_error.py b/seed/python-sdk/validation/no-custom-config/src/seed/core/api_error.py index 2e9fc5431cd..da734b58068 100644 --- a/seed/python-sdk/validation/no-custom-config/src/seed/core/api_error.py +++ b/seed/python-sdk/validation/no-custom-config/src/seed/core/api_error.py @@ -7,7 +7,9 @@ class ApiError(Exception): status_code: typing.Optional[int] body: typing.Any - def __init__(self, *, status_code: typing.Optional[int] = None, body: typing.Any = None): + def __init__( + self, *, status_code: typing.Optional[int] = None, body: typing.Any = None + ): self.status_code = status_code self.body = body diff --git a/seed/python-sdk/validation/no-custom-config/src/seed/core/client_wrapper.py b/seed/python-sdk/validation/no-custom-config/src/seed/core/client_wrapper.py index 45bff809ee6..f39bc7193c8 100644 --- a/seed/python-sdk/validation/no-custom-config/src/seed/core/client_wrapper.py +++ b/seed/python-sdk/validation/no-custom-config/src/seed/core/client_wrapper.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .http_client import AsyncHttpClient, HttpClient +from .http_client import HttpClient +from .http_client import AsyncHttpClient class BaseClientWrapper: @@ -28,7 +27,13 @@ def get_timeout(self) -> typing.Optional[float]: class SyncClientWrapper(BaseClientWrapper): - def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, httpx_client: httpx.Client): + def __init__( + self, + *, + base_url: str, + timeout: typing.Optional[float] = None, + httpx_client: httpx.Client, + ): super().__init__(base_url=base_url, timeout=timeout) self.httpx_client = HttpClient( httpx_client=httpx_client, @@ -39,7 +44,13 @@ def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, htt class AsyncClientWrapper(BaseClientWrapper): - def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, httpx_client: httpx.AsyncClient): + def __init__( + self, + *, + base_url: str, + timeout: typing.Optional[float] = None, + httpx_client: httpx.AsyncClient, + ): super().__init__(base_url=base_url, timeout=timeout) self.httpx_client = AsyncHttpClient( httpx_client=httpx_client, diff --git a/seed/python-sdk/validation/no-custom-config/src/seed/core/datetime_utils.py b/seed/python-sdk/validation/no-custom-config/src/seed/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/python-sdk/validation/no-custom-config/src/seed/core/datetime_utils.py +++ b/seed/python-sdk/validation/no-custom-config/src/seed/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/python-sdk/validation/no-custom-config/src/seed/core/file.py b/seed/python-sdk/validation/no-custom-config/src/seed/core/file.py index cb0d40bbbf3..6e0f92bfcb1 100644 --- a/seed/python-sdk/validation/no-custom-config/src/seed/core/file.py +++ b/seed/python-sdk/validation/no-custom-config/src/seed/core/file.py @@ -13,12 +13,17 @@ # (filename, file (or bytes), content_type) typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str]], # (filename, file (or bytes), content_type, headers) - typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str], typing.Mapping[str, str]], + typing.Tuple[ + typing.Optional[str], + FileContent, + typing.Optional[str], + typing.Mapping[str, str], + ], ] def convert_file_dict_to_httpx_tuples( - d: typing.Dict[str, typing.Union[File, typing.List[File]]] + d: typing.Dict[str, typing.Union[File, typing.List[File]]], ) -> typing.List[typing.Tuple[str, File]]: """ The format we use is a list of tuples, where the first element is the diff --git a/seed/python-sdk/validation/no-custom-config/src/seed/core/http_client.py b/seed/python-sdk/validation/no-custom-config/src/seed/core/http_client.py index 9333d8a7f15..091f71bc185 100644 --- a/seed/python-sdk/validation/no-custom-config/src/seed/core/http_client.py +++ b/seed/python-sdk/validation/no-custom-config/src/seed/core/http_client.py @@ -77,7 +77,9 @@ def _retry_timeout(response: httpx.Response, retries: int) -> float: return retry_after # Apply exponential backoff, capped at MAX_RETRY_DELAY_SECONDS. - retry_delay = min(INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS) + retry_delay = min( + INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS + ) # Add a randomness / jitter to the retry delay to avoid overwhelming the server with retries. timeout = retry_delay * (1 - 0.25 * random()) @@ -90,7 +92,8 @@ def _should_retry(response: httpx.Response) -> bool: def remove_omit_from_dict( - original: typing.Dict[str, typing.Optional[typing.Any]], omit: typing.Optional[typing.Any] + original: typing.Dict[str, typing.Optional[typing.Any]], + omit: typing.Optional[typing.Any], ) -> typing.Dict[str, typing.Any]: if omit is None: return original @@ -108,7 +111,8 @@ def maybe_filter_request_body( ) -> typing.Optional[typing.Any]: if data is None: return ( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else None ) @@ -118,7 +122,8 @@ def maybe_filter_request_body( data_content = { **(jsonable_encoder(remove_omit_from_dict(data, omit))), # type: ignore **( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else {} ), @@ -162,7 +167,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url def request( @@ -174,8 +181,12 @@ def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -184,11 +195,14 @@ def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) response = self.httpx_client.request( method=method, @@ -198,7 +212,11 @@ def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -209,7 +227,10 @@ def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -222,11 +243,15 @@ def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: time.sleep(_retry_timeout(response=response, retries=retries)) @@ -256,8 +281,12 @@ def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -266,11 +295,14 @@ def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) with self.httpx_client.stream( method=method, @@ -280,7 +312,11 @@ def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -291,7 +327,9 @@ def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -304,7 +342,9 @@ def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream @@ -327,7 +367,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url async def request( @@ -339,8 +381,12 @@ async def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -349,11 +395,14 @@ async def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) # Add the input to each of these and do None-safety checks response = await self.httpx_client.request( @@ -364,7 +413,11 @@ async def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -375,7 +428,10 @@ async def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -388,11 +444,15 @@ async def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: await asyncio.sleep(_retry_timeout(response=response, retries=retries)) @@ -421,8 +481,12 @@ async def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -431,11 +495,14 @@ async def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) async with self.httpx_client.stream( method=method, @@ -445,7 +512,11 @@ async def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -456,7 +527,9 @@ async def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -469,7 +542,9 @@ async def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream diff --git a/seed/python-sdk/validation/no-custom-config/src/seed/core/jsonable_encoder.py b/seed/python-sdk/validation/no-custom-config/src/seed/core/jsonable_encoder.py index d3fd328fd41..12a8b52fc22 100644 --- a/seed/python-sdk/validation/no-custom-config/src/seed/core/jsonable_encoder.py +++ b/seed/python-sdk/validation/no-custom-config/src/seed/core/jsonable_encoder.py @@ -19,13 +19,19 @@ import pydantic from .datetime_utils import serialize_datetime -from .pydantic_utilities import IS_PYDANTIC_V2, encode_by_type, to_jsonable_with_fallback +from .pydantic_utilities import ( + IS_PYDANTIC_V2, + encode_by_type, + to_jsonable_with_fallback, +) SetIntStr = Set[Union[int, str]] DictIntStrAny = Dict[Union[int, str], Any] -def jsonable_encoder(obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None) -> Any: +def jsonable_encoder( + obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None +) -> Any: custom_encoder = custom_encoder or {} if custom_encoder: if type(obj) in custom_encoder: diff --git a/seed/python-sdk/validation/no-custom-config/src/seed/core/pydantic_utilities.py b/seed/python-sdk/validation/no-custom-config/src/seed/core/pydantic_utilities.py index 170a563d6eb..c63935c32a2 100644 --- a/seed/python-sdk/validation/no-custom-config/src/seed/core/pydantic_utilities.py +++ b/seed/python-sdk/validation/no-custom-config/src/seed/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) # type: ignore # Pydantic v1 diff --git a/seed/python-sdk/validation/no-custom-config/src/seed/core/query_encoder.py b/seed/python-sdk/validation/no-custom-config/src/seed/core/query_encoder.py index 24076d72ee9..7cb98f52cd7 100644 --- a/seed/python-sdk/validation/no-custom-config/src/seed/core/query_encoder.py +++ b/seed/python-sdk/validation/no-custom-config/src/seed/core/query_encoder.py @@ -7,7 +7,9 @@ # Flattens dicts to be of the form {"key[subkey][subkey2]": value} where value is not a dict -def traverse_query_dict(dict_flat: Dict[str, Any], key_prefix: Optional[str] = None) -> Dict[str, Any]: +def traverse_query_dict( + dict_flat: Dict[str, Any], key_prefix: Optional[str] = None +) -> Dict[str, Any]: result = {} for k, v in dict_flat.items(): key = f"{key_prefix}[{k}]" if key_prefix is not None else k @@ -30,4 +32,8 @@ def single_query_encoder(query_key: str, query_value: Any) -> Dict[str, Any]: def encode_query(query: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: - return dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) if query is not None else None + return ( + dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) + if query is not None + else None + ) diff --git a/seed/python-sdk/validation/no-custom-config/src/seed/core/serialization.py b/seed/python-sdk/validation/no-custom-config/src/seed/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/python-sdk/validation/no-custom-config/src/seed/core/serialization.py +++ b/seed/python-sdk/validation/no-custom-config/src/seed/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/python-sdk/validation/no-custom-config/src/seed/types/__init__.py b/seed/python-sdk/validation/no-custom-config/src/seed/types/__init__.py index d30f52138d4..51957e8c8c5 100644 --- a/seed/python-sdk/validation/no-custom-config/src/seed/types/__init__.py +++ b/seed/python-sdk/validation/no-custom-config/src/seed/types/__init__.py @@ -8,4 +8,12 @@ from .type import Type from .word import Word -__all__ = ["Double", "LargeInteger", "Sentence", "Shape", "SmallInteger", "Type", "Word"] +__all__ = [ + "Double", + "LargeInteger", + "Sentence", + "Shape", + "SmallInteger", + "Type", + "Word", +] diff --git a/seed/python-sdk/validation/no-custom-config/src/seed/types/type.py b/seed/python-sdk/validation/no-custom-config/src/seed/types/type.py index d30111853a9..2a37dc192e1 100644 --- a/seed/python-sdk/validation/no-custom-config/src/seed/types/type.py +++ b/seed/python-sdk/validation/no-custom-config/src/seed/types/type.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. +from ..core.pydantic_utilities import UniversalBaseModel +from .shape import Shape +from ..core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .shape import Shape - class Type(UniversalBaseModel): """ @@ -30,7 +29,9 @@ class Type(UniversalBaseModel): shape: Shape if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/validation/no-custom-config/src/seed/version.py b/seed/python-sdk/validation/no-custom-config/src/seed/version.py index 7a4010f0235..29cc1476df1 100644 --- a/seed/python-sdk/validation/no-custom-config/src/seed/version.py +++ b/seed/python-sdk/validation/no-custom-config/src/seed/version.py @@ -1,4 +1,3 @@ - from importlib import metadata __version__ = metadata.version("fern_validation") diff --git a/seed/python-sdk/validation/no-custom-config/tests/conftest.py b/seed/python-sdk/validation/no-custom-config/tests/conftest.py index 43d45d17627..7eacc89b29e 100644 --- a/seed/python-sdk/validation/no-custom-config/tests/conftest.py +++ b/seed/python-sdk/validation/no-custom-config/tests/conftest.py @@ -1,9 +1,9 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedValidation import os - import pytest -from seed import AsyncSeedValidation, SeedValidation +from seed import AsyncSeedValidation @pytest.fixture diff --git a/seed/python-sdk/validation/no-custom-config/tests/custom/test_client.py b/seed/python-sdk/validation/no-custom-config/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/python-sdk/validation/no-custom-config/tests/custom/test_client.py +++ b/seed/python-sdk/validation/no-custom-config/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/python-sdk/validation/no-custom-config/tests/test_root.py b/seed/python-sdk/validation/no-custom-config/tests/test_root.py index d3d9ab31af5..7f91d676ddf 100644 --- a/seed/python-sdk/validation/no-custom-config/tests/test_root.py +++ b/seed/python-sdk/validation/no-custom-config/tests/test_root.py @@ -1,25 +1,48 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedValidation +from seed import AsyncSeedValidation import typing - -from seed import AsyncSeedValidation, SeedValidation - from .utilities import validate_response -async def test_create(client: SeedValidation, async_client: AsyncSeedValidation) -> None: - expected_response: typing.Any = {"decimal": 1.1, "even": 2, "name": "rules", "shape": "SQUARE"} - expected_types: typing.Any = {"decimal": None, "even": "integer", "name": None, "shape": None} +async def test_create( + client: SeedValidation, async_client: AsyncSeedValidation +) -> None: + expected_response: typing.Any = { + "decimal": 1.1, + "even": 2, + "name": "rules", + "shape": "SQUARE", + } + expected_types: typing.Any = { + "decimal": None, + "even": "integer", + "name": None, + "shape": None, + } response = client.create(decimal=1.1, even=1, name="string", shape="SQUARE") validate_response(response, expected_response, expected_types) - async_response = await async_client.create(decimal=1.1, even=1, name="string", shape="SQUARE") + async_response = await async_client.create( + decimal=1.1, even=1, name="string", shape="SQUARE" + ) validate_response(async_response, expected_response, expected_types) async def test_get(client: SeedValidation, async_client: AsyncSeedValidation) -> None: - expected_response: typing.Any = {"decimal": 1.1, "even": 2, "name": "rules", "shape": "SQUARE"} - expected_types: typing.Any = {"decimal": None, "even": "integer", "name": None, "shape": None} + expected_response: typing.Any = { + "decimal": 1.1, + "even": 2, + "name": "rules", + "shape": "SQUARE", + } + expected_types: typing.Any = { + "decimal": None, + "even": "integer", + "name": None, + "shape": None, + } response = client.get(decimal=1.1, even=1, name="string") validate_response(response, expected_response, expected_types) diff --git a/seed/python-sdk/validation/no-custom-config/tests/utilities.py b/seed/python-sdk/validation/no-custom-config/tests/utilities.py index 13da208eb3a..e8f4472564c 100644 --- a/seed/python-sdk/validation/no-custom-config/tests/utilities.py +++ b/seed/python-sdk/validation/no-custom-config/tests/utilities.py @@ -3,11 +3,14 @@ import typing import uuid -import pydantic from dateutil import parser +import pydantic + -def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> typing.Any: +def cast_field( + json_expectation: typing.Any, type_expectation: typing.Any +) -> typing.Any: # Cast these specific types which come through as string and expect our # models to cast to the correct type. if type_expectation == "uuid": @@ -25,7 +28,9 @@ def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> ty return json_expectation -def validate_field(response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any) -> None: +def validate_field( + response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectation == "no_validate": return @@ -44,7 +49,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(entry_expectation, dict): is_container_of_complex_type = True validate_response( - response=response[idx], json_expectation=ex, type_expectations=entry_expectation + response=response[idx], + json_expectation=ex, + type_expectations=entry_expectation, ) else: cast_json_expectation.append(cast_field(ex, entry_expectation)) @@ -56,7 +63,10 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # if any of the values of the set have a type_expectation of a dict, we're assuming it's a pydantic # model and keeping it a list. if container_expectation != "set" or not any( - map(lambda value: isinstance(value, dict), list(contents_expectation.values())) + map( + lambda value: isinstance(value, dict), + list(contents_expectation.values()), + ) ): json_expectation = cast_field(json_expectation, container_expectation) elif isinstance(type_expectation, tuple): @@ -65,9 +75,15 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(contents_expectation, dict): json_expectation = { cast_field( - key, contents_expectation.get(idx)[0] if contents_expectation.get(idx) is not None else None # type: ignore + key, + contents_expectation.get(idx)[0] + if contents_expectation.get(idx) is not None + else None, # type: ignore ): cast_field( - value, contents_expectation.get(idx)[1] if contents_expectation.get(idx) is not None else None # type: ignore + value, + contents_expectation.get(idx)[1] + if contents_expectation.get(idx) is not None + else None, # type: ignore ) for idx, (key, value) in enumerate(json_expectation.items()) } @@ -86,7 +102,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # Arg type_expectations is a deeply nested structure that matches the response, but with the values replaced with the expected types -def validate_response(response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any) -> None: +def validate_response( + response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectations == "no_validate": return @@ -96,11 +114,17 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e and not isinstance(response, dict) and not issubclass(type(response), pydantic.BaseModel) ): - validate_field(response=response, json_expectation=json_expectation, type_expectation=type_expectations) + validate_field( + response=response, + json_expectation=json_expectation, + type_expectation=type_expectations, + ) return if isinstance(response, list): - assert len(response) == len(json_expectation), "Length mismatch, expected: {0}, Actual: {1}".format( + assert len(response) == len( + json_expectation + ), "Length mismatch, expected: {0}, Actual: {1}".format( len(response), len(json_expectation) ) content_expectation = type_expectations @@ -108,7 +132,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e content_expectation = type_expectations[1] for idx, item in enumerate(response): validate_response( - response=item, json_expectation=json_expectation[idx], type_expectations=content_expectation[idx] + response=item, + json_expectation=json_expectation[idx], + type_expectations=content_expectation[idx], ) else: response_json = response @@ -116,7 +142,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e response_json = response.dict(by_alias=True) for key, value in json_expectation.items(): - assert key in response_json, "Field {0} not found within the response object: {1}".format( + assert ( + key in response_json + ), "Field {0} not found within the response object: {1}".format( key, response_json ) @@ -128,11 +156,19 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e # Otherwise, we're just validating a single field that's a pydantic model. if isinstance(value, dict) and not isinstance(type_expectation, tuple): validate_response( - response=response_json[key], json_expectation=value, type_expectations=type_expectation + response=response_json[key], + json_expectation=value, + type_expectations=type_expectation, ) else: - validate_field(response=response_json[key], json_expectation=value, type_expectation=type_expectation) + validate_field( + response=response_json[key], + json_expectation=value, + type_expectation=type_expectation, + ) # Ensure there are no additional fields here either del response_json[key] - assert len(response_json) == 0, "Additional fields found, expected None: {0}".format(response_json) + assert ( + len(response_json) == 0 + ), "Additional fields found, expected None: {0}".format(response_json) diff --git a/seed/python-sdk/validation/no-custom-config/tests/utils/assets/models/__init__.py b/seed/python-sdk/validation/no-custom-config/tests/utils/assets/models/__init__.py index 2cf01263529..3a1c852e71e 100644 --- a/seed/python-sdk/validation/no-custom-config/tests/utils/assets/models/__init__.py +++ b/seed/python-sdk/validation/no-custom-config/tests/utils/assets/models/__init__.py @@ -5,7 +5,7 @@ from .circle import CircleParams from .object_with_defaults import ObjectWithDefaultsParams from .object_with_optional_field import ObjectWithOptionalFieldParams -from .shape import Shape_CircleParams, Shape_SquareParams, ShapeParams +from .shape import ShapeParams, Shape_CircleParams, Shape_SquareParams from .square import SquareParams from .undiscriminated_shape import UndiscriminatedShapeParams diff --git a/seed/python-sdk/validation/no-custom-config/tests/utils/assets/models/circle.py b/seed/python-sdk/validation/no-custom-config/tests/utils/assets/models/circle.py index af7a1bf8a8e..253f12d38b3 100644 --- a/seed/python-sdk/validation/no-custom-config/tests/utils/assets/models/circle.py +++ b/seed/python-sdk/validation/no-custom-config/tests/utils/assets/models/circle.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class CircleParams(typing_extensions.TypedDict): - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] diff --git a/seed/python-sdk/validation/no-custom-config/tests/utils/assets/models/object_with_optional_field.py b/seed/python-sdk/validation/no-custom-config/tests/utils/assets/models/object_with_optional_field.py index 3ad93d5f305..ebe7dc80547 100644 --- a/seed/python-sdk/validation/no-custom-config/tests/utils/assets/models/object_with_optional_field.py +++ b/seed/python-sdk/validation/no-custom-config/tests/utils/assets/models/object_with_optional_field.py @@ -7,8 +7,8 @@ import uuid import typing_extensions -from seed.core.serialization import FieldMetadata +from seed.core.serialization import FieldMetadata from .color import Color from .shape import ShapeParams from .undiscriminated_shape import UndiscriminatedShapeParams @@ -18,16 +18,30 @@ class ObjectWithOptionalFieldParams(typing_extensions.TypedDict): literal: typing.Literal["lit_one"] string: typing_extensions.NotRequired[str] integer: typing_extensions.NotRequired[int] - long_: typing_extensions.NotRequired[typing_extensions.Annotated[int, FieldMetadata(alias="long")]] + long_: typing_extensions.NotRequired[ + typing_extensions.Annotated[int, FieldMetadata(alias="long")] + ] double: typing_extensions.NotRequired[float] - bool_: typing_extensions.NotRequired[typing_extensions.Annotated[bool, FieldMetadata(alias="bool")]] + bool_: typing_extensions.NotRequired[ + typing_extensions.Annotated[bool, FieldMetadata(alias="bool")] + ] datetime: typing_extensions.NotRequired[dt.datetime] date: typing_extensions.NotRequired[dt.date] - uuid_: typing_extensions.NotRequired[typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")]] - base_64: typing_extensions.NotRequired[typing_extensions.Annotated[str, FieldMetadata(alias="base64")]] - list_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")]] - set_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")]] - map_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")]] + uuid_: typing_extensions.NotRequired[ + typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")] + ] + base_64: typing_extensions.NotRequired[ + typing_extensions.Annotated[str, FieldMetadata(alias="base64")] + ] + list_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")] + ] + set_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")] + ] + map_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")] + ] enum: typing_extensions.NotRequired[Color] union: typing_extensions.NotRequired[ShapeParams] second_union: typing_extensions.NotRequired[ShapeParams] diff --git a/seed/python-sdk/validation/no-custom-config/tests/utils/assets/models/shape.py b/seed/python-sdk/validation/no-custom-config/tests/utils/assets/models/shape.py index 2c33c877951..816ffc51bdc 100644 --- a/seed/python-sdk/validation/no-custom-config/tests/utils/assets/models/shape.py +++ b/seed/python-sdk/validation/no-custom-config/tests/utils/assets/models/shape.py @@ -7,6 +7,7 @@ import typing import typing_extensions + from seed.core.serialization import FieldMetadata @@ -15,13 +16,21 @@ class Base(typing_extensions.TypedDict): class Shape_CircleParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["circle"], FieldMetadata(alias="shapeType")] - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["circle"], FieldMetadata(alias="shapeType") + ] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] class Shape_SquareParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["square"], FieldMetadata(alias="shapeType")] - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["square"], FieldMetadata(alias="shapeType") + ] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] ShapeParams = typing.Union[Shape_CircleParams, Shape_SquareParams] diff --git a/seed/python-sdk/validation/no-custom-config/tests/utils/assets/models/square.py b/seed/python-sdk/validation/no-custom-config/tests/utils/assets/models/square.py index b9b7dd319bc..bcf08a723c5 100644 --- a/seed/python-sdk/validation/no-custom-config/tests/utils/assets/models/square.py +++ b/seed/python-sdk/validation/no-custom-config/tests/utils/assets/models/square.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class SquareParams(typing_extensions.TypedDict): - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] diff --git a/seed/python-sdk/validation/no-custom-config/tests/utils/test_http_client.py b/seed/python-sdk/validation/no-custom-config/tests/utils/test_http_client.py index edd11ca7afb..f5a874a75f3 100644 --- a/seed/python-sdk/validation/no-custom-config/tests/utils/test_http_client.py +++ b/seed/python-sdk/validation/no-custom-config/tests/utils/test_http_client.py @@ -9,12 +9,17 @@ def get_request_options() -> RequestOptions: def test_get_json_request_body() -> None: - json_body, data_body = get_request_body(json={"hello": "world"}, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json={"hello": "world"}, data=None, request_options=None, omit=None + ) assert json_body == {"hello": "world"} assert data_body is None json_body_extras, data_body_extras = get_request_body( - json={"goodbye": "world"}, data=None, request_options=get_request_options(), omit=None + json={"goodbye": "world"}, + data=None, + request_options=get_request_options(), + omit=None, ) assert json_body_extras == {"goodbye": "world", "see you": "later"} @@ -22,12 +27,17 @@ def test_get_json_request_body() -> None: def test_get_files_request_body() -> None: - json_body, data_body = get_request_body(json=None, data={"hello": "world"}, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data={"hello": "world"}, request_options=None, omit=None + ) assert data_body == {"hello": "world"} assert json_body is None json_body_extras, data_body_extras = get_request_body( - json=None, data={"goodbye": "world"}, request_options=get_request_options(), omit=None + json=None, + data={"goodbye": "world"}, + request_options=get_request_options(), + omit=None, ) assert data_body_extras == {"goodbye": "world", "see you": "later"} @@ -35,7 +45,9 @@ def test_get_files_request_body() -> None: def test_get_none_request_body() -> None: - json_body, data_body = get_request_body(json=None, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data=None, request_options=None, omit=None + ) assert data_body is None assert json_body is None diff --git a/seed/python-sdk/validation/no-custom-config/tests/utils/test_query_encoding.py b/seed/python-sdk/validation/no-custom-config/tests/utils/test_query_encoding.py index 247e1551b46..fbc8f402167 100644 --- a/seed/python-sdk/validation/no-custom-config/tests/utils/test_query_encoding.py +++ b/seed/python-sdk/validation/no-custom-config/tests/utils/test_query_encoding.py @@ -4,9 +4,15 @@ def test_query_encoding() -> None: - assert encode_query({"hello world": "hello world"}) == {"hello world": "hello world"} - assert encode_query({"hello_world": {"hello": "world"}}) == {"hello_world[hello]": "world"} - assert encode_query({"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"}) == { + assert encode_query({"hello world": "hello world"}) == { + "hello world": "hello world" + } + assert encode_query({"hello_world": {"hello": "world"}}) == { + "hello_world[hello]": "world" + } + assert encode_query( + {"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"} + ) == { "hello_world[hello][world]": "today", "hello_world[test]": "this", "hi": "there", diff --git a/seed/python-sdk/validation/no-custom-config/tests/utils/test_serialization.py b/seed/python-sdk/validation/no-custom-config/tests/utils/test_serialization.py index 58b1ed66e6d..5ca956916dd 100644 --- a/seed/python-sdk/validation/no-custom-config/tests/utils/test_serialization.py +++ b/seed/python-sdk/validation/no-custom-config/tests/utils/test_serialization.py @@ -1,10 +1,12 @@ # This file was auto-generated by Fern from our API Definition. -from typing import Any, List +from typing import List, Any -from seed.core.serialization import convert_and_respect_annotation_metadata +from seed.core.serialization import ( + convert_and_respect_annotation_metadata, +) +from .assets.models import ShapeParams, ObjectWithOptionalFieldParams -from .assets.models import ObjectWithOptionalFieldParams, ShapeParams UNION_TEST: ShapeParams = {"radius_measurement": 1.0, "shape_type": "circle", "id": "1"} UNION_TEST_CONVERTED = {"shapeType": "circle", "radiusMeasurement": 1.0, "id": "1"} @@ -18,20 +20,54 @@ def test_convert_and_respect_annotation_metadata() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) - assert converted == {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"} + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) + assert converted == { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + } def test_convert_and_respect_annotation_metadata_in_list() -> None: data: List[ObjectWithOptionalFieldParams] = [ - {"string": "string", "long_": 12345, "bool_": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long_": 67890, "list_": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long_": 12345, + "bool_": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long_": 67890, + "list_": [], + "literal": "lit_one", + "any": "any", + }, ] - converted = convert_and_respect_annotation_metadata(object_=data, annotation=List[ObjectWithOptionalFieldParams]) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=List[ObjectWithOptionalFieldParams] + ) assert converted == [ - {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long": 67890, "list": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long": 67890, + "list": [], + "literal": "lit_one", + "any": "any", + }, ] @@ -43,7 +79,9 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) assert converted == { "string": "string", @@ -55,12 +93,16 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: def test_convert_and_respect_annotation_metadata_in_union() -> None: - converted = convert_and_respect_annotation_metadata(object_=UNION_TEST, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=UNION_TEST, annotation=ShapeParams + ) assert converted == UNION_TEST_CONVERTED def test_convert_and_respect_annotation_metadata_with_empty_object() -> None: data: Any = {} - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ShapeParams + ) assert converted == data diff --git a/seed/python-sdk/validation/with-defaults/pyproject.toml b/seed/python-sdk/validation/with-defaults/pyproject.toml index c2ab3b9a3dc..baaabff02ec 100644 --- a/seed/python-sdk/validation/with-defaults/pyproject.toml +++ b/seed/python-sdk/validation/with-defaults/pyproject.toml @@ -43,6 +43,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/python-sdk/validation/with-defaults/src/seed/client.py b/seed/python-sdk/validation/with-defaults/src/seed/client.py index 5e90e4c6c90..4050882acd9 100644 --- a/seed/python-sdk/validation/with-defaults/src/seed/client.py +++ b/seed/python-sdk/validation/with-defaults/src/seed/client.py @@ -1,16 +1,15 @@ # This file was auto-generated by Fern from our API Definition. import typing -from json.decoder import JSONDecodeError - import httpx - -from .core.api_error import ApiError -from .core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from .core.pydantic_utilities import parse_obj_as -from .core.request_options import RequestOptions +from .core.client_wrapper import SyncClientWrapper from .types.shape import Shape +from .core.request_options import RequestOptions from .types.type import Type +from .core.pydantic_utilities import parse_obj_as +from json.decoder import JSONDecodeError +from .core.api_error import ApiError +from .core.client_wrapper import AsyncClientWrapper # this is used as the default value for optional parameters OMIT = typing.cast(typing.Any, ...) @@ -49,14 +48,18 @@ def __init__( base_url: str, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.Client] = None + httpx_client: typing.Optional[httpx.Client] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = SyncClientWrapper( base_url=base_url, httpx_client=httpx_client if httpx_client is not None - else httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.Client( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.Client(timeout=_defaulted_timeout), timeout=_defaulted_timeout, @@ -69,7 +72,7 @@ def create( even: int = 42, name: str = "fern", shape: Shape, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> Type: """ Parameters @@ -106,13 +109,20 @@ def create( _response = self._client_wrapper.httpx_client.request( "create", method="POST", - json={"decimal": decimal, "even": even, "name": name, "shape": shape}, + json={ + "decimal": decimal, + "even": even, + "name": name, + "shape": shape, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(Type, parse_obj_as(type_=Type, object_=_response.json())) # type: ignore + return typing.cast( + Type, parse_obj_as(type_=Type, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -124,7 +134,7 @@ def get( decimal: float = 1.1, even: int = 42, name: str = "fern", - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> Type: """ Parameters @@ -156,11 +166,19 @@ def get( ) """ _response = self._client_wrapper.httpx_client.request( - method="GET", params={"decimal": decimal, "even": even, "name": name}, request_options=request_options + method="GET", + params={ + "decimal": decimal, + "even": even, + "name": name, + }, + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(Type, parse_obj_as(type_=Type, object_=_response.json())) # type: ignore + return typing.cast( + Type, parse_obj_as(type_=Type, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -200,14 +218,18 @@ def __init__( base_url: str, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.AsyncClient] = None + httpx_client: typing.Optional[httpx.AsyncClient] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = AsyncClientWrapper( base_url=base_url, httpx_client=httpx_client if httpx_client is not None - else httpx.AsyncClient(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.AsyncClient( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.AsyncClient(timeout=_defaulted_timeout), timeout=_defaulted_timeout, @@ -220,7 +242,7 @@ async def create( even: int = 42, name: str = "fern", shape: Shape, - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> Type: """ Parameters @@ -265,13 +287,20 @@ async def main() -> None: _response = await self._client_wrapper.httpx_client.request( "create", method="POST", - json={"decimal": decimal, "even": even, "name": name, "shape": shape}, + json={ + "decimal": decimal, + "even": even, + "name": name, + "shape": shape, + }, request_options=request_options, omit=OMIT, ) try: if 200 <= _response.status_code < 300: - return typing.cast(Type, parse_obj_as(type_=Type, object_=_response.json())) # type: ignore + return typing.cast( + Type, parse_obj_as(type_=Type, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -283,7 +312,7 @@ async def get( decimal: float = 1.1, even: int = 42, name: str = "fern", - request_options: typing.Optional[RequestOptions] = None + request_options: typing.Optional[RequestOptions] = None, ) -> Type: """ Parameters @@ -323,11 +352,19 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - method="GET", params={"decimal": decimal, "even": even, "name": name}, request_options=request_options + method="GET", + params={ + "decimal": decimal, + "even": even, + "name": name, + }, + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(Type, parse_obj_as(type_=Type, object_=_response.json())) # type: ignore + return typing.cast( + Type, parse_obj_as(type_=Type, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/validation/with-defaults/src/seed/core/api_error.py b/seed/python-sdk/validation/with-defaults/src/seed/core/api_error.py index 2e9fc5431cd..da734b58068 100644 --- a/seed/python-sdk/validation/with-defaults/src/seed/core/api_error.py +++ b/seed/python-sdk/validation/with-defaults/src/seed/core/api_error.py @@ -7,7 +7,9 @@ class ApiError(Exception): status_code: typing.Optional[int] body: typing.Any - def __init__(self, *, status_code: typing.Optional[int] = None, body: typing.Any = None): + def __init__( + self, *, status_code: typing.Optional[int] = None, body: typing.Any = None + ): self.status_code = status_code self.body = body diff --git a/seed/python-sdk/validation/with-defaults/src/seed/core/client_wrapper.py b/seed/python-sdk/validation/with-defaults/src/seed/core/client_wrapper.py index 45bff809ee6..f39bc7193c8 100644 --- a/seed/python-sdk/validation/with-defaults/src/seed/core/client_wrapper.py +++ b/seed/python-sdk/validation/with-defaults/src/seed/core/client_wrapper.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .http_client import AsyncHttpClient, HttpClient +from .http_client import HttpClient +from .http_client import AsyncHttpClient class BaseClientWrapper: @@ -28,7 +27,13 @@ def get_timeout(self) -> typing.Optional[float]: class SyncClientWrapper(BaseClientWrapper): - def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, httpx_client: httpx.Client): + def __init__( + self, + *, + base_url: str, + timeout: typing.Optional[float] = None, + httpx_client: httpx.Client, + ): super().__init__(base_url=base_url, timeout=timeout) self.httpx_client = HttpClient( httpx_client=httpx_client, @@ -39,7 +44,13 @@ def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, htt class AsyncClientWrapper(BaseClientWrapper): - def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, httpx_client: httpx.AsyncClient): + def __init__( + self, + *, + base_url: str, + timeout: typing.Optional[float] = None, + httpx_client: httpx.AsyncClient, + ): super().__init__(base_url=base_url, timeout=timeout) self.httpx_client = AsyncHttpClient( httpx_client=httpx_client, diff --git a/seed/python-sdk/validation/with-defaults/src/seed/core/datetime_utils.py b/seed/python-sdk/validation/with-defaults/src/seed/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/python-sdk/validation/with-defaults/src/seed/core/datetime_utils.py +++ b/seed/python-sdk/validation/with-defaults/src/seed/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/python-sdk/validation/with-defaults/src/seed/core/file.py b/seed/python-sdk/validation/with-defaults/src/seed/core/file.py index cb0d40bbbf3..6e0f92bfcb1 100644 --- a/seed/python-sdk/validation/with-defaults/src/seed/core/file.py +++ b/seed/python-sdk/validation/with-defaults/src/seed/core/file.py @@ -13,12 +13,17 @@ # (filename, file (or bytes), content_type) typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str]], # (filename, file (or bytes), content_type, headers) - typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str], typing.Mapping[str, str]], + typing.Tuple[ + typing.Optional[str], + FileContent, + typing.Optional[str], + typing.Mapping[str, str], + ], ] def convert_file_dict_to_httpx_tuples( - d: typing.Dict[str, typing.Union[File, typing.List[File]]] + d: typing.Dict[str, typing.Union[File, typing.List[File]]], ) -> typing.List[typing.Tuple[str, File]]: """ The format we use is a list of tuples, where the first element is the diff --git a/seed/python-sdk/validation/with-defaults/src/seed/core/http_client.py b/seed/python-sdk/validation/with-defaults/src/seed/core/http_client.py index 9333d8a7f15..091f71bc185 100644 --- a/seed/python-sdk/validation/with-defaults/src/seed/core/http_client.py +++ b/seed/python-sdk/validation/with-defaults/src/seed/core/http_client.py @@ -77,7 +77,9 @@ def _retry_timeout(response: httpx.Response, retries: int) -> float: return retry_after # Apply exponential backoff, capped at MAX_RETRY_DELAY_SECONDS. - retry_delay = min(INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS) + retry_delay = min( + INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS + ) # Add a randomness / jitter to the retry delay to avoid overwhelming the server with retries. timeout = retry_delay * (1 - 0.25 * random()) @@ -90,7 +92,8 @@ def _should_retry(response: httpx.Response) -> bool: def remove_omit_from_dict( - original: typing.Dict[str, typing.Optional[typing.Any]], omit: typing.Optional[typing.Any] + original: typing.Dict[str, typing.Optional[typing.Any]], + omit: typing.Optional[typing.Any], ) -> typing.Dict[str, typing.Any]: if omit is None: return original @@ -108,7 +111,8 @@ def maybe_filter_request_body( ) -> typing.Optional[typing.Any]: if data is None: return ( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else None ) @@ -118,7 +122,8 @@ def maybe_filter_request_body( data_content = { **(jsonable_encoder(remove_omit_from_dict(data, omit))), # type: ignore **( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else {} ), @@ -162,7 +167,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url def request( @@ -174,8 +181,12 @@ def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -184,11 +195,14 @@ def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) response = self.httpx_client.request( method=method, @@ -198,7 +212,11 @@ def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -209,7 +227,10 @@ def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -222,11 +243,15 @@ def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: time.sleep(_retry_timeout(response=response, retries=retries)) @@ -256,8 +281,12 @@ def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -266,11 +295,14 @@ def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) with self.httpx_client.stream( method=method, @@ -280,7 +312,11 @@ def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -291,7 +327,9 @@ def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -304,7 +342,9 @@ def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream @@ -327,7 +367,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url async def request( @@ -339,8 +381,12 @@ async def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -349,11 +395,14 @@ async def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) # Add the input to each of these and do None-safety checks response = await self.httpx_client.request( @@ -364,7 +413,11 @@ async def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -375,7 +428,10 @@ async def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -388,11 +444,15 @@ async def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: await asyncio.sleep(_retry_timeout(response=response, retries=retries)) @@ -421,8 +481,12 @@ async def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -431,11 +495,14 @@ async def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) async with self.httpx_client.stream( method=method, @@ -445,7 +512,11 @@ async def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -456,7 +527,9 @@ async def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -469,7 +542,9 @@ async def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream diff --git a/seed/python-sdk/validation/with-defaults/src/seed/core/jsonable_encoder.py b/seed/python-sdk/validation/with-defaults/src/seed/core/jsonable_encoder.py index d3fd328fd41..12a8b52fc22 100644 --- a/seed/python-sdk/validation/with-defaults/src/seed/core/jsonable_encoder.py +++ b/seed/python-sdk/validation/with-defaults/src/seed/core/jsonable_encoder.py @@ -19,13 +19,19 @@ import pydantic from .datetime_utils import serialize_datetime -from .pydantic_utilities import IS_PYDANTIC_V2, encode_by_type, to_jsonable_with_fallback +from .pydantic_utilities import ( + IS_PYDANTIC_V2, + encode_by_type, + to_jsonable_with_fallback, +) SetIntStr = Set[Union[int, str]] DictIntStrAny = Dict[Union[int, str], Any] -def jsonable_encoder(obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None) -> Any: +def jsonable_encoder( + obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None +) -> Any: custom_encoder = custom_encoder or {} if custom_encoder: if type(obj) in custom_encoder: diff --git a/seed/python-sdk/validation/with-defaults/src/seed/core/pydantic_utilities.py b/seed/python-sdk/validation/with-defaults/src/seed/core/pydantic_utilities.py index 170a563d6eb..c63935c32a2 100644 --- a/seed/python-sdk/validation/with-defaults/src/seed/core/pydantic_utilities.py +++ b/seed/python-sdk/validation/with-defaults/src/seed/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) # type: ignore # Pydantic v1 diff --git a/seed/python-sdk/validation/with-defaults/src/seed/core/query_encoder.py b/seed/python-sdk/validation/with-defaults/src/seed/core/query_encoder.py index 24076d72ee9..7cb98f52cd7 100644 --- a/seed/python-sdk/validation/with-defaults/src/seed/core/query_encoder.py +++ b/seed/python-sdk/validation/with-defaults/src/seed/core/query_encoder.py @@ -7,7 +7,9 @@ # Flattens dicts to be of the form {"key[subkey][subkey2]": value} where value is not a dict -def traverse_query_dict(dict_flat: Dict[str, Any], key_prefix: Optional[str] = None) -> Dict[str, Any]: +def traverse_query_dict( + dict_flat: Dict[str, Any], key_prefix: Optional[str] = None +) -> Dict[str, Any]: result = {} for k, v in dict_flat.items(): key = f"{key_prefix}[{k}]" if key_prefix is not None else k @@ -30,4 +32,8 @@ def single_query_encoder(query_key: str, query_value: Any) -> Dict[str, Any]: def encode_query(query: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: - return dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) if query is not None else None + return ( + dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) + if query is not None + else None + ) diff --git a/seed/python-sdk/validation/with-defaults/src/seed/core/serialization.py b/seed/python-sdk/validation/with-defaults/src/seed/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/python-sdk/validation/with-defaults/src/seed/core/serialization.py +++ b/seed/python-sdk/validation/with-defaults/src/seed/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/python-sdk/validation/with-defaults/src/seed/types/__init__.py b/seed/python-sdk/validation/with-defaults/src/seed/types/__init__.py index d30f52138d4..51957e8c8c5 100644 --- a/seed/python-sdk/validation/with-defaults/src/seed/types/__init__.py +++ b/seed/python-sdk/validation/with-defaults/src/seed/types/__init__.py @@ -8,4 +8,12 @@ from .type import Type from .word import Word -__all__ = ["Double", "LargeInteger", "Sentence", "Shape", "SmallInteger", "Type", "Word"] +__all__ = [ + "Double", + "LargeInteger", + "Sentence", + "Shape", + "SmallInteger", + "Type", + "Word", +] diff --git a/seed/python-sdk/validation/with-defaults/src/seed/types/type.py b/seed/python-sdk/validation/with-defaults/src/seed/types/type.py index d44685f20fa..356ad9e2cd5 100644 --- a/seed/python-sdk/validation/with-defaults/src/seed/types/type.py +++ b/seed/python-sdk/validation/with-defaults/src/seed/types/type.py @@ -1,12 +1,11 @@ # This file was auto-generated by Fern from our API Definition. +from ..core.pydantic_utilities import UniversalBaseModel +from .shape import Shape +from ..core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .shape import Shape - class Type(UniversalBaseModel): """ @@ -30,7 +29,9 @@ class Type(UniversalBaseModel): shape: Shape if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/validation/with-defaults/src/seed/version.py b/seed/python-sdk/validation/with-defaults/src/seed/version.py index 7a4010f0235..29cc1476df1 100644 --- a/seed/python-sdk/validation/with-defaults/src/seed/version.py +++ b/seed/python-sdk/validation/with-defaults/src/seed/version.py @@ -1,4 +1,3 @@ - from importlib import metadata __version__ = metadata.version("fern_validation") diff --git a/seed/python-sdk/validation/with-defaults/tests/conftest.py b/seed/python-sdk/validation/with-defaults/tests/conftest.py index 43d45d17627..7eacc89b29e 100644 --- a/seed/python-sdk/validation/with-defaults/tests/conftest.py +++ b/seed/python-sdk/validation/with-defaults/tests/conftest.py @@ -1,9 +1,9 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedValidation import os - import pytest -from seed import AsyncSeedValidation, SeedValidation +from seed import AsyncSeedValidation @pytest.fixture diff --git a/seed/python-sdk/validation/with-defaults/tests/custom/test_client.py b/seed/python-sdk/validation/with-defaults/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/python-sdk/validation/with-defaults/tests/custom/test_client.py +++ b/seed/python-sdk/validation/with-defaults/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/python-sdk/validation/with-defaults/tests/test_root.py b/seed/python-sdk/validation/with-defaults/tests/test_root.py index d3d9ab31af5..7f91d676ddf 100644 --- a/seed/python-sdk/validation/with-defaults/tests/test_root.py +++ b/seed/python-sdk/validation/with-defaults/tests/test_root.py @@ -1,25 +1,48 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedValidation +from seed import AsyncSeedValidation import typing - -from seed import AsyncSeedValidation, SeedValidation - from .utilities import validate_response -async def test_create(client: SeedValidation, async_client: AsyncSeedValidation) -> None: - expected_response: typing.Any = {"decimal": 1.1, "even": 2, "name": "rules", "shape": "SQUARE"} - expected_types: typing.Any = {"decimal": None, "even": "integer", "name": None, "shape": None} +async def test_create( + client: SeedValidation, async_client: AsyncSeedValidation +) -> None: + expected_response: typing.Any = { + "decimal": 1.1, + "even": 2, + "name": "rules", + "shape": "SQUARE", + } + expected_types: typing.Any = { + "decimal": None, + "even": "integer", + "name": None, + "shape": None, + } response = client.create(decimal=1.1, even=1, name="string", shape="SQUARE") validate_response(response, expected_response, expected_types) - async_response = await async_client.create(decimal=1.1, even=1, name="string", shape="SQUARE") + async_response = await async_client.create( + decimal=1.1, even=1, name="string", shape="SQUARE" + ) validate_response(async_response, expected_response, expected_types) async def test_get(client: SeedValidation, async_client: AsyncSeedValidation) -> None: - expected_response: typing.Any = {"decimal": 1.1, "even": 2, "name": "rules", "shape": "SQUARE"} - expected_types: typing.Any = {"decimal": None, "even": "integer", "name": None, "shape": None} + expected_response: typing.Any = { + "decimal": 1.1, + "even": 2, + "name": "rules", + "shape": "SQUARE", + } + expected_types: typing.Any = { + "decimal": None, + "even": "integer", + "name": None, + "shape": None, + } response = client.get(decimal=1.1, even=1, name="string") validate_response(response, expected_response, expected_types) diff --git a/seed/python-sdk/validation/with-defaults/tests/utilities.py b/seed/python-sdk/validation/with-defaults/tests/utilities.py index 13da208eb3a..e8f4472564c 100644 --- a/seed/python-sdk/validation/with-defaults/tests/utilities.py +++ b/seed/python-sdk/validation/with-defaults/tests/utilities.py @@ -3,11 +3,14 @@ import typing import uuid -import pydantic from dateutil import parser +import pydantic + -def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> typing.Any: +def cast_field( + json_expectation: typing.Any, type_expectation: typing.Any +) -> typing.Any: # Cast these specific types which come through as string and expect our # models to cast to the correct type. if type_expectation == "uuid": @@ -25,7 +28,9 @@ def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> ty return json_expectation -def validate_field(response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any) -> None: +def validate_field( + response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectation == "no_validate": return @@ -44,7 +49,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(entry_expectation, dict): is_container_of_complex_type = True validate_response( - response=response[idx], json_expectation=ex, type_expectations=entry_expectation + response=response[idx], + json_expectation=ex, + type_expectations=entry_expectation, ) else: cast_json_expectation.append(cast_field(ex, entry_expectation)) @@ -56,7 +63,10 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # if any of the values of the set have a type_expectation of a dict, we're assuming it's a pydantic # model and keeping it a list. if container_expectation != "set" or not any( - map(lambda value: isinstance(value, dict), list(contents_expectation.values())) + map( + lambda value: isinstance(value, dict), + list(contents_expectation.values()), + ) ): json_expectation = cast_field(json_expectation, container_expectation) elif isinstance(type_expectation, tuple): @@ -65,9 +75,15 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(contents_expectation, dict): json_expectation = { cast_field( - key, contents_expectation.get(idx)[0] if contents_expectation.get(idx) is not None else None # type: ignore + key, + contents_expectation.get(idx)[0] + if contents_expectation.get(idx) is not None + else None, # type: ignore ): cast_field( - value, contents_expectation.get(idx)[1] if contents_expectation.get(idx) is not None else None # type: ignore + value, + contents_expectation.get(idx)[1] + if contents_expectation.get(idx) is not None + else None, # type: ignore ) for idx, (key, value) in enumerate(json_expectation.items()) } @@ -86,7 +102,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # Arg type_expectations is a deeply nested structure that matches the response, but with the values replaced with the expected types -def validate_response(response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any) -> None: +def validate_response( + response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectations == "no_validate": return @@ -96,11 +114,17 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e and not isinstance(response, dict) and not issubclass(type(response), pydantic.BaseModel) ): - validate_field(response=response, json_expectation=json_expectation, type_expectation=type_expectations) + validate_field( + response=response, + json_expectation=json_expectation, + type_expectation=type_expectations, + ) return if isinstance(response, list): - assert len(response) == len(json_expectation), "Length mismatch, expected: {0}, Actual: {1}".format( + assert len(response) == len( + json_expectation + ), "Length mismatch, expected: {0}, Actual: {1}".format( len(response), len(json_expectation) ) content_expectation = type_expectations @@ -108,7 +132,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e content_expectation = type_expectations[1] for idx, item in enumerate(response): validate_response( - response=item, json_expectation=json_expectation[idx], type_expectations=content_expectation[idx] + response=item, + json_expectation=json_expectation[idx], + type_expectations=content_expectation[idx], ) else: response_json = response @@ -116,7 +142,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e response_json = response.dict(by_alias=True) for key, value in json_expectation.items(): - assert key in response_json, "Field {0} not found within the response object: {1}".format( + assert ( + key in response_json + ), "Field {0} not found within the response object: {1}".format( key, response_json ) @@ -128,11 +156,19 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e # Otherwise, we're just validating a single field that's a pydantic model. if isinstance(value, dict) and not isinstance(type_expectation, tuple): validate_response( - response=response_json[key], json_expectation=value, type_expectations=type_expectation + response=response_json[key], + json_expectation=value, + type_expectations=type_expectation, ) else: - validate_field(response=response_json[key], json_expectation=value, type_expectation=type_expectation) + validate_field( + response=response_json[key], + json_expectation=value, + type_expectation=type_expectation, + ) # Ensure there are no additional fields here either del response_json[key] - assert len(response_json) == 0, "Additional fields found, expected None: {0}".format(response_json) + assert ( + len(response_json) == 0 + ), "Additional fields found, expected None: {0}".format(response_json) diff --git a/seed/python-sdk/validation/with-defaults/tests/utils/assets/models/__init__.py b/seed/python-sdk/validation/with-defaults/tests/utils/assets/models/__init__.py index 2cf01263529..3a1c852e71e 100644 --- a/seed/python-sdk/validation/with-defaults/tests/utils/assets/models/__init__.py +++ b/seed/python-sdk/validation/with-defaults/tests/utils/assets/models/__init__.py @@ -5,7 +5,7 @@ from .circle import CircleParams from .object_with_defaults import ObjectWithDefaultsParams from .object_with_optional_field import ObjectWithOptionalFieldParams -from .shape import Shape_CircleParams, Shape_SquareParams, ShapeParams +from .shape import ShapeParams, Shape_CircleParams, Shape_SquareParams from .square import SquareParams from .undiscriminated_shape import UndiscriminatedShapeParams diff --git a/seed/python-sdk/validation/with-defaults/tests/utils/assets/models/circle.py b/seed/python-sdk/validation/with-defaults/tests/utils/assets/models/circle.py index af7a1bf8a8e..253f12d38b3 100644 --- a/seed/python-sdk/validation/with-defaults/tests/utils/assets/models/circle.py +++ b/seed/python-sdk/validation/with-defaults/tests/utils/assets/models/circle.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class CircleParams(typing_extensions.TypedDict): - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] diff --git a/seed/python-sdk/validation/with-defaults/tests/utils/assets/models/object_with_optional_field.py b/seed/python-sdk/validation/with-defaults/tests/utils/assets/models/object_with_optional_field.py index 3ad93d5f305..ebe7dc80547 100644 --- a/seed/python-sdk/validation/with-defaults/tests/utils/assets/models/object_with_optional_field.py +++ b/seed/python-sdk/validation/with-defaults/tests/utils/assets/models/object_with_optional_field.py @@ -7,8 +7,8 @@ import uuid import typing_extensions -from seed.core.serialization import FieldMetadata +from seed.core.serialization import FieldMetadata from .color import Color from .shape import ShapeParams from .undiscriminated_shape import UndiscriminatedShapeParams @@ -18,16 +18,30 @@ class ObjectWithOptionalFieldParams(typing_extensions.TypedDict): literal: typing.Literal["lit_one"] string: typing_extensions.NotRequired[str] integer: typing_extensions.NotRequired[int] - long_: typing_extensions.NotRequired[typing_extensions.Annotated[int, FieldMetadata(alias="long")]] + long_: typing_extensions.NotRequired[ + typing_extensions.Annotated[int, FieldMetadata(alias="long")] + ] double: typing_extensions.NotRequired[float] - bool_: typing_extensions.NotRequired[typing_extensions.Annotated[bool, FieldMetadata(alias="bool")]] + bool_: typing_extensions.NotRequired[ + typing_extensions.Annotated[bool, FieldMetadata(alias="bool")] + ] datetime: typing_extensions.NotRequired[dt.datetime] date: typing_extensions.NotRequired[dt.date] - uuid_: typing_extensions.NotRequired[typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")]] - base_64: typing_extensions.NotRequired[typing_extensions.Annotated[str, FieldMetadata(alias="base64")]] - list_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")]] - set_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")]] - map_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")]] + uuid_: typing_extensions.NotRequired[ + typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")] + ] + base_64: typing_extensions.NotRequired[ + typing_extensions.Annotated[str, FieldMetadata(alias="base64")] + ] + list_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")] + ] + set_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")] + ] + map_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")] + ] enum: typing_extensions.NotRequired[Color] union: typing_extensions.NotRequired[ShapeParams] second_union: typing_extensions.NotRequired[ShapeParams] diff --git a/seed/python-sdk/validation/with-defaults/tests/utils/assets/models/shape.py b/seed/python-sdk/validation/with-defaults/tests/utils/assets/models/shape.py index 2c33c877951..816ffc51bdc 100644 --- a/seed/python-sdk/validation/with-defaults/tests/utils/assets/models/shape.py +++ b/seed/python-sdk/validation/with-defaults/tests/utils/assets/models/shape.py @@ -7,6 +7,7 @@ import typing import typing_extensions + from seed.core.serialization import FieldMetadata @@ -15,13 +16,21 @@ class Base(typing_extensions.TypedDict): class Shape_CircleParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["circle"], FieldMetadata(alias="shapeType")] - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["circle"], FieldMetadata(alias="shapeType") + ] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] class Shape_SquareParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["square"], FieldMetadata(alias="shapeType")] - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["square"], FieldMetadata(alias="shapeType") + ] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] ShapeParams = typing.Union[Shape_CircleParams, Shape_SquareParams] diff --git a/seed/python-sdk/validation/with-defaults/tests/utils/assets/models/square.py b/seed/python-sdk/validation/with-defaults/tests/utils/assets/models/square.py index b9b7dd319bc..bcf08a723c5 100644 --- a/seed/python-sdk/validation/with-defaults/tests/utils/assets/models/square.py +++ b/seed/python-sdk/validation/with-defaults/tests/utils/assets/models/square.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class SquareParams(typing_extensions.TypedDict): - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] diff --git a/seed/python-sdk/validation/with-defaults/tests/utils/test_http_client.py b/seed/python-sdk/validation/with-defaults/tests/utils/test_http_client.py index edd11ca7afb..f5a874a75f3 100644 --- a/seed/python-sdk/validation/with-defaults/tests/utils/test_http_client.py +++ b/seed/python-sdk/validation/with-defaults/tests/utils/test_http_client.py @@ -9,12 +9,17 @@ def get_request_options() -> RequestOptions: def test_get_json_request_body() -> None: - json_body, data_body = get_request_body(json={"hello": "world"}, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json={"hello": "world"}, data=None, request_options=None, omit=None + ) assert json_body == {"hello": "world"} assert data_body is None json_body_extras, data_body_extras = get_request_body( - json={"goodbye": "world"}, data=None, request_options=get_request_options(), omit=None + json={"goodbye": "world"}, + data=None, + request_options=get_request_options(), + omit=None, ) assert json_body_extras == {"goodbye": "world", "see you": "later"} @@ -22,12 +27,17 @@ def test_get_json_request_body() -> None: def test_get_files_request_body() -> None: - json_body, data_body = get_request_body(json=None, data={"hello": "world"}, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data={"hello": "world"}, request_options=None, omit=None + ) assert data_body == {"hello": "world"} assert json_body is None json_body_extras, data_body_extras = get_request_body( - json=None, data={"goodbye": "world"}, request_options=get_request_options(), omit=None + json=None, + data={"goodbye": "world"}, + request_options=get_request_options(), + omit=None, ) assert data_body_extras == {"goodbye": "world", "see you": "later"} @@ -35,7 +45,9 @@ def test_get_files_request_body() -> None: def test_get_none_request_body() -> None: - json_body, data_body = get_request_body(json=None, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data=None, request_options=None, omit=None + ) assert data_body is None assert json_body is None diff --git a/seed/python-sdk/validation/with-defaults/tests/utils/test_query_encoding.py b/seed/python-sdk/validation/with-defaults/tests/utils/test_query_encoding.py index 247e1551b46..fbc8f402167 100644 --- a/seed/python-sdk/validation/with-defaults/tests/utils/test_query_encoding.py +++ b/seed/python-sdk/validation/with-defaults/tests/utils/test_query_encoding.py @@ -4,9 +4,15 @@ def test_query_encoding() -> None: - assert encode_query({"hello world": "hello world"}) == {"hello world": "hello world"} - assert encode_query({"hello_world": {"hello": "world"}}) == {"hello_world[hello]": "world"} - assert encode_query({"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"}) == { + assert encode_query({"hello world": "hello world"}) == { + "hello world": "hello world" + } + assert encode_query({"hello_world": {"hello": "world"}}) == { + "hello_world[hello]": "world" + } + assert encode_query( + {"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"} + ) == { "hello_world[hello][world]": "today", "hello_world[test]": "this", "hi": "there", diff --git a/seed/python-sdk/validation/with-defaults/tests/utils/test_serialization.py b/seed/python-sdk/validation/with-defaults/tests/utils/test_serialization.py index 58b1ed66e6d..5ca956916dd 100644 --- a/seed/python-sdk/validation/with-defaults/tests/utils/test_serialization.py +++ b/seed/python-sdk/validation/with-defaults/tests/utils/test_serialization.py @@ -1,10 +1,12 @@ # This file was auto-generated by Fern from our API Definition. -from typing import Any, List +from typing import List, Any -from seed.core.serialization import convert_and_respect_annotation_metadata +from seed.core.serialization import ( + convert_and_respect_annotation_metadata, +) +from .assets.models import ShapeParams, ObjectWithOptionalFieldParams -from .assets.models import ObjectWithOptionalFieldParams, ShapeParams UNION_TEST: ShapeParams = {"radius_measurement": 1.0, "shape_type": "circle", "id": "1"} UNION_TEST_CONVERTED = {"shapeType": "circle", "radiusMeasurement": 1.0, "id": "1"} @@ -18,20 +20,54 @@ def test_convert_and_respect_annotation_metadata() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) - assert converted == {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"} + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) + assert converted == { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + } def test_convert_and_respect_annotation_metadata_in_list() -> None: data: List[ObjectWithOptionalFieldParams] = [ - {"string": "string", "long_": 12345, "bool_": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long_": 67890, "list_": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long_": 12345, + "bool_": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long_": 67890, + "list_": [], + "literal": "lit_one", + "any": "any", + }, ] - converted = convert_and_respect_annotation_metadata(object_=data, annotation=List[ObjectWithOptionalFieldParams]) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=List[ObjectWithOptionalFieldParams] + ) assert converted == [ - {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long": 67890, "list": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long": 67890, + "list": [], + "literal": "lit_one", + "any": "any", + }, ] @@ -43,7 +79,9 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) assert converted == { "string": "string", @@ -55,12 +93,16 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: def test_convert_and_respect_annotation_metadata_in_union() -> None: - converted = convert_and_respect_annotation_metadata(object_=UNION_TEST, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=UNION_TEST, annotation=ShapeParams + ) assert converted == UNION_TEST_CONVERTED def test_convert_and_respect_annotation_metadata_with_empty_object() -> None: data: Any = {} - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ShapeParams + ) assert converted == data diff --git a/seed/python-sdk/variables/pyproject.toml b/seed/python-sdk/variables/pyproject.toml index c9b9cfb3ac8..e5f14859195 100644 --- a/seed/python-sdk/variables/pyproject.toml +++ b/seed/python-sdk/variables/pyproject.toml @@ -43,6 +43,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/python-sdk/variables/src/seed/client.py b/seed/python-sdk/variables/src/seed/client.py index 2d05705a94f..01b6e9b5251 100644 --- a/seed/python-sdk/variables/src/seed/client.py +++ b/seed/python-sdk/variables/src/seed/client.py @@ -1,11 +1,11 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from .service.client import AsyncServiceClient, ServiceClient +from .core.client_wrapper import SyncClientWrapper +from .service.client import ServiceClient +from .core.client_wrapper import AsyncClientWrapper +from .service.client import AsyncServiceClient class SeedVariables: @@ -41,14 +41,18 @@ def __init__( base_url: str, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.Client] = None + httpx_client: typing.Optional[httpx.Client] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = SyncClientWrapper( base_url=base_url, httpx_client=httpx_client if httpx_client is not None - else httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.Client( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.Client(timeout=_defaulted_timeout), timeout=_defaulted_timeout, @@ -89,14 +93,18 @@ def __init__( base_url: str, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.AsyncClient] = None + httpx_client: typing.Optional[httpx.AsyncClient] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = AsyncClientWrapper( base_url=base_url, httpx_client=httpx_client if httpx_client is not None - else httpx.AsyncClient(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.AsyncClient( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.AsyncClient(timeout=_defaulted_timeout), timeout=_defaulted_timeout, diff --git a/seed/python-sdk/variables/src/seed/core/api_error.py b/seed/python-sdk/variables/src/seed/core/api_error.py index 2e9fc5431cd..da734b58068 100644 --- a/seed/python-sdk/variables/src/seed/core/api_error.py +++ b/seed/python-sdk/variables/src/seed/core/api_error.py @@ -7,7 +7,9 @@ class ApiError(Exception): status_code: typing.Optional[int] body: typing.Any - def __init__(self, *, status_code: typing.Optional[int] = None, body: typing.Any = None): + def __init__( + self, *, status_code: typing.Optional[int] = None, body: typing.Any = None + ): self.status_code = status_code self.body = body diff --git a/seed/python-sdk/variables/src/seed/core/client_wrapper.py b/seed/python-sdk/variables/src/seed/core/client_wrapper.py index 70df8e6ae67..de80d0c53e5 100644 --- a/seed/python-sdk/variables/src/seed/core/client_wrapper.py +++ b/seed/python-sdk/variables/src/seed/core/client_wrapper.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .http_client import AsyncHttpClient, HttpClient +from .http_client import HttpClient +from .http_client import AsyncHttpClient class BaseClientWrapper: @@ -28,7 +27,13 @@ def get_timeout(self) -> typing.Optional[float]: class SyncClientWrapper(BaseClientWrapper): - def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, httpx_client: httpx.Client): + def __init__( + self, + *, + base_url: str, + timeout: typing.Optional[float] = None, + httpx_client: httpx.Client, + ): super().__init__(base_url=base_url, timeout=timeout) self.httpx_client = HttpClient( httpx_client=httpx_client, @@ -39,7 +44,13 @@ def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, htt class AsyncClientWrapper(BaseClientWrapper): - def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, httpx_client: httpx.AsyncClient): + def __init__( + self, + *, + base_url: str, + timeout: typing.Optional[float] = None, + httpx_client: httpx.AsyncClient, + ): super().__init__(base_url=base_url, timeout=timeout) self.httpx_client = AsyncHttpClient( httpx_client=httpx_client, diff --git a/seed/python-sdk/variables/src/seed/core/datetime_utils.py b/seed/python-sdk/variables/src/seed/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/python-sdk/variables/src/seed/core/datetime_utils.py +++ b/seed/python-sdk/variables/src/seed/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/python-sdk/variables/src/seed/core/file.py b/seed/python-sdk/variables/src/seed/core/file.py index cb0d40bbbf3..6e0f92bfcb1 100644 --- a/seed/python-sdk/variables/src/seed/core/file.py +++ b/seed/python-sdk/variables/src/seed/core/file.py @@ -13,12 +13,17 @@ # (filename, file (or bytes), content_type) typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str]], # (filename, file (or bytes), content_type, headers) - typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str], typing.Mapping[str, str]], + typing.Tuple[ + typing.Optional[str], + FileContent, + typing.Optional[str], + typing.Mapping[str, str], + ], ] def convert_file_dict_to_httpx_tuples( - d: typing.Dict[str, typing.Union[File, typing.List[File]]] + d: typing.Dict[str, typing.Union[File, typing.List[File]]], ) -> typing.List[typing.Tuple[str, File]]: """ The format we use is a list of tuples, where the first element is the diff --git a/seed/python-sdk/variables/src/seed/core/http_client.py b/seed/python-sdk/variables/src/seed/core/http_client.py index 9333d8a7f15..091f71bc185 100644 --- a/seed/python-sdk/variables/src/seed/core/http_client.py +++ b/seed/python-sdk/variables/src/seed/core/http_client.py @@ -77,7 +77,9 @@ def _retry_timeout(response: httpx.Response, retries: int) -> float: return retry_after # Apply exponential backoff, capped at MAX_RETRY_DELAY_SECONDS. - retry_delay = min(INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS) + retry_delay = min( + INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS + ) # Add a randomness / jitter to the retry delay to avoid overwhelming the server with retries. timeout = retry_delay * (1 - 0.25 * random()) @@ -90,7 +92,8 @@ def _should_retry(response: httpx.Response) -> bool: def remove_omit_from_dict( - original: typing.Dict[str, typing.Optional[typing.Any]], omit: typing.Optional[typing.Any] + original: typing.Dict[str, typing.Optional[typing.Any]], + omit: typing.Optional[typing.Any], ) -> typing.Dict[str, typing.Any]: if omit is None: return original @@ -108,7 +111,8 @@ def maybe_filter_request_body( ) -> typing.Optional[typing.Any]: if data is None: return ( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else None ) @@ -118,7 +122,8 @@ def maybe_filter_request_body( data_content = { **(jsonable_encoder(remove_omit_from_dict(data, omit))), # type: ignore **( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else {} ), @@ -162,7 +167,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url def request( @@ -174,8 +181,12 @@ def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -184,11 +195,14 @@ def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) response = self.httpx_client.request( method=method, @@ -198,7 +212,11 @@ def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -209,7 +227,10 @@ def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -222,11 +243,15 @@ def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: time.sleep(_retry_timeout(response=response, retries=retries)) @@ -256,8 +281,12 @@ def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -266,11 +295,14 @@ def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) with self.httpx_client.stream( method=method, @@ -280,7 +312,11 @@ def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -291,7 +327,9 @@ def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -304,7 +342,9 @@ def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream @@ -327,7 +367,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url async def request( @@ -339,8 +381,12 @@ async def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -349,11 +395,14 @@ async def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) # Add the input to each of these and do None-safety checks response = await self.httpx_client.request( @@ -364,7 +413,11 @@ async def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -375,7 +428,10 @@ async def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -388,11 +444,15 @@ async def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: await asyncio.sleep(_retry_timeout(response=response, retries=retries)) @@ -421,8 +481,12 @@ async def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -431,11 +495,14 @@ async def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) async with self.httpx_client.stream( method=method, @@ -445,7 +512,11 @@ async def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -456,7 +527,9 @@ async def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -469,7 +542,9 @@ async def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream diff --git a/seed/python-sdk/variables/src/seed/core/jsonable_encoder.py b/seed/python-sdk/variables/src/seed/core/jsonable_encoder.py index d3fd328fd41..12a8b52fc22 100644 --- a/seed/python-sdk/variables/src/seed/core/jsonable_encoder.py +++ b/seed/python-sdk/variables/src/seed/core/jsonable_encoder.py @@ -19,13 +19,19 @@ import pydantic from .datetime_utils import serialize_datetime -from .pydantic_utilities import IS_PYDANTIC_V2, encode_by_type, to_jsonable_with_fallback +from .pydantic_utilities import ( + IS_PYDANTIC_V2, + encode_by_type, + to_jsonable_with_fallback, +) SetIntStr = Set[Union[int, str]] DictIntStrAny = Dict[Union[int, str], Any] -def jsonable_encoder(obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None) -> Any: +def jsonable_encoder( + obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None +) -> Any: custom_encoder = custom_encoder or {} if custom_encoder: if type(obj) in custom_encoder: diff --git a/seed/python-sdk/variables/src/seed/core/pydantic_utilities.py b/seed/python-sdk/variables/src/seed/core/pydantic_utilities.py index 170a563d6eb..c63935c32a2 100644 --- a/seed/python-sdk/variables/src/seed/core/pydantic_utilities.py +++ b/seed/python-sdk/variables/src/seed/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) # type: ignore # Pydantic v1 diff --git a/seed/python-sdk/variables/src/seed/core/query_encoder.py b/seed/python-sdk/variables/src/seed/core/query_encoder.py index 24076d72ee9..7cb98f52cd7 100644 --- a/seed/python-sdk/variables/src/seed/core/query_encoder.py +++ b/seed/python-sdk/variables/src/seed/core/query_encoder.py @@ -7,7 +7,9 @@ # Flattens dicts to be of the form {"key[subkey][subkey2]": value} where value is not a dict -def traverse_query_dict(dict_flat: Dict[str, Any], key_prefix: Optional[str] = None) -> Dict[str, Any]: +def traverse_query_dict( + dict_flat: Dict[str, Any], key_prefix: Optional[str] = None +) -> Dict[str, Any]: result = {} for k, v in dict_flat.items(): key = f"{key_prefix}[{k}]" if key_prefix is not None else k @@ -30,4 +32,8 @@ def single_query_encoder(query_key: str, query_value: Any) -> Dict[str, Any]: def encode_query(query: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: - return dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) if query is not None else None + return ( + dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) + if query is not None + else None + ) diff --git a/seed/python-sdk/variables/src/seed/core/serialization.py b/seed/python-sdk/variables/src/seed/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/python-sdk/variables/src/seed/core/serialization.py +++ b/seed/python-sdk/variables/src/seed/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/python-sdk/variables/src/seed/service/client.py b/seed/python-sdk/variables/src/seed/service/client.py index be59becf6e2..3297fa252ea 100644 --- a/seed/python-sdk/variables/src/seed/service/client.py +++ b/seed/python-sdk/variables/src/seed/service/client.py @@ -1,19 +1,24 @@ # This file was auto-generated by Fern from our API Definition. +from ..core.client_wrapper import SyncClientWrapper import typing +from ..core.request_options import RequestOptions +from ..core.jsonable_encoder import jsonable_encoder from json.decoder import JSONDecodeError - from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.jsonable_encoder import jsonable_encoder -from ..core.request_options import RequestOptions +from ..core.client_wrapper import AsyncClientWrapper class ServiceClient: def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper - def post(self, endpoint_param: str, *, request_options: typing.Optional[RequestOptions] = None) -> None: + def post( + self, + endpoint_param: str, + *, + request_options: typing.Optional[RequestOptions] = None, + ) -> None: """ Parameters ---------- @@ -38,7 +43,9 @@ def post(self, endpoint_param: str, *, request_options: typing.Optional[RequestO ) """ _response = self._client_wrapper.httpx_client.request( - f"{jsonable_encoder(endpoint_param)}", method="POST", request_options=request_options + f"{jsonable_encoder(endpoint_param)}", + method="POST", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: @@ -53,7 +60,12 @@ class AsyncServiceClient: def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper - async def post(self, endpoint_param: str, *, request_options: typing.Optional[RequestOptions] = None) -> None: + async def post( + self, + endpoint_param: str, + *, + request_options: typing.Optional[RequestOptions] = None, + ) -> None: """ Parameters ---------- @@ -86,7 +98,9 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - f"{jsonable_encoder(endpoint_param)}", method="POST", request_options=request_options + f"{jsonable_encoder(endpoint_param)}", + method="POST", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: diff --git a/seed/python-sdk/variables/src/seed/version.py b/seed/python-sdk/variables/src/seed/version.py index 5844ba84fc4..15ed0b91edc 100644 --- a/seed/python-sdk/variables/src/seed/version.py +++ b/seed/python-sdk/variables/src/seed/version.py @@ -1,4 +1,3 @@ - from importlib import metadata __version__ = metadata.version("fern_variables") diff --git a/seed/python-sdk/variables/tests/conftest.py b/seed/python-sdk/variables/tests/conftest.py index 865378e2aea..6d971cbe3a6 100644 --- a/seed/python-sdk/variables/tests/conftest.py +++ b/seed/python-sdk/variables/tests/conftest.py @@ -1,9 +1,9 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedVariables import os - import pytest -from seed import AsyncSeedVariables, SeedVariables +from seed import AsyncSeedVariables @pytest.fixture diff --git a/seed/python-sdk/variables/tests/custom/test_client.py b/seed/python-sdk/variables/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/python-sdk/variables/tests/custom/test_client.py +++ b/seed/python-sdk/variables/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/python-sdk/variables/tests/test_service.py b/seed/python-sdk/variables/tests/test_service.py index 38d4378592c..7e514b1800b 100644 --- a/seed/python-sdk/variables/tests/test_service.py +++ b/seed/python-sdk/variables/tests/test_service.py @@ -1,6 +1,7 @@ # This file was auto-generated by Fern from our API Definition. -from seed import AsyncSeedVariables, SeedVariables +from seed import SeedVariables +from seed import AsyncSeedVariables async def test_post(client: SeedVariables, async_client: AsyncSeedVariables) -> None: diff --git a/seed/python-sdk/variables/tests/utilities.py b/seed/python-sdk/variables/tests/utilities.py index 13da208eb3a..e8f4472564c 100644 --- a/seed/python-sdk/variables/tests/utilities.py +++ b/seed/python-sdk/variables/tests/utilities.py @@ -3,11 +3,14 @@ import typing import uuid -import pydantic from dateutil import parser +import pydantic + -def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> typing.Any: +def cast_field( + json_expectation: typing.Any, type_expectation: typing.Any +) -> typing.Any: # Cast these specific types which come through as string and expect our # models to cast to the correct type. if type_expectation == "uuid": @@ -25,7 +28,9 @@ def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> ty return json_expectation -def validate_field(response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any) -> None: +def validate_field( + response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectation == "no_validate": return @@ -44,7 +49,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(entry_expectation, dict): is_container_of_complex_type = True validate_response( - response=response[idx], json_expectation=ex, type_expectations=entry_expectation + response=response[idx], + json_expectation=ex, + type_expectations=entry_expectation, ) else: cast_json_expectation.append(cast_field(ex, entry_expectation)) @@ -56,7 +63,10 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # if any of the values of the set have a type_expectation of a dict, we're assuming it's a pydantic # model and keeping it a list. if container_expectation != "set" or not any( - map(lambda value: isinstance(value, dict), list(contents_expectation.values())) + map( + lambda value: isinstance(value, dict), + list(contents_expectation.values()), + ) ): json_expectation = cast_field(json_expectation, container_expectation) elif isinstance(type_expectation, tuple): @@ -65,9 +75,15 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(contents_expectation, dict): json_expectation = { cast_field( - key, contents_expectation.get(idx)[0] if contents_expectation.get(idx) is not None else None # type: ignore + key, + contents_expectation.get(idx)[0] + if contents_expectation.get(idx) is not None + else None, # type: ignore ): cast_field( - value, contents_expectation.get(idx)[1] if contents_expectation.get(idx) is not None else None # type: ignore + value, + contents_expectation.get(idx)[1] + if contents_expectation.get(idx) is not None + else None, # type: ignore ) for idx, (key, value) in enumerate(json_expectation.items()) } @@ -86,7 +102,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # Arg type_expectations is a deeply nested structure that matches the response, but with the values replaced with the expected types -def validate_response(response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any) -> None: +def validate_response( + response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectations == "no_validate": return @@ -96,11 +114,17 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e and not isinstance(response, dict) and not issubclass(type(response), pydantic.BaseModel) ): - validate_field(response=response, json_expectation=json_expectation, type_expectation=type_expectations) + validate_field( + response=response, + json_expectation=json_expectation, + type_expectation=type_expectations, + ) return if isinstance(response, list): - assert len(response) == len(json_expectation), "Length mismatch, expected: {0}, Actual: {1}".format( + assert len(response) == len( + json_expectation + ), "Length mismatch, expected: {0}, Actual: {1}".format( len(response), len(json_expectation) ) content_expectation = type_expectations @@ -108,7 +132,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e content_expectation = type_expectations[1] for idx, item in enumerate(response): validate_response( - response=item, json_expectation=json_expectation[idx], type_expectations=content_expectation[idx] + response=item, + json_expectation=json_expectation[idx], + type_expectations=content_expectation[idx], ) else: response_json = response @@ -116,7 +142,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e response_json = response.dict(by_alias=True) for key, value in json_expectation.items(): - assert key in response_json, "Field {0} not found within the response object: {1}".format( + assert ( + key in response_json + ), "Field {0} not found within the response object: {1}".format( key, response_json ) @@ -128,11 +156,19 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e # Otherwise, we're just validating a single field that's a pydantic model. if isinstance(value, dict) and not isinstance(type_expectation, tuple): validate_response( - response=response_json[key], json_expectation=value, type_expectations=type_expectation + response=response_json[key], + json_expectation=value, + type_expectations=type_expectation, ) else: - validate_field(response=response_json[key], json_expectation=value, type_expectation=type_expectation) + validate_field( + response=response_json[key], + json_expectation=value, + type_expectation=type_expectation, + ) # Ensure there are no additional fields here either del response_json[key] - assert len(response_json) == 0, "Additional fields found, expected None: {0}".format(response_json) + assert ( + len(response_json) == 0 + ), "Additional fields found, expected None: {0}".format(response_json) diff --git a/seed/python-sdk/variables/tests/utils/assets/models/__init__.py b/seed/python-sdk/variables/tests/utils/assets/models/__init__.py index 2cf01263529..3a1c852e71e 100644 --- a/seed/python-sdk/variables/tests/utils/assets/models/__init__.py +++ b/seed/python-sdk/variables/tests/utils/assets/models/__init__.py @@ -5,7 +5,7 @@ from .circle import CircleParams from .object_with_defaults import ObjectWithDefaultsParams from .object_with_optional_field import ObjectWithOptionalFieldParams -from .shape import Shape_CircleParams, Shape_SquareParams, ShapeParams +from .shape import ShapeParams, Shape_CircleParams, Shape_SquareParams from .square import SquareParams from .undiscriminated_shape import UndiscriminatedShapeParams diff --git a/seed/python-sdk/variables/tests/utils/assets/models/circle.py b/seed/python-sdk/variables/tests/utils/assets/models/circle.py index af7a1bf8a8e..253f12d38b3 100644 --- a/seed/python-sdk/variables/tests/utils/assets/models/circle.py +++ b/seed/python-sdk/variables/tests/utils/assets/models/circle.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class CircleParams(typing_extensions.TypedDict): - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] diff --git a/seed/python-sdk/variables/tests/utils/assets/models/object_with_optional_field.py b/seed/python-sdk/variables/tests/utils/assets/models/object_with_optional_field.py index 3ad93d5f305..ebe7dc80547 100644 --- a/seed/python-sdk/variables/tests/utils/assets/models/object_with_optional_field.py +++ b/seed/python-sdk/variables/tests/utils/assets/models/object_with_optional_field.py @@ -7,8 +7,8 @@ import uuid import typing_extensions -from seed.core.serialization import FieldMetadata +from seed.core.serialization import FieldMetadata from .color import Color from .shape import ShapeParams from .undiscriminated_shape import UndiscriminatedShapeParams @@ -18,16 +18,30 @@ class ObjectWithOptionalFieldParams(typing_extensions.TypedDict): literal: typing.Literal["lit_one"] string: typing_extensions.NotRequired[str] integer: typing_extensions.NotRequired[int] - long_: typing_extensions.NotRequired[typing_extensions.Annotated[int, FieldMetadata(alias="long")]] + long_: typing_extensions.NotRequired[ + typing_extensions.Annotated[int, FieldMetadata(alias="long")] + ] double: typing_extensions.NotRequired[float] - bool_: typing_extensions.NotRequired[typing_extensions.Annotated[bool, FieldMetadata(alias="bool")]] + bool_: typing_extensions.NotRequired[ + typing_extensions.Annotated[bool, FieldMetadata(alias="bool")] + ] datetime: typing_extensions.NotRequired[dt.datetime] date: typing_extensions.NotRequired[dt.date] - uuid_: typing_extensions.NotRequired[typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")]] - base_64: typing_extensions.NotRequired[typing_extensions.Annotated[str, FieldMetadata(alias="base64")]] - list_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")]] - set_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")]] - map_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")]] + uuid_: typing_extensions.NotRequired[ + typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")] + ] + base_64: typing_extensions.NotRequired[ + typing_extensions.Annotated[str, FieldMetadata(alias="base64")] + ] + list_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")] + ] + set_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")] + ] + map_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")] + ] enum: typing_extensions.NotRequired[Color] union: typing_extensions.NotRequired[ShapeParams] second_union: typing_extensions.NotRequired[ShapeParams] diff --git a/seed/python-sdk/variables/tests/utils/assets/models/shape.py b/seed/python-sdk/variables/tests/utils/assets/models/shape.py index 2c33c877951..816ffc51bdc 100644 --- a/seed/python-sdk/variables/tests/utils/assets/models/shape.py +++ b/seed/python-sdk/variables/tests/utils/assets/models/shape.py @@ -7,6 +7,7 @@ import typing import typing_extensions + from seed.core.serialization import FieldMetadata @@ -15,13 +16,21 @@ class Base(typing_extensions.TypedDict): class Shape_CircleParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["circle"], FieldMetadata(alias="shapeType")] - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["circle"], FieldMetadata(alias="shapeType") + ] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] class Shape_SquareParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["square"], FieldMetadata(alias="shapeType")] - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["square"], FieldMetadata(alias="shapeType") + ] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] ShapeParams = typing.Union[Shape_CircleParams, Shape_SquareParams] diff --git a/seed/python-sdk/variables/tests/utils/assets/models/square.py b/seed/python-sdk/variables/tests/utils/assets/models/square.py index b9b7dd319bc..bcf08a723c5 100644 --- a/seed/python-sdk/variables/tests/utils/assets/models/square.py +++ b/seed/python-sdk/variables/tests/utils/assets/models/square.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class SquareParams(typing_extensions.TypedDict): - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] diff --git a/seed/python-sdk/variables/tests/utils/test_http_client.py b/seed/python-sdk/variables/tests/utils/test_http_client.py index edd11ca7afb..f5a874a75f3 100644 --- a/seed/python-sdk/variables/tests/utils/test_http_client.py +++ b/seed/python-sdk/variables/tests/utils/test_http_client.py @@ -9,12 +9,17 @@ def get_request_options() -> RequestOptions: def test_get_json_request_body() -> None: - json_body, data_body = get_request_body(json={"hello": "world"}, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json={"hello": "world"}, data=None, request_options=None, omit=None + ) assert json_body == {"hello": "world"} assert data_body is None json_body_extras, data_body_extras = get_request_body( - json={"goodbye": "world"}, data=None, request_options=get_request_options(), omit=None + json={"goodbye": "world"}, + data=None, + request_options=get_request_options(), + omit=None, ) assert json_body_extras == {"goodbye": "world", "see you": "later"} @@ -22,12 +27,17 @@ def test_get_json_request_body() -> None: def test_get_files_request_body() -> None: - json_body, data_body = get_request_body(json=None, data={"hello": "world"}, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data={"hello": "world"}, request_options=None, omit=None + ) assert data_body == {"hello": "world"} assert json_body is None json_body_extras, data_body_extras = get_request_body( - json=None, data={"goodbye": "world"}, request_options=get_request_options(), omit=None + json=None, + data={"goodbye": "world"}, + request_options=get_request_options(), + omit=None, ) assert data_body_extras == {"goodbye": "world", "see you": "later"} @@ -35,7 +45,9 @@ def test_get_files_request_body() -> None: def test_get_none_request_body() -> None: - json_body, data_body = get_request_body(json=None, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data=None, request_options=None, omit=None + ) assert data_body is None assert json_body is None diff --git a/seed/python-sdk/variables/tests/utils/test_query_encoding.py b/seed/python-sdk/variables/tests/utils/test_query_encoding.py index 247e1551b46..fbc8f402167 100644 --- a/seed/python-sdk/variables/tests/utils/test_query_encoding.py +++ b/seed/python-sdk/variables/tests/utils/test_query_encoding.py @@ -4,9 +4,15 @@ def test_query_encoding() -> None: - assert encode_query({"hello world": "hello world"}) == {"hello world": "hello world"} - assert encode_query({"hello_world": {"hello": "world"}}) == {"hello_world[hello]": "world"} - assert encode_query({"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"}) == { + assert encode_query({"hello world": "hello world"}) == { + "hello world": "hello world" + } + assert encode_query({"hello_world": {"hello": "world"}}) == { + "hello_world[hello]": "world" + } + assert encode_query( + {"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"} + ) == { "hello_world[hello][world]": "today", "hello_world[test]": "this", "hi": "there", diff --git a/seed/python-sdk/variables/tests/utils/test_serialization.py b/seed/python-sdk/variables/tests/utils/test_serialization.py index 58b1ed66e6d..5ca956916dd 100644 --- a/seed/python-sdk/variables/tests/utils/test_serialization.py +++ b/seed/python-sdk/variables/tests/utils/test_serialization.py @@ -1,10 +1,12 @@ # This file was auto-generated by Fern from our API Definition. -from typing import Any, List +from typing import List, Any -from seed.core.serialization import convert_and_respect_annotation_metadata +from seed.core.serialization import ( + convert_and_respect_annotation_metadata, +) +from .assets.models import ShapeParams, ObjectWithOptionalFieldParams -from .assets.models import ObjectWithOptionalFieldParams, ShapeParams UNION_TEST: ShapeParams = {"radius_measurement": 1.0, "shape_type": "circle", "id": "1"} UNION_TEST_CONVERTED = {"shapeType": "circle", "radiusMeasurement": 1.0, "id": "1"} @@ -18,20 +20,54 @@ def test_convert_and_respect_annotation_metadata() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) - assert converted == {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"} + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) + assert converted == { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + } def test_convert_and_respect_annotation_metadata_in_list() -> None: data: List[ObjectWithOptionalFieldParams] = [ - {"string": "string", "long_": 12345, "bool_": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long_": 67890, "list_": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long_": 12345, + "bool_": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long_": 67890, + "list_": [], + "literal": "lit_one", + "any": "any", + }, ] - converted = convert_and_respect_annotation_metadata(object_=data, annotation=List[ObjectWithOptionalFieldParams]) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=List[ObjectWithOptionalFieldParams] + ) assert converted == [ - {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long": 67890, "list": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long": 67890, + "list": [], + "literal": "lit_one", + "any": "any", + }, ] @@ -43,7 +79,9 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) assert converted == { "string": "string", @@ -55,12 +93,16 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: def test_convert_and_respect_annotation_metadata_in_union() -> None: - converted = convert_and_respect_annotation_metadata(object_=UNION_TEST, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=UNION_TEST, annotation=ShapeParams + ) assert converted == UNION_TEST_CONVERTED def test_convert_and_respect_annotation_metadata_with_empty_object() -> None: data: Any = {} - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ShapeParams + ) assert converted == data diff --git a/seed/python-sdk/version-no-default/pyproject.toml b/seed/python-sdk/version-no-default/pyproject.toml index 8b62c31b78c..eca2bfb63ca 100644 --- a/seed/python-sdk/version-no-default/pyproject.toml +++ b/seed/python-sdk/version-no-default/pyproject.toml @@ -43,6 +43,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/python-sdk/version-no-default/src/seed/client.py b/seed/python-sdk/version-no-default/src/seed/client.py index 0ff83750815..1e45922e8b3 100644 --- a/seed/python-sdk/version-no-default/src/seed/client.py +++ b/seed/python-sdk/version-no-default/src/seed/client.py @@ -1,11 +1,11 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from .user.client import AsyncUserClient, UserClient +from .core.client_wrapper import SyncClientWrapper +from .user.client import UserClient +from .core.client_wrapper import AsyncClientWrapper +from .user.client import AsyncUserClient class SeedVersion: @@ -41,14 +41,18 @@ def __init__( base_url: str, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.Client] = None + httpx_client: typing.Optional[httpx.Client] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = SyncClientWrapper( base_url=base_url, httpx_client=httpx_client if httpx_client is not None - else httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.Client( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.Client(timeout=_defaulted_timeout), timeout=_defaulted_timeout, @@ -89,14 +93,18 @@ def __init__( base_url: str, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.AsyncClient] = None + httpx_client: typing.Optional[httpx.AsyncClient] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = AsyncClientWrapper( base_url=base_url, httpx_client=httpx_client if httpx_client is not None - else httpx.AsyncClient(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.AsyncClient( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.AsyncClient(timeout=_defaulted_timeout), timeout=_defaulted_timeout, diff --git a/seed/python-sdk/version-no-default/src/seed/core/api_error.py b/seed/python-sdk/version-no-default/src/seed/core/api_error.py index 2e9fc5431cd..da734b58068 100644 --- a/seed/python-sdk/version-no-default/src/seed/core/api_error.py +++ b/seed/python-sdk/version-no-default/src/seed/core/api_error.py @@ -7,7 +7,9 @@ class ApiError(Exception): status_code: typing.Optional[int] body: typing.Any - def __init__(self, *, status_code: typing.Optional[int] = None, body: typing.Any = None): + def __init__( + self, *, status_code: typing.Optional[int] = None, body: typing.Any = None + ): self.status_code = status_code self.body = body diff --git a/seed/python-sdk/version-no-default/src/seed/core/client_wrapper.py b/seed/python-sdk/version-no-default/src/seed/core/client_wrapper.py index e7b427f07c0..cb30889a1cf 100644 --- a/seed/python-sdk/version-no-default/src/seed/core/client_wrapper.py +++ b/seed/python-sdk/version-no-default/src/seed/core/client_wrapper.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .http_client import AsyncHttpClient, HttpClient +from .http_client import HttpClient +from .http_client import AsyncHttpClient class BaseClientWrapper: @@ -28,7 +27,13 @@ def get_timeout(self) -> typing.Optional[float]: class SyncClientWrapper(BaseClientWrapper): - def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, httpx_client: httpx.Client): + def __init__( + self, + *, + base_url: str, + timeout: typing.Optional[float] = None, + httpx_client: httpx.Client, + ): super().__init__(base_url=base_url, timeout=timeout) self.httpx_client = HttpClient( httpx_client=httpx_client, @@ -39,7 +44,13 @@ def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, htt class AsyncClientWrapper(BaseClientWrapper): - def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, httpx_client: httpx.AsyncClient): + def __init__( + self, + *, + base_url: str, + timeout: typing.Optional[float] = None, + httpx_client: httpx.AsyncClient, + ): super().__init__(base_url=base_url, timeout=timeout) self.httpx_client = AsyncHttpClient( httpx_client=httpx_client, diff --git a/seed/python-sdk/version-no-default/src/seed/core/datetime_utils.py b/seed/python-sdk/version-no-default/src/seed/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/python-sdk/version-no-default/src/seed/core/datetime_utils.py +++ b/seed/python-sdk/version-no-default/src/seed/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/python-sdk/version-no-default/src/seed/core/file.py b/seed/python-sdk/version-no-default/src/seed/core/file.py index cb0d40bbbf3..6e0f92bfcb1 100644 --- a/seed/python-sdk/version-no-default/src/seed/core/file.py +++ b/seed/python-sdk/version-no-default/src/seed/core/file.py @@ -13,12 +13,17 @@ # (filename, file (or bytes), content_type) typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str]], # (filename, file (or bytes), content_type, headers) - typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str], typing.Mapping[str, str]], + typing.Tuple[ + typing.Optional[str], + FileContent, + typing.Optional[str], + typing.Mapping[str, str], + ], ] def convert_file_dict_to_httpx_tuples( - d: typing.Dict[str, typing.Union[File, typing.List[File]]] + d: typing.Dict[str, typing.Union[File, typing.List[File]]], ) -> typing.List[typing.Tuple[str, File]]: """ The format we use is a list of tuples, where the first element is the diff --git a/seed/python-sdk/version-no-default/src/seed/core/http_client.py b/seed/python-sdk/version-no-default/src/seed/core/http_client.py index 9333d8a7f15..091f71bc185 100644 --- a/seed/python-sdk/version-no-default/src/seed/core/http_client.py +++ b/seed/python-sdk/version-no-default/src/seed/core/http_client.py @@ -77,7 +77,9 @@ def _retry_timeout(response: httpx.Response, retries: int) -> float: return retry_after # Apply exponential backoff, capped at MAX_RETRY_DELAY_SECONDS. - retry_delay = min(INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS) + retry_delay = min( + INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS + ) # Add a randomness / jitter to the retry delay to avoid overwhelming the server with retries. timeout = retry_delay * (1 - 0.25 * random()) @@ -90,7 +92,8 @@ def _should_retry(response: httpx.Response) -> bool: def remove_omit_from_dict( - original: typing.Dict[str, typing.Optional[typing.Any]], omit: typing.Optional[typing.Any] + original: typing.Dict[str, typing.Optional[typing.Any]], + omit: typing.Optional[typing.Any], ) -> typing.Dict[str, typing.Any]: if omit is None: return original @@ -108,7 +111,8 @@ def maybe_filter_request_body( ) -> typing.Optional[typing.Any]: if data is None: return ( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else None ) @@ -118,7 +122,8 @@ def maybe_filter_request_body( data_content = { **(jsonable_encoder(remove_omit_from_dict(data, omit))), # type: ignore **( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else {} ), @@ -162,7 +167,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url def request( @@ -174,8 +181,12 @@ def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -184,11 +195,14 @@ def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) response = self.httpx_client.request( method=method, @@ -198,7 +212,11 @@ def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -209,7 +227,10 @@ def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -222,11 +243,15 @@ def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: time.sleep(_retry_timeout(response=response, retries=retries)) @@ -256,8 +281,12 @@ def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -266,11 +295,14 @@ def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) with self.httpx_client.stream( method=method, @@ -280,7 +312,11 @@ def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -291,7 +327,9 @@ def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -304,7 +342,9 @@ def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream @@ -327,7 +367,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url async def request( @@ -339,8 +381,12 @@ async def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -349,11 +395,14 @@ async def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) # Add the input to each of these and do None-safety checks response = await self.httpx_client.request( @@ -364,7 +413,11 @@ async def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -375,7 +428,10 @@ async def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -388,11 +444,15 @@ async def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: await asyncio.sleep(_retry_timeout(response=response, retries=retries)) @@ -421,8 +481,12 @@ async def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -431,11 +495,14 @@ async def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) async with self.httpx_client.stream( method=method, @@ -445,7 +512,11 @@ async def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -456,7 +527,9 @@ async def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -469,7 +542,9 @@ async def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream diff --git a/seed/python-sdk/version-no-default/src/seed/core/jsonable_encoder.py b/seed/python-sdk/version-no-default/src/seed/core/jsonable_encoder.py index d3fd328fd41..12a8b52fc22 100644 --- a/seed/python-sdk/version-no-default/src/seed/core/jsonable_encoder.py +++ b/seed/python-sdk/version-no-default/src/seed/core/jsonable_encoder.py @@ -19,13 +19,19 @@ import pydantic from .datetime_utils import serialize_datetime -from .pydantic_utilities import IS_PYDANTIC_V2, encode_by_type, to_jsonable_with_fallback +from .pydantic_utilities import ( + IS_PYDANTIC_V2, + encode_by_type, + to_jsonable_with_fallback, +) SetIntStr = Set[Union[int, str]] DictIntStrAny = Dict[Union[int, str], Any] -def jsonable_encoder(obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None) -> Any: +def jsonable_encoder( + obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None +) -> Any: custom_encoder = custom_encoder or {} if custom_encoder: if type(obj) in custom_encoder: diff --git a/seed/python-sdk/version-no-default/src/seed/core/pydantic_utilities.py b/seed/python-sdk/version-no-default/src/seed/core/pydantic_utilities.py index 170a563d6eb..c63935c32a2 100644 --- a/seed/python-sdk/version-no-default/src/seed/core/pydantic_utilities.py +++ b/seed/python-sdk/version-no-default/src/seed/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) # type: ignore # Pydantic v1 diff --git a/seed/python-sdk/version-no-default/src/seed/core/query_encoder.py b/seed/python-sdk/version-no-default/src/seed/core/query_encoder.py index 24076d72ee9..7cb98f52cd7 100644 --- a/seed/python-sdk/version-no-default/src/seed/core/query_encoder.py +++ b/seed/python-sdk/version-no-default/src/seed/core/query_encoder.py @@ -7,7 +7,9 @@ # Flattens dicts to be of the form {"key[subkey][subkey2]": value} where value is not a dict -def traverse_query_dict(dict_flat: Dict[str, Any], key_prefix: Optional[str] = None) -> Dict[str, Any]: +def traverse_query_dict( + dict_flat: Dict[str, Any], key_prefix: Optional[str] = None +) -> Dict[str, Any]: result = {} for k, v in dict_flat.items(): key = f"{key_prefix}[{k}]" if key_prefix is not None else k @@ -30,4 +32,8 @@ def single_query_encoder(query_key: str, query_value: Any) -> Dict[str, Any]: def encode_query(query: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: - return dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) if query is not None else None + return ( + dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) + if query is not None + else None + ) diff --git a/seed/python-sdk/version-no-default/src/seed/core/serialization.py b/seed/python-sdk/version-no-default/src/seed/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/python-sdk/version-no-default/src/seed/core/serialization.py +++ b/seed/python-sdk/version-no-default/src/seed/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/python-sdk/version-no-default/src/seed/user/client.py b/seed/python-sdk/version-no-default/src/seed/user/client.py index ec27306d594..2980e9a81b9 100644 --- a/seed/python-sdk/version-no-default/src/seed/user/client.py +++ b/seed/python-sdk/version-no-default/src/seed/user/client.py @@ -1,22 +1,27 @@ # This file was auto-generated by Fern from our API Definition. +from ..core.client_wrapper import SyncClientWrapper +from .types.user_id import UserId import typing -from json.decoder import JSONDecodeError - -from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.jsonable_encoder import jsonable_encoder -from ..core.pydantic_utilities import parse_obj_as from ..core.request_options import RequestOptions from .types.user import User -from .types.user_id import UserId +from ..core.jsonable_encoder import jsonable_encoder +from ..core.pydantic_utilities import parse_obj_as +from json.decoder import JSONDecodeError +from ..core.api_error import ApiError +from ..core.client_wrapper import AsyncClientWrapper class UserClient: def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper - def get_user(self, user_id: UserId, *, request_options: typing.Optional[RequestOptions] = None) -> User: + def get_user( + self, + user_id: UserId, + *, + request_options: typing.Optional[RequestOptions] = None, + ) -> User: """ Parameters ---------- @@ -41,11 +46,15 @@ def get_user(self, user_id: UserId, *, request_options: typing.Optional[RequestO ) """ _response = self._client_wrapper.httpx_client.request( - f"users/{jsonable_encoder(user_id)}", method="GET", request_options=request_options + f"users/{jsonable_encoder(user_id)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(User, parse_obj_as(type_=User, object_=_response.json())) # type: ignore + return typing.cast( + User, parse_obj_as(type_=User, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -56,7 +65,12 @@ class AsyncUserClient: def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper - async def get_user(self, user_id: UserId, *, request_options: typing.Optional[RequestOptions] = None) -> User: + async def get_user( + self, + user_id: UserId, + *, + request_options: typing.Optional[RequestOptions] = None, + ) -> User: """ Parameters ---------- @@ -89,11 +103,15 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - f"users/{jsonable_encoder(user_id)}", method="GET", request_options=request_options + f"users/{jsonable_encoder(user_id)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(User, parse_obj_as(type_=User, object_=_response.json())) # type: ignore + return typing.cast( + User, parse_obj_as(type_=User, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/version-no-default/src/seed/user/types/user.py b/seed/python-sdk/version-no-default/src/seed/user/types/user.py index ac9f66a554e..bb490559bfb 100644 --- a/seed/python-sdk/version-no-default/src/seed/user/types/user.py +++ b/seed/python-sdk/version-no-default/src/seed/user/types/user.py @@ -1,19 +1,20 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from .user_id import UserId +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .user_id import UserId - class User(UniversalBaseModel): id: UserId name: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/version-no-default/src/seed/version.py b/seed/python-sdk/version-no-default/src/seed/version.py index f3043e9432c..9086f5a95ec 100644 --- a/seed/python-sdk/version-no-default/src/seed/version.py +++ b/seed/python-sdk/version-no-default/src/seed/version.py @@ -1,4 +1,3 @@ - from importlib import metadata __version__ = metadata.version("fern_version-no-default") diff --git a/seed/python-sdk/version-no-default/tests/conftest.py b/seed/python-sdk/version-no-default/tests/conftest.py index 306ba26953d..2425d84c521 100644 --- a/seed/python-sdk/version-no-default/tests/conftest.py +++ b/seed/python-sdk/version-no-default/tests/conftest.py @@ -1,9 +1,9 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedVersion import os - import pytest -from seed import AsyncSeedVersion, SeedVersion +from seed import AsyncSeedVersion @pytest.fixture diff --git a/seed/python-sdk/version-no-default/tests/custom/test_client.py b/seed/python-sdk/version-no-default/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/python-sdk/version-no-default/tests/custom/test_client.py +++ b/seed/python-sdk/version-no-default/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/python-sdk/version-no-default/tests/test_user.py b/seed/python-sdk/version-no-default/tests/test_user.py index dbdb640a2f2..19027eeafcd 100644 --- a/seed/python-sdk/version-no-default/tests/test_user.py +++ b/seed/python-sdk/version-no-default/tests/test_user.py @@ -1,9 +1,8 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedVersion +from seed import AsyncSeedVersion import typing - -from seed import AsyncSeedVersion, SeedVersion - from .utilities import validate_response diff --git a/seed/python-sdk/version-no-default/tests/utilities.py b/seed/python-sdk/version-no-default/tests/utilities.py index 13da208eb3a..e8f4472564c 100644 --- a/seed/python-sdk/version-no-default/tests/utilities.py +++ b/seed/python-sdk/version-no-default/tests/utilities.py @@ -3,11 +3,14 @@ import typing import uuid -import pydantic from dateutil import parser +import pydantic + -def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> typing.Any: +def cast_field( + json_expectation: typing.Any, type_expectation: typing.Any +) -> typing.Any: # Cast these specific types which come through as string and expect our # models to cast to the correct type. if type_expectation == "uuid": @@ -25,7 +28,9 @@ def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> ty return json_expectation -def validate_field(response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any) -> None: +def validate_field( + response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectation == "no_validate": return @@ -44,7 +49,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(entry_expectation, dict): is_container_of_complex_type = True validate_response( - response=response[idx], json_expectation=ex, type_expectations=entry_expectation + response=response[idx], + json_expectation=ex, + type_expectations=entry_expectation, ) else: cast_json_expectation.append(cast_field(ex, entry_expectation)) @@ -56,7 +63,10 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # if any of the values of the set have a type_expectation of a dict, we're assuming it's a pydantic # model and keeping it a list. if container_expectation != "set" or not any( - map(lambda value: isinstance(value, dict), list(contents_expectation.values())) + map( + lambda value: isinstance(value, dict), + list(contents_expectation.values()), + ) ): json_expectation = cast_field(json_expectation, container_expectation) elif isinstance(type_expectation, tuple): @@ -65,9 +75,15 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(contents_expectation, dict): json_expectation = { cast_field( - key, contents_expectation.get(idx)[0] if contents_expectation.get(idx) is not None else None # type: ignore + key, + contents_expectation.get(idx)[0] + if contents_expectation.get(idx) is not None + else None, # type: ignore ): cast_field( - value, contents_expectation.get(idx)[1] if contents_expectation.get(idx) is not None else None # type: ignore + value, + contents_expectation.get(idx)[1] + if contents_expectation.get(idx) is not None + else None, # type: ignore ) for idx, (key, value) in enumerate(json_expectation.items()) } @@ -86,7 +102,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # Arg type_expectations is a deeply nested structure that matches the response, but with the values replaced with the expected types -def validate_response(response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any) -> None: +def validate_response( + response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectations == "no_validate": return @@ -96,11 +114,17 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e and not isinstance(response, dict) and not issubclass(type(response), pydantic.BaseModel) ): - validate_field(response=response, json_expectation=json_expectation, type_expectation=type_expectations) + validate_field( + response=response, + json_expectation=json_expectation, + type_expectation=type_expectations, + ) return if isinstance(response, list): - assert len(response) == len(json_expectation), "Length mismatch, expected: {0}, Actual: {1}".format( + assert len(response) == len( + json_expectation + ), "Length mismatch, expected: {0}, Actual: {1}".format( len(response), len(json_expectation) ) content_expectation = type_expectations @@ -108,7 +132,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e content_expectation = type_expectations[1] for idx, item in enumerate(response): validate_response( - response=item, json_expectation=json_expectation[idx], type_expectations=content_expectation[idx] + response=item, + json_expectation=json_expectation[idx], + type_expectations=content_expectation[idx], ) else: response_json = response @@ -116,7 +142,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e response_json = response.dict(by_alias=True) for key, value in json_expectation.items(): - assert key in response_json, "Field {0} not found within the response object: {1}".format( + assert ( + key in response_json + ), "Field {0} not found within the response object: {1}".format( key, response_json ) @@ -128,11 +156,19 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e # Otherwise, we're just validating a single field that's a pydantic model. if isinstance(value, dict) and not isinstance(type_expectation, tuple): validate_response( - response=response_json[key], json_expectation=value, type_expectations=type_expectation + response=response_json[key], + json_expectation=value, + type_expectations=type_expectation, ) else: - validate_field(response=response_json[key], json_expectation=value, type_expectation=type_expectation) + validate_field( + response=response_json[key], + json_expectation=value, + type_expectation=type_expectation, + ) # Ensure there are no additional fields here either del response_json[key] - assert len(response_json) == 0, "Additional fields found, expected None: {0}".format(response_json) + assert ( + len(response_json) == 0 + ), "Additional fields found, expected None: {0}".format(response_json) diff --git a/seed/python-sdk/version-no-default/tests/utils/assets/models/__init__.py b/seed/python-sdk/version-no-default/tests/utils/assets/models/__init__.py index 2cf01263529..3a1c852e71e 100644 --- a/seed/python-sdk/version-no-default/tests/utils/assets/models/__init__.py +++ b/seed/python-sdk/version-no-default/tests/utils/assets/models/__init__.py @@ -5,7 +5,7 @@ from .circle import CircleParams from .object_with_defaults import ObjectWithDefaultsParams from .object_with_optional_field import ObjectWithOptionalFieldParams -from .shape import Shape_CircleParams, Shape_SquareParams, ShapeParams +from .shape import ShapeParams, Shape_CircleParams, Shape_SquareParams from .square import SquareParams from .undiscriminated_shape import UndiscriminatedShapeParams diff --git a/seed/python-sdk/version-no-default/tests/utils/assets/models/circle.py b/seed/python-sdk/version-no-default/tests/utils/assets/models/circle.py index af7a1bf8a8e..253f12d38b3 100644 --- a/seed/python-sdk/version-no-default/tests/utils/assets/models/circle.py +++ b/seed/python-sdk/version-no-default/tests/utils/assets/models/circle.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class CircleParams(typing_extensions.TypedDict): - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] diff --git a/seed/python-sdk/version-no-default/tests/utils/assets/models/object_with_optional_field.py b/seed/python-sdk/version-no-default/tests/utils/assets/models/object_with_optional_field.py index 3ad93d5f305..ebe7dc80547 100644 --- a/seed/python-sdk/version-no-default/tests/utils/assets/models/object_with_optional_field.py +++ b/seed/python-sdk/version-no-default/tests/utils/assets/models/object_with_optional_field.py @@ -7,8 +7,8 @@ import uuid import typing_extensions -from seed.core.serialization import FieldMetadata +from seed.core.serialization import FieldMetadata from .color import Color from .shape import ShapeParams from .undiscriminated_shape import UndiscriminatedShapeParams @@ -18,16 +18,30 @@ class ObjectWithOptionalFieldParams(typing_extensions.TypedDict): literal: typing.Literal["lit_one"] string: typing_extensions.NotRequired[str] integer: typing_extensions.NotRequired[int] - long_: typing_extensions.NotRequired[typing_extensions.Annotated[int, FieldMetadata(alias="long")]] + long_: typing_extensions.NotRequired[ + typing_extensions.Annotated[int, FieldMetadata(alias="long")] + ] double: typing_extensions.NotRequired[float] - bool_: typing_extensions.NotRequired[typing_extensions.Annotated[bool, FieldMetadata(alias="bool")]] + bool_: typing_extensions.NotRequired[ + typing_extensions.Annotated[bool, FieldMetadata(alias="bool")] + ] datetime: typing_extensions.NotRequired[dt.datetime] date: typing_extensions.NotRequired[dt.date] - uuid_: typing_extensions.NotRequired[typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")]] - base_64: typing_extensions.NotRequired[typing_extensions.Annotated[str, FieldMetadata(alias="base64")]] - list_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")]] - set_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")]] - map_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")]] + uuid_: typing_extensions.NotRequired[ + typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")] + ] + base_64: typing_extensions.NotRequired[ + typing_extensions.Annotated[str, FieldMetadata(alias="base64")] + ] + list_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")] + ] + set_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")] + ] + map_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")] + ] enum: typing_extensions.NotRequired[Color] union: typing_extensions.NotRequired[ShapeParams] second_union: typing_extensions.NotRequired[ShapeParams] diff --git a/seed/python-sdk/version-no-default/tests/utils/assets/models/shape.py b/seed/python-sdk/version-no-default/tests/utils/assets/models/shape.py index 2c33c877951..816ffc51bdc 100644 --- a/seed/python-sdk/version-no-default/tests/utils/assets/models/shape.py +++ b/seed/python-sdk/version-no-default/tests/utils/assets/models/shape.py @@ -7,6 +7,7 @@ import typing import typing_extensions + from seed.core.serialization import FieldMetadata @@ -15,13 +16,21 @@ class Base(typing_extensions.TypedDict): class Shape_CircleParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["circle"], FieldMetadata(alias="shapeType")] - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["circle"], FieldMetadata(alias="shapeType") + ] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] class Shape_SquareParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["square"], FieldMetadata(alias="shapeType")] - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["square"], FieldMetadata(alias="shapeType") + ] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] ShapeParams = typing.Union[Shape_CircleParams, Shape_SquareParams] diff --git a/seed/python-sdk/version-no-default/tests/utils/assets/models/square.py b/seed/python-sdk/version-no-default/tests/utils/assets/models/square.py index b9b7dd319bc..bcf08a723c5 100644 --- a/seed/python-sdk/version-no-default/tests/utils/assets/models/square.py +++ b/seed/python-sdk/version-no-default/tests/utils/assets/models/square.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class SquareParams(typing_extensions.TypedDict): - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] diff --git a/seed/python-sdk/version-no-default/tests/utils/test_http_client.py b/seed/python-sdk/version-no-default/tests/utils/test_http_client.py index edd11ca7afb..f5a874a75f3 100644 --- a/seed/python-sdk/version-no-default/tests/utils/test_http_client.py +++ b/seed/python-sdk/version-no-default/tests/utils/test_http_client.py @@ -9,12 +9,17 @@ def get_request_options() -> RequestOptions: def test_get_json_request_body() -> None: - json_body, data_body = get_request_body(json={"hello": "world"}, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json={"hello": "world"}, data=None, request_options=None, omit=None + ) assert json_body == {"hello": "world"} assert data_body is None json_body_extras, data_body_extras = get_request_body( - json={"goodbye": "world"}, data=None, request_options=get_request_options(), omit=None + json={"goodbye": "world"}, + data=None, + request_options=get_request_options(), + omit=None, ) assert json_body_extras == {"goodbye": "world", "see you": "later"} @@ -22,12 +27,17 @@ def test_get_json_request_body() -> None: def test_get_files_request_body() -> None: - json_body, data_body = get_request_body(json=None, data={"hello": "world"}, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data={"hello": "world"}, request_options=None, omit=None + ) assert data_body == {"hello": "world"} assert json_body is None json_body_extras, data_body_extras = get_request_body( - json=None, data={"goodbye": "world"}, request_options=get_request_options(), omit=None + json=None, + data={"goodbye": "world"}, + request_options=get_request_options(), + omit=None, ) assert data_body_extras == {"goodbye": "world", "see you": "later"} @@ -35,7 +45,9 @@ def test_get_files_request_body() -> None: def test_get_none_request_body() -> None: - json_body, data_body = get_request_body(json=None, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data=None, request_options=None, omit=None + ) assert data_body is None assert json_body is None diff --git a/seed/python-sdk/version-no-default/tests/utils/test_query_encoding.py b/seed/python-sdk/version-no-default/tests/utils/test_query_encoding.py index 247e1551b46..fbc8f402167 100644 --- a/seed/python-sdk/version-no-default/tests/utils/test_query_encoding.py +++ b/seed/python-sdk/version-no-default/tests/utils/test_query_encoding.py @@ -4,9 +4,15 @@ def test_query_encoding() -> None: - assert encode_query({"hello world": "hello world"}) == {"hello world": "hello world"} - assert encode_query({"hello_world": {"hello": "world"}}) == {"hello_world[hello]": "world"} - assert encode_query({"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"}) == { + assert encode_query({"hello world": "hello world"}) == { + "hello world": "hello world" + } + assert encode_query({"hello_world": {"hello": "world"}}) == { + "hello_world[hello]": "world" + } + assert encode_query( + {"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"} + ) == { "hello_world[hello][world]": "today", "hello_world[test]": "this", "hi": "there", diff --git a/seed/python-sdk/version-no-default/tests/utils/test_serialization.py b/seed/python-sdk/version-no-default/tests/utils/test_serialization.py index 58b1ed66e6d..5ca956916dd 100644 --- a/seed/python-sdk/version-no-default/tests/utils/test_serialization.py +++ b/seed/python-sdk/version-no-default/tests/utils/test_serialization.py @@ -1,10 +1,12 @@ # This file was auto-generated by Fern from our API Definition. -from typing import Any, List +from typing import List, Any -from seed.core.serialization import convert_and_respect_annotation_metadata +from seed.core.serialization import ( + convert_and_respect_annotation_metadata, +) +from .assets.models import ShapeParams, ObjectWithOptionalFieldParams -from .assets.models import ObjectWithOptionalFieldParams, ShapeParams UNION_TEST: ShapeParams = {"radius_measurement": 1.0, "shape_type": "circle", "id": "1"} UNION_TEST_CONVERTED = {"shapeType": "circle", "radiusMeasurement": 1.0, "id": "1"} @@ -18,20 +20,54 @@ def test_convert_and_respect_annotation_metadata() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) - assert converted == {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"} + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) + assert converted == { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + } def test_convert_and_respect_annotation_metadata_in_list() -> None: data: List[ObjectWithOptionalFieldParams] = [ - {"string": "string", "long_": 12345, "bool_": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long_": 67890, "list_": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long_": 12345, + "bool_": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long_": 67890, + "list_": [], + "literal": "lit_one", + "any": "any", + }, ] - converted = convert_and_respect_annotation_metadata(object_=data, annotation=List[ObjectWithOptionalFieldParams]) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=List[ObjectWithOptionalFieldParams] + ) assert converted == [ - {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long": 67890, "list": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long": 67890, + "list": [], + "literal": "lit_one", + "any": "any", + }, ] @@ -43,7 +79,9 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) assert converted == { "string": "string", @@ -55,12 +93,16 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: def test_convert_and_respect_annotation_metadata_in_union() -> None: - converted = convert_and_respect_annotation_metadata(object_=UNION_TEST, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=UNION_TEST, annotation=ShapeParams + ) assert converted == UNION_TEST_CONVERTED def test_convert_and_respect_annotation_metadata_with_empty_object() -> None: data: Any = {} - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ShapeParams + ) assert converted == data diff --git a/seed/python-sdk/version/pyproject.toml b/seed/python-sdk/version/pyproject.toml index a5aaa4dc707..ddad323bd5c 100644 --- a/seed/python-sdk/version/pyproject.toml +++ b/seed/python-sdk/version/pyproject.toml @@ -43,6 +43,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/python-sdk/version/src/seed/client.py b/seed/python-sdk/version/src/seed/client.py index 0ff83750815..1e45922e8b3 100644 --- a/seed/python-sdk/version/src/seed/client.py +++ b/seed/python-sdk/version/src/seed/client.py @@ -1,11 +1,11 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from .user.client import AsyncUserClient, UserClient +from .core.client_wrapper import SyncClientWrapper +from .user.client import UserClient +from .core.client_wrapper import AsyncClientWrapper +from .user.client import AsyncUserClient class SeedVersion: @@ -41,14 +41,18 @@ def __init__( base_url: str, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.Client] = None + httpx_client: typing.Optional[httpx.Client] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = SyncClientWrapper( base_url=base_url, httpx_client=httpx_client if httpx_client is not None - else httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.Client( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.Client(timeout=_defaulted_timeout), timeout=_defaulted_timeout, @@ -89,14 +93,18 @@ def __init__( base_url: str, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.AsyncClient] = None + httpx_client: typing.Optional[httpx.AsyncClient] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = AsyncClientWrapper( base_url=base_url, httpx_client=httpx_client if httpx_client is not None - else httpx.AsyncClient(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.AsyncClient( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.AsyncClient(timeout=_defaulted_timeout), timeout=_defaulted_timeout, diff --git a/seed/python-sdk/version/src/seed/core/api_error.py b/seed/python-sdk/version/src/seed/core/api_error.py index 2e9fc5431cd..da734b58068 100644 --- a/seed/python-sdk/version/src/seed/core/api_error.py +++ b/seed/python-sdk/version/src/seed/core/api_error.py @@ -7,7 +7,9 @@ class ApiError(Exception): status_code: typing.Optional[int] body: typing.Any - def __init__(self, *, status_code: typing.Optional[int] = None, body: typing.Any = None): + def __init__( + self, *, status_code: typing.Optional[int] = None, body: typing.Any = None + ): self.status_code = status_code self.body = body diff --git a/seed/python-sdk/version/src/seed/core/client_wrapper.py b/seed/python-sdk/version/src/seed/core/client_wrapper.py index 6dbffd039a9..8744e8afaf9 100644 --- a/seed/python-sdk/version/src/seed/core/client_wrapper.py +++ b/seed/python-sdk/version/src/seed/core/client_wrapper.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .http_client import AsyncHttpClient, HttpClient +from .http_client import HttpClient +from .http_client import AsyncHttpClient class BaseClientWrapper: @@ -28,7 +27,13 @@ def get_timeout(self) -> typing.Optional[float]: class SyncClientWrapper(BaseClientWrapper): - def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, httpx_client: httpx.Client): + def __init__( + self, + *, + base_url: str, + timeout: typing.Optional[float] = None, + httpx_client: httpx.Client, + ): super().__init__(base_url=base_url, timeout=timeout) self.httpx_client = HttpClient( httpx_client=httpx_client, @@ -39,7 +44,13 @@ def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, htt class AsyncClientWrapper(BaseClientWrapper): - def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, httpx_client: httpx.AsyncClient): + def __init__( + self, + *, + base_url: str, + timeout: typing.Optional[float] = None, + httpx_client: httpx.AsyncClient, + ): super().__init__(base_url=base_url, timeout=timeout) self.httpx_client = AsyncHttpClient( httpx_client=httpx_client, diff --git a/seed/python-sdk/version/src/seed/core/datetime_utils.py b/seed/python-sdk/version/src/seed/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/python-sdk/version/src/seed/core/datetime_utils.py +++ b/seed/python-sdk/version/src/seed/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/python-sdk/version/src/seed/core/file.py b/seed/python-sdk/version/src/seed/core/file.py index cb0d40bbbf3..6e0f92bfcb1 100644 --- a/seed/python-sdk/version/src/seed/core/file.py +++ b/seed/python-sdk/version/src/seed/core/file.py @@ -13,12 +13,17 @@ # (filename, file (or bytes), content_type) typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str]], # (filename, file (or bytes), content_type, headers) - typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str], typing.Mapping[str, str]], + typing.Tuple[ + typing.Optional[str], + FileContent, + typing.Optional[str], + typing.Mapping[str, str], + ], ] def convert_file_dict_to_httpx_tuples( - d: typing.Dict[str, typing.Union[File, typing.List[File]]] + d: typing.Dict[str, typing.Union[File, typing.List[File]]], ) -> typing.List[typing.Tuple[str, File]]: """ The format we use is a list of tuples, where the first element is the diff --git a/seed/python-sdk/version/src/seed/core/http_client.py b/seed/python-sdk/version/src/seed/core/http_client.py index 9333d8a7f15..091f71bc185 100644 --- a/seed/python-sdk/version/src/seed/core/http_client.py +++ b/seed/python-sdk/version/src/seed/core/http_client.py @@ -77,7 +77,9 @@ def _retry_timeout(response: httpx.Response, retries: int) -> float: return retry_after # Apply exponential backoff, capped at MAX_RETRY_DELAY_SECONDS. - retry_delay = min(INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS) + retry_delay = min( + INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS + ) # Add a randomness / jitter to the retry delay to avoid overwhelming the server with retries. timeout = retry_delay * (1 - 0.25 * random()) @@ -90,7 +92,8 @@ def _should_retry(response: httpx.Response) -> bool: def remove_omit_from_dict( - original: typing.Dict[str, typing.Optional[typing.Any]], omit: typing.Optional[typing.Any] + original: typing.Dict[str, typing.Optional[typing.Any]], + omit: typing.Optional[typing.Any], ) -> typing.Dict[str, typing.Any]: if omit is None: return original @@ -108,7 +111,8 @@ def maybe_filter_request_body( ) -> typing.Optional[typing.Any]: if data is None: return ( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else None ) @@ -118,7 +122,8 @@ def maybe_filter_request_body( data_content = { **(jsonable_encoder(remove_omit_from_dict(data, omit))), # type: ignore **( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else {} ), @@ -162,7 +167,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url def request( @@ -174,8 +181,12 @@ def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -184,11 +195,14 @@ def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) response = self.httpx_client.request( method=method, @@ -198,7 +212,11 @@ def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -209,7 +227,10 @@ def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -222,11 +243,15 @@ def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: time.sleep(_retry_timeout(response=response, retries=retries)) @@ -256,8 +281,12 @@ def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -266,11 +295,14 @@ def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) with self.httpx_client.stream( method=method, @@ -280,7 +312,11 @@ def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -291,7 +327,9 @@ def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -304,7 +342,9 @@ def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream @@ -327,7 +367,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url async def request( @@ -339,8 +381,12 @@ async def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -349,11 +395,14 @@ async def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) # Add the input to each of these and do None-safety checks response = await self.httpx_client.request( @@ -364,7 +413,11 @@ async def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -375,7 +428,10 @@ async def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -388,11 +444,15 @@ async def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: await asyncio.sleep(_retry_timeout(response=response, retries=retries)) @@ -421,8 +481,12 @@ async def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -431,11 +495,14 @@ async def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) async with self.httpx_client.stream( method=method, @@ -445,7 +512,11 @@ async def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -456,7 +527,9 @@ async def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -469,7 +542,9 @@ async def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream diff --git a/seed/python-sdk/version/src/seed/core/jsonable_encoder.py b/seed/python-sdk/version/src/seed/core/jsonable_encoder.py index d3fd328fd41..12a8b52fc22 100644 --- a/seed/python-sdk/version/src/seed/core/jsonable_encoder.py +++ b/seed/python-sdk/version/src/seed/core/jsonable_encoder.py @@ -19,13 +19,19 @@ import pydantic from .datetime_utils import serialize_datetime -from .pydantic_utilities import IS_PYDANTIC_V2, encode_by_type, to_jsonable_with_fallback +from .pydantic_utilities import ( + IS_PYDANTIC_V2, + encode_by_type, + to_jsonable_with_fallback, +) SetIntStr = Set[Union[int, str]] DictIntStrAny = Dict[Union[int, str], Any] -def jsonable_encoder(obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None) -> Any: +def jsonable_encoder( + obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None +) -> Any: custom_encoder = custom_encoder or {} if custom_encoder: if type(obj) in custom_encoder: diff --git a/seed/python-sdk/version/src/seed/core/pydantic_utilities.py b/seed/python-sdk/version/src/seed/core/pydantic_utilities.py index 170a563d6eb..c63935c32a2 100644 --- a/seed/python-sdk/version/src/seed/core/pydantic_utilities.py +++ b/seed/python-sdk/version/src/seed/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) # type: ignore # Pydantic v1 diff --git a/seed/python-sdk/version/src/seed/core/query_encoder.py b/seed/python-sdk/version/src/seed/core/query_encoder.py index 24076d72ee9..7cb98f52cd7 100644 --- a/seed/python-sdk/version/src/seed/core/query_encoder.py +++ b/seed/python-sdk/version/src/seed/core/query_encoder.py @@ -7,7 +7,9 @@ # Flattens dicts to be of the form {"key[subkey][subkey2]": value} where value is not a dict -def traverse_query_dict(dict_flat: Dict[str, Any], key_prefix: Optional[str] = None) -> Dict[str, Any]: +def traverse_query_dict( + dict_flat: Dict[str, Any], key_prefix: Optional[str] = None +) -> Dict[str, Any]: result = {} for k, v in dict_flat.items(): key = f"{key_prefix}[{k}]" if key_prefix is not None else k @@ -30,4 +32,8 @@ def single_query_encoder(query_key: str, query_value: Any) -> Dict[str, Any]: def encode_query(query: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: - return dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) if query is not None else None + return ( + dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) + if query is not None + else None + ) diff --git a/seed/python-sdk/version/src/seed/core/serialization.py b/seed/python-sdk/version/src/seed/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/python-sdk/version/src/seed/core/serialization.py +++ b/seed/python-sdk/version/src/seed/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/python-sdk/version/src/seed/user/client.py b/seed/python-sdk/version/src/seed/user/client.py index ec27306d594..2980e9a81b9 100644 --- a/seed/python-sdk/version/src/seed/user/client.py +++ b/seed/python-sdk/version/src/seed/user/client.py @@ -1,22 +1,27 @@ # This file was auto-generated by Fern from our API Definition. +from ..core.client_wrapper import SyncClientWrapper +from .types.user_id import UserId import typing -from json.decoder import JSONDecodeError - -from ..core.api_error import ApiError -from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper -from ..core.jsonable_encoder import jsonable_encoder -from ..core.pydantic_utilities import parse_obj_as from ..core.request_options import RequestOptions from .types.user import User -from .types.user_id import UserId +from ..core.jsonable_encoder import jsonable_encoder +from ..core.pydantic_utilities import parse_obj_as +from json.decoder import JSONDecodeError +from ..core.api_error import ApiError +from ..core.client_wrapper import AsyncClientWrapper class UserClient: def __init__(self, *, client_wrapper: SyncClientWrapper): self._client_wrapper = client_wrapper - def get_user(self, user_id: UserId, *, request_options: typing.Optional[RequestOptions] = None) -> User: + def get_user( + self, + user_id: UserId, + *, + request_options: typing.Optional[RequestOptions] = None, + ) -> User: """ Parameters ---------- @@ -41,11 +46,15 @@ def get_user(self, user_id: UserId, *, request_options: typing.Optional[RequestO ) """ _response = self._client_wrapper.httpx_client.request( - f"users/{jsonable_encoder(user_id)}", method="GET", request_options=request_options + f"users/{jsonable_encoder(user_id)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(User, parse_obj_as(type_=User, object_=_response.json())) # type: ignore + return typing.cast( + User, parse_obj_as(type_=User, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) @@ -56,7 +65,12 @@ class AsyncUserClient: def __init__(self, *, client_wrapper: AsyncClientWrapper): self._client_wrapper = client_wrapper - async def get_user(self, user_id: UserId, *, request_options: typing.Optional[RequestOptions] = None) -> User: + async def get_user( + self, + user_id: UserId, + *, + request_options: typing.Optional[RequestOptions] = None, + ) -> User: """ Parameters ---------- @@ -89,11 +103,15 @@ async def main() -> None: asyncio.run(main()) """ _response = await self._client_wrapper.httpx_client.request( - f"users/{jsonable_encoder(user_id)}", method="GET", request_options=request_options + f"users/{jsonable_encoder(user_id)}", + method="GET", + request_options=request_options, ) try: if 200 <= _response.status_code < 300: - return typing.cast(User, parse_obj_as(type_=User, object_=_response.json())) # type: ignore + return typing.cast( + User, parse_obj_as(type_=User, object_=_response.json()) + ) # type: ignore _response_json = _response.json() except JSONDecodeError: raise ApiError(status_code=_response.status_code, body=_response.text) diff --git a/seed/python-sdk/version/src/seed/user/types/user.py b/seed/python-sdk/version/src/seed/user/types/user.py index ac9f66a554e..bb490559bfb 100644 --- a/seed/python-sdk/version/src/seed/user/types/user.py +++ b/seed/python-sdk/version/src/seed/user/types/user.py @@ -1,19 +1,20 @@ # This file was auto-generated by Fern from our API Definition. +from ...core.pydantic_utilities import UniversalBaseModel +from .user_id import UserId +from ...core.pydantic_utilities import IS_PYDANTIC_V2 import typing - import pydantic -from ...core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel -from .user_id import UserId - class User(UniversalBaseModel): id: UserId name: str if IS_PYDANTIC_V2: - model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow", frozen=True) # type: ignore # Pydantic v2 + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict( + extra="allow", frozen=True + ) # type: ignore # Pydantic v2 else: class Config: diff --git a/seed/python-sdk/version/src/seed/version.py b/seed/python-sdk/version/src/seed/version.py index 87efec6f85c..a105e6a421f 100644 --- a/seed/python-sdk/version/src/seed/version.py +++ b/seed/python-sdk/version/src/seed/version.py @@ -1,4 +1,3 @@ - from importlib import metadata __version__ = metadata.version("fern_version") diff --git a/seed/python-sdk/version/tests/conftest.py b/seed/python-sdk/version/tests/conftest.py index 306ba26953d..2425d84c521 100644 --- a/seed/python-sdk/version/tests/conftest.py +++ b/seed/python-sdk/version/tests/conftest.py @@ -1,9 +1,9 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedVersion import os - import pytest -from seed import AsyncSeedVersion, SeedVersion +from seed import AsyncSeedVersion @pytest.fixture diff --git a/seed/python-sdk/version/tests/custom/test_client.py b/seed/python-sdk/version/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/python-sdk/version/tests/custom/test_client.py +++ b/seed/python-sdk/version/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/python-sdk/version/tests/test_user.py b/seed/python-sdk/version/tests/test_user.py index dbdb640a2f2..19027eeafcd 100644 --- a/seed/python-sdk/version/tests/test_user.py +++ b/seed/python-sdk/version/tests/test_user.py @@ -1,9 +1,8 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedVersion +from seed import AsyncSeedVersion import typing - -from seed import AsyncSeedVersion, SeedVersion - from .utilities import validate_response diff --git a/seed/python-sdk/version/tests/utilities.py b/seed/python-sdk/version/tests/utilities.py index 13da208eb3a..e8f4472564c 100644 --- a/seed/python-sdk/version/tests/utilities.py +++ b/seed/python-sdk/version/tests/utilities.py @@ -3,11 +3,14 @@ import typing import uuid -import pydantic from dateutil import parser +import pydantic + -def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> typing.Any: +def cast_field( + json_expectation: typing.Any, type_expectation: typing.Any +) -> typing.Any: # Cast these specific types which come through as string and expect our # models to cast to the correct type. if type_expectation == "uuid": @@ -25,7 +28,9 @@ def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> ty return json_expectation -def validate_field(response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any) -> None: +def validate_field( + response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectation == "no_validate": return @@ -44,7 +49,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(entry_expectation, dict): is_container_of_complex_type = True validate_response( - response=response[idx], json_expectation=ex, type_expectations=entry_expectation + response=response[idx], + json_expectation=ex, + type_expectations=entry_expectation, ) else: cast_json_expectation.append(cast_field(ex, entry_expectation)) @@ -56,7 +63,10 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # if any of the values of the set have a type_expectation of a dict, we're assuming it's a pydantic # model and keeping it a list. if container_expectation != "set" or not any( - map(lambda value: isinstance(value, dict), list(contents_expectation.values())) + map( + lambda value: isinstance(value, dict), + list(contents_expectation.values()), + ) ): json_expectation = cast_field(json_expectation, container_expectation) elif isinstance(type_expectation, tuple): @@ -65,9 +75,15 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(contents_expectation, dict): json_expectation = { cast_field( - key, contents_expectation.get(idx)[0] if contents_expectation.get(idx) is not None else None # type: ignore + key, + contents_expectation.get(idx)[0] + if contents_expectation.get(idx) is not None + else None, # type: ignore ): cast_field( - value, contents_expectation.get(idx)[1] if contents_expectation.get(idx) is not None else None # type: ignore + value, + contents_expectation.get(idx)[1] + if contents_expectation.get(idx) is not None + else None, # type: ignore ) for idx, (key, value) in enumerate(json_expectation.items()) } @@ -86,7 +102,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # Arg type_expectations is a deeply nested structure that matches the response, but with the values replaced with the expected types -def validate_response(response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any) -> None: +def validate_response( + response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectations == "no_validate": return @@ -96,11 +114,17 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e and not isinstance(response, dict) and not issubclass(type(response), pydantic.BaseModel) ): - validate_field(response=response, json_expectation=json_expectation, type_expectation=type_expectations) + validate_field( + response=response, + json_expectation=json_expectation, + type_expectation=type_expectations, + ) return if isinstance(response, list): - assert len(response) == len(json_expectation), "Length mismatch, expected: {0}, Actual: {1}".format( + assert len(response) == len( + json_expectation + ), "Length mismatch, expected: {0}, Actual: {1}".format( len(response), len(json_expectation) ) content_expectation = type_expectations @@ -108,7 +132,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e content_expectation = type_expectations[1] for idx, item in enumerate(response): validate_response( - response=item, json_expectation=json_expectation[idx], type_expectations=content_expectation[idx] + response=item, + json_expectation=json_expectation[idx], + type_expectations=content_expectation[idx], ) else: response_json = response @@ -116,7 +142,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e response_json = response.dict(by_alias=True) for key, value in json_expectation.items(): - assert key in response_json, "Field {0} not found within the response object: {1}".format( + assert ( + key in response_json + ), "Field {0} not found within the response object: {1}".format( key, response_json ) @@ -128,11 +156,19 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e # Otherwise, we're just validating a single field that's a pydantic model. if isinstance(value, dict) and not isinstance(type_expectation, tuple): validate_response( - response=response_json[key], json_expectation=value, type_expectations=type_expectation + response=response_json[key], + json_expectation=value, + type_expectations=type_expectation, ) else: - validate_field(response=response_json[key], json_expectation=value, type_expectation=type_expectation) + validate_field( + response=response_json[key], + json_expectation=value, + type_expectation=type_expectation, + ) # Ensure there are no additional fields here either del response_json[key] - assert len(response_json) == 0, "Additional fields found, expected None: {0}".format(response_json) + assert ( + len(response_json) == 0 + ), "Additional fields found, expected None: {0}".format(response_json) diff --git a/seed/python-sdk/version/tests/utils/assets/models/__init__.py b/seed/python-sdk/version/tests/utils/assets/models/__init__.py index 2cf01263529..3a1c852e71e 100644 --- a/seed/python-sdk/version/tests/utils/assets/models/__init__.py +++ b/seed/python-sdk/version/tests/utils/assets/models/__init__.py @@ -5,7 +5,7 @@ from .circle import CircleParams from .object_with_defaults import ObjectWithDefaultsParams from .object_with_optional_field import ObjectWithOptionalFieldParams -from .shape import Shape_CircleParams, Shape_SquareParams, ShapeParams +from .shape import ShapeParams, Shape_CircleParams, Shape_SquareParams from .square import SquareParams from .undiscriminated_shape import UndiscriminatedShapeParams diff --git a/seed/python-sdk/version/tests/utils/assets/models/circle.py b/seed/python-sdk/version/tests/utils/assets/models/circle.py index af7a1bf8a8e..253f12d38b3 100644 --- a/seed/python-sdk/version/tests/utils/assets/models/circle.py +++ b/seed/python-sdk/version/tests/utils/assets/models/circle.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class CircleParams(typing_extensions.TypedDict): - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] diff --git a/seed/python-sdk/version/tests/utils/assets/models/object_with_optional_field.py b/seed/python-sdk/version/tests/utils/assets/models/object_with_optional_field.py index 3ad93d5f305..ebe7dc80547 100644 --- a/seed/python-sdk/version/tests/utils/assets/models/object_with_optional_field.py +++ b/seed/python-sdk/version/tests/utils/assets/models/object_with_optional_field.py @@ -7,8 +7,8 @@ import uuid import typing_extensions -from seed.core.serialization import FieldMetadata +from seed.core.serialization import FieldMetadata from .color import Color from .shape import ShapeParams from .undiscriminated_shape import UndiscriminatedShapeParams @@ -18,16 +18,30 @@ class ObjectWithOptionalFieldParams(typing_extensions.TypedDict): literal: typing.Literal["lit_one"] string: typing_extensions.NotRequired[str] integer: typing_extensions.NotRequired[int] - long_: typing_extensions.NotRequired[typing_extensions.Annotated[int, FieldMetadata(alias="long")]] + long_: typing_extensions.NotRequired[ + typing_extensions.Annotated[int, FieldMetadata(alias="long")] + ] double: typing_extensions.NotRequired[float] - bool_: typing_extensions.NotRequired[typing_extensions.Annotated[bool, FieldMetadata(alias="bool")]] + bool_: typing_extensions.NotRequired[ + typing_extensions.Annotated[bool, FieldMetadata(alias="bool")] + ] datetime: typing_extensions.NotRequired[dt.datetime] date: typing_extensions.NotRequired[dt.date] - uuid_: typing_extensions.NotRequired[typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")]] - base_64: typing_extensions.NotRequired[typing_extensions.Annotated[str, FieldMetadata(alias="base64")]] - list_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")]] - set_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")]] - map_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")]] + uuid_: typing_extensions.NotRequired[ + typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")] + ] + base_64: typing_extensions.NotRequired[ + typing_extensions.Annotated[str, FieldMetadata(alias="base64")] + ] + list_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")] + ] + set_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")] + ] + map_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")] + ] enum: typing_extensions.NotRequired[Color] union: typing_extensions.NotRequired[ShapeParams] second_union: typing_extensions.NotRequired[ShapeParams] diff --git a/seed/python-sdk/version/tests/utils/assets/models/shape.py b/seed/python-sdk/version/tests/utils/assets/models/shape.py index 2c33c877951..816ffc51bdc 100644 --- a/seed/python-sdk/version/tests/utils/assets/models/shape.py +++ b/seed/python-sdk/version/tests/utils/assets/models/shape.py @@ -7,6 +7,7 @@ import typing import typing_extensions + from seed.core.serialization import FieldMetadata @@ -15,13 +16,21 @@ class Base(typing_extensions.TypedDict): class Shape_CircleParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["circle"], FieldMetadata(alias="shapeType")] - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["circle"], FieldMetadata(alias="shapeType") + ] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] class Shape_SquareParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["square"], FieldMetadata(alias="shapeType")] - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["square"], FieldMetadata(alias="shapeType") + ] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] ShapeParams = typing.Union[Shape_CircleParams, Shape_SquareParams] diff --git a/seed/python-sdk/version/tests/utils/assets/models/square.py b/seed/python-sdk/version/tests/utils/assets/models/square.py index b9b7dd319bc..bcf08a723c5 100644 --- a/seed/python-sdk/version/tests/utils/assets/models/square.py +++ b/seed/python-sdk/version/tests/utils/assets/models/square.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class SquareParams(typing_extensions.TypedDict): - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] diff --git a/seed/python-sdk/version/tests/utils/test_http_client.py b/seed/python-sdk/version/tests/utils/test_http_client.py index edd11ca7afb..f5a874a75f3 100644 --- a/seed/python-sdk/version/tests/utils/test_http_client.py +++ b/seed/python-sdk/version/tests/utils/test_http_client.py @@ -9,12 +9,17 @@ def get_request_options() -> RequestOptions: def test_get_json_request_body() -> None: - json_body, data_body = get_request_body(json={"hello": "world"}, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json={"hello": "world"}, data=None, request_options=None, omit=None + ) assert json_body == {"hello": "world"} assert data_body is None json_body_extras, data_body_extras = get_request_body( - json={"goodbye": "world"}, data=None, request_options=get_request_options(), omit=None + json={"goodbye": "world"}, + data=None, + request_options=get_request_options(), + omit=None, ) assert json_body_extras == {"goodbye": "world", "see you": "later"} @@ -22,12 +27,17 @@ def test_get_json_request_body() -> None: def test_get_files_request_body() -> None: - json_body, data_body = get_request_body(json=None, data={"hello": "world"}, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data={"hello": "world"}, request_options=None, omit=None + ) assert data_body == {"hello": "world"} assert json_body is None json_body_extras, data_body_extras = get_request_body( - json=None, data={"goodbye": "world"}, request_options=get_request_options(), omit=None + json=None, + data={"goodbye": "world"}, + request_options=get_request_options(), + omit=None, ) assert data_body_extras == {"goodbye": "world", "see you": "later"} @@ -35,7 +45,9 @@ def test_get_files_request_body() -> None: def test_get_none_request_body() -> None: - json_body, data_body = get_request_body(json=None, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data=None, request_options=None, omit=None + ) assert data_body is None assert json_body is None diff --git a/seed/python-sdk/version/tests/utils/test_query_encoding.py b/seed/python-sdk/version/tests/utils/test_query_encoding.py index 247e1551b46..fbc8f402167 100644 --- a/seed/python-sdk/version/tests/utils/test_query_encoding.py +++ b/seed/python-sdk/version/tests/utils/test_query_encoding.py @@ -4,9 +4,15 @@ def test_query_encoding() -> None: - assert encode_query({"hello world": "hello world"}) == {"hello world": "hello world"} - assert encode_query({"hello_world": {"hello": "world"}}) == {"hello_world[hello]": "world"} - assert encode_query({"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"}) == { + assert encode_query({"hello world": "hello world"}) == { + "hello world": "hello world" + } + assert encode_query({"hello_world": {"hello": "world"}}) == { + "hello_world[hello]": "world" + } + assert encode_query( + {"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"} + ) == { "hello_world[hello][world]": "today", "hello_world[test]": "this", "hi": "there", diff --git a/seed/python-sdk/version/tests/utils/test_serialization.py b/seed/python-sdk/version/tests/utils/test_serialization.py index 58b1ed66e6d..5ca956916dd 100644 --- a/seed/python-sdk/version/tests/utils/test_serialization.py +++ b/seed/python-sdk/version/tests/utils/test_serialization.py @@ -1,10 +1,12 @@ # This file was auto-generated by Fern from our API Definition. -from typing import Any, List +from typing import List, Any -from seed.core.serialization import convert_and_respect_annotation_metadata +from seed.core.serialization import ( + convert_and_respect_annotation_metadata, +) +from .assets.models import ShapeParams, ObjectWithOptionalFieldParams -from .assets.models import ObjectWithOptionalFieldParams, ShapeParams UNION_TEST: ShapeParams = {"radius_measurement": 1.0, "shape_type": "circle", "id": "1"} UNION_TEST_CONVERTED = {"shapeType": "circle", "radiusMeasurement": 1.0, "id": "1"} @@ -18,20 +20,54 @@ def test_convert_and_respect_annotation_metadata() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) - assert converted == {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"} + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) + assert converted == { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + } def test_convert_and_respect_annotation_metadata_in_list() -> None: data: List[ObjectWithOptionalFieldParams] = [ - {"string": "string", "long_": 12345, "bool_": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long_": 67890, "list_": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long_": 12345, + "bool_": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long_": 67890, + "list_": [], + "literal": "lit_one", + "any": "any", + }, ] - converted = convert_and_respect_annotation_metadata(object_=data, annotation=List[ObjectWithOptionalFieldParams]) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=List[ObjectWithOptionalFieldParams] + ) assert converted == [ - {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long": 67890, "list": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long": 67890, + "list": [], + "literal": "lit_one", + "any": "any", + }, ] @@ -43,7 +79,9 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) assert converted == { "string": "string", @@ -55,12 +93,16 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: def test_convert_and_respect_annotation_metadata_in_union() -> None: - converted = convert_and_respect_annotation_metadata(object_=UNION_TEST, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=UNION_TEST, annotation=ShapeParams + ) assert converted == UNION_TEST_CONVERTED def test_convert_and_respect_annotation_metadata_with_empty_object() -> None: data: Any = {} - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ShapeParams + ) assert converted == data diff --git a/seed/python-sdk/websocket/pyproject.toml b/seed/python-sdk/websocket/pyproject.toml index f29c8816c9a..6479e2867f6 100644 --- a/seed/python-sdk/websocket/pyproject.toml +++ b/seed/python-sdk/websocket/pyproject.toml @@ -43,6 +43,7 @@ pytest = "^7.4.0" pytest-asyncio = "^0.23.5" python-dateutil = "^2.9.0" types-python-dateutil = "^2.9.0.20240316" +ruff = "^0.5.6" [tool.pytest.ini_options] testpaths = [ "tests" ] diff --git a/seed/python-sdk/websocket/src/seed/client.py b/seed/python-sdk/websocket/src/seed/client.py index 7c8a26aec4f..f962e00c5e3 100644 --- a/seed/python-sdk/websocket/src/seed/client.py +++ b/seed/python-sdk/websocket/src/seed/client.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .core.client_wrapper import AsyncClientWrapper, SyncClientWrapper +from .core.client_wrapper import SyncClientWrapper +from .core.client_wrapper import AsyncClientWrapper class SeedWebsocket: @@ -40,14 +39,18 @@ def __init__( base_url: str, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.Client] = None + httpx_client: typing.Optional[httpx.Client] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = SyncClientWrapper( base_url=base_url, httpx_client=httpx_client if httpx_client is not None - else httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.Client( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.Client(timeout=_defaulted_timeout), timeout=_defaulted_timeout, @@ -87,14 +90,18 @@ def __init__( base_url: str, timeout: typing.Optional[float] = None, follow_redirects: typing.Optional[bool] = True, - httpx_client: typing.Optional[httpx.AsyncClient] = None + httpx_client: typing.Optional[httpx.AsyncClient] = None, ): - _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None + _defaulted_timeout = ( + timeout if timeout is not None else 60 if httpx_client is None else None + ) self._client_wrapper = AsyncClientWrapper( base_url=base_url, httpx_client=httpx_client if httpx_client is not None - else httpx.AsyncClient(timeout=_defaulted_timeout, follow_redirects=follow_redirects) + else httpx.AsyncClient( + timeout=_defaulted_timeout, follow_redirects=follow_redirects + ) if follow_redirects is not None else httpx.AsyncClient(timeout=_defaulted_timeout), timeout=_defaulted_timeout, diff --git a/seed/python-sdk/websocket/src/seed/core/api_error.py b/seed/python-sdk/websocket/src/seed/core/api_error.py index 2e9fc5431cd..da734b58068 100644 --- a/seed/python-sdk/websocket/src/seed/core/api_error.py +++ b/seed/python-sdk/websocket/src/seed/core/api_error.py @@ -7,7 +7,9 @@ class ApiError(Exception): status_code: typing.Optional[int] body: typing.Any - def __init__(self, *, status_code: typing.Optional[int] = None, body: typing.Any = None): + def __init__( + self, *, status_code: typing.Optional[int] = None, body: typing.Any = None + ): self.status_code = status_code self.body = body diff --git a/seed/python-sdk/websocket/src/seed/core/client_wrapper.py b/seed/python-sdk/websocket/src/seed/core/client_wrapper.py index 918281e5157..5b123e9274b 100644 --- a/seed/python-sdk/websocket/src/seed/core/client_wrapper.py +++ b/seed/python-sdk/websocket/src/seed/core/client_wrapper.py @@ -1,10 +1,9 @@ # This file was auto-generated by Fern from our API Definition. import typing - import httpx - -from .http_client import AsyncHttpClient, HttpClient +from .http_client import HttpClient +from .http_client import AsyncHttpClient class BaseClientWrapper: @@ -28,7 +27,13 @@ def get_timeout(self) -> typing.Optional[float]: class SyncClientWrapper(BaseClientWrapper): - def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, httpx_client: httpx.Client): + def __init__( + self, + *, + base_url: str, + timeout: typing.Optional[float] = None, + httpx_client: httpx.Client, + ): super().__init__(base_url=base_url, timeout=timeout) self.httpx_client = HttpClient( httpx_client=httpx_client, @@ -39,7 +44,13 @@ def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, htt class AsyncClientWrapper(BaseClientWrapper): - def __init__(self, *, base_url: str, timeout: typing.Optional[float] = None, httpx_client: httpx.AsyncClient): + def __init__( + self, + *, + base_url: str, + timeout: typing.Optional[float] = None, + httpx_client: httpx.AsyncClient, + ): super().__init__(base_url=base_url, timeout=timeout) self.httpx_client = AsyncHttpClient( httpx_client=httpx_client, diff --git a/seed/python-sdk/websocket/src/seed/core/datetime_utils.py b/seed/python-sdk/websocket/src/seed/core/datetime_utils.py index 7c9864a944c..47344e9d9cc 100644 --- a/seed/python-sdk/websocket/src/seed/core/datetime_utils.py +++ b/seed/python-sdk/websocket/src/seed/core/datetime_utils.py @@ -13,7 +13,9 @@ def serialize_datetime(v: dt.datetime) -> str: """ def _serialize_zoned_datetime(v: dt.datetime) -> str: - if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): + if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname( + None + ): # UTC is a special case where we use "Z" at the end instead of "+00:00" return v.isoformat().replace("+00:00", "Z") else: diff --git a/seed/python-sdk/websocket/src/seed/core/file.py b/seed/python-sdk/websocket/src/seed/core/file.py index cb0d40bbbf3..6e0f92bfcb1 100644 --- a/seed/python-sdk/websocket/src/seed/core/file.py +++ b/seed/python-sdk/websocket/src/seed/core/file.py @@ -13,12 +13,17 @@ # (filename, file (or bytes), content_type) typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str]], # (filename, file (or bytes), content_type, headers) - typing.Tuple[typing.Optional[str], FileContent, typing.Optional[str], typing.Mapping[str, str]], + typing.Tuple[ + typing.Optional[str], + FileContent, + typing.Optional[str], + typing.Mapping[str, str], + ], ] def convert_file_dict_to_httpx_tuples( - d: typing.Dict[str, typing.Union[File, typing.List[File]]] + d: typing.Dict[str, typing.Union[File, typing.List[File]]], ) -> typing.List[typing.Tuple[str, File]]: """ The format we use is a list of tuples, where the first element is the diff --git a/seed/python-sdk/websocket/src/seed/core/http_client.py b/seed/python-sdk/websocket/src/seed/core/http_client.py index 9333d8a7f15..091f71bc185 100644 --- a/seed/python-sdk/websocket/src/seed/core/http_client.py +++ b/seed/python-sdk/websocket/src/seed/core/http_client.py @@ -77,7 +77,9 @@ def _retry_timeout(response: httpx.Response, retries: int) -> float: return retry_after # Apply exponential backoff, capped at MAX_RETRY_DELAY_SECONDS. - retry_delay = min(INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS) + retry_delay = min( + INITIAL_RETRY_DELAY_SECONDS * pow(2.0, retries), MAX_RETRY_DELAY_SECONDS + ) # Add a randomness / jitter to the retry delay to avoid overwhelming the server with retries. timeout = retry_delay * (1 - 0.25 * random()) @@ -90,7 +92,8 @@ def _should_retry(response: httpx.Response) -> bool: def remove_omit_from_dict( - original: typing.Dict[str, typing.Optional[typing.Any]], omit: typing.Optional[typing.Any] + original: typing.Dict[str, typing.Optional[typing.Any]], + omit: typing.Optional[typing.Any], ) -> typing.Dict[str, typing.Any]: if omit is None: return original @@ -108,7 +111,8 @@ def maybe_filter_request_body( ) -> typing.Optional[typing.Any]: if data is None: return ( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else None ) @@ -118,7 +122,8 @@ def maybe_filter_request_body( data_content = { **(jsonable_encoder(remove_omit_from_dict(data, omit))), # type: ignore **( - jsonable_encoder(request_options.get("additional_body_parameters", {})) or {} + jsonable_encoder(request_options.get("additional_body_parameters", {})) + or {} if request_options is not None else {} ), @@ -162,7 +167,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url def request( @@ -174,8 +181,12 @@ def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -184,11 +195,14 @@ def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) response = self.httpx_client.request( method=method, @@ -198,7 +212,11 @@ def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -209,7 +227,10 @@ def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -222,11 +243,15 @@ def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: time.sleep(_retry_timeout(response=response, retries=retries)) @@ -256,8 +281,12 @@ def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -266,11 +295,14 @@ def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) with self.httpx_client.stream( method=method, @@ -280,7 +312,11 @@ def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -291,7 +327,9 @@ def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -304,7 +342,9 @@ def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream @@ -327,7 +367,9 @@ def __init__( def get_base_url(self, maybe_base_url: typing.Optional[str]) -> str: base_url = self.base_url if maybe_base_url is None else maybe_base_url if base_url is None: - raise ValueError("A base_url is required to make this request, please provide one and try again.") + raise ValueError( + "A base_url is required to make this request, please provide one and try again." + ) return base_url async def request( @@ -339,8 +381,12 @@ async def request( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -349,11 +395,14 @@ async def request( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) # Add the input to each of these and do None-safety checks response = await self.httpx_client.request( @@ -364,7 +413,11 @@ async def request( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) or {} if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) or {} + if request_options is not None + else {} + ), } ) ), @@ -375,7 +428,10 @@ async def request( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) or {} + request_options.get( + "additional_query_parameters", {} + ) + or {} if request_options is not None else {} ), @@ -388,11 +444,15 @@ async def request( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) - max_retries: int = request_options.get("max_retries", 0) if request_options is not None else 0 + max_retries: int = ( + request_options.get("max_retries", 0) if request_options is not None else 0 + ) if _should_retry(response=response): if max_retries > retries: await asyncio.sleep(_retry_timeout(response=response, retries=retries)) @@ -421,8 +481,12 @@ async def stream( params: typing.Optional[typing.Dict[str, typing.Any]] = None, json: typing.Optional[typing.Any] = None, data: typing.Optional[typing.Any] = None, - content: typing.Optional[typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]]] = None, - files: typing.Optional[typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]]] = None, + content: typing.Optional[ + typing.Union[bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]] + ] = None, + files: typing.Optional[ + typing.Dict[str, typing.Optional[typing.Union[File, typing.List[File]]]] + ] = None, headers: typing.Optional[typing.Dict[str, typing.Any]] = None, request_options: typing.Optional[RequestOptions] = None, retries: int = 0, @@ -431,11 +495,14 @@ async def stream( base_url = self.get_base_url(base_url) timeout = ( request_options.get("timeout_in_seconds") - if request_options is not None and request_options.get("timeout_in_seconds") is not None + if request_options is not None + and request_options.get("timeout_in_seconds") is not None else self.base_timeout ) - json_body, data_body = get_request_body(json=json, data=data, request_options=request_options, omit=omit) + json_body, data_body = get_request_body( + json=json, data=data, request_options=request_options, omit=omit + ) async with self.httpx_client.stream( method=method, @@ -445,7 +512,11 @@ async def stream( { **self.base_headers, **(headers if headers is not None else {}), - **(request_options.get("additional_headers", {}) if request_options is not None else {}), + **( + request_options.get("additional_headers", {}) + if request_options is not None + else {} + ), } ) ), @@ -456,7 +527,9 @@ async def stream( { **(params if params is not None else {}), **( - request_options.get("additional_query_parameters", {}) + request_options.get( + "additional_query_parameters", {} + ) if request_options is not None else {} ), @@ -469,7 +542,9 @@ async def stream( json=json_body, data=data_body, content=content, - files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) if files is not None else None, + files=convert_file_dict_to_httpx_tuples(remove_none_from_dict(files)) + if files is not None + else None, timeout=timeout, ) as stream: yield stream diff --git a/seed/python-sdk/websocket/src/seed/core/jsonable_encoder.py b/seed/python-sdk/websocket/src/seed/core/jsonable_encoder.py index d3fd328fd41..12a8b52fc22 100644 --- a/seed/python-sdk/websocket/src/seed/core/jsonable_encoder.py +++ b/seed/python-sdk/websocket/src/seed/core/jsonable_encoder.py @@ -19,13 +19,19 @@ import pydantic from .datetime_utils import serialize_datetime -from .pydantic_utilities import IS_PYDANTIC_V2, encode_by_type, to_jsonable_with_fallback +from .pydantic_utilities import ( + IS_PYDANTIC_V2, + encode_by_type, + to_jsonable_with_fallback, +) SetIntStr = Set[Union[int, str]] DictIntStrAny = Dict[Union[int, str], Any] -def jsonable_encoder(obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None) -> Any: +def jsonable_encoder( + obj: Any, custom_encoder: Optional[Dict[Any, Callable[[Any], Any]]] = None +) -> Any: custom_encoder = custom_encoder or {} if custom_encoder: if type(obj) in custom_encoder: diff --git a/seed/python-sdk/websocket/src/seed/core/pydantic_utilities.py b/seed/python-sdk/websocket/src/seed/core/pydantic_utilities.py index 170a563d6eb..c63935c32a2 100644 --- a/seed/python-sdk/websocket/src/seed/core/pydantic_utilities.py +++ b/seed/python-sdk/websocket/src/seed/core/pydantic_utilities.py @@ -27,11 +27,15 @@ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 get_args as get_args, ) - from pydantic.v1.typing import get_origin as get_origin # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + get_origin as get_origin, + ) from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 is_literal_type as is_literal_type, ) - from pydantic.v1.typing import is_union as is_union # pyright: ignore[reportMissingImports] # Pydantic v2 + from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2 + is_union as is_union, + ) from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2 else: from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1 @@ -90,15 +94,27 @@ class Config: json_encoders = {dt.datetime: serialize_datetime} def json(self, **kwargs: typing.Any) -> str: - kwargs_with_defaults: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} + kwargs_with_defaults: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } if IS_PYDANTIC_V2: return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2 else: return super().json(**kwargs_with_defaults) def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: - kwargs_with_defaults_exclude_unset: typing.Any = {"by_alias": True, "exclude_unset": True, **kwargs} - kwargs_with_defaults_exclude_none: typing.Any = {"by_alias": True, "exclude_none": True, **kwargs} + kwargs_with_defaults_exclude_unset: typing.Any = { + "by_alias": True, + "exclude_unset": True, + **kwargs, + } + kwargs_with_defaults_exclude_none: typing.Any = { + "by_alias": True, + "exclude_none": True, + **kwargs, + } if IS_PYDANTIC_V2: return deep_union_pydantic_dicts( @@ -107,7 +123,8 @@ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]: ) else: return deep_union_pydantic_dicts( - super().dict(**kwargs_with_defaults_exclude_unset), super().dict(**kwargs_with_defaults_exclude_none) + super().dict(**kwargs_with_defaults_exclude_unset), + super().dict(**kwargs_with_defaults_exclude_none), ) @@ -147,12 +164,16 @@ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> N AnyCallable = typing.Callable[..., typing.Any] -def universal_root_validator(pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_root_validator( + pre: bool = False, +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.model_validator("before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.model_validator("before" if pre else "after")( + func + ) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1 @@ -163,12 +184,16 @@ def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: return decorator -def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]: +def universal_field_validator( + field_name: str, pre: bool = False +) -> typing.Callable[[AnyCallable], AnyCallable]: def decorator(func: AnyCallable) -> AnyCallable: @wraps(func) def validate(*args: typing.Any, **kwargs: typing.Any) -> AnyCallable: if IS_PYDANTIC_V2: - wrapped_func = pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2 + wrapped_func = pydantic.field_validator( + field_name, mode="before" if pre else "after" + )(func) # type: ignore # Pydantic v2 else: wrapped_func = pydantic.validator(field_name, pre=pre)(func) # type: ignore # Pydantic v1 diff --git a/seed/python-sdk/websocket/src/seed/core/query_encoder.py b/seed/python-sdk/websocket/src/seed/core/query_encoder.py index 24076d72ee9..7cb98f52cd7 100644 --- a/seed/python-sdk/websocket/src/seed/core/query_encoder.py +++ b/seed/python-sdk/websocket/src/seed/core/query_encoder.py @@ -7,7 +7,9 @@ # Flattens dicts to be of the form {"key[subkey][subkey2]": value} where value is not a dict -def traverse_query_dict(dict_flat: Dict[str, Any], key_prefix: Optional[str] = None) -> Dict[str, Any]: +def traverse_query_dict( + dict_flat: Dict[str, Any], key_prefix: Optional[str] = None +) -> Dict[str, Any]: result = {} for k, v in dict_flat.items(): key = f"{key_prefix}[{k}]" if key_prefix is not None else k @@ -30,4 +32,8 @@ def single_query_encoder(query_key: str, query_value: Any) -> Dict[str, Any]: def encode_query(query: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: - return dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) if query is not None else None + return ( + dict(ChainMap(*[single_query_encoder(k, v) for k, v in query.items()])) + if query is not None + else None + ) diff --git a/seed/python-sdk/websocket/src/seed/core/serialization.py b/seed/python-sdk/websocket/src/seed/core/serialization.py index 8ad5cf8125f..5400ca0bc3b 100644 --- a/seed/python-sdk/websocket/src/seed/core/serialization.py +++ b/seed/python-sdk/websocket/src/seed/core/serialization.py @@ -25,7 +25,10 @@ def __init__(self, *, alias: str) -> None: def convert_and_respect_annotation_metadata( - *, object_: typing.Any, annotation: typing.Any, inner_type: typing.Optional[typing.Any] = None + *, + object_: typing.Any, + annotation: typing.Any, + inner_type: typing.Optional[typing.Any] = None, ) -> typing.Any: """ Respect the metadata annotations on a field, such as aliasing. This function effectively @@ -53,7 +56,9 @@ def convert_and_respect_annotation_metadata( inner_type = annotation clean_type = _remove_annotations(inner_type) - if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping): + if typing_extensions.is_typeddict(clean_type) and isinstance( + object_, typing.Mapping + ): return _convert_typeddict(object_, clean_type) if ( @@ -79,7 +84,8 @@ def convert_and_respect_annotation_metadata( or ( ( typing_extensions.get_origin(clean_type) == typing.Sequence - or typing_extensions.get_origin(clean_type) == collections.abc.Sequence + or typing_extensions.get_origin(clean_type) + == collections.abc.Sequence or clean_type == typing.Sequence ) and isinstance(object_, typing.Sequence) @@ -88,7 +94,9 @@ def convert_and_respect_annotation_metadata( ): inner_type = typing_extensions.get_args(clean_type)[0] return [ - convert_and_respect_annotation_metadata(object_=item, annotation=annotation, inner_type=inner_type) + convert_and_respect_annotation_metadata( + object_=item, annotation=annotation, inner_type=inner_type + ) for item in object_ ] @@ -98,7 +106,9 @@ def convert_and_respect_annotation_metadata( # of the same name to a different name from another member # Or if another member aliases a field of the same name that another member does not. for member in typing_extensions.get_args(clean_type): - object_ = convert_and_respect_annotation_metadata(object_=object_, annotation=annotation, inner_type=member) + object_ = convert_and_respect_annotation_metadata( + object_=object_, annotation=annotation, inner_type=member + ) return object_ annotated_type = _get_annotation(annotation) @@ -110,7 +120,9 @@ def convert_and_respect_annotation_metadata( return object_ -def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typing.Any) -> typing.Mapping[str, object]: +def _convert_typeddict( + object_: typing.Mapping[str, object], expected_type: typing.Any +) -> typing.Mapping[str, object]: converted_object: typing.Dict[str, object] = {} annotations = typing_extensions.get_type_hints(expected_type, include_extras=True) for key, value in object_.items(): @@ -118,8 +130,8 @@ def _convert_typeddict(object_: typing.Mapping[str, object], expected_type: typi if type_ is None: converted_object[key] = value else: - converted_object[_alias_key(key, type_)] = convert_and_respect_annotation_metadata( - object_=value, annotation=type_ + converted_object[_alias_key(key, type_)] = ( + convert_and_respect_annotation_metadata(object_=value, annotation=type_) ) return converted_object diff --git a/seed/python-sdk/websocket/src/seed/version.py b/seed/python-sdk/websocket/src/seed/version.py index 4c955b95822..a30df08113b 100644 --- a/seed/python-sdk/websocket/src/seed/version.py +++ b/seed/python-sdk/websocket/src/seed/version.py @@ -1,4 +1,3 @@ - from importlib import metadata __version__ = metadata.version("fern_websocket") diff --git a/seed/python-sdk/websocket/tests/conftest.py b/seed/python-sdk/websocket/tests/conftest.py index 5f3abe063c1..94cebc1176f 100644 --- a/seed/python-sdk/websocket/tests/conftest.py +++ b/seed/python-sdk/websocket/tests/conftest.py @@ -1,9 +1,9 @@ # This file was auto-generated by Fern from our API Definition. +from seed import SeedWebsocket import os - import pytest -from seed import AsyncSeedWebsocket, SeedWebsocket +from seed import AsyncSeedWebsocket @pytest.fixture diff --git a/seed/python-sdk/websocket/tests/custom/test_client.py b/seed/python-sdk/websocket/tests/custom/test_client.py index 60a58e64c27..73f811f5ede 100644 --- a/seed/python-sdk/websocket/tests/custom/test_client.py +++ b/seed/python-sdk/websocket/tests/custom/test_client.py @@ -1,5 +1,6 @@ import pytest + # Get started with writing tests with pytest at https://docs.pytest.org @pytest.mark.skip(reason="Unimplemented") def test_client() -> None: diff --git a/seed/python-sdk/websocket/tests/utilities.py b/seed/python-sdk/websocket/tests/utilities.py index 13da208eb3a..e8f4472564c 100644 --- a/seed/python-sdk/websocket/tests/utilities.py +++ b/seed/python-sdk/websocket/tests/utilities.py @@ -3,11 +3,14 @@ import typing import uuid -import pydantic from dateutil import parser +import pydantic + -def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> typing.Any: +def cast_field( + json_expectation: typing.Any, type_expectation: typing.Any +) -> typing.Any: # Cast these specific types which come through as string and expect our # models to cast to the correct type. if type_expectation == "uuid": @@ -25,7 +28,9 @@ def cast_field(json_expectation: typing.Any, type_expectation: typing.Any) -> ty return json_expectation -def validate_field(response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any) -> None: +def validate_field( + response: typing.Any, json_expectation: typing.Any, type_expectation: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectation == "no_validate": return @@ -44,7 +49,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(entry_expectation, dict): is_container_of_complex_type = True validate_response( - response=response[idx], json_expectation=ex, type_expectations=entry_expectation + response=response[idx], + json_expectation=ex, + type_expectations=entry_expectation, ) else: cast_json_expectation.append(cast_field(ex, entry_expectation)) @@ -56,7 +63,10 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # if any of the values of the set have a type_expectation of a dict, we're assuming it's a pydantic # model and keeping it a list. if container_expectation != "set" or not any( - map(lambda value: isinstance(value, dict), list(contents_expectation.values())) + map( + lambda value: isinstance(value, dict), + list(contents_expectation.values()), + ) ): json_expectation = cast_field(json_expectation, container_expectation) elif isinstance(type_expectation, tuple): @@ -65,9 +75,15 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe if isinstance(contents_expectation, dict): json_expectation = { cast_field( - key, contents_expectation.get(idx)[0] if contents_expectation.get(idx) is not None else None # type: ignore + key, + contents_expectation.get(idx)[0] + if contents_expectation.get(idx) is not None + else None, # type: ignore ): cast_field( - value, contents_expectation.get(idx)[1] if contents_expectation.get(idx) is not None else None # type: ignore + value, + contents_expectation.get(idx)[1] + if contents_expectation.get(idx) is not None + else None, # type: ignore ) for idx, (key, value) in enumerate(json_expectation.items()) } @@ -86,7 +102,9 @@ def validate_field(response: typing.Any, json_expectation: typing.Any, type_expe # Arg type_expectations is a deeply nested structure that matches the response, but with the values replaced with the expected types -def validate_response(response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any) -> None: +def validate_response( + response: typing.Any, json_expectation: typing.Any, type_expectations: typing.Any +) -> None: # Allow for an escape hatch if the object cannot be validated if type_expectations == "no_validate": return @@ -96,11 +114,17 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e and not isinstance(response, dict) and not issubclass(type(response), pydantic.BaseModel) ): - validate_field(response=response, json_expectation=json_expectation, type_expectation=type_expectations) + validate_field( + response=response, + json_expectation=json_expectation, + type_expectation=type_expectations, + ) return if isinstance(response, list): - assert len(response) == len(json_expectation), "Length mismatch, expected: {0}, Actual: {1}".format( + assert len(response) == len( + json_expectation + ), "Length mismatch, expected: {0}, Actual: {1}".format( len(response), len(json_expectation) ) content_expectation = type_expectations @@ -108,7 +132,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e content_expectation = type_expectations[1] for idx, item in enumerate(response): validate_response( - response=item, json_expectation=json_expectation[idx], type_expectations=content_expectation[idx] + response=item, + json_expectation=json_expectation[idx], + type_expectations=content_expectation[idx], ) else: response_json = response @@ -116,7 +142,9 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e response_json = response.dict(by_alias=True) for key, value in json_expectation.items(): - assert key in response_json, "Field {0} not found within the response object: {1}".format( + assert ( + key in response_json + ), "Field {0} not found within the response object: {1}".format( key, response_json ) @@ -128,11 +156,19 @@ def validate_response(response: typing.Any, json_expectation: typing.Any, type_e # Otherwise, we're just validating a single field that's a pydantic model. if isinstance(value, dict) and not isinstance(type_expectation, tuple): validate_response( - response=response_json[key], json_expectation=value, type_expectations=type_expectation + response=response_json[key], + json_expectation=value, + type_expectations=type_expectation, ) else: - validate_field(response=response_json[key], json_expectation=value, type_expectation=type_expectation) + validate_field( + response=response_json[key], + json_expectation=value, + type_expectation=type_expectation, + ) # Ensure there are no additional fields here either del response_json[key] - assert len(response_json) == 0, "Additional fields found, expected None: {0}".format(response_json) + assert ( + len(response_json) == 0 + ), "Additional fields found, expected None: {0}".format(response_json) diff --git a/seed/python-sdk/websocket/tests/utils/assets/models/__init__.py b/seed/python-sdk/websocket/tests/utils/assets/models/__init__.py index 2cf01263529..3a1c852e71e 100644 --- a/seed/python-sdk/websocket/tests/utils/assets/models/__init__.py +++ b/seed/python-sdk/websocket/tests/utils/assets/models/__init__.py @@ -5,7 +5,7 @@ from .circle import CircleParams from .object_with_defaults import ObjectWithDefaultsParams from .object_with_optional_field import ObjectWithOptionalFieldParams -from .shape import Shape_CircleParams, Shape_SquareParams, ShapeParams +from .shape import ShapeParams, Shape_CircleParams, Shape_SquareParams from .square import SquareParams from .undiscriminated_shape import UndiscriminatedShapeParams diff --git a/seed/python-sdk/websocket/tests/utils/assets/models/circle.py b/seed/python-sdk/websocket/tests/utils/assets/models/circle.py index af7a1bf8a8e..253f12d38b3 100644 --- a/seed/python-sdk/websocket/tests/utils/assets/models/circle.py +++ b/seed/python-sdk/websocket/tests/utils/assets/models/circle.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class CircleParams(typing_extensions.TypedDict): - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] diff --git a/seed/python-sdk/websocket/tests/utils/assets/models/object_with_optional_field.py b/seed/python-sdk/websocket/tests/utils/assets/models/object_with_optional_field.py index 3ad93d5f305..ebe7dc80547 100644 --- a/seed/python-sdk/websocket/tests/utils/assets/models/object_with_optional_field.py +++ b/seed/python-sdk/websocket/tests/utils/assets/models/object_with_optional_field.py @@ -7,8 +7,8 @@ import uuid import typing_extensions -from seed.core.serialization import FieldMetadata +from seed.core.serialization import FieldMetadata from .color import Color from .shape import ShapeParams from .undiscriminated_shape import UndiscriminatedShapeParams @@ -18,16 +18,30 @@ class ObjectWithOptionalFieldParams(typing_extensions.TypedDict): literal: typing.Literal["lit_one"] string: typing_extensions.NotRequired[str] integer: typing_extensions.NotRequired[int] - long_: typing_extensions.NotRequired[typing_extensions.Annotated[int, FieldMetadata(alias="long")]] + long_: typing_extensions.NotRequired[ + typing_extensions.Annotated[int, FieldMetadata(alias="long")] + ] double: typing_extensions.NotRequired[float] - bool_: typing_extensions.NotRequired[typing_extensions.Annotated[bool, FieldMetadata(alias="bool")]] + bool_: typing_extensions.NotRequired[ + typing_extensions.Annotated[bool, FieldMetadata(alias="bool")] + ] datetime: typing_extensions.NotRequired[dt.datetime] date: typing_extensions.NotRequired[dt.date] - uuid_: typing_extensions.NotRequired[typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")]] - base_64: typing_extensions.NotRequired[typing_extensions.Annotated[str, FieldMetadata(alias="base64")]] - list_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")]] - set_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")]] - map_: typing_extensions.NotRequired[typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")]] + uuid_: typing_extensions.NotRequired[ + typing_extensions.Annotated[uuid.UUID, FieldMetadata(alias="uuid")] + ] + base_64: typing_extensions.NotRequired[ + typing_extensions.Annotated[str, FieldMetadata(alias="base64")] + ] + list_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Sequence[str], FieldMetadata(alias="list")] + ] + set_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Set[str], FieldMetadata(alias="set")] + ] + map_: typing_extensions.NotRequired[ + typing_extensions.Annotated[typing.Dict[int, str], FieldMetadata(alias="map")] + ] enum: typing_extensions.NotRequired[Color] union: typing_extensions.NotRequired[ShapeParams] second_union: typing_extensions.NotRequired[ShapeParams] diff --git a/seed/python-sdk/websocket/tests/utils/assets/models/shape.py b/seed/python-sdk/websocket/tests/utils/assets/models/shape.py index 2c33c877951..816ffc51bdc 100644 --- a/seed/python-sdk/websocket/tests/utils/assets/models/shape.py +++ b/seed/python-sdk/websocket/tests/utils/assets/models/shape.py @@ -7,6 +7,7 @@ import typing import typing_extensions + from seed.core.serialization import FieldMetadata @@ -15,13 +16,21 @@ class Base(typing_extensions.TypedDict): class Shape_CircleParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["circle"], FieldMetadata(alias="shapeType")] - radius_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="radiusMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["circle"], FieldMetadata(alias="shapeType") + ] + radius_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="radiusMeasurement") + ] class Shape_SquareParams(Base): - shape_type: typing_extensions.Annotated[typing.Literal["square"], FieldMetadata(alias="shapeType")] - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + shape_type: typing_extensions.Annotated[ + typing.Literal["square"], FieldMetadata(alias="shapeType") + ] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] ShapeParams = typing.Union[Shape_CircleParams, Shape_SquareParams] diff --git a/seed/python-sdk/websocket/tests/utils/assets/models/square.py b/seed/python-sdk/websocket/tests/utils/assets/models/square.py index b9b7dd319bc..bcf08a723c5 100644 --- a/seed/python-sdk/websocket/tests/utils/assets/models/square.py +++ b/seed/python-sdk/websocket/tests/utils/assets/models/square.py @@ -3,8 +3,11 @@ # This file was auto-generated by Fern from our API Definition. import typing_extensions + from seed.core.serialization import FieldMetadata class SquareParams(typing_extensions.TypedDict): - length_measurement: typing_extensions.Annotated[float, FieldMetadata(alias="lengthMeasurement")] + length_measurement: typing_extensions.Annotated[ + float, FieldMetadata(alias="lengthMeasurement") + ] diff --git a/seed/python-sdk/websocket/tests/utils/test_http_client.py b/seed/python-sdk/websocket/tests/utils/test_http_client.py index edd11ca7afb..f5a874a75f3 100644 --- a/seed/python-sdk/websocket/tests/utils/test_http_client.py +++ b/seed/python-sdk/websocket/tests/utils/test_http_client.py @@ -9,12 +9,17 @@ def get_request_options() -> RequestOptions: def test_get_json_request_body() -> None: - json_body, data_body = get_request_body(json={"hello": "world"}, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json={"hello": "world"}, data=None, request_options=None, omit=None + ) assert json_body == {"hello": "world"} assert data_body is None json_body_extras, data_body_extras = get_request_body( - json={"goodbye": "world"}, data=None, request_options=get_request_options(), omit=None + json={"goodbye": "world"}, + data=None, + request_options=get_request_options(), + omit=None, ) assert json_body_extras == {"goodbye": "world", "see you": "later"} @@ -22,12 +27,17 @@ def test_get_json_request_body() -> None: def test_get_files_request_body() -> None: - json_body, data_body = get_request_body(json=None, data={"hello": "world"}, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data={"hello": "world"}, request_options=None, omit=None + ) assert data_body == {"hello": "world"} assert json_body is None json_body_extras, data_body_extras = get_request_body( - json=None, data={"goodbye": "world"}, request_options=get_request_options(), omit=None + json=None, + data={"goodbye": "world"}, + request_options=get_request_options(), + omit=None, ) assert data_body_extras == {"goodbye": "world", "see you": "later"} @@ -35,7 +45,9 @@ def test_get_files_request_body() -> None: def test_get_none_request_body() -> None: - json_body, data_body = get_request_body(json=None, data=None, request_options=None, omit=None) + json_body, data_body = get_request_body( + json=None, data=None, request_options=None, omit=None + ) assert data_body is None assert json_body is None diff --git a/seed/python-sdk/websocket/tests/utils/test_query_encoding.py b/seed/python-sdk/websocket/tests/utils/test_query_encoding.py index 247e1551b46..fbc8f402167 100644 --- a/seed/python-sdk/websocket/tests/utils/test_query_encoding.py +++ b/seed/python-sdk/websocket/tests/utils/test_query_encoding.py @@ -4,9 +4,15 @@ def test_query_encoding() -> None: - assert encode_query({"hello world": "hello world"}) == {"hello world": "hello world"} - assert encode_query({"hello_world": {"hello": "world"}}) == {"hello_world[hello]": "world"} - assert encode_query({"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"}) == { + assert encode_query({"hello world": "hello world"}) == { + "hello world": "hello world" + } + assert encode_query({"hello_world": {"hello": "world"}}) == { + "hello_world[hello]": "world" + } + assert encode_query( + {"hello_world": {"hello": {"world": "today"}, "test": "this"}, "hi": "there"} + ) == { "hello_world[hello][world]": "today", "hello_world[test]": "this", "hi": "there", diff --git a/seed/python-sdk/websocket/tests/utils/test_serialization.py b/seed/python-sdk/websocket/tests/utils/test_serialization.py index 58b1ed66e6d..5ca956916dd 100644 --- a/seed/python-sdk/websocket/tests/utils/test_serialization.py +++ b/seed/python-sdk/websocket/tests/utils/test_serialization.py @@ -1,10 +1,12 @@ # This file was auto-generated by Fern from our API Definition. -from typing import Any, List +from typing import List, Any -from seed.core.serialization import convert_and_respect_annotation_metadata +from seed.core.serialization import ( + convert_and_respect_annotation_metadata, +) +from .assets.models import ShapeParams, ObjectWithOptionalFieldParams -from .assets.models import ObjectWithOptionalFieldParams, ShapeParams UNION_TEST: ShapeParams = {"radius_measurement": 1.0, "shape_type": "circle", "id": "1"} UNION_TEST_CONVERTED = {"shapeType": "circle", "radiusMeasurement": 1.0, "id": "1"} @@ -18,20 +20,54 @@ def test_convert_and_respect_annotation_metadata() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) - assert converted == {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"} + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) + assert converted == { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + } def test_convert_and_respect_annotation_metadata_in_list() -> None: data: List[ObjectWithOptionalFieldParams] = [ - {"string": "string", "long_": 12345, "bool_": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long_": 67890, "list_": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long_": 12345, + "bool_": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long_": 67890, + "list_": [], + "literal": "lit_one", + "any": "any", + }, ] - converted = convert_and_respect_annotation_metadata(object_=data, annotation=List[ObjectWithOptionalFieldParams]) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=List[ObjectWithOptionalFieldParams] + ) assert converted == [ - {"string": "string", "long": 12345, "bool": True, "literal": "lit_one", "any": "any"}, - {"string": "another string", "long": 67890, "list": [], "literal": "lit_one", "any": "any"}, + { + "string": "string", + "long": 12345, + "bool": True, + "literal": "lit_one", + "any": "any", + }, + { + "string": "another string", + "long": 67890, + "list": [], + "literal": "lit_one", + "any": "any", + }, ] @@ -43,7 +79,9 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: "literal": "lit_one", "any": "any", } - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ObjectWithOptionalFieldParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ObjectWithOptionalFieldParams + ) assert converted == { "string": "string", @@ -55,12 +93,16 @@ def test_convert_and_respect_annotation_metadata_in_nested_object() -> None: def test_convert_and_respect_annotation_metadata_in_union() -> None: - converted = convert_and_respect_annotation_metadata(object_=UNION_TEST, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=UNION_TEST, annotation=ShapeParams + ) assert converted == UNION_TEST_CONVERTED def test_convert_and_respect_annotation_metadata_with_empty_object() -> None: data: Any = {} - converted = convert_and_respect_annotation_metadata(object_=data, annotation=ShapeParams) + converted = convert_and_respect_annotation_metadata( + object_=data, annotation=ShapeParams + ) assert converted == data